Hiring Partners
Segilola Resources Operating LimitedTaviatech TechnologiesFCMBMTN NigeriaAdvans La Fayette Microfinance BankAboki AfricaFirst Bank of NigeriaOPay
← Big Data Engineering WIth Spark · Lesson 8 of 9

Module Seven

📖 Every lesson in this course is free to read right here, no account needed. Create a free account to track your progress, take the exam, and earn your certificate.
8
Module 7 – Spark Streaming and Real-Time Data

🌊 Module 7 – Spark Streaming and Real-Time Data

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:

  • Explain what streaming data is and why it's important.
  • Understand the difference between batch and stream processing.
  • Explain how Spark Streaming works.
  • Create a Spark Streaming application.
  • Process data from sources like Kafka, sockets, and files.
  • Use window operations on streaming data.
  • Handle late data and stateful processing.
  • Build a real-time dashboard with Spark Streaming.

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.


Main Lessons

Lesson 1: What is Streaming Data?

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.


Lesson 2: Batch vs Stream Processing

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.


Lesson 3: Introducing Spark Streaming

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.


Lesson 4: How Spark Streaming Works – Micro‑Batches

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.


Lesson 5: DStreams – The Streaming RDD

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.


Lesson 6: Creating a Streaming Context

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.


Lesson 7: Data Sources – Where Does Stream Data Come From?

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.


Lesson 8: Transformations on DStreams

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.


Lesson 9: Actions on DStreams

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.


Lesson 10: Window Operations

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.


Lesson 11: Stateful Operations – Remembering Across Batches

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.


Lesson 12: Handling Late Data with Watermarks

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.


Lesson 13: Structured Streaming – The Modern Way

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.


Lesson 14: Output Sinks – Where Results Go

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.


Lesson 15: Building a Real‑Time Dashboard

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.


Key Vocabulary (with simple definitions)

  • Streaming Data: Data that arrives continuously over time.
  • Batch Processing: Processing data all at once.
  • Stream Processing: Processing data as it arrives.
  • Spark Streaming: Spark's module for processing streaming data.
  • Micro‑batch: A small chunk of streaming data processed like a batch.
  • DStream: Discretized Stream – the basic streaming data structure.
  • StreamingContext: Main object for Spark Streaming.
  • Window Operation: Processing data over a time window.
  • Stateful Operation: Remembering data across micro‑batches.
  • Watermark: A threshold for handling late data.
  • Structured Streaming: The newer, DataFrame‑based streaming API.
  • Output Sink: Where streaming results are sent.
  • Kafka: A popular streaming data source.
  • Latency: The delay between data arrival and processing.
  • Exactly‑once: Processing each data item exactly once, even if failures occur.

Important Concepts

  1. Micro‑batching: Spark Streaming processes data in small batches.
  2. Fault Tolerance: Spark Streaming can recover from failures using checkpoints.
  3. Exactly‑Once Semantics: Each data item is processed exactly once.
  4. Event Time vs Processing Time: When the data was generated vs when it was processed.
  5. Checkpointing: Saving the state of a streaming application for recovery.

Step‑by‑Step Explanations

How to build a Spark Streaming application:

  1. Create a StreamingContext (or SparkSession for Structured Streaming).
  2. Define the data source (socket, Kafka, files, etc.).
  3. Apply transformations to the data (filter, map, reduce, etc.).
  4. Define window or stateful operations if needed.
  5. Define the output sink (console, file, database, etc.).
  6. Start the streaming application.
  7. Wait for termination or stop when done.
   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

Real‑life Examples

  • Uber: Uses Spark Streaming to track ride requests and driver locations.
  • Twitter: Uses streaming to analyse tweets in real-time.
  • Financial Services: Uses streaming to detect fraudulent transactions.
  • IoT: Uses streaming to monitor sensor data from devices.
  • E‑commerce: Uses streaming to track user activity and recommend products.

