VAYULearn
Colour theme
Investigate a failure
VAYU Learn

Kafka & Streaming

Real-Time Traffic Analytics with Kafka, PostgreSQL, ARIMA & XGBoost

💡Building a real-world streaming analytics system for congestion detection and traffic speed forecasting — powered by open data, Kafka…

Kafka & StreamingSQL & Databases

💡Building a real-world streaming analytics system for congestion detection and traffic speed forecasting — powered by open data, Kafka pipelines, predictive ML models, and a fully interactive Streamlit dashboard

⚡ TL;DR

In this hands-on project, you’ll learn how to build a real-time traffic analytics system using:

  • Kafka → for ingesting live Chicago traffic data
  • PostgreSQL → for persistent storage
  • XGBoost → for congestion prediction
  • ARIMA → for forecasting speed trends
  • Streamlit → for interactive dashboards

You’ll see how data flows from public real-time APIs → Kafka → PostgreSQL → ML models → dashboard.
Full working code, diagrams, explanations, and project structure included.


🏗️ What You Will Build

In this hands-on project, you will build a complete real-time analytics platform that includes:

✅ 1. Kafka Streaming Pipeline

  • Polls live Chicago traffic data
  • Sends messages to Kafka
  • Processes them via a consumer

✅ 2. PostgreSQL-Backed Feature Store

  • Stores live + historical traffic datasets
  • Acts as a data source for ML models

✅ 3. Real-Time Interactive Dashboard

  • Live traffic heatmap
  • Street filtering
  • Speed summaries
  • Forecast charts

✅ 4. Machine Learning Components

  • XGBoost Congestion Classifier
  • ARIMA Traffic Speed Forecaster

✅ 5. End-to-End Real-Time Flow

From API → Kafka → PostgreSQL → ML → Dashboard

By the end, you’ll have a deployable system that mimics real smart-city traffic intelligence platforms.


🚀 1. Introduction — Why Real-Time Traffic Analytics Matters

Modern cities run on data.
From emergency response to fleet optimization, real-time traffic intelligence drives critical decisions:

  • Detect congestion & accidents early
  • Plan alternative routes dynamically
  • Forecast traffic behavior for the next 5–30 minutes
  • Analyze violations & high-risk zones
  • Optimize parking, tolling, and traffic light timing
  • Improve urban mobility & reduce travel time

With open public datasets like Chicago’s real-time traffic feeds, we can build production-grade analytics systems accessible to anyone.

This project demonstrates exactly that:
A real-world pipeline that ingests live traffic conditions, applies machine learning, and visualizes insights instantly.

🌍 1.1 Real-World Use Cases of a Real-Time Traffic Analytics System

Real-time traffic intelligence systems like the one you built are used across smart cities, logistics companies, and transportation departments. Here are the most meaningful practical applications:

🚔 1. Accident & Incident Detection

Sudden drops in speed or abnormal congestion patterns can trigger alerts to:

  • City traffic control rooms
  • Police departments
  • Emergency responders
  • Ambulance dispatch systems

This reduces response time and saves lives.

🚕 2. Ride-Hailing & Fleet Optimization

Companies like Uber, Ola, Lyft and logistics services use real-time traffic data to:

  • Reroute drivers dynamically
  • Avoid congestion zones
  • Predict travel time more accurately
  • Reduce fuel cost & idle time

Your XGBoost congestion classifier is a perfect early-warning system.

🌆 3. Smart City Traffic Signal Optimization

Urban mobility teams can use congestion predictions to:

  • Adjust light timings dynamically
  • Tune green corridors
  • Reduce bottlenecks during peak hours
  • Optimize traffic during events (marathons, concerts, match days)

Your ARIMA speed forecasting model is ideal for short-term signal control.

🚚 4. Logistics & Delivery Route Planning

Delivery networks like Amazon, FedEx, Zomato, Swiggy can leverage:

  • Live speed feeds to update ETAs
  • Congestion detection for route selection
  • Historical patterns for demand forecasting

Helps reduce delay penalties and fuel consumption.

🚦 5. Infrastructure Planning & City Development

Urban planners analyze long-term traffic patterns to:

  • Identify congested segments
  • Plan new flyovers, turns, or service roads
  • Analyze crash hotspots
  • Improve road safety infrastructure

Your system stores both real-time and batch data → valuable for trend analysis.

📊 6. Traffic Compliance & Violation Analysis

