Module Introduction
Hello, real-time data explorer! ⚡ So far in our Spark journey, we have been working with data that is already stored in files or databases. That's called batch processing – we process data in chunks, like reading a whole book at once.
But what if data keeps coming all the time, like water flowing from a tap? What if we want to analyse it as it arrives – second by second? That's called real-time processing or streaming.
Imagine you are watching a football match and you want to count how many goals are scored as they happen. You don't wait until the match is over. You count them live! That's exactly what Spark Streaming does – it processes data live, as it arrives.
In this module, we will learn about Spark Streaming, how it works, and how to build real-time applications. Let's dive into the stream! 🌊
Learning Objectives
By the end of this module, you will be able to:
Warm‑up Story – The Busy Bakery
Remember Mama Chidi's bakery from Module 4? Her bakery is now very popular! Every minute, customers buy bread, cakes, and pastries. Mama Chidi wants to know right now how many items are being sold, which items are most popular, and if they are running out of stock.
She can't wait until the end of the day to count everything. She needs to know as it happens. So she installs a computer system at the cash register that sends data to Spark every time a customer buys something.
Spark receives this data continuously, like a river of information. It counts the items, updates the dashboard, and even sends an alert if stock is low. This is streaming data processing!
Customer buys bread → Cash register sends data → Spark processes → Dashboard updates (every second) (continuously) (in real-time) (live view)
🌟 Mini summary: Streaming processes data as it arrives, giving us real-time insights.
Definition: Streaming data is data that is generated continuously and arrives in small pieces over time.
Why it is important: Many things in life happen continuously. We need to analyse them as they happen, not wait until later.
Simple explanation: Think of a river. Water keeps flowing. You can't wait for the whole river to pass – you need to analyse the water as it flows.
Real-life example: Tweets on Twitter. Every second, thousands of new tweets are posted.
School example: Students entering the school gate every morning. The gate counts them as they enter.
Home example: Water dripping from a tap. Each drop is data.
Nigerian example: Mobile money transactions on Opay. Every transaction is a piece of streaming data.
Batch Data (static): [all data at once] → process → result Streaming Data (live): [data1, data2, data3, ...] → process continuously → results
📌 Mini summary: Streaming data comes continuously, like water from a tap.
Definition: Batch processing means collecting data over a period and processing it all at once. Stream processing means processing data as it arrives.
Why it is important: Different problems need different approaches. Some need real-time answers; others can wait.
Simple explanation: Batch is like washing all your clothes at the end of the week. Stream is like washing each item as soon as it gets dirty.
Real-life example: A bank processes daily transactions in a batch at night (batch). It also detects fraud instantly as transactions happen (stream).
School example: Grading all exams at the end of the term (batch). Taking attendance each morning (stream).
Home example: Cleaning the whole house on Saturday (batch). Wiping the kitchen counter after each meal (stream).
Nigerian example: Counting votes after the election (batch). Monitoring election results as they are announced (stream).
+-----------------------+-----------------------+ | Batch Processing | Stream Processing | +-----------------------+-----------------------+ | Process at once | Process continuously | | Wait for all data | Process as it arrives | | Good for large files | Good for live data | | Example: daily report | Example: live dashboard | +-----------------------+-----------------------+
📌 Mini summary: Batch processes data all at once; stream processes data as it arrives.
Definition: Spark Streaming is a module in Spark that allows us to process streaming data in real-time.
Why it is important: It brings the power of Spark to live data, allowing us to analyse tweets, sensor data, transactions, and more in real-time.
Simple explanation: Spark Streaming is like a live filter that catches and processes data as it flies by.
Real-life example: Uber uses Spark Streaming to track ride requests and driver locations in real-time.
School example: A system that counts students as they enter the school compound.
Home example: A smart doorbell that sends data every time someone rings it.
Nigerian example: A traffic monitoring system that counts cars on the Third Mainland Bridge in Lagos.
Spark Streaming Architecture:
+-------------+ +-------------+ +-------------+
| Data Source | → | Spark | → | Output |
| (Kafka, | | Streaming | | (Dashboard, |
| Socket, etc)| | Engine | | Database, |
+-------------+ +-------------+ | Alert) |
+-------------+
📌 Mini summary: Spark Streaming is Spark's tool for processing live data as it arrives.
Definition: Spark Streaming processes streaming data by dividing it into small chunks called micro‑batches. Each micro‑batch is processed like a small batch job.
Why it is important: This approach combines the best of batch and streaming. It's fast and reliable.
Simple explanation: Imagine you are drinking juice through a straw. You don't drink it all at once. You take small sips. Each sip is a micro‑batch.
Real-life example: A bus picks up passengers every 10 minutes. Each busload is a micro‑batch.
School example: The teacher collects homework every morning. Each morning's collection is a micro‑batch.
Home example: You check your phone every few minutes for new messages. Each check is a micro‑batch.
Nigerian example: A market trader counts sales every hour. Each hour is a micro‑batch.
Streaming Data Flow: Time: |----|----|----|----|----|----| Data: | d1 | d2 | d3 | d4 | d5 | d6 | Micro-batches: [d1,d2] [d3,d4] [d5,d6] Spark processes each micro-batch one at a time.
📌 Mini summary: Spark Streaming uses micro‑batches – small chunks of data processed one at a time.
Definition: DStream stands for Discretized Stream. It is the basic data structure in Spark Streaming, representing a continuous stream of data.
Why it is important: DStreams are to streaming what RDDs are to batch – the fundamental building block.
Simple explanation: A DStream is like a conveyor belt with boxes of data. Each box is a small RDD.
Real-life example: A conveyor belt at an airport luggage carousel. Each bag is a piece of data.
School example: A line of students entering the assembly hall. Each student is a piece of data.
Home example: A stream of water droplets from a dripping tap. Each droplet is data.
Nigerian example: A line of people waiting at a bus stop. Each person is a piece of data.
DStream = continuous sequence of RDDs Time: |----|----|----|----| RDDs: [RDD1][RDD2][RDD3][RDD4] Each RDD contains data from one micro-batch interval.
📌 Mini summary: DStream is a stream of data divided into small RDDs.
Definition: A StreamingContext is the main entry point for Spark Streaming applications, similar to SparkContext for batch.
Why it is important: You need a StreamingContext to create and manage your streaming pipeline.
Simple explanation: It's like the control centre for your streaming application.
Real-life example: The air traffic control tower that manages all flights.
School example: The principal's office that manages school activities.
Home example: The remote control for your TV – it controls everything.
Nigerian example: The dispatcher at a taxi company that coordinates all drivers.
How to create a StreamingContext:
from pyspark import SparkContext
from pyspark.streaming import StreamingContext
sc = SparkContext("local[2]", "StreamingApp")
ssc = StreamingContext(sc, batchDuration=1) # 1 second micro-batches
# Now you can create DStreams and process data
📌 Mini summary: StreamingContext is the main object for creating Spark Streaming applications.
Definition: Data sources are places where streaming data originates, like message queues, sockets, or files.
Why it is important: You need to connect to a data source to receive streaming data.
Simple explanation: It's like a pipe bringing water into your house. You need to connect to it.
Real-life example: Kafka is a popular data source that streams messages between applications.
School example: The school bell is a source – it sends a signal every hour.
Home example: A smart doorbell sends data when someone rings it.
Nigerian example: A mobile app sends data when a user makes a transaction.
Common Streaming Sources:
1. Socket (network connection)
2. Kafka (message queue)
3. Files (new files in a directory)
4. Flume (log collector)
5. Kinesis (AWS streaming service)
Example: reading from a socket
lines = ssc.socketTextStream("localhost", 9999)
📌 Mini summary: Data sources like Kafka or sockets provide the streaming data to Spark.
Definition: Transformations are operations that change a DStream, similar to transformations on RDDs.
Why it is important: Transformations let you clean, filter, and prepare streaming data.
Simple explanation: It's like having a sieve that separates sand from stones as the water flows through.
Real-life example: Filtering out all tweets that are not in English.
School example: Separating students by grade as they enter the school.
Home example: Sorting laundry into whites and colours as you pick it up.
Nigerian example: Filtering transactions by amount (> ₦10,000).
Common DStream Transformations:
- map() : apply a function to each element
- filter() : keep only elements that satisfy a condition
- flatMap() : split each element into multiple elements
- union() : combine two DStreams
- reduceByKey(): aggregate by key
- count() : count elements
Example: Word count on streaming data
words = lines.flatMap(lambda line: line.split(" "))
pairs = words.map(lambda word: (word, 1))
word_counts = pairs.reduceByKey(lambda a, b: a + b)
📌 Mini summary: Transformations on DStreams change, filter, and process the streaming data.
Definition: Actions are operations that produce results from a DStream, like printing or saving data.
Why it is important: Actions are what you do with the processed data – you need to see results!
Simple explanation: After you've sorted the laundry, you put it in the drawers – that's the action.
Real-life example: A dashboard that displays live sales data.
School example: A bell that rings when a certain number of students arrive.
Home example: A notification on your phone when you get a message.
Nigerian example: An SMS alert when a large transaction is made.
Common DStream Actions:
- print() : print the first 10 elements
- saveAsTextFiles(): save to text files
- saveAsHadoopFiles(): save to Hadoop
- count() : count elements (returns a stream)
- foreachRDD() : apply a function to each RDD (most flexible)
Example: Print word counts
word_counts.print()
Example: Save to file
word_counts.saveAsTextFiles("output/wordcount")
📌 Mini summary: Actions output the results of your streaming processing.
Definition: Window operations allow you to process data over a sliding window of time, not just the current micro‑batch.
Why it is important: Sometimes you want to see trends over the last 5 minutes, not just the last second.
Simple explanation: It's like looking through a moving window. You see what's happening now and what happened recently.
Real-life example: A traffic report shows traffic conditions over the last 15 minutes.
School example: A teacher looks at the last 5 minutes of students entering to estimate total attendance.
Home example: You check how many messages you received in the last hour.
Nigerian example: A security monitor checks the last 10 minutes of camera footage.
Window Operations:
+------------------------------------------+
| windowDuration = how long the window is |
| slideDuration = how often the window moves|
+------------------------------------------+
Example: Count words in the last 10 seconds, updated every 2 seconds
windowed_counts = pairs.reduceByKeyAndWindow(
lambda a, b: a + b, # add function
lambda a, b: a - b, # subtract function (for sliding)
10, # window duration (10 seconds)
2 # slide duration (2 seconds)
)
📌 Mini summary: Window operations let you analyse data over a period of time, like the last 10 seconds.
Definition: Stateful operations maintain information across micro‑batches. They "remember" what happened before.
Why it is important: Some analyses need to accumulate data over time, like total visitors per day.
Simple explanation: It's like keeping a running total of how many goals have been scored in a match so far.
Real-life example: Tracking total sales for the day, updated every minute.
School example: Keeping a running count of total students who have arrived in the morning.
Home example: Keeping a running total of how many steps you've walked today.
Nigerian example: Keeping a running count of total votes cast in an election as they arrive.
Stateful Operations:
1. updateStateByKey() - maintains state for each key
2. mapWithState() - more efficient state management
Example: Running count per word
def update_func(new_values, running_count):
if running_count is None:
running_count = 0
return sum(new_values) + running_count
running_counts = pairs.updateStateByKey(update_func)
📌 Mini summary: Stateful operations remember data across micro‑batches.
Definition: Late data is data that arrives after its expected time. Watermarks help the system decide when to wait for late data.
Why it is important: In real-world streaming, data can arrive late due to network delays or other issues.
Simple explanation: It's like waiting a little bit longer for a friend who is running late. You set a time you'll wait (the watermark).
Real-life example: A sensor sends data but there is a network delay.
School example: A student arrives late to class – you still count them but you know they are late.
Home example: A package arrives a day late – you still accept it.
Nigerian example: Election results from a remote village arrive late – they are still counted.
Watermark in Spark Structured Streaming:
from pyspark.sql.functions import current_timestamp
streaming_df = spark.readStream.format("kafka")...
# Add watermark (wait 10 minutes for late data)
streaming_df = streaming_df.withWatermark("timestamp", "10 minutes")
# Now window operations will handle late data
📌 Mini summary: Watermarks handle late data by setting how long to wait for it.
Definition: Structured Streaming is the newer, more powerful version of Spark Streaming. It uses DataFrames and SQL instead of DStreams.
Why it is important: It's easier to use, more powerful, and handles exactly‑once processing.
Simple explanation: It's like upgrading from a bicycle to a car – faster, smoother, and more features.
Real-life example: Netflix uses Structured Streaming to analyse viewing data in real-time.
School example: A school uses a modern attendance system that updates live.
Home example: A smart home system that monitors all devices in real-time.
Nigerian example: A modern payment system that processes transactions in real-time.
Structured Streaming Example:
from pyspark.sql import SparkSession
spark = SparkSession.builder.appName("StructuredStreaming").getOrCreate()
# Read streaming data
lines = spark.readStream.format("socket")
.option("host", "localhost")
.option("port", 9999)
.load()
# Process with SQL
words = lines.selectExpr("split(value, ' ') as words")
word_counts = words.groupBy("words").count()
# Write the output (sink)
query = word_counts.writeStream.outputMode("complete")
.format("console")
.start()
query.awaitTermination()
📌 Mini summary: Structured Streaming is the newer, easier way to do streaming with DataFrames.
Definition: Output sinks are where the results of streaming processing are sent, like a database, file, or console.
Why it is important: You need to deliver your results somewhere useful.
Simple explanation: It's like deciding where to put the food after cooking – on a plate, in a box, or in the fridge.
Real-life example: A dashboard displays results on a screen.
School example: Results are written on the notice board.
Home example: A notification pops up on your phone.
Nigerian example: Results are saved to a database for later analysis.
Output Sinks in Structured Streaming:
1. Console sink: print to the console (good for testing)
2. File sink: save to files (CSV, Parquet, etc.)
3. Kafka sink: send to Kafka topic
4. Foreach sink: custom processing (write to database, etc.)
5. Memory sink: store in memory (for testing)
Example: Write to console
query = word_counts.writeStream.outputMode("complete")
.format("console")
.start()
Example: Write to Parquet files
query = word_counts.writeStream.outputMode("append")
.format("parquet")
.option("path", "output/")
.start()
📌 Mini summary: Output sinks decide where to send the processed streaming results.
Let's build a complete real‑time dashboard that shows live sales data from a bakery.
Problem: A bakery wants to see live sales: total items sold, most popular item, and revenue.
Data Source: A socket sends sales data: item, price, quantity, timestamp.
Steps:
# Import Spark
from pyspark.sql import SparkSession
from pyspark.sql.functions import *
spark = SparkSession.builder.appName("BakeryDashboard").getOrCreate()
# 1. Read streaming data from socket
sales_df = spark.readStream.format("socket")
.option("host", "localhost")
.option("port", 9999)
.load()
# 2. Parse the data (assuming format: item,price,quantity)
sales_df = sales_df.selectExpr(
"split(value, ',')[0] as item",
"cast(split(value, ',')[1] as double) as price",
"cast(split(value, ',')[2] as int) as quantity"
)
# 3. Add total_sales column
sales_df = sales_df.withColumn("total_sales", sales_df.price * sales_df.quantity)
# 4. Window operations - 1 minute windows
sales_df = sales_df.withWatermark("timestamp", "1 minute")
# 5. Calculate aggregations
totals = sales_df.groupBy("item").agg(
sum("total_sales").alias("revenue"),
sum("quantity").alias("items_sold")
)
# 6. Write to console (dashboard)
query = totals.writeStream.outputMode("complete")
.format("console")
.trigger(processingTime="5 seconds")
.start()
# 7. Also write to memory for dashboard
query2 = totals.writeStream.outputMode("complete")
.format("memory")
.queryName("dashboard")
.start()
query.awaitTermination()
📌 Mini summary: A real‑time dashboard shows live data updates as they happen.
How to build a Spark Streaming application:
Step 1: Create StreamingContext Step 2: Connect to source (socket, Kafka) Step 3: Process with transformations Step 4: Apply windows/state Step 5: Write to sink Step 6: Start streaming Step 7: Wait/stop
Streaming Pipeline:
Data Source → Spark Streaming → Transformations → Window/State → Sink → Results (Kafka) (micro-batches) (map, filter) (time windows) (DB) (Dashboard)
Micro‑batch Concept:
Data Stream: |------|------|------|------|------|------| | d1d2 | d3d4 | d5d6 | d7d8 | d9d10| ... | |----| |----| |----| |----| |----| |----| Batch1 Batch2 Batch3 Batch4 Batch5 Each batch = 2 seconds of data
Window Operation:
Time: |--|--|--|--|--|--|--|--|--|
Windows: |---------| (10 seconds)
|---------| (slides every 2 seconds)
|---------|
Each window covers the last 10 seconds
Structured Streaming Flow:
Input Stream → DataFrame → SQL/Transform → Output Stream (live data) (table) (groupBy, etc) (console/file/DB)
Batch vs Stream Processing:
| Feature | Batch | Stream |
|---|---|---|
| Data | Static/Complete | Continuous/Infinite |
| Processing | All at once | As it arrives |
| Latency | Hours to days | Milliseconds to seconds |
| Use case | Daily reports | Live dashboards |
| Output | Complete result | Continuous updates |
DStream vs Structured Streaming:
| Feature | DStream (Old) | Structured Streaming (New) |
|---|---|---|
| API | RDD-based | DataFrame/SQL-based |
| Ease of use | Harder | Easier |
| Exactly-once | Harder | Built-in |
| Late data | Manual | Watermarks |
| Performance | Good | Better |
Streaming Sources Comparison:
| Source | Description | Best For |
|---|---|---|
| Socket | Network connection | Testing |
| Kafka | Message queue | Production |
| Files | New files in a directory | Log files |
| Kinesis | AWS streaming | AWS users |
Congratulations! 🎉 You have completed Module 7 – Spark Streaming and Real‑Time Data. Here's what we learned:
You are now ready for Module 8 – Machine Learning with Spark MLlib! 🤖
Match the term with its description:
| Term | Description |
|---|---|
| 1. Stream | A. Small chunk of streaming data |
| 2. Micro‑batch | B. Data that arrives continuously |
| 3. DStream | C. Processing over time |
| 4. Window | D. Handles late data |
| 5. Watermark | E. Streaming data structure |
Answers: 1-B, 2-A, 3-E, 4-C, 5-D
Title: Design a Real‑Time Monitoring System
Instructions: In groups of 4, design a real‑time monitoring system for a Nigerian business of your choice (e.g., a bank, a supermarket, a traffic system). Answer:
Title: Simple Socket Streaming
Instructions: Set up a simple socket server on your computer. Write a Spark Streaming application that reads from the socket and counts words. Send some sentences to the socket and observe the word counts updating live.
Title: Real‑Time Social Media Monitoring
Description: Build a Spark Streaming application that monitors social media posts (simulated by a socket). The application should:
Deliverable: Working Spark Streaming code.
Title: Kafka and Spark Streaming
Instructions:
Title: Real‑Time Anomaly Detection
Problem: A sensor network sends data every second. Build a streaming application that detects anomalies (values that are more than 3 standard deviations from the mean). Use a sliding window to compute the mean and standard deviation in real‑time.
Fill‑in‑the‑Blank Answers: 1. continuously, 2. all at once, 3. micro‑batches, 4. Discretized Stream, 5. DataFrames
True/False Answers: 1. True, 2. False, 3. True, 4. False, 5. True
Multiple Choice Answers: 1-B, 2-B, 3-B, 4-B, 5-B, 6-B, 7-B, 8-B, 9-B, 10-B, 11-B, 12-C, 13-B, 14-B, 15-A
Matching Answers: 1-B, 2-A, 3-E, 4-C, 5-D
In Module 8, we will explore the exciting world of Machine Learning with Spark. We will learn how to build models that can learn from data and make predictions.
What to bring:
See you in Module 8 – let's teach computers to learn! 🤖