Nigerian Examples

  • Flutterwave: Uses streaming to process transactions and detect fraud.
  • Opay: Uses streaming to monitor mobile money transactions.
  • Traffic Monitoring: Uses streaming to count cars on Lagos roads.
  • Election Monitoring: Uses streaming to track voting results as they arrive.
  • Agriculture: Uses streaming to monitor weather data for crop predictions.

Fun Examples Children Can Relate To

  • Game scores: Tracking scores in a video game as they happen.
  • Classroom noise: Measuring how loud the class gets in real-time.
  • Candy counting: Counting how many candies you eat in real-time.
  • Step counter: Tracking steps as you walk.

Everyday Examples

  • Traffic updates: Showing traffic conditions as they change.
  • Weather updates: Showing temperature changes in real-time.
  • News feed: Showing news as it happens.
  • Social media: Showing posts as they are made.

Teacher Notes

  • Start with the "tap water" analogy to explain streaming.
  • Show the difference between batch and streaming with a simple count (students entering class).
  • Emphasise that streaming is useful for time‑sensitive decisions.
  • Use a live demo if possible (simple socket program).
  • Stress the importance of handling late data.

Parent Tips

  • Discuss real‑time data in daily life (traffic, weather, sports scores).
  • Talk about how businesses use live data to make decisions.
  • Explain the difference between "now" and "later" when it comes to data.
  • Watch a live sports match and talk about the live statistics.

Interesting Facts

  • Every day, over 500 million tweets are sent – that's streaming data!
  • IoT devices generate 2.5 quintillion bytes of data every day.
  • Stock markets process millions of transactions every second.
  • Uber processes over 10 million trips per day using streaming.
  • Spark Streaming can process data with sub‑second latency.

Did You Know?

  • 🤔 Did you know that Spark Streaming was originally called "Spark Streaming" because it streams data?
  • 🤔 Did you know that Netflix uses streaming to handle 10 million streaming requests per second?
  • 🤔 Did you know that some streaming applications process data in microseconds?
  • 🤔 Did you know that streaming is used in self‑driving cars to process sensor data?
  • 🤔 Did you know that streaming data is often called "data in motion"?

Remember This

  • Streaming = processing data as it arrives.
  • Batch = processing data all at once.
  • Spark Streaming uses micro‑batches.
  • DStreams are the basic streaming data structure.
  • Window operations analyse data over time.
  • Stateful operations remember across batches.
  • Structured Streaming is the new, easier way.

Common Mistakes

  • ❌ Forgetting to start the streaming context.
  • ❌ Not handling late data.
  • ❌ Using stateful operations without checkpointing.
  • ❌ Setting the batch duration too short (overhead) or too long (latency).
  • ❌ Forgetting to stop the streaming application.
  • ❌ Not testing with small data first.

Best Practices

  • ✅ Use Structured Streaming for new applications.
  • ✅ Set checkpointing for fault tolerance.
  • ✅ Use appropriate batch duration (usually 1-5 seconds).
  • ✅ Handle late data with watermarks.
  • ✅ Use exactly‑once processing for critical applications.
  • ✅ Monitor your streaming application.
  • ✅ Test with small data before running at full scale.

ASCII Illustrations

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)

Comparison Tables

Batch vs Stream Processing:

FeatureBatchStream
DataStatic/CompleteContinuous/Infinite
ProcessingAll at onceAs it arrives
LatencyHours to daysMilliseconds to seconds
Use caseDaily reportsLive dashboards
OutputComplete resultContinuous updates

DStream vs Structured Streaming:

FeatureDStream (Old)Structured Streaming (New)
APIRDD-basedDataFrame/SQL-based
Ease of useHarderEasier
Exactly-onceHarderBuilt-in
Late dataManualWatermarks
PerformanceGoodBetter

Streaming Sources Comparison:

SourceDescriptionBest For
SocketNetwork connectionTesting
KafkaMessage queueProduction
FilesNew files in a directoryLog files
KinesisAWS streamingAWS users

End‑of‑Module Summary