Red-light violations, speed-camera data, and crash datasets can be combined to:

  • Detect high-risk zones
  • Identify behavioral trends
  • Improve law enforcement strategies

Since your project includes violation datasets, it already supports this.

🚌 7. Public Transit Optimization

Agencies like CTA (Chicago Transit Authority) use such data to:

  • Understand bus delays
  • Reassign fleet during high traffic
  • Identify recurring slow-moving corridors

Your congestion label (speed < 20 mph) directly supports this use-case.

🎮 8. Event Traffic Monitoring

During:

  • Stadium matches
  • Concerts
  • Marathons
  • Festivals
  • Parades

Live traffic dashboards help city teams anticipate congestion waves and deploy officers proactively.

🌐 9. Dashboards for Public Awareness

Cities often publish real-time dashboards for citizens, like:

  • “Live traffic conditions”
  • “Slowest roads right now”
  • “Expected congestion in next 10 minutes”

Your Streamlit UI can be deployed as a public-facing portal.

🤖 10. Foundation for Advanced AI Traffic Models

This project lays groundwork for:

  • LSTM or Prophet-based forecasting
  • Real-time anomaly detection
  • Graph neural network modeling of city road networks
  • Reinforcement learning for traffic control

This is the next step beyond ARIMA and XGBoost.

🧰 Tech Stack Overview

Here’s the complete technology stack powering the real-time traffic analytics system:

Programming & Core Tools

  • Python — glue for Kafka, PostgreSQL, ML, and Streamlit
  • Pandas, SQLAlchemy — data handling & database connections

Streaming Layer

  • Apache Kafka (Aiven Cloud Kafka)
  • Real-time ingestion
  • Producer–Consumer pipeline
  • SSL-secured communication

Storage Layer

  • PostgreSQL
  • Stores batch + real-time traffic datasets
  • Serves as a feature store for ML models

Machine Learning Layer

  • XGBoost — binary congestion classification
  • ARIMA (pmdarima) — short-term speed forecasting

Visualization & Dashboard

  • Streamlit — interactive UI
  • Altair — visual charts and line plots

Datasets

  • Chicago Open Data API — real-time traffic speeds
  • Historical datasets — crashes, red-light violations, speed violations

This combination of technologies forms a production-style real-time analytics stack.


🧱 2. Architecture Overview

The following diagram shows how real-time traffic data flows through the system.

📷 Figure 1 — Real-time Traffic Analysis Pipeline

🔄 End-to-End Data Flow (High-Level Pipeline)

To better visualize how data moves through the system, here’s the complete end-to-end flow from ingestion to prediction:

Chicago Traffic API
↓
Kafka Producer (Polls API & pushes messages)
↓
Kafka Topic: realtime_traffic
↓
Kafka Consumer (Reads & normalizes records)
↓
PostgreSQL (Stores real-time + batch datasets)
↓
ML Models (XGBoost for congestion, ARIMA for forecasting)
↓
Streamlit Dashboard (Heatmap • Forecast • ML Predictions)

This flow shows how each component interacts to deliver real-time traffic intelligence.

🧠 Architecture Description

  1. Chicago Open Data API
  • Live traffic speed feed
  • Historical datasets

2. Kafka Producer

  • Polls the real-time API
  • Streams traffic rows into Kafka topic realtime_traffic
  • SSL-secured

3. Kafka Consumer

  • Reads streaming messages
  • Normalizes & persists them into PostgreSQL (realtime_traffic_data)

4. PostgreSQL Database

  • Stores batch + real-time datasets
  • Acts as the feature store for ML models

5. Machine Learning Layer

  • XGBoost → Congestion classification (speed < 20 mph)
  • ARIMA → Short-term traffic speed forecasting

6. Streamlit Dashboard

  • Live heatmap
  • Segment-level speed summary
  • Street filtering
  • Forecasting panel
  • Congestion predictions

This is a complete end-to-end traffic intelligence platform.


🧩 3. Components Table

➡️ The following table summarizes each system component and its purpose.

Table 1 : Core Components of the Real-Time Traffic Analytics System

📂 4. Folder Structure

Using the exact structure from your GitHub repo:

SmartTrafficInsights/
│
├── data/
│ ├── historical_traffic.csv
│ ├── red_light_violations.csv
│ ├── speed_camera_violations.csv
│ └── traffic_crashes.csv
│
├── images/
│ ├── heatmap.png
│ ├── forecast.png
│ └── model.png
│
├── .env
├── .gitignore
├── requirements.txt
├── realtimetrafficanalysis.py
└── README.md

