Spark & PySpark
Building a Real-Time Pipeline with Spark Streaming + Kafka
💡 Power your data flow — from real-time events to live insights.
🧠 TL;DR: Build a real-time analytics pipeline using Kafka + Spark Streaming — from simulated events to live dashboards.
🚀 Introduction
Real-time data isn’t just cool — it’s essential. Whether it’s tracking live transactions, social media mentions, or sensor data, streaming pipelines make your data come alive.
In this blog, we’ll walk through how to build a real-time data pipeline using Apache Spark Streaming and Apache Kafka — two open-source powerhouses that together form the backbone of modern streaming architectures.
We’ll simulate a live data stream, send it into Kafka, consume it with Spark Streaming, and process it in near real-time.
🧩 What We’ll Build
Here’s the simple flow we’ll create 👇
Data Source → Kafka Topic → Spark Streaming → Real-Time Console Output
We’ll simulate live “transactions” — small JSON messages like:
{"user":"alice","amount":120.5,"city":"Bangalore"}Spark Streaming will read them from Kafka, parse, and aggregate totals by city — in real-time.
📦 Step 1: Setup — Dependencies and Environment
If you’re running on Databricks, most dependencies are pre-installed.
For local setup, ensure you have:
!apt-get install openjdk-11-jdk -y
!wget https://downloads.apache.org/kafka/3.7.0/kafka_2.13-3.7.0.tgz
!tar -xzf kafka_2.13-3.7.0.tgz⚙️ Note:
This example is meant to be run on Databricks or a local Spark setup connected to a Kafka broker.
Environments like Google Colab don’t support live streaming jobs, since they require background services and persistent network connections.
🧪 Step 2: Create a Sample Dataset (Simulated Stream)
Let’s generate a small mock “transactions” dataset — it’ll act as our live Kafka feed.
import json, time, random
users = ["alice", "bob", "carol", "dave"]
cities = ["Bangalore", "Delhi", "Mumbai", "Hyderabad"]
with open("transactions.txt", "w") as f:
for _ in range(20):
record = {
"user": random.choice(users),
"amount": round(random.uniform(10, 500), 2),
"city": random.choice(cities)
}
f.write(json.dumps(record) + "\n")🗂️ Output: transactions.txt – a file with fake, event-like JSON data.
🔗 Step 3: Start Kafka Locally
Run these commands to start your Kafka environment (skip if on Databricks):
# Start Zookeeper
!kafka_2.13-3.7.0/bin/zookeeper-server-start.sh -daemon kafka_2.13-3.7.0/config/zookeeper.properties
# Start Kafka broker
!kafka_2.13-3.7.0/bin/kafka-server-start.sh -daemon kafka_2.13-3.7.0/config/server.properties
# Create a topic
!kafka_2.13-3.7.0/bin/kafka-topics.sh --create --topic transactions --bootstrap-server localhost:9092📨 Step 4: Produce Messages to Kafka
Simulate live event ingestion by pushing messages to the topic:
!kafka_2.13-3.7.0/bin/kafka-console-producer.sh --topic transactions --bootstrap-server localhost:9092 < transactions.txtNow your Kafka topic has continuous input like:
{"user":"alice","amount":120.5,"city":"Bangalore"}
{"user":"bob","amount":80.0,"city":"Delhi"}⚡ Step 5: Consume Data in Spark Streaming
Here’s where Spark Streaming takes over.
from pyspark import SparkContext
from pyspark.streaming import StreamingContext
from pyspark.streaming.kafka import KafkaUtils
sc = SparkContext(appName="KafkaSparkStreaming")
ssc = StreamingContext(sc, 5) # 5-second batch interval
# Connect to Kafka topic
kafkaStream = KafkaUtils.createStream(ssc, "localhost:2181", "spark-streaming-group", {"transactions":1})
# Extract message value
lines = kafkaStream.map(lambda msg: msg[1])
# Parse JSON and extract fields
import json
records = lines.map(lambda line: json.loads(line))
city_amounts = records.map(lambda r: (r["city"], float(r["amount"])))
# Aggregate totals by city
city_totals = city_amounts.reduceByKey(lambda a, b: a + b)
city_totals.pprint()
ssc.start()
ssc.awaitTermination()Note: TheKafkaUtilsAPI shown here belongs to the older DStream-based Spark Streaming. In upcoming blogs, we’ll move to Structured Streaming, which provides better scalability, fault tolerance, and exactly-once semantics with thespark.readStreamAPI.
🧠 What’s Happening Behind the Scenes
- Kafka acts as the message queue, buffering live events.
- Spark Streaming consumes these in micro-batches.
- Each micro-batch runs standard RDD transformations — filter, map, reduce.
- You get near real-time aggregation with fault tolerance.
🧩 Architecture Overview