Congratulations! 🎉 You have completed Module 7 – Spark Streaming and Real‑Time Data. Here's what we learned:

  • Streaming data arrives continuously, like water from a tap.
  • Batch processing processes all data at once; stream processes as it arrives.
  • Spark Streaming uses micro‑batches to process streaming data.
  • DStreams are the basic streaming data structure (older API).
  • Structured Streaming uses DataFrames and is easier and more powerful.
  • Window operations analyse data over time periods.
  • Stateful operations remember data across micro‑batches.
  • Watermarks handle late data.
  • Output sinks decide where results go.
  • You can build real‑time dashboards with Spark Streaming.

You are now ready for Module 8 – Machine Learning with Spark MLlib! 🤖

Frequently Asked Questions (FAQs)

  1. Q: What is streaming data? A: Data that arrives continuously over time.
  2. Q: What is the difference between batch and stream? A: Batch processes all data at once; stream processes as it arrives.
  3. Q: What is a micro‑batch? A: A small chunk of streaming data processed like a batch.
  4. Q: What is a DStream? A: The basic streaming data structure in Spark Streaming.
  5. Q: What is Structured Streaming? A: The newer, DataFrame‑based streaming API.
  6. Q: What is a window operation? A: Processing data over a time window (e.g., last 10 seconds).
  7. Q: What is a stateful operation? A: Remembering data across micro‑batches.
  8. Q: What is a watermark? A: A threshold for handling late data.
  9. Q: What is an output sink? A: Where the streaming results are sent.
  10. Q: Can Spark Streaming handle exactly‑once processing? A: Yes, especially with Structured Streaming.

Review Questions

  1. What is streaming data?
  2. What is the difference between batch and stream processing?
  3. What is Spark Streaming?
  4. What is a micro‑batch?
  5. What is a DStream?
  6. What is the StreamingContext used for?
  7. Name three streaming data sources.
  8. What is a window operation?
  9. What is a stateful operation?
  10. What is a watermark used for?
  11. What is Structured Streaming?
  12. What is an output sink?
  13. Name three output sinks.
  14. What is checkpointing?
  15. Give an example of a real‑time application.

Fill‑in‑the‑Blank Exercises

  1. Streaming data arrives __________ (continuously / once).
  2. Batch processing processes data __________ (all at once / as it arrives).
  3. Spark Streaming uses __________ (micro‑batches / one big batch).
  4. DStream stands for __________ (Discretized Stream / Data Stream).
  5. Structured Streaming uses __________ (DataFrames / DStreams).

True or False Exercises

  1. Streaming data arrives continuously. (True)
  2. Batch processing is faster than stream processing. (False)
  3. Spark Streaming uses micro‑batches. (True)
  4. DStreams are used in Structured Streaming. (False)
  5. Watermarks are used to handle late data. (True)

Multiple Choice Questions

  1. What is streaming data?
    A) Data stored in a file
    B) Data that arrives continuously
    C) Data that never arrives
    Answer: B
  2. Batch processing processes data:
    A) As it arrives
    B) All at once
    C) Never
    Answer: B
  3. Spark Streaming uses:
    A) One big batch
    B) Micro‑batches
    C) No batches
    Answer: B
  4. What does DStream stand for?
    A) Data Stream
    B) Discretized Stream
    C) Digital Stream
    Answer: B
  5. What is the main object for Spark Streaming?
    A) SparkContext
    B) StreamingContext
    C) SparkSession
    Answer: B
  6. Which is a streaming data source?
    A) CSV file
    B) Kafka
    C) Excel file
    Answer: B
  7. A window operation analyses data over:
    A) One micro‑batch
    B) A time period
    C) All time
    Answer: B
  8. Stateful operations:
    A) Forget everything
    B) Remember across batches
    C) Delete data
    Answer: B
  9. Watermarks are used for:
    A) Early data
    B) Late data
    C) No data
    Answer: B
  10. Which is the newer streaming API?
    A) DStream
    B) Structured Streaming
    C) Both are new
    Answer: B
  11. What is an output sink?
    A) Data source
    B) Where results go
    C) A transformation
    Answer: B
  12. Which is NOT an output sink?
    A) Console
    B) File
    C) DStream
    Answer: C
  13. Checkpointing is used for:
    A) Speed
    B) Fault tolerance
    C) Data deletion
    Answer: B
  14. What is latency in streaming?
    A) Speed of processing
    B) Delay between data arrival and processing
    C) Amount of data
    Answer: B
  15. Which company uses Spark Streaming?
    A) Uber
    B) A bakery
    C) A school
    Answer: A

