ML & Data Science

Real-Time Traffic Analytics

Streaming data · IoT

MSc Data Science · Big Data coursework (Task 2) · Coventry University

Traffic sensor readings streamed, aggregated, stored, and charted in real time, so a city operator sees congestion and failing sensors as they happen, not in tomorrow's batch report.

Role
Data Engineer
Year
2025
Focus
Streaming data
Stack
8 technologies
  • Apache Kafka
  • ZooKeeper
  • Python
  • PostgreSQL
  • Grafana
  • Docker Compose
  • Pandas
  • Socrata API
  • 5 s

    Sensor interval and dashboard refresh

  • 3

    Live metrics per sensor

  • 2

    Kafka topics: raw and metrics

  • 7

    Grafana panels, auto-provisioned

  • 96

    Expected 15-min slots per sensor per day

  • 4

    Containers with health checks

Growing cities need traffic information in seconds, but traditional batch processing delivers it hours later. The pipeline has to ingest high-frequency IoT readings, turn them into useful metrics (traffic trends, daily peaks, sensor health), keep them queryable for history, and keep working if one part fails.

The data comes from the City of Austin's GridSmart Camera Traffic Counts dataset, pulled from the open-data portal with the Socrata API. A preprocessing script drops rows missing the device ID, timestamp, or volume, converts timestamps to ISO 8601, normalises the heavy-vehicle flag, renames fields, and converts every CSV row into a JSON object, the standard format for event streaming.

Kafka is the backbone and separates ingestion from processing with two topics: traffic_raw (the 'firehose' of every reading) and traffic_metrics (the refined results, so other services can reuse them without reprocessing). A producer simulates live sensors, sending a reading for each device every 5 seconds with UTC timestamps.

A Python consumer reads traffic_raw and computes three metrics on the fly, publishing each update to traffic_metrics and upserting it into PostgreSQL. Upserts (INSERT … ON CONFLICT DO UPDATE) keep one current row per sensor and window instead of an ever-growing log. Grafana reads PostgreSQL directly and shows the results on a dashboard that is provisioned from YAML and JSON, so it appears automatically every time the container starts.

Microservices pipeline

Each service runs in its own Docker container on a shared network, so one failing component doesn't take the whole pipeline down.

  • External API
  • Service
  • Data & infra
  1. Source

    • Austin open data

      GridSmart camera counts via Socrata

    • Preprocessing

      Pandas: clean, ISO 8601, CSV → JSON

    • Live producer

      5 sensors, one reading each per 5 s

    JSON events
  2. Streaming backbone

    • ZooKeeper

      Broker metadata and leader election

    • Kafka · traffic_raw

      Every raw reading

    • Kafka · traffic_metrics

      Computed averages, peaks, availability

    consume, compute, publish
  3. Processing

    • Metrics consumer

      Hourly average, daily peak, availability

    upsert
  4. Storage & visualisation

    • PostgreSQL 16

      Raw readings plus three metric tables

    • Grafana 10

      Provisioned datasource and dashboard

Streaming analytics logic

For every incoming message, the consumer updates in-memory state and writes the new value straight through to Kafka and PostgreSQL.

  1. 01

    Persist raw reading

    upsert

    Stored in traffic_readings, keyed on (device_id, read_time) and indexed for time-range queries, to feed the live panels.

  2. 02

    Hourly average

    metric 1

    Running sum ÷ count of vehicle volume per sensor and hour. Smooths individual-car noise to show the broader flow trend.

  3. 03

    Daily peak

    metric 2

    Sums volume per sensor per hour and keeps the day's maximum: a streaming MAX() that shows maximum load for urban planning.

  4. 04

    Sensor availability

    metric 3

    Unique 15-minute slots received ÷ 96 × 100. Below about 80% points to packet loss or a failing device.

  5. 05

    Publish & store

    Kafka · PostgreSQL

    Each updated metric goes to traffic_metrics and is upserted into hourly_avg_volume, daily_peak_volume or daily_sensor_availability.

Screenshots of the provisioned Grafana dashboard during a live run. Tap any figure to zoom.

  1. Fig. 01 · Grafana · live

    Real-time panels

    Top to bottom: a datasource probe, every raw reading of the last hour coloured by sensor, and hourly averages per sensor.

    • Datasource probe: a 15-second SQL heartbeat. A flat, unbroken line proves Grafana stayed connected to PostgreSQL for the whole run.
    • Live minute flow: a dense, continuous band of points shows the producers sending without gaps and the consumer keeping up with little delay.
    • Hourly average: removes minute-level noise. Some sensors trend slowly down while others stay steady, showing different road conditions per location.
  2. Fig. 02 · Grafana · aggregates

    Daily analytics and sensor health

    Below the live panels: 7-day daily peak and daily average volume, a per-sensor availability table, and a gauge for sensor 7038.

    • Daily peak is plotted at noon each day so it is always visible regardless of the selected time range. A single big spike stands out from the steady rise.
    • Comparing peak with average separates genuine heavy-traffic days from one-off outlier readings.
    • The availability gauge read 20.8% (20 of 96 expected slots). Availability is counted against a full day, so a sensor that has only reported for part of the day reads low, which is exactly the signal to alert on if it persists.
  • Microservices in Docker Compose make the stack modular and reproducible. Health checks plus depends_on conditions start Kafka only after ZooKeeper is healthy, and Grafana only after PostgreSQL is ready.
  • Kafka decouples producers from consumers, so ingestion keeps running even if processing slows down, and messages persist until they are read.
  • PostgreSQL complements Kafka: Kafka moves data, but SQL is needed for joins, history, and Grafana queries.
  • JSON is self-describing and handles nested fields, which suits IoT sensor payloads and REST-style integrations.
  • Grafana provisioning (datasource and dashboard as code) means every deployment gets the same dashboard with no manual setup.
  • The live panel kept receiving new readings throughout the run, showing low latency and steady throughput through the pipeline.
  • Hourly and daily metrics were always current, with no visible lag or data loss in aggregation.
  • PostgreSQL queries stayed fast at a 5-second refresh, helped by the composite primary key and the (read_time, device_id) index.
  • Move the stateful metrics into Flink or Kafka Streams with event-time windows, so state survives restarts and scales across partitions.
  • Alerting rules in Grafana for availability below 80% and sudden drops in hourly averages.
  • Replay the full historical dataset to backtest congestion detection.