VAYULearn
Colour theme
Investigate a failure
VAYU Learn

Spark & PySpark

Introduction to Spark Streaming — Real-Time Data Made Simple

💡 Imagine data flowing in like a river — tweets, sensor readings, or transactions every second

Spark & PySparkKafka & Streaming

How do we process it as it arrives, instead of waiting for a batch file?
That’s where Spark Streaming comes in.

In this post, we’ll break down Spark Streaming from zero:

  • What it is
  • How micro-batches work
  • Setting up a stream with Python
  • A simple real-world simulation
  • Common use cases
  • And how it fits into the modern streaming world

Let’s make real-time data feel simple.


🚀 What is Spark Streaming?

Spark Streaming is an extension of the core Apache Spark framework that lets you process real-time (or near real-time) data streams.

It divides incoming data into small batches, processes them with Spark’s powerful engine, and outputs results continuously.

✅ Key idea:
Instead of one big DataFrame → you get many small DataFrames processed every few seconds.

🧠 In simple terms: Spark Streaming processes real-time data in small, time-based batches called micro-batches, enabling near real-time analytics with Spark’s distributed engine.

⚙️ How Spark Streaming Works

Imagine a stream of events flowing in — say, user clicks from a website. Spark divides this continuous flow into small batches, processes each batch using standard Spark jobs, and outputs the results.

This is the Discretized Stream (DStream) model — micro-batch-based streaming.

Later, Spark introduced Structured Streaming, a more powerful abstraction built on DataFrames and Datasets.
Structured Streaming treats live data like an unbounded table that keeps updating — allowing you to use the same APIs you already know from Spark SQL.

Before diving into the code, let’s visualize the flow of data in Spark Streaming — from input to real-time output.

⏳ The Flow

Figure 1: Spark Streaming Data Flow

The figure shows how Spark breaks incoming data streams into micro-batches, processes them using the Spark engine, and outputs the results in near real time.

Each batch runs a mini Spark job behind the scenes.

📊 Think of it like:

  • Batch Processing → Spark runs once on large dataset
  • Streaming Processing → Spark runs repeatedly on tiny slices of data

🧩 Architecture Overview

Every Spark Streaming app includes three main parts:

  1. Input Sources — where data comes from
    (Kafka, socket, HDFS, AWS Kinesis, etc.)
  2. Processing Logic — transformations you define
    (map, reduceByKey, window operations)
  3. Output Sinks — where results go
    (console, database, or dashboard)
Figure 2: Spark Streaming Architecture Overview

Illustrates the complete pipeline — from multiple input sources (like Kafka, Flume, HDFS, or Twitter) through Spark’s processing logic to output sinks such as databases, dashboards, or HDFS.


🧩 Key Concepts

🕒 1. Micro-Batches

Spark collects incoming data for a small time window (e.g., 1 second) and runs a mini batch job for it.

📦 2. DStreams

Older API based on RDD transformations like map(), reduceByKey().
Each batch = one RDD.

🧠 3. Structured Streaming

Newer, higher-level API built on DataFrames.
Easier, faster, supports SQL queries, event-time processing, and fault tolerance.

🔁 4. Trigger

Defines how often Spark should process data (e.g., every 5 seconds).

💾 5. Sink

Where you send the results — console, file, Kafka, database, etc.


💻 Let’s Code a Simple Streaming Example

We’ll simulate a real-time text stream — like log lines or chat messages — flowing into Spark every few seconds.

🧩 Note: Streaming jobs need a persistent environment like Databricks, AWS EMR, or local Spark setup — they won’t run properly on Colab because the session ends before the stream completes.

Step 1: Create a Streaming Context

from pyspark import SparkContext
from pyspark.streaming import StreamingContext

# Create local Spark context with 2 threads
sc = SparkContext("local[2]", "NetworkWordCount")
ssc = StreamingContext(sc, 5) # 5-second batch interval

Step 2: Connect to a Data Stream

We’ll simulate a real-time text feed using a socket.

# Create DStream from localhost:9999
lines = ssc.socketTextStream("localhost", 9999)

Start a socket stream from your terminal:

nc -lk 9999

Then type:

hello spark
hello streaming

Step 3: Transform the Stream

words = lines.flatMap(lambda line: line.split(" "))
pairs = words.map(lambda word: (word, 1))
wordCounts = pairs.reduceByKey(lambda x, y: x + y)
wordCounts.pprint()

This prints real-time word counts every 5 seconds.


Step 4: Start the Stream

ssc.start()
ssc.awaitTermination()

✅ Spark now continuously listens to your input stream and processes it in micro-batches.


🧠 Real-World Case: Real-Time Transaction Monitoring

Let’s take a real-world case.

A fintech company needs to detect unusual spending patterns instantly — not hours later.

  • Input: Real-time transaction events from Kafka
  • Processing: Spark Streaming detects anomalies based on amount thresholds or frequency
  • Output: Sends alerts to a fraud detection system