🧠 5. Machine Learning Models Used

🤖 XGBoost — Congestion Detection

  • Input features:
  • Road length
  • bus_count
  • Target label:
  • is_congested → whether speed < 20 mph
  • Model type: Binary classifier
  • Accuracy: Printed directly on the dashboard after training.

📈 ARIMA — Speed Forecasting

  • Time-series forecasting
  • Predicts speed for next 5 future periods

Useful for:

  • Congestion anticipation
  • Traffic control
  • Predictive routing

🖥️ 6. Streamlit Dashboard — Key Panels

Your project includes a beautifully designed live dashboard with:

6.1 Heatmap View

The heatmap displays current speed intensities across all tracked segments.

📷 Figure 2 — Real-Time Traffic Speed Heatmap

6.2 ARIMA Forecast View

Forecasting next 5 speed intervals for selected street.

📷 Figure 3 — ARIMA Speed Forecast Visualization

6.3 XGBoost Congestion Prediction View

Predicts whether each segment is congested based on ML classification.

📷 Figure 4 — XGBoost Congestion Prediction Output

🔧 7. Full Working Code (With Placeholders)

⚠️ Note: Replace environment variable placeholders (DATABASE_URL, KAFKA_BROKER_URL, etc.) with real values in your .env file.
⚠️ Note: This is a simplified version of the full production code.
Some API fields or responses may have changed since publication.
The architecture and logic remain the same, but minor adjustments may be required depending on dataset availability.
import os
import pandas as pd
import json
import time
import requests
import xgboost as xgb
import psycopg2
import streamlit as st
from sqlalchemy import create_engine
from kafka import KafkaProducer, KafkaConsumer
from kafka.errors import KafkaError
from pmdarima import auto_arima
from dotenv import load_dotenv
import io
import threading
from sklearn.metrics import accuracy_score
import altair as alt


# Load environment variables from .env
load_dotenv()

DATABASE_URL = os.getenv("DATABASE_URL")
KAFKA_BROKER_URL = os.getenv("KAFKA_BROKER_URL")
CA_CERT_PATH = os.getenv("CA_CERT_PATH")
SSL_CERT_PATH = os.getenv("SSL_CERT_PATH")
SSL_KEY_PATH = os.getenv("SSL_KEY_PATH")

ssl_config = {
'security_protocol': 'SSL',
'ssl_cafile': CA_CERT_PATH,
'ssl_certfile': SSL_CERT_PATH,
'ssl_keyfile': SSL_KEY_PATH,
'ssl_check_hostname': True
}
engine = create_engine(DATABASE_URL)

# 📥 Ensure PostgreSQL table exists
def ensure_realtime_table_exists():
conn = psycopg2.connect(DATABASE_URL)
cur = conn.cursor()
cur.execute("""
CREATE TABLE IF NOT EXISTS realtime_traffic_data (
segmentid TEXT,
street TEXT,
direction TEXT,
from_street TEXT,
to_street TEXT,
length FLOAT,
street_heading TEXT,
comments TEXT,
start_longitude FLOAT,
start_latitude FLOAT,
end_longitude FLOAT,
end_latitude FLOAT,
current_speed FLOAT,
last_updated TEXT
)
"""
)
conn.commit()
conn.close()
print("✅ realtime_traffic_data table ensured")

# 🧊 Load batch data
def load_csv_to_postgres():
files = {
"historical_traffic": "data/historical_traffic.csv",
"red_light_violations": "data/red_light_violations.csv",
"speed_camera_violations": "data/speed_camera_violations.csv",
"traffic_crashes": "data/traffic_crashes.csv"
}
for table, path in files.items():
df = pd.read_csv(path)
df.to_sql(table, engine, if_exists="replace", index=False)
print("✅ Batch data loaded")

# 🚚 Produce real-time data to Kafka
def produce_realtime_data():
api_url = "https://data.cityofchicago.org/resource/n4j6-wkkf.csv"
try:
response = requests.get(api_url)
df = pd.read_csv(io.StringIO(response.text))

producer = KafkaProducer(
bootstrap_servers=KAFKA_BROKER_URL,
value_serializer=lambda v: json.dumps(v).encode('utf-8'),
**ssl_config
)
for _, row in df.iterrows():
producer.send('realtime_traffic', row.to_dict())
print("✅ Real-time data sent to Kafka")
except Exception as e:
print(f"❌ Failed to fetch/send data: {e}")