📊 Kafka ingests event streams, Spark Streaming processes them in micro-batches, and outputs real-time analytics.
📈 Table: Common Transformations in Spark Streaming
Here are some of the most common transformations you’ll use when building real-time pipelines in Spark Streaming — from simple mappings to stateful aggregations across micro-batches:

🧩 Step 6: Visualize the Output
You’ll see something like this in your console every 5 seconds:
-------------------------------
Time: 2025-11-05 12:30:00
-------------------------------
('Bangalore', 1250.40)
('Delhi', 980.10)
('Hyderabad', 620.75)
('Mumbai', 1430.60)This shows real-time totals per city — continuously updating as data streams in.
You’ve just built your first real-time pipeline with Kafka and Spark Streaming!
🌍 Real-World Example: Streaming Transaction Monitoring
Let’s put this in perspective with a real scenario.
A retail company streams millions of payment events every hour.
They use Kafka as their event backbone and Spark Streaming to process transactions in near real-time.
During scaling, they noticed:
- Slow consumers causing backlog
- Duplicate aggregations due to replayed batches
They resolved these issues by:
✅ Introducing Kafka partitions for better parallelism
✅ Using checkpointing to achieve exactly-once semantics
✅ Persisting output to Delta tables for downstream BI and reporting
💡 Result: Their real-time dashboards now refresh every 5 seconds, replacing previously hourly batch jobs — a massive upgrade in speed and business visibility.
🔧 Debugging These Failures in Practice
If you’re hitting errors like these in production — Airflow failures, Spark OOM,Kafka SSL issues — I built a tool to help.
Paste your broken code + error logs into Vayu and get back:
→ Exact root cause
→ Before/After code fix
→ Confidence score (HIGH/MEDIUM/LOW)
Free to try at vayufix.com
No signup needed for first 3 fixes.
🏁 Conclusion
✅ You’ve now learned how to connect Kafka and Spark Streaming to build an end-to-end, real-time analytics pipeline.
In this setup:
- Kafka acts as your data buffer and reliable source of truth.
- Spark Streaming consumes and processes events with fault tolerance.
- Together, they enable near-instant data-driven insights.
Next in the series, we’ll move to the modern successor — Structured Streaming with Kafka, to achieve true end-to-end exactly-once semantics and better scalability.
🔜 Next in Series
Coming up next:
👉 “Handling Late Data & Watermarking in Spark Streaming”
We’ll dive into how Spark Streaming and Structured Streaming handle out-of-order data, event-time processing, and watermarks to maintain accuracy even when data arrives late.
💡 Think of it as bringing order to streaming chaos — one watermark at a time.
🔔 Follow for More
If you found this helpful, follow TheDataForge for your daily Spark in Data Engineering & Machine Learning ⚡
💬 Let’s connect — I post daily Big Data & Spark insights at DataForgeX on X.
💬 Comment below — What’s your favorite use case for Kafka + Spark?
🏷️ Tags
#ApacheSpark #PySpark #BigData #DataEngineering #DataForge #SparkOptimization #LazyEvaluation #DAG #RealTimeData #StructuredStreaming #DataPipeline