Kafka & Streaming
Build a Real-Time Analytics Pipeline with Kafka, Spark Structured Streaming, and Streamlit…
💡 Turning live data into instant insight — one stream at a time.
⚡Build a Real-Time Analytics Pipeline with Kafka, Spark Structured Streaming, and Streamlit (end-to-end)
💡 Turning live data into instant insight — one stream at a time.
TL;DR: Build an end-to-end real-time analytics pipeline — Kafka for ingestion, Spark Structured Streaming for event-time processing (windowing, watermarking, checkpointing), and Streamlit for live dashboards — using the included demo code to run locally or on Aiven.
🚀 Introduction
In today’s data-driven world, waiting for batch jobs means reacting late. Businesses now need instant visibility — whether it’s monitoring transactions, tracking user behavior, or detecting system anomalies.
That’s where real-time analytics pipelines shine.
And one of the most powerful, open-source stacks for building them is:
Apache Kafka + Apache Spark + Streamlit Dashboards.
In this post, we’ll explore how real-time pipelines are built, why they’re game-changers for modern data platforms, and finally build a mini end-to-end example — from data ingestion to visualization.
🧩 1. Why Real-Time Analytics Matters
Traditional batch ETL pipelines operate on fixed intervals (hourly or daily). That’s fine for reports — but not for alerts or decisions that can’t wait.
⚙️ With real-time analytics, you can:
- Detect fraud as it happens (not hours later)
- Monitor IoT devices and take automated actions
- See product or sales trends evolve live
- Provide interactive, always-updated dashboards
Essentially, it’s the difference between reacting and responding instantly.
🧠 2. Architecture Overview — Spark + Kafka + Dashboard
The entire real-time pipeline can be visualized through the following flow — from ingestion to processing to visualization.Here’s what a modern real-time pipeline looks like:

📊 Kafka ingests live data streams, Spark processes and aggregates them, and Streamlit visualizes results on dashboards — all in real time.
[API / Event Source] → [Kafka Topic] → [Spark Structured Streaming] → [Delta / Memory Sink] → [Dashboard (Streamlit)]💡 Kafka is the transport layer, Spark is the brain, and Streamlit is the face.
💾 3. Setting Up the Demo Dataset
Let’s simulate a real-time transactions stream — similar to a payment or e-commerce system.
We’ll create mock data (like user, amount, and city) and push it into Kafka to mimic continuous ingestion.
# Simulated real-time transaction generator
import json, time, random
from kafka import KafkaProducer
producer = KafkaProducer(
bootstrap_servers='localhost:9092',
value_serializer=lambda v: json.dumps(v).encode('utf-8')
)
cities = ['Delhi', 'Bangalore', 'Mumbai', 'Chennai']
while True:
record = {
"user_id": random.randint(1000, 2000),
"city": random.choice(cities),
"amount": round(random.uniform(10, 500), 2),
"timestamp": time.strftime('%Y-%m-%d %H:%M:%S')
}
producer.send('transactions', value=record)
print("Sent:", record)
time.sleep(1)✅ Explanation:
- Generates a random transaction per second.
- Pushes JSON events into Kafka topic
transactions. - Can be scaled to thousands of messages per second.
⚙️ 4. Processing Streams in Spark Structured Streaming
Now, let’s consume those events in Spark for real-time aggregation.
We’ll use Structured Streaming since it integrates seamlessly with Kafka and supports SQL queries.
from pyspark.sql import SparkSession
from pyspark.sql.functions import from_json, col, window
from pyspark.sql.types import StructType, StringType, FloatType, TimestampType
spark = SparkSession.builder.appName("RealtimeAnalytics").getOrCreate()
# Define schema for incoming data
schema = StructType() \
.add("user_id", StringType()) \
.add("city", StringType()) \
.add("amount", FloatType()) \
.add("timestamp", TimestampType())
# Read from Kafka topic
stream = spark.readStream.format("kafka") \
.option("kafka.bootstrap.servers", "localhost:9092") \
.option("subscribe", "transactions") \
.load()
# Parse and select fields
parsed = stream.select(from_json(col("value").cast("string"), schema).alias("data")).select("data.*")
# Aggregate spending per city in 1-minute windows
aggregated = parsed \
.groupBy(window(col("timestamp"), "1 minute"), col("city")) \
.sum("amount") \
.withColumnRenamed("sum(amount)", "total_spend")✅ Spark handles:
- JSON parsing
- Windowed aggregations
- Late data using watermark (add
.withWatermark("timestamp", "2 minutes")if needed)
📊 5. Writing Results — From Stream to Dashboard
Now that we’ve processed the live stream, let’s push the results somewhere our dashboard can read them.
For simplicity, we’ll write to a memory sink, which allows quick querying from Python or Streamlit.
# Write results to in-memory table
query = aggregated.writeStream \
.outputMode("complete") \
.format("memory") \
.queryName("city_spend") \
.start()You can now query the live table in Spark SQL anytime:
spark.sql("SELECT * FROM city_spend ORDER BY window DESC").show()Note: The memory sink is ideal for demos but not for production.
For real deployments, write to Delta Lake, Parquet on S3, or a database (e.g., Postgres/ClickHouse) so multiple processes can safely read the results.
🎨 6. Visualizing with Streamlit Dashboards
We’ll now connect a Streamlit app to Spark’s live table.
(Think of Streamlit as your visualization frontend for real-time metrics.)
# streamlit_app.py
import streamlit as st
from pyspark.sql import SparkSession
spark = SparkSession.builder.appName("StreamlitDashboard").getOrCreate()
st.title("⚡ Real-Time City Spend Dashboard")
st.caption("Live analytics from Kafka → Spark → Streamlit")
# Fetch updated Spark table
data = spark.sql("SELECT * FROM city_spend ORDER BY window DESC LIMIT 10").toPandas()
st.bar_chart(data, x='city', y='total_spend')Run Streamlit:
streamlit run streamlit_app.py✅ Result:
Live dashboard auto-refreshes every few seconds, showing spend per city updated in near real-time.
🌍 7. Real-World Example — Real-Time Transaction Monitoring
A retail fintech company streams millions of payments every hour.
They use Kafka to buffer events and Spark Streaming to process transactions in real time.
When latency issues appeared due to skewed partitions and missed updates, they fixed it by:
- Scaling Kafka partitions for higher throughput.
- Using checkpointing + watermarking to ensure exactly-once guarantees.
- Storing results in Delta tables for BI dashboards.
💡 Result: Dashboards now refresh every 5 seconds instead of 15 minutes — transforming the monitoring workflow into a live analytics system.
🧩 8. Putting It All Together — End-to-End Pipeline (Generic Example)
Here’s the complete integrated code outline for local or Databricks setup:
# 1️⃣ Produce data → Kafka
# (from earlier generator)
# 2️⃣ Consume + Process → Spark Structured Streaming
aggregated = parsed \
.withWatermark("timestamp", "2 minutes") \
.groupBy(window(col("timestamp"), "1 minute"), col("city")) \
.sum("amount") \
.withColumnRenamed("sum(amount)", "total_spend")
query = aggregated.writeStream \
.outputMode("complete") \
.format("memory") \
.queryName("city_spend") \
.option("checkpointLocation", "/tmp/checkpoints/transactions") \
.start()
# 3️⃣ Visualize → Streamlit
# Live updates every few seconds📌 This single workflow turns raw events into live dashboards — a production-ready pattern used by major analytics platforms.
Here is the perfect way to introduce your full Binance + Kafka + Spark + Streamlit pipeline right after Section 8 — with clean heading, inflow line, and improved structure.
This version fits your DataForge tone, transitions naturally, and prepares readers for the full-code section.
🧩 9. Putting It All Together — End-to-End Real-Time Pipeline
Now that we’ve explored individual components — Kafka ingestion, Spark Structured Streaming, and real-time dashboards — let’s combine everything into a single, production-style pipeline.
This final section shows how a real system works in the wild:
Binance Live Prices → Kafka Topic → Spark Streaming → Windowed Aggregations → Streamlit Dashboard
We’ll now integrate all three layers so you can run a complete real-time analytics flow from one Python file.
🔧 Complete Integrated Workflow (Full Pipeline)
Below is the workflow we will implement:
1️⃣ Ingest real-time data → Kafka
We stream live crypto ticks (symbol, price, volume) from Binance WebSocket and push them into Kafka.
2️⃣ Process real-time stream → Spark Structured Streaming
Spark consumes the Kafka topic, parses messages, applies event-time windowing, and computes 1-minute aggregated insights.
3️⃣ Visualize insights → Streamlit Dashboard
Streamlit queries Spark’s in-memory table and shows live charts that refresh every few seconds.