# 📦 Kafka Consumer → PostgreSQL
def consume_realtime_data():
try:
ensure_realtime_table_exists()
consumer = KafkaConsumer(
'realtime_traffic',
bootstrap_servers=KAFKA_BROKER_URL,
auto_offset_reset='earliest',
value_deserializer=lambda m: json.loads(m.decode('utf-8')),
consumer_timeout_ms=10000,
**ssl_config
)

conn = psycopg2.connect(DATABASE_URL)
cur = conn.cursor()
record_count = 0

for msg in consumer:
d = {k.lower(): v for k, v in msg.value.items()}
fields = [
"segmentid", "street", "direction", "from_street", "to_street",
"length", "street_heading", "comments", "start_longitude",
"start_latitude", "end_longitude", "end_latitude",
"current_speed", "last_updated"
]
values = tuple(d.get(k, None) for k in fields)
cur.execute(f"""
INSERT INTO realtime_traffic_data ({', '.join(fields)})
VALUES ({', '.join(['%s'] * len(fields))})
"""
, values)
conn.commit()

record_count += 1
if record_count >= 200:
print("✅ 200 real-time records processed")
break

except Exception as e:
print(f"❌ Kafka Error: {e}")

# 🚦 XGBoost Model Training
def train_xgboost():
df = pd.read_sql("SELECT * FROM historical_traffic", engine)
df['is_congested'] = df['speed'] < 20
X = df[['bus_count', 'length']].fillna(0)
y = df['is_congested']
model = xgb.XGBClassifier()
model.fit(X, y)
accuracy = accuracy_score(y, model.predict(X))
print("✅ XGBoost model trained with accuracy:", accuracy)
return model, X.columns.tolist(), accuracy


# 🔮 ARIMA Forecast
def run_arima(street):
df = pd.read_sql("SELECT * FROM historical_traffic", engine)
df = df[df['street'] == street].copy()
if len(df) < 10 or df['speed'].isnull().all():
return None
df['time'] = pd.to_datetime(df['time'])
df.sort_values('time', inplace=True)
model = auto_arima(df['speed'].ffill(), seasonal=False)
return model.predict(n_periods=5)

# 🖥️ Streamlit UI
def run_dashboard():
st.set_page_config(layout="wide")
st.title("🚦 Traffic Congestion Dashboard")

df = pd.read_sql("SELECT * FROM realtime_traffic_data", engine)
df['current_speed'] = pd.to_numeric(df['current_speed'], errors='coerce')
df['current_speed'] = df['current_speed'].replace(-1, pd.NA)
df.dropna(subset=['current_speed'], inplace=True)
df['is_congested'] = df['current_speed'] < 20

# Train and apply XGBoost
model, feature_order, accuracy = train_xgboost()
df_xgb = df[['length']].copy()
df_xgb['bus_count'] = 2 # Default/mock value
df_xgb = df_xgb[feature_order] # Ensure order match
df['predicted_congestion'] = model.predict(df_xgb)

tab1, tab2, tab3, tab4, tab5 = st.tabs([
"Heatmap", "Summary", "Street Filter", "Forecast", "Model Predictions"
])

with tab1:
st.subheader("🧊 Congestion Heatmap")
styled = df[['segmentid', 'street', 'current_speed']].style.background_gradient(
subset=['current_speed'], cmap='RdYlGn_r')
st.dataframe(styled)

with tab2:
st.subheader("📊 Speed Summary")
chart_data = df[['segmentid', 'current_speed']].dropna()

bar_chart = alt.Chart(chart_data).mark_bar().encode(
x=alt.X('segmentid:N', title='Segment ID'),
y=alt.Y('current_speed:Q', title='Current Speed (mph)')
)
st.altair_chart(bar_chart, use_container_width=True)

st.subheader("🚥 Congestion Counts")
summary = df['is_congested'].value_counts().rename({0: "Clear", 1: "Congested"})
summary_df = summary.reset_index()
summary_df.columns = ['Condition', 'Count']

summary_chart = alt.Chart(summary_df).mark_bar().encode(
x=alt.X('Condition:N', title='Traffic Condition'),
y=alt.Y('Count:Q', title='Count')
)
st.altair_chart(summary_chart, use_container_width=True)

with tab3:
st.subheader("🔍 Filter by Street")
streets = df['street'].dropna().unique().tolist()
selected = st.selectbox("Street", streets)

@st.cache_data
def filter_street(s):
return df[df['street'] == s]

st.dataframe(filter_street(selected))

with tab4:
st.subheader("📈 Speed Forecast (ARIMA)")
hist_df = pd.read_sql("SELECT street FROM historical_traffic GROUP BY street HAVING COUNT(*) >= 10", engine)
streets = hist_df['street'].tolist()
if streets:
selected_street = st.selectbox("Choose Street", streets)
forecast = run_arima(selected_street)
if forecast is not None:
forecast_df = pd.DataFrame({'Time': list(range(len(forecast))), 'Speed': forecast})
forecast_chart = alt.Chart(forecast_df).mark_line().encode(
x=alt.X('Time:Q', title='Forecast Step'),
y=alt.Y('Speed:Q', title='Predicted Speed (mph)')
)
st.altair_chart(forecast_chart, use_container_width=True)
else:
st.warning("⚠️ Not enough data for forecast.")

with tab5:
st.subheader("🧠 Congestion Prediction (XGBoost)")
st.write("Based on road `length` and `bus_count`")
st.write(f"**Model Accuracy:** {accuracy:.2%}")
st.dataframe(df[['segmentid', 'street', 'length', 'predicted_congestion']])

# 🚀 Main
def main():
ensure_realtime_table_exists()
load_csv_to_postgres()
threading.Thread(target=consume_realtime_data).start()
run_dashboard()

if __name__ == "__main__":
main()

⏱️ 8. Real-Time Behaviour & Latency Notes

Why this system is real-time (sub-second to few seconds latency)

  • Chicago Open Data updates periodically (approx every 1 min)
  • Kafka pipeline adds near-zero buffering
  • PostgreSQL ingestion occurs on-message
  • Streamlit refreshes views dynamically
  • ARIMA & XGBoost run locally with minimal overhead

Expected End-to-End Latency

Total: ~0.1 to ~2 seconds (excluding API refresh interval)

This makes the system ideal for real-world monitoring.


🧪 9. Sample System Output (As Shown in README)

✅ realtime_traffic_data table ensured
✅ Batch data loaded
✅ Real-time data sent to Kafka
✅ 200 real-time records processed
✅ XGBoost model trained with accuracy: 95.00%

🔧 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. Conclusion — Why This Project Stands Out

This project demonstrates how to build a real-world streaming system without the complexity of Spark or enterprise clusters.

You combined:

  • Real-time ingestion
  • Kafka streaming
  • Database persistence
  • Two ML models (classification + forecasting)
  • Interactive dashboard
  • Open city datasets

This architecture is scalable, modular, and replicable for:

  • Smart city applications
  • Ride-hailing companies
  • Fleet logistics
  • Traffic research & urban planning
  • IoT sensor analysis

A textbook example of modern data engineering + ML systems.


🔗 12. GitHub Repository

For the complete project source code, Kafka + PostgreSQL pipeline, Streamlit dashboard, SSL configuration examples, and all architecture assets, you can explore the full repository here:

🔗 GitHub Repository

This repository includes:

✅ Full Project Source Code

  • Real-time Kafka producer (Chicago API → Kafka)
  • Kafka consumer (Kafka → PostgreSQL)
  • Streamlit dashboard (heatmap, forecasts, ML predictions)
  • XGBoost model training pipeline
  • ARIMA forecasting engine
  • Schema normalization + data validation utilities

🔮 11. Next in Series

Coming Next : “Project Walkthrough:Building a Fully Automated Spotify ETL Data Pipeline on AWS”

A serverless ETL pipeline that extracts Spotify playlist data via API, transforms it with AWS Lambda, stores clean datasets in S3, and enables instant querying through Glue & Athena.


🔔 Follow for More

If you found this helpful, follow TheDataForge for your daily Spark, Databricks in Data Engineering ,Machine Learning and real-world data engineering content⚡

Let’s connect — I post daily Big Data & Spark insights at DataForgeX on X.
💬 Comment below:
Which part of the real-time traffic pipeline should I deep-dive next — Kafka, ARIMA forecasting, or XGBoost congestion prediction?


🏷️ Tags

#DataEngineering #Kafka #MachineLearning #XGBoost #ARIMA #Streamlit #RealTimeAnalytics #PostgreSQL #TrafficData #SmartCity #Python #Forecasting #TimeSeries #TrafficAnalytics #BigData #ETL #DashboardDevelopment #PredictiveAnalytics #UrbanMobility