⚙️ Spark Streaming is perfect for this because:

  • It scales horizontally with your data volume
  • It provides built-in fault tolerance
  • It integrates easily with Kafka, HDFS, and databases

🧮 Simulated Demo: Mini Real-Time Pipeline

Let’s simulate a tiny continuous data flow inside Colab.

import time
import random

transactions = [
{"id": i, "amount": random.randint(10, 1000), "region": random.choice(["US", "IN", "UK"])}
for i in range(1, 11)
]

for txn in transactions:
print(txn)
time.sleep(1)

This mimics live data every second — similar to Kafka topic events.


⚡ Common Transformations in Spark Streaming

Now that we understand how the data flows through Spark Streaming, let’s look at the key transformations that make real-time analytics possible.

Table — Common transformations you’ll frequently use while building real-time Spark streaming pipelines.

🧰 Benefits of Spark Streaming

✅ Unified batch + stream engine
✅ Micro-batch design ensures reliability
✅ Built-in fault tolerance
✅ Works with Kafka, Flume, HDFS, S3
✅ Easy scaling + Spark ecosystem integration (MLlib, SQL)


⚠️ Limitations

  • Processes data in micro-batches, not record-by-record
  • Small latency (a few seconds)
  • Being gradually replaced by Structured Streaming
⚡ Performance Note: Spark Streaming typically operates with batch intervals ranging from 500 milliseconds to 10 seconds, depending on workload, cluster size, and latency requirements.

🔁 From Spark Streaming to Structured Streaming

Spark Streaming’s micro-batch design made real-time data processing reliable and scalable.
However, as data systems evolved, a few limitations (like small latency and lower-level APIs) became bottlenecks.

💡 That’s why Structured Streaming was introduced — Spark’s next-generation streaming engine.
It builds on DataFrames and SQL, offering:

  • Lower latency (near-continuous processing)
  • Simpler, declarative APIs
  • Built-in event-time handling and exactly-once guarantees

👉 In the next post, we’ll dive deep into
“Spark Streaming vs Structured Streaming — Key Differences,”
and see how Spark reimagined streaming for the modern data world.


🧪 Try It Yourself on Databricks

You can easily run this example on Databricks or your local Spark setup (Colab isn’t ideal for streaming).

Steps:

1️⃣ Install dependencies (for local setup only)
(Skip this on Databricks — it already has Java & Spark preinstalled.)

!apt-get update
!apt-get install openjdk-11-jdk netcat -y

2️⃣ Start a socket stream (in a separate terminal)

nc -lk 9999

Type a few words — these will act as real-time data input.

3️⃣ Run the Spark Streaming code

from pyspark.sql import SparkSession
from pyspark.streaming import StreamingContext

spark = SparkSession.builder.appName("StreamingDemo").getOrCreate()
sc = spark.sparkContext
ssc = StreamingContext(sc, 5) # 5-second batch interval

lines = ssc.socketTextStream("localhost", 9999)
words = lines.flatMap(lambda line: line.split(" "))
pairs = words.map(lambda word: (word, 1))
word_counts = pairs.reduceByKey(lambda x, y: x + y)
word_counts.pprint()

ssc.start()
ssc.awaitTermination()

You’ll see real-time word counts printed to the console every 5 seconds 🚀


🧩 Spark Streaming in Modern Pipelines

Today, Spark Streaming powers real-time dashboards and alerts across:

  • Financial transactions
  • IoT sensor data
  • Web clickstream analytics
  • Social media monitoring
  • Real-time ETL pipelines

Add checkpointing for reliability:

ssc.checkpoint("checkpoint_dir")

🧠 Conclusion

Spark Streaming made real-time analytics approachable — long before “streaming-first” frameworks dominated.
Its micro-batch architecture balanced speed, reliability, and scalability beautifully.

While Structured Streaming has now evolved as Spark’s modern engine, mastering Spark Streaming helps you truly understand the roots of real-time processing.

Understanding Spark Streaming gives you the foundation to appreciate how Structured Streaming achieves true continuous processing.

If you’ve ever wondered “How does Spark handle real-time?” — this was your foundation.


🔜 Next in the Series

📘 Coming Up Next:
👉 “Spark Streaming vs Structured Streaming — Key Differences”
We’ll compare how Spark evolved from DStreams to Structured Streaming,
what changed under the hood, and why DataFrames made streaming faster, simpler, and more declarative.

💡 Think of it as Spark’s evolution story — from the classic engine to the modern streaming brain.


🔔 Follow for More

If you found this helpful, follow TheDataForge for your daily Spark in Data Engineering & Machine Learning ⚡
💬 Comment below — what’s the toughest real-time Spark Streaming issue you’ve faced (like late data, skew, or checkpointing gone wrong)?


🏷️ Tags

#ApacheSpark #PySpark #BigData #DataEngineering #DataForge #SparkOptimization #LazyEvaluation #DAG