📌 This single script transforms raw streaming events into real-time dashboards — the same pattern used in trading platforms, IoT analytics, fraud detection systems, and retail monitoring pipelines.
Prerequisites & Environment
Before running the examples, install the required packages:
# Recommended, tested versions (pin to avoid drift)
pip install \
pyspark==3.5.1 \
kafka-python==2.0.2 \
websocket-client==1.6.2 \
streamlit==1.25.0 \
pandas==2.2.2 \
pyarrow==11.0.0
# Optional helper for auto-refresh (see pattern B below)
pip install streamlit-autorefreshInstall Spark 3.5+ and ensure Java 11 is available:
java -version
spark-submit --versionFull Binance → Kafka → Spark → Streamlit Pipeline (Single File Code)
Below is the complete, ready-to-run Python script that connects Binance WebSocket → sends data to Kafka (Aiven or local) → processes it in Spark Structured Streaming → and renders a real-time dashboard in Streamlit.
Just fill in your Kafka connection values, run the file, and watch live analytics appear instantly.
#!/usr/bin/env python3
"""
realtime_pipeline.py
Binance WebSocket -> Aiven Kafka -> Spark Structured Streaming -> Streamlit dashboard
Run with:
streamlit run realtime_pipeline.py
Fill in AIVEN KAFKA details below before running.
"""
import os
import sys
import time
import json
import glob
import ssl
import socket
import traceback
import subprocess
import multiprocessing
from typing import Optional
# Third-party libs
import pandas as pd
import websocket
import streamlit as st
from kafka import KafkaProducer
from kafka.errors import KafkaError
from pyspark.sql import SparkSession
from pyspark.sql.functions import from_json, col, window, from_unixtime, avg as _avg
from pyspark.sql.types import StructType, StringType, DoubleType, LongType
# -----------------------------
# USER CONFIG - replace placeholders
# -----------------------------
# Aiven Kafka bootstrap host:port (example from Aiven console)
KAFKA_BOOTSTRAP = "url"
KAFKA_TOPIC = "crypto_prices"
KAFKA_USERNAME = "admin"
KAFKA_PASSWORD = "password"
# Local filenames - put your Aiven CA PEM here (download from Aiven -> Connection details)
CA_PEM_PATH = "ca.pem"
FULL_CHAIN_PEM = "full_chain.pem" # generated if you use auto-download
TRUSTSTORE_PATH = "kafka-truststore.jks" # Java truststore generated from pem
TRUSTSTORE_PASSWORD = "changeit" # default; you may change
# Output / checkpoint locations (local)
OUTPUT_PATH = "/tmp/crypto_output"
CHECKPOINT_PATH = "/tmp/crypto_checkpoint"
# Spark & pipeline tuning
SPARK_JARS_PACKAGES = "org.apache.spark:spark-sql-kafka-0-10_2.12:3.5.1"
SPARK_SHUFFLE_PARTITIONS = "10"
SPARK_PROGRESS_LOG_LEVEL = "WARN"
# Binance websocket symbol (example)
BINANCE_WS_SYMBOL = "btcusdt" # lowercase symbol for endpoint
BINANCE_WS_URL = f"wss://stream.binance.com:9443/ws/{BINANCE_WS_SYMBOL}@ticker"
# ---------------------------------------------------------------------
# Helper: create Java truststore from PEM (calls keytool)
# We try to import provided CA_PEM_PATH. If not present and
# environment allows, we can attempt to download server cert (optional).
# ---------------------------------------------------------------------
def create_truststore_from_pem(pem_path: str, truststore_path: str, truststore_pass: str) -> bool:
"""
Create a Java truststore (JKS/PKCS12) using keytool and a PEM certificate.
Returns True if created / exists.
"""
if not os.path.exists(pem_path):
print(f"❌ PEM file not found at {pem_path}")
return False
# Make sure keytool exists
keytool = shutil_which("keytool")
if not keytool:
print("❌ keytool not found on PATH. Install JDK (brew install openjdk) and ensure keytool is available.")
return False
# If truststore already exists, remove to avoid alias conflicts
if os.path.exists(truststore_path):
try:
os.remove(truststore_path)
print("🗑️ Removed old truststore")
except Exception as e:
print("⚠ Could not remove old truststore:", e)
# Use keytool to import (noprompt -> -noprompt)
cmd = [
keytool,
"-importcert",
"-trustcacerts",
"-alias", "aiven-kafka",
"-file", pem_path,
"-keystore", truststore_path,
"-storepass", truststore_pass,
"-noprompt"
]
try:
print("🔧 Creating Java truststore (this may prompt if keytool behaves differently on your JVM)...")
proc = subprocess.run(cmd, capture_output=True, text=True)
if proc.returncode != 0:
print("❌ keytool failed:", proc.stderr.strip())
return False
print("✅ Truststore created:", truststore_path)
return True
except Exception as e:
print("❌ Exception while running keytool:", e)
traceback.print_exc()
return False
def shutil_which(name):
# small wrapper to support older Python if necessary
from shutil import which
return which(name)
# ---------------------------------------------------------------------
# Kafka producer creation (kafka-python)
# - uses ssl_cafile (PEM)
# - uses SASL PLAIN for Aiven (if username/pass provided)
# ---------------------------------------------------------------------
def create_kafka_producer(bootstrap_servers: str,
topic: str,
username: Optional[str],
password: Optional[str],
ca_certs: Optional[str]) -> Optional[KafkaProducer]:
"""Create and return a KafkaProducer or None on failure."""
print("📡 Creating Kafka producer...")
try:
kwargs = {
"bootstrap_servers": bootstrap_servers,
"value_serializer": lambda v: json.dumps(v).encode("utf-8"),
"retries": 5,
"acks": "all",
}
if ca_certs:
kwargs.update({
"security_protocol": "SASL_SSL" if username and password else "SSL",
"ssl_cafile": ca_certs,
})
else:
# no CA provided -> try plaintext? but Aiven requires SSL
kwargs.update({"security_protocol": "SASL_SSL" if username and password else "PLAINTEXT"})
if username and password:
# kafka-python expects sasl_plain_username/password for SASL
kwargs.update({
"sasl_mechanism": "PLAIN",
"sasl_plain_username": username,
"sasl_plain_password": password
})
producer = KafkaProducer(**kwargs)
print("✅ Kafka producer created!")
return producer
except Exception as e:
print("❌ Error creating producer:", e)
traceback.print_exc()
return None
# ---------------------------------------------------------------------
# Binance -> Kafka producer process
# ---------------------------------------------------------------------
def binance_producer_process():
"""Connect to Binance websocket and send JSON messages to Kafka."""
print("📡 Binance producer process starting...")
# Create Kafka producer
ca_path = CA_PEM_PATH if os.path.exists(CA_PEM_PATH) else None
producer = create_kafka_producer(KAFKA_BOOTSTRAP, KAFKA_TOPIC, KAFKA_USERNAME, KAFKA_PASSWORD, ca_path)
if not producer:
print("❌ Producer not available, exiting producer process.")
return
def on_msg(ws, message):
try:
msg = json.loads(message)
# The Binance ticker payload has fields; using typical keys s (symbol), c (last price), v (volume)
rec = {
"symbol": msg.get("s"),
"price": float(msg.get("c", 0.0)),
"volume": float(msg.get("v", 0.0)),
"timestamp": int(time.time() * 1000)
}
producer.send(KAFKA_TOPIC, value=rec)
# flush occasionally? producer.flush()
print("🔥 Sent:", rec)
except Exception as e:
print("❌ Error handling WS message:", e)
def on_error(ws, err):
print("❌ Websocket error:", err)
def on_open(ws):
print("✅ Binance websocket opened")
print("🔗 Connecting to Binance WS:", BINANCE_WS_URL)
ws = websocket.WebSocketApp(BINANCE_WS_URL, on_message=on_msg, on_error=on_error, on_open=on_open)
# run forever (blocks)
ws.run_forever()
# ---------------------------------------------------------------------
# Spark Structured Streaming process
# ---------------------------------------------------------------------
def spark_streaming_process():
"""Spark Structured Streaming job that reads from Kafka and writes parquet output."""
print("⚡ Spark streaming process starting...")
# If truststore not present, try to create it from CA_PEM_PATH
if not os.path.exists(TRUSTSTORE_PATH):
if os.path.exists(CA_PEM_PATH):
created = create_truststore_from_pem(CA_PEM_PATH, TRUSTSTORE_PATH, TRUSTSTORE_PASSWORD)
if not created:
print("⚠ Could not create truststore. Spark Kafka SSL may fail.")
else:
print("⚠ Neither truststore nor CA PEM found; Spark Kafka SSL will likely fail if Aiven requires TLS.")
truststore_abs = os.path.abspath(TRUSTSTORE_PATH) if os.path.exists(TRUSTSTORE_PATH) else None
if truststore_abs:
print("🔐 Using Java truststore at:", truststore_abs)
else:
print("🔐 No truststore available; proceeding but SSL may fail.")
# Build JVM options for truststore if available
java_opts = ""
if truststore_abs:
java_opts = (
f"-Djavax.net.ssl.trustStore={truststore_abs} "
f"-Djavax.net.ssl.trustStorePassword={TRUSTSTORE_PASSWORD} "
f"-Djavax.net.ssl.trustStoreType=JKS"
)
# Initialize SparkSession with Kafka package
spark_builder = SparkSession.builder.appName("AivenKafkaStreaming") \
.config("spark.sql.shuffle.partitions", SPARK_SHUFFLE_PARTITIONS) \
.config("spark.jars.packages", SPARK_JARS_PACKAGES)
if java_opts:
spark_builder = spark_builder.config("spark.driver.extraJavaOptions", java_opts) \
.config("spark.executor.extraJavaOptions", java_opts)
spark = spark_builder.getOrCreate()
spark.sparkContext.setLogLevel(SPARK_PROGRESS_LOG_LEVEL)
# Schema for incoming JSON
schema = StructType().add("symbol", StringType()) \
.add("price", DoubleType()) \
.add("volume", DoubleType()) \
.add("timestamp", LongType())
# Prepare Kafka options for Spark
kafka_options = {
"kafka.bootstrap.servers": KAFKA_BOOTSTRAP,
"subscribe": KAFKA_TOPIC,
"startingOffsets": "latest",
"failOnDataLoss": "false"
}
# If SASL credentials are provided, add JAAS config
if KAFKA_USERNAME and KAFKA_PASSWORD:
jaas = (
'org.apache.kafka.common.security.plain.PlainLoginModule required '
f'username="{KAFKA_USERNAME}" '
f'password="{KAFKA_PASSWORD}";'
)
kafka_options.update({
"kafka.security.protocol": "SASL_SSL",
"kafka.sasl.mechanism": "PLAIN",
"kafka.sasl.jaas.config": jaas
})
# If truststore exists, set ssl related options
if truststore_abs:
kafka_options.update({
"kafka.ssl.truststore.location": truststore_abs,
"kafka.ssl.truststore.password": TRUSTSTORE_PASSWORD,
# Some environments require disabling endpoint identification (hostname verification)
# Use with caution; prefer proper certs.
"kafka.ssl.truststore.type": "JKS",
"kafka.ssl.endpoint.identification.algorithm": ""
})
print("🔌 Spark connecting to Kafka with options (sanitized):")
print({k: ("***" if "password" in k or "sasl" in k else v) for k, v in kafka_options.items()})
try:
df = spark.readStream.format("kafka").options(**kafka_options).load()
print("✅ Spark connected to Kafka (readStream created).")
except Exception as e:
print("❌ Spark failed to connect to Kafka:", e)
traceback.print_exc()
spark.stop()
return
# Convert Kafka value (bytes) to string, parse JSON
parsed = df.select(from_json(col("value").cast("string"), schema).alias("data")).select("data.*")
# Convert timestamp -> event_time
parsed = parsed.withColumn("event_time", from_unixtime(col("timestamp") / 1000).cast("timestamp"))
# Windowed average price per symbol
aggregated = parsed.withWatermark("event_time", "2 minutes") \
.groupBy(window(col("event_time"), "1 minute"), col("symbol")) \
.agg(_avg("price").alias("avg_price")) \
.select(
col("window.start").alias("window_start"),
col("window.end").alias("window_end"),
col("symbol"),
col("avg_price")
)
# Ensure output/checkpoint paths exist
os.makedirs(OUTPUT_PATH, exist_ok=True)
os.makedirs(CHECKPOINT_PATH, exist_ok=True)
# Write to parquet files (append)
query = aggregated.writeStream \
.outputMode("append") \
.format("parquet") \
.option("path", OUTPUT_PATH) \
.option("checkpointLocation", CHECKPOINT_PATH) \
.trigger(processingTime="6 seconds") \
.start()
print("✅ Spark streaming query started; writing parquet to", OUTPUT_PATH)
query.awaitTermination()
# ---------------------------------------------------------------------
# Streamlit dashboard (main process)
# - reads parquet files in OUTPUT_PATH and shows metrics
# ---------------------------------------------------------------------
def streamlit_dashboard():
st.set_page_config(page_title="Real-Time Crypto Dashboard", layout="wide")
st.title("⚡ Real-Time Crypto Dashboard")
st.caption("Binance → Aiven Kafka → Spark → Streamlit (demo)")
col1, col2 = st.columns([3, 1])
chart_placeholder = col1.empty()
stat_box = col2.empty()
st.write("Reading parquet files from:", OUTPUT_PATH)
refresh_seconds = 8
while True:
try:
files = glob.glob(os.path.join(OUTPUT_PATH, "*.parquet"))
if not files:
col1.write("⏳ Waiting for data (Spark writing parquet)...")
time.sleep(refresh_seconds)
continue
valid_dfs = []
for f in files:
try:
tmp = pd.read_parquet(f)
valid_dfs.append(tmp)
except Exception:
# file is incomplete (still being written) -> skip
continue
if not valid_dfs:
time.sleep(refresh_seconds)
continue
df = pd.concat(valid_dfs, ignore_index=True)
if df.empty:
time.sleep(refresh_seconds)
continue
# pick latest window_start ordering descending
df = df.sort_values("window_start", ascending=False).head(200)
# Simple line chart aggregated by window_start
if "avg_price" in df.columns:
series = df.groupby("window_start")["avg_price"].mean().sort_index()
chart_placeholder.line_chart(series)
else:
chart_placeholder.write(df.head(10))
# Stats
latest = df.iloc[0]["avg_price"]
stat_box.metric("Latest", f"${latest:,.2f}")
stat_box.metric("Min", f"${df['avg_price'].min():,.2f}")
stat_box.metric("Max", f"${df['avg_price'].max():,.2f}")
stat_box.metric("Records", len(df))
except Exception as e:
st.error("Dashboard error: " + str(e))
traceback.print_exc()
time.sleep(refresh_seconds)
# ---------------------------------------------------------------------
# Entrypoint - launch processes
# ---------------------------------------------------------------------
def main():
print("="*60)
print("🚀 Aiven Kafka Real-Time Pipeline (single-file demo)")
print("="*60)
# Validate minimal config
if "<AVIN_USERNAME>" in KAFKA_USERNAME or "<AVIN_PASSWORD>" in KAFKA_PASSWORD:
print("⚠ Using placeholder credentials. Replace KAFKA_USERNAME/KAFKA_PASSWORD with real values before production.")
if not os.path.exists(CA_PEM_PATH):
print(f"⚠ CA PEM not found at {CA_PEM_PATH}. Place Aiven CA PEM in script directory or update CA_PEM_PATH.")
# Clean previous output (optional)
try:
if os.path.exists(OUTPUT_PATH):
# don't auto-delete in production; here we clear for demo
pass
except Exception:
pass
# Multiprocessing start method
try:
multiprocessing.set_start_method('spawn', force=True)
except RuntimeError:
pass
# Start producer and spark consumer in background processes
p_producer = multiprocessing.Process(target=binance_producer_process, daemon=True)
p_spark = multiprocessing.Process(target=spark_streaming_process, daemon=True)
p_producer.start()
print("✅ Binance->Kafka producer started (pid=%s)" % p_producer.pid)
time.sleep(2)
p_spark.start()
print("✅ Spark consumer started (pid=%s)" % p_spark.pid)
time.sleep(3)
# Run Streamlit dashboard (main process)
try:
streamlit_dashboard()
except KeyboardInterrupt:
print("Interrupted by user")
finally:
print("Shutting down background processes...")
for p in (p_producer, p_spark):
try:
if p.is_alive():
p.terminate()
except Exception:
pass
if __name__ == "__main__":
main()🏭 Production Notes
- Use Delta Lake or S3/ADLS for Spark streaming checkpoints.
- Use a durable sink (Delta/Parquet/DB) instead of Streamlit reading local files.
- Avoid multiprocessing for production Spark jobs — deploy Spark streaming as a standalone job.
- Store Kafka credentials in environment variables, not in code.
🛠️ How to Run This Pipeline (Aiven or Local Kafka)
Before you deploy this real-time pipeline, you need one key component running: Kafka.
You have two ways to run it:
- Aiven Kafka (Cloud) → Best for production, secure, SASL_SSL enabled
- Local Kafka → Perfect for local development and testing
Below is a full step-by-step guide for both setups — just plug in your values and run the pipeline.
☁️ Option A — Using Aiven Kafka (Recommended for Real Deployments)
If you’re using Aiven-hosted Kafka, the pipeline works almost as-is.
You only need to:
1. Create the Kafka topic
Go to:
Aiven Console → Your Kafka Service → Topics → Create TopicChoose a topic name (e.g., crypto_prices).
2. Fill the Aiven credentials in the script
Inside realtime_pipeline.py, update:
KAFKA_BOOTSTRAP = "kafka-xx.aivencloud.com:xxxxx"
KAFKA_TOPIC = "crypto_prices"
KAFKA_USERNAME = "avn-username"
KAFKA_PASSWORD = "avn-password"You will find all details under:
Aiven → Kafka → Connection Information → SASL/SSL settings
3. (Optional) Add CA bundle if your service requires it
In KafkaProducer() add:
ssl_cafile="/path/to/aiven-ca.pem"And for Spark Streaming add:
"kafka.ssl.truststore.location": "/path/to/truststore.jks"This depends on your Aiven service settings.
4. Run the pipeline
Start Streamlit (which also triggers Spark + WebSocket producer):
streamlit run realtime_pipeline.pyThen open your dashboard:
Aiven Notes
- Topic creation must be done manually, Aiven doesn’t allow automatic topic creation by producers.
- Ensure your IP is whitelisted in Aiven (Project → Access Control).
- Network must allow outbound access to:
wss://stream.binance.com:9443(Binance WebSocket)
💻 Option B — Using Local Kafka (Development)
If you’re running Kafka locally (recommended for testing), follow these steps.
1. Start Kafka Locally
Ubuntu / Linux (Apache Kafka tarball example):
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
cd kafka_2.13-3.7.0Start Zookeeper:
bin/zookeeper-server-start.sh config/zookeeper.properties &Start Kafka Broker:
bin/kafka-server-start.sh config/server.properties &Create topic:
bin/kafka-topics.sh --create --topic crypto_prices --bootstrap-server localhost:9092 --partitions 3 --replication-factor 12. Update the Script for Local Kafka
In realtime_pipeline.py, replace the config with:
KAFKA_BOOTSTRAP = "localhost:9092"
KAFKA_TOPIC = "crypto_prices"
KAFKA_USERNAME = None
KAFKA_PASSWORD = NoneReplace the producer (no SASL/SSL):
producer = KafkaProducer(
bootstrap_servers="localhost:9092",
value_serializer=lambda v: json.dumps(v).encode("utf-8"),
)Replace Spark Kafka options:
kafka_options = {
"kafka.bootstrap.servers": "localhost:9092",
"subscribe": KAFKA_TOPIC,
"startingOffsets": "latest"
}That’s it — local Kafka uses no encryption, no SASL, no certificates.
3. Run the pipeline
streamlit run realtime_pipeline.py(Leave Kafka running in the background.)
🔧 Quick Reference — Code Changes Summary
Aiven Kafka (Cloud)
✔️ Keep SASL_SSL + username/password
✔️ Use provided bootstrap host
✔️ Topic created manually
✔️ Optional CA bundle
KAFKA_BOOTSTRAP = "kafka-xyz.aivencloud.com:12345"
KAFKA_TOPIC = "crypto_prices"
KAFKA_USERNAME = "avn-user"
KAFKA_PASSWORD = "avn-password"Local Kafka
Change to:
KAFKA_BOOTSTRAP = "localhost:9092"
KAFKA_TOPIC = "crypto_prices"
KAFKA_USERNAME = None
KAFKA_PASSWORD = NonePlus remove SASL/SSL fields from both producer and Spark.
🩺 Troubleshooting (DataForge Quick Fixes)
No data on dashboard?
✔️ Check WebSocket connectivity
✔️ Check Kafka consumer:
kafka-console-consumer.sh --topic crypto_prices --bootstrap-server localhost:9092✔️ Check Spark logs for serialization or schema errors
SASL/SSL failures on Aiven?
✔️ Wrong password
✔️ Wrong username
✔️ Missing CA file
Checkpoint errors?
✔️ Ensure /tmp/aiven_checkpoint exists
✔️ Use S3/HDFS for production
Firewall issues?
✔️ Whitelist your public IP in Aiven
✔️ Allow outbound port 9443
⚙️ DataForge Note (Blog-Friendly Summary)
Use Aiven Kafka for production — the script already supports SASL/SSL.
For local development, switch the bootstrap server tolocalhost:9092and remove all SASL/SSL configs. Start Kafka locally using Zookeeper + the Kafka broker.
Local Kafka is perfect for experimenting, debugging, and learning before moving to Aiven.
🔧 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.
🧭 10. Key Takeaways

🧠 Conclusion
Building real-time data pipelines doesn’t have to be complex — Spark + Kafka + Streamlit provide everything you need: scalability, fault-tolerance, and simplicity.
With Structured Streaming, your code looks like batch processing — but operates continuously.
You can now observe, act, and adapt your data in motion — not after the fact.
💡 Real-time isn’t the future anymore — it’s the standard.
🔜 Next in Series
Coming up next:
👉 “Data Engineering in the Cloud: AWS vs Azure vs GCP”
We’ll explore how the three major cloud platforms compare for modern data engineering workloads — from storage to compute to streaming.
You’ll learn which platform fits which use case, how their pricing differs, and where each one shines for Spark, Kafka, and real-time analytics pipelines.
💡 Think of it as your roadmap for choosing the right cloud for your next data engineering project.
🔔 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 real-time analytics use case are you planning to build next?
🏷️ Tags
#ApacheSpark #PySpark #BigData #DataEngineering #DataForge #SparkOptimization #LazyEvaluation #DAG #RealTimeData #SparkStreaming #FaultTolerance #Checkpointing #RealTimeAnalytics #SparkStructuredStreaming #StreamingData #StreamingAnalytics #Dashboarding #Dashboard #Streamlit #DataPipelines #StructuredStreaming #ApacheKafka #DataProject