Matching Exercises

Match the term with its description:

TermDescription
1. StreamA. Small chunk of streaming data
2. Micro‑batchB. Data that arrives continuously
3. DStreamC. Processing over time
4. WindowD. Handles late data
5. WatermarkE. Streaming data structure

Answers: 1-B, 2-A, 3-E, 4-C, 5-D

Short Answer Questions

  1. Explain the difference between batch and stream processing.
  2. What are micro‑batches and why does Spark use them?
  3. What is a window operation and when would you use it?
  4. What is the difference between DStreams and Structured Streaming?
  5. How do watermarks help with late data?

Scenario‑based Exercises

  1. Scenario: You are monitoring a factory that produces widgets. Sensors send data every second about temperature and pressure. Design a streaming application to alert if temperature exceeds 100°C.
  2. Scenario: An e‑commerce company wants to see live sales on a dashboard. Data comes from Kafka. Design the Spark Streaming pipeline.
  3. Scenario: You are tracking Twitter mentions of a brand. You want to count mentions per minute and alert if mentions drop suddenly. How would you build this?

Group Activity

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:

  • What data is being monitored?
  • Where does the data come from?
  • What Spark Streaming pipeline would you build?
  • How would you alert for problems?
  • What would the dashboard look like?

Individual Activity

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.

Classroom Discussion Questions

  1. What are some real‑time applications you use every day?
  2. Why is real‑time data more challenging than static data?
  3. What would happen if a streaming application stopped working?
  4. How do businesses benefit from real‑time data?
  5. What are the privacy concerns with real‑time data?

Mini Project

Title: Real‑Time Social Media Monitoring

Description: Build a Spark Streaming application that monitors social media posts (simulated by a socket). The application should:

  1. Read posts from a socket.
  2. Filter posts by keyword.
  3. Count posts per minute using a window operation.
  4. Alert if more than 10 posts per minute.
  5. Print results to the console.

Deliverable: Working Spark Streaming code.

Practical Assignment

Title: Kafka and Spark Streaming

Instructions:

  1. Set up a Kafka producer that sends messages.
  2. Write a Spark Streaming application to read from Kafka.
  3. Process the messages (e.g., word count).
  4. Write results to a file sink.
  5. Run the application and verify the output.

Challenge Exercise

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.

Quiz Answers

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

Key Takeaways

  • Streaming processes data as it arrives.
  • Spark Streaming uses micro‑batches for reliability.
  • DStreams are the basic streaming data structure.
  • Structured Streaming is the newer, easier API.
  • Window operations analyse data over time.
  • Stateful operations maintain data across batches.
  • Watermarks handle late data.
  • Output sinks deliver results to dashboards, files, or databases.
  • Real‑time dashboards provide live insights.

Preparation for Module 8 – Machine Learning with Spark MLlib

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:

  • Your Spark knowledge from all modules.
  • Understanding of DataFrames and transformations.
  • Curiosity about how computers learn!

See you in Module 8 – let's teach computers to learn! 🤖

🏆 Get Certified

🔒

Earn this certificate

Every lesson is already free to read. Sign up, finish the lessons, pass the exam (₦2,000 or 20,000 coins), and get a verified certificate with your name on it.

🎓 Sign Up to Get Certified
🛠️ Practice Tools
Hands-on simulators & labs - subscription required.
→
🎯 Internship Tasks
Real-world tasks to build your portfolio - unlock them with a subscription.
→