Real-Time Smart City Analytics with Streaming SQL: Traffic, Transit, Parking, Air Quality, and Emergency Response

Real-Time Smart City Analytics with Streaming SQL: Traffic, Transit, Parking, Air Quality, and Emergency Response

·

Updated

·

19 min read

Real-time smart city analytics with streaming SQL means loop detector readings, GPS probes, transit vehicle positions, parking sensor events, air quality samples, video analytics classifications, and dispatch records are all evaluated as they arrive, so congestion, incidents, bus bunching, full garages, unhealthy air, and response-time breaches surface within seconds instead of in the next 15-minute report. This guide builds the city data layer on RisingWave, a PostgreSQL-compatible streaming database, starting with traffic flow and extending to transit, parking, air quality, urban safety, and emergency response.

Why City Operations Need a Streaming Database

Urban congestion costs the average city driver 50 to 100 hours a year, and stop-and-go traffic burns three to five times the fuel of steady flow. Traditional traffic management runs on fixed signal timing plans updated quarterly and congestion reports pulled from SCADA historians with a 5 to 15 minute lag. Bus bunching compounds from small delays within minutes, while most agencies still compute headway in overnight batch. A fifth to a third of downtown congestion is drivers circling for parking they cannot see is full. Reference-grade air quality stations report with 1 to 24 hour delays. A crowd crush or vehicle intrusion escalates from incident to catastrophe in under two minutes, and a 15-minute dashboard refresh cannot coordinate a response at that speed.

The data to do better already exists. Loop detectors every 500 meters report count, speed, and occupancy every 20 to 60 seconds. GTFS-Realtime positions arrive every 10 to 30 seconds. Parking sensors emit on every state change. Low-cost air sensors report every one to five minutes. Video analytics and computer-aided dispatch publish events continuously. What has been missing is a layer that joins and aggregates these streams and keeps the results current. RisingWave maintains that layer as incrementally updated materialized views, serves it over the PostgreSQL protocol to Grafana and operations dashboards, and pushes alerts through Kafka sinks to signal controllers, variable message signs, transit dispatch, and emergency systems. RisingWave is open source under Apache 2.0, written in Rust, and checkpoints state to S3.

Traffic Flow: Detectors, Probes, Congestion, and Incidents

Two sources carry the traffic picture: loop detector readings and GPS probes from connected vehicles.

CREATE SOURCE loop_detector_readings (
    detector_id     VARCHAR,
    zone_id         VARCHAR,
    intersection_id VARCHAR,
    lane_id         VARCHAR,
    direction       VARCHAR,  -- 'NB','SB','EB','WB'
    vehicle_count   INT,      -- vehicles in this interval
    avg_speed_kmh   NUMERIC,
    occupancy_pct   NUMERIC,  -- percent of time the loop is occupied
    reading_ts      TIMESTAMPTZ
) WITH (connector = 'kafka', topic = 'traffic.detectors.loop', properties.bootstrap.server = 'kafka:9092', scan.startup.mode = 'latest')
FORMAT PLAIN ENCODE JSON;

CREATE SOURCE gps_probes (
    probe_id    VARCHAR,
    zone_id     VARCHAR,
    segment_id  VARCHAR,
    speed_kmh   NUMERIC,
    heading_deg NUMERIC,
    lat         NUMERIC,
    lon         NUMERIC,
    probe_ts    TIMESTAMPTZ
) WITH (connector = 'kafka', topic = 'traffic.probes.gps', properties.bootstrap.server = 'kafka:9092', scan.startup.mode = 'latest')
FORMAT PLAIN ENCODE JSON;

Five-minute tumbling windows give flow, speed, occupancy, and a simplified Highway Capacity Manual level of service per detector. Zone congestion rolls detectors up to a 0 to 100 score, and probe speeds give segment travel time independent of fixed infrastructure.

CREATE MATERIALIZED VIEW traffic_flow_5min AS
SELECT detector_id, zone_id, intersection_id, lane_id, direction, window_start, window_end,
       SUM(vehicle_count)   AS flow_vehicles,
       AVG(avg_speed_kmh)   AS avg_speed_kmh,
       AVG(occupancy_pct)   AS avg_occupancy_pct,
       MAX(occupancy_pct)   AS peak_occupancy_pct,
       CASE WHEN AVG(avg_speed_kmh) >= 90 THEN 'A' WHEN AVG(avg_speed_kmh) >= 70 THEN 'B'
            WHEN AVG(avg_speed_kmh) >= 50 THEN 'C' WHEN AVG(avg_speed_kmh) >= 40 THEN 'D'
            WHEN AVG(avg_speed_kmh) >= 25 THEN 'E' ELSE 'F' END AS level_of_service
FROM TUMBLE(loop_detector_readings, reading_ts, INTERVAL '5 minutes')
GROUP BY detector_id, zone_id, intersection_id, lane_id, direction, window_start, window_end;

CREATE MATERIALIZED VIEW zone_congestion_5min AS
SELECT zone_id, window_start, window_end,
       AVG(avg_speed_kmh)          AS zone_avg_speed_kmh,
       AVG(avg_occupancy_pct)      AS zone_avg_occupancy_pct,
       SUM(flow_vehicles)          AS zone_total_flow,
       COUNT(DISTINCT detector_id) AS active_detectors,
       ROUND(LEAST(100, (100 - AVG(avg_speed_kmh)) * 0.5 + AVG(avg_occupancy_pct) * 0.5), 1) AS congestion_score
FROM traffic_flow_5min
GROUP BY zone_id, window_start, window_end;

CREATE MATERIALIZED VIEW segment_travel_time_5min AS
SELECT segment_id, zone_id, window_start, window_end, AVG(speed_kmh) AS avg_probe_speed_kmh, COUNT(DISTINCT probe_id) AS probe_count
FROM TUMBLE(gps_probes, probe_ts, INTERVAL '5 minutes')
GROUP BY segment_id, zone_id, window_start, window_end;

A sudden speed drop combined with an occupancy spike is the signature of a lane-blocking incident, and it is a filter over the flow view. Congestion above 75 is the signal for adaptive signal timing.

CREATE MATERIALIZED VIEW incident_candidates AS
SELECT detector_id, zone_id, intersection_id, direction, avg_speed_kmh, avg_occupancy_pct, flow_vehicles, window_start, window_end,
       CASE WHEN avg_speed_kmh < 10 AND avg_occupancy_pct > 85 THEN 'HIGH'
            WHEN avg_speed_kmh < 20 AND avg_occupancy_pct > 70 THEN 'MEDIUM' ELSE 'LOW' END AS incident_confidence
FROM traffic_flow_5min
WHERE avg_speed_kmh < 20 AND avg_occupancy_pct > 70;

CREATE MATERIALIZED VIEW congestion_alerts AS
SELECT zone_id, congestion_score, zone_avg_speed_kmh, zone_total_flow, window_start, window_end
FROM zone_congestion_5min
WHERE congestion_score > 75;

Requiring two consecutive congested windows before alerting, with LAG over window_start partitioned by zone, suppresses the single-window blips that come from a signal cycle or a bus stop.

Transit: Adherence, Headway, Bunching, and Crowding

Bus bunching happens because a slightly late vehicle picks up more passengers, falls further behind, and the vehicle behind it catches up. The GTFS-Realtime position feed and AVL stop events, with automatic passenger counts when available, give schedule adherence, headway between consecutive vehicles at each stop, and load factor.

CREATE SOURCE stop_events (
    event_id        VARCHAR,
    vehicle_id      VARCHAR,
    route_id        VARCHAR,
    trip_id         VARCHAR,
    direction_id    INT,
    stop_id         VARCHAR,
    stop_sequence   INT,
    event_type      VARCHAR,    -- 'arrive','depart'
    scheduled_ts    TIMESTAMPTZ,
    actual_ts       TIMESTAMPTZ,
    passenger_count INT,        -- from APC if available
    capacity        INT
) WITH (connector = 'kafka', topic = 'transit.avl.stop-events', properties.bootstrap.server = 'kafka:9092', scan.startup.mode = 'latest')
FORMAT PLAIN ENCODE JSON;

CREATE MATERIALIZED VIEW vehicle_adherence AS
SELECT vehicle_id, route_id, trip_id, direction_id, stop_id, stop_sequence, scheduled_ts, actual_ts,
       ROUND(EXTRACT(EPOCH FROM (scheduled_ts - actual_ts)) / 60.0, 1) AS adherence_minutes,   -- positive is early
       CASE WHEN EXTRACT(EPOCH FROM (scheduled_ts - actual_ts)) / 60.0 > 1  THEN 'early'
            WHEN EXTRACT(EPOCH FROM (scheduled_ts - actual_ts)) / 60.0 < -5 THEN 'late' ELSE 'on_time' END AS adherence_status,
       passenger_count, capacity,
       ROUND(passenger_count * 100.0 / NULLIF(capacity, 0), 1) AS load_factor_pct,
       actual_ts AS event_ts
FROM stop_events
WHERE event_type = 'depart';

CREATE MATERIALIZED VIEW stop_headways AS
SELECT route_id, stop_id, direction_id, vehicle_id AS current_vehicle, actual_ts AS current_arrival,
       LAG(vehicle_id) OVER (PARTITION BY route_id, stop_id, direction_id ORDER BY actual_ts) AS preceding_vehicle,
       ROUND(EXTRACT(EPOCH FROM (actual_ts - LAG(actual_ts) OVER (PARTITION BY route_id, stop_id, direction_id ORDER BY actual_ts))) / 60.0, 1) AS headway_minutes
FROM stop_events
WHERE event_type = 'arrive';

CREATE MATERIALIZED VIEW route_kpis_hourly AS
SELECT route_id, direction_id, window_start, window_end,
       COUNT(*) AS stop_visits,
       ROUND(COUNT(*) FILTER (WHERE adherence_status = 'on_time') * 100.0 / NULLIF(COUNT(*), 0), 1) AS on_time_pct,
       AVG(ABS(adherence_minutes)) AS avg_abs_adherence_min,
       AVG(load_factor_pct) AS avg_load_factor_pct, MAX(load_factor_pct) AS max_load_factor_pct
FROM TUMBLE(vehicle_adherence, event_ts, INTERVAL '1 hour')
GROUP BY route_id, direction_id, window_start, window_end;

CREATE MATERIALIZED VIEW bunching_alerts AS
SELECT route_id, stop_id, direction_id, current_vehicle, preceding_vehicle, current_arrival, headway_minutes
FROM stop_headways
WHERE headway_minutes IS NOT NULL AND headway_minutes < 2.0;

CREATE MATERIALIZED VIEW overcrowding_alerts AS
SELECT vehicle_id, route_id, trip_id, stop_id, passenger_count, capacity, load_factor_pct, event_ts
FROM vehicle_adherence
WHERE load_factor_pct > 85.0;

CREATE MATERIALIZED VIEW headway_variance_alerts AS
SELECT route_id, direction_id, window_start, window_end,
       AVG(headway_minutes) AS avg_headway_min, STDDEV(headway_minutes) AS stddev_headway_min,
       MIN(headway_minutes) AS min_headway_min, MAX(headway_minutes) AS max_headway_min, COUNT(*) AS observations
FROM TUMBLE(stop_headways, current_arrival, INTERVAL '30 minutes')
WHERE headway_minutes IS NOT NULL
GROUP BY route_id, direction_id, window_start, window_end
HAVING STDDEV(headway_minutes) > 3.0;

A headway under two minutes is the bunching event; a 30-minute headway standard deviation above three minutes is the route drifting toward it, which is when a holding or expressing instruction still helps. The same adherence view powers next-arrival predictions for riders and the monthly on-time report, so the two never disagree.

Parking: Space State, Occupancy, Turnover, and EV Availability

Parking sensors, magnetic, ultrasonic, loop, or camera-based license plate recognition, emit an event when a space changes state. Entry and exit terminals emit transactions. The latest state per space is a DISTINCT ON, and everything above it is a rollup.

CREATE SOURCE parking_sensor_events (
    sensor_id    VARCHAR,
    space_id     VARCHAR,
    zone_id      VARCHAR,
    facility_id  VARCHAR,
    space_type   VARCHAR,  -- 'standard','accessible','ev','reserved'
    floor_level  INT,
    state        VARCHAR,  -- 'occupied','vacant'
    event_ts     TIMESTAMPTZ
) WITH (connector = 'kafka', topic = 'parking.sensors.events', properties.bootstrap.server = 'kafka:9092', scan.startup.mode = 'latest')
FORMAT PLAIN ENCODE JSON;

CREATE SOURCE parking_transactions (
    transaction_id VARCHAR, facility_id VARCHAR, zone_id VARCHAR, terminal_id VARCHAR,
    event_type VARCHAR,     -- 'entry','exit'
    vehicle_type VARCHAR, ticket_type VARCHAR, event_ts TIMESTAMPTZ
) WITH (connector = 'kafka', topic = 'parking.transactions', properties.bootstrap.server = 'kafka:9092', scan.startup.mode = 'latest')
FORMAT PLAIN ENCODE JSON;

CREATE MATERIALIZED VIEW space_current_state AS
SELECT DISTINCT ON (space_id) sensor_id, space_id, zone_id, facility_id, space_type, floor_level, state, event_ts AS last_updated_ts
FROM parking_sensor_events
ORDER BY space_id, event_ts DESC;

CREATE MATERIALIZED VIEW zone_occupancy AS
SELECT zone_id, facility_id, space_type,
       COUNT(*) AS total_spaces,
       COUNT(*) FILTER (WHERE state = 'occupied') AS occupied_spaces,
       COUNT(*) FILTER (WHERE state = 'vacant')   AS vacant_spaces,
       ROUND(COUNT(*) FILTER (WHERE state = 'occupied') * 100.0 / NULLIF(COUNT(*), 0), 1) AS occupancy_rate_pct,
       MAX(last_updated_ts) AS last_event_ts
FROM space_current_state
GROUP BY zone_id, facility_id, space_type;

CREATE MATERIALIZED VIEW facility_occupancy AS
SELECT facility_id, SUM(total_spaces) AS total_spaces, SUM(occupied_spaces) AS occupied_spaces, SUM(vacant_spaces) AS vacant_spaces,
       ROUND(SUM(occupied_spaces) * 100.0 / NULLIF(SUM(total_spaces), 0), 1) AS occupancy_rate_pct
FROM zone_occupancy
GROUP BY facility_id;

CREATE MATERIALIZED VIEW parking_turnover_hourly AS
SELECT facility_id, zone_id, vehicle_type, ticket_type, window_start, window_end,
       COUNT(*) FILTER (WHERE event_type = 'entry') AS entries, COUNT(*) FILTER (WHERE event_type = 'exit') AS exits
FROM TUMBLE(parking_transactions, event_ts, INTERVAL '1 hour')
GROUP BY facility_id, zone_id, vehicle_type, ticket_type, window_start, window_end;

CREATE MATERIALIZED VIEW near_capacity_alerts AS
SELECT zone_id, facility_id, space_type, total_spaces, occupied_spaces, vacant_spaces, occupancy_rate_pct, last_event_ts
FROM zone_occupancy
WHERE occupancy_rate_pct > 90.0;

CREATE MATERIALIZED VIEW ev_availability AS
SELECT zone_id, facility_id,
       COUNT(*) FILTER (WHERE state = 'vacant') AS available_ev_spaces, COUNT(*) FILTER (WHERE state = 'occupied') AS occupied_ev_spaces,
       COUNT(*) AS total_ev_spaces, MAX(last_updated_ts) AS last_updated
FROM space_current_state
WHERE space_type = 'ev'
GROUP BY zone_id, facility_id;

CREATE MATERIALIZED VIEW occupancy_by_hour_of_week AS
SELECT zone_id, facility_id, EXTRACT(DOW FROM window_start) AS day_of_week, EXTRACT(HOUR FROM window_start) AS hour_of_day,
       AVG(occupied_spaces * 100.0 / NULLIF(total_spaces, 0)) AS avg_occupancy_pct
FROM (SELECT zone_id, facility_id, window_start, COUNT(*) FILTER (WHERE state = 'occupied') AS occupied_spaces, COUNT(*) AS total_spaces
      FROM TUMBLE(parking_sensor_events, event_ts, INTERVAL '1 hour') GROUP BY zone_id, facility_id, window_start) hourly
GROUP BY zone_id, facility_id, day_of_week, hour_of_day;

facility_occupancy feeds the variable message signs at the garage entrance and the navigation app API. A garage at 70 percent average occupancy that reaches 80 percent through better guidance earns the difference without adding a space. The hour-of-week pattern is the input to dynamic pricing and to pre-positioning enforcement.

Air Quality: Hourly Smoothing, AQI, Neighborhood Rollup, and Spikes

Low-cost sensor networks put hundreds of PM2.5, NO2, CO, and ozone sensors across a city at a fraction of the cost of reference stations. AQI standards require rolling averages, so the hourly view comes first; EPA breakpoints convert PM2.5 to a sub-index and a category; the neighborhood view takes the worst sensor as the category residents see.

CREATE SOURCE aq_sensor_readings (
    sensor_id VARCHAR, zone_id VARCHAR, neighborhood_id VARCHAR, city_id VARCHAR, lat NUMERIC, lon NUMERIC,
    pm25_ugm3 NUMERIC, pm10_ugm3 NUMERIC, no2_ppb NUMERIC, co_ppm NUMERIC, o3_ppb NUMERIC, so2_ppb NUMERIC,
    temperature_c NUMERIC, humidity_pct NUMERIC, reading_ts TIMESTAMPTZ
) WITH (connector = 'kafka', topic = 'aq.sensors.readings', properties.bootstrap.server = 'kafka:9092', scan.startup.mode = 'latest')
FORMAT PLAIN ENCODE JSON;

CREATE MATERIALIZED VIEW sensor_hourly_avg AS
SELECT sensor_id, zone_id, neighborhood_id, city_id, window_start, window_end,
       AVG(pm25_ugm3) AS avg_pm25, AVG(pm10_ugm3) AS avg_pm10, AVG(no2_ppb) AS avg_no2, AVG(co_ppm) AS avg_co, AVG(o3_ppb) AS avg_o3,
       MAX(pm25_ugm3) AS max_pm25, COUNT(*) AS reading_count
FROM TUMBLE(aq_sensor_readings, reading_ts, INTERVAL '1 hour')
GROUP BY sensor_id, zone_id, neighborhood_id, city_id, window_start, window_end;

CREATE MATERIALIZED VIEW sensor_aqi AS
SELECT sensor_id, zone_id, neighborhood_id, window_start, window_end, avg_pm25, avg_no2, avg_co, reading_count,
       CASE WHEN avg_pm25 <= 12.0  THEN ROUND(avg_pm25 * 50.0 / 12.0, 0)
            WHEN avg_pm25 <= 35.4  THEN ROUND(50 + (avg_pm25 - 12.1) * 49.0 / 23.3, 0)
            WHEN avg_pm25 <= 55.4  THEN ROUND(100 + (avg_pm25 - 35.5) * 49.0 / 19.9, 0)
            WHEN avg_pm25 <= 150.4 THEN ROUND(150 + (avg_pm25 - 55.5) * 49.0 / 94.9, 0)
            WHEN avg_pm25 <= 250.4 THEN ROUND(200 + (avg_pm25 - 150.5) * 99.0 / 99.9, 0)
            ELSE 301 END AS pm25_aqi,
       CASE WHEN avg_pm25 <= 12.0 THEN 'Good' WHEN avg_pm25 <= 35.4 THEN 'Moderate'
            WHEN avg_pm25 <= 55.4 THEN 'Unhealthy for Sensitive Groups' WHEN avg_pm25 <= 150.4 THEN 'Unhealthy'
            WHEN avg_pm25 <= 250.4 THEN 'Very Unhealthy' ELSE 'Hazardous' END AS aqi_category
FROM sensor_hourly_avg;

CREATE MATERIALIZED VIEW neighborhood_aqi AS
SELECT neighborhood_id, city_id, window_start, window_end,
       AVG(avg_pm25) AS avg_pm25, AVG(avg_no2) AS avg_no2, MAX(pm25_aqi) AS max_pm25_aqi, AVG(pm25_aqi) AS avg_pm25_aqi,
       COUNT(DISTINCT sensor_id) AS sensor_count,
       CASE WHEN MAX(pm25_aqi) <= 50 THEN 'Good' WHEN MAX(pm25_aqi) <= 100 THEN 'Moderate'
            WHEN MAX(pm25_aqi) <= 150 THEN 'Unhealthy for Sensitive Groups' WHEN MAX(pm25_aqi) <= 200 THEN 'Unhealthy'
            WHEN MAX(pm25_aqi) <= 300 THEN 'Very Unhealthy' ELSE 'Hazardous' END AS worst_aqi_category
FROM sensor_aqi
GROUP BY neighborhood_id, city_id, window_start, window_end;

CREATE MATERIALIZED VIEW health_alerts AS
SELECT sensor_id, zone_id, neighborhood_id, avg_pm25, avg_no2, pm25_aqi, aqi_category, window_start, window_end
FROM sensor_aqi
WHERE pm25_aqi > 150;

CREATE MATERIALIZED VIEW pm25_spike_alerts AS
SELECT cur.sensor_id, cur.zone_id, cur.avg_pm25 AS current_pm25, prev.avg_pm25 AS prior_pm25,
       ROUND((cur.avg_pm25 - prev.avg_pm25) * 100.0 / NULLIF(prev.avg_pm25, 0), 1) AS pct_increase, cur.window_start
FROM sensor_hourly_avg cur
JOIN sensor_hourly_avg prev ON cur.sensor_id = prev.sensor_id AND prev.window_start = cur.window_start - INTERVAL '1 hour'
WHERE cur.avg_pm25 > prev.avg_pm25 * 1.5 AND cur.avg_pm25 > 20;

A 50 percent hour-over-hour spike at one sensor while its neighbors hold steady is a local source, industrial, a fire, or a sensor fault, and joining the spike view to a pollution incident feed on zone and time tells you which. A spike across a whole neighborhood is weather or a regional event. Hourly sensor averages archived to Iceberg are the dataset for the trend analysis and the regulatory reporting that citizens, planners, and agencies each read differently.

Urban Safety: Zone Summaries, Multi-Signal Threats, and Dispatch SLAs

Safety operations centers juggle CCTV event classifications, crowd occupancy counts, sensor alarms, and dispatch records. One-minute zone summaries over the video analytics stream are the base; a correlated audio alarm plus repeated motion anomalies in a crowded zone within two minutes is the threat pattern no human watching individual feeds catches in time; joining dispatch to the zone summary gives response time in the context of what sensors saw.

CREATE SOURCE safety_events (
    event_id VARCHAR, sensor_node_id VARCHAR, zone_code VARCHAR, event_time TIMESTAMPTZ,
    event_class VARCHAR,                -- 'CROWD_DENSITY','MOTION_ANOMALY','AUDIO_ALARM'
    confidence_score DOUBLE PRECISION, occupancy_count INTEGER
) WITH (connector = 'kafka', topic = 'city.safety.events', properties.bootstrap.server = 'kafka:9092', scan.startup.mode = 'latest')
FORMAT PLAIN ENCODE JSON;

CREATE SOURCE dispatch_events (
    dispatch_id VARCHAR, zone_code VARCHAR, call_time TIMESTAMPTZ, unit_assigned VARCHAR,
    response_time_s INTEGER, incident_type VARCHAR, status VARCHAR    -- 'DISPATCHED','ON_SCENE','CLEARED'
) WITH (connector = 'kafka', topic = 'city.dispatch', properties.bootstrap.server = 'kafka:9092', scan.startup.mode = 'latest')
FORMAT PLAIN ENCODE JSON;

CREATE MATERIALIZED VIEW zone_safety_summary_1m AS
SELECT zone_code, window_start, window_end,
       MAX(occupancy_count) AS peak_occupancy, COUNT(*) AS total_events,
       COUNT(*) FILTER (WHERE event_class = 'CROWD_DENSITY')  AS crowd_events,
       COUNT(*) FILTER (WHERE event_class = 'MOTION_ANOMALY') AS motion_events,
       COUNT(*) FILTER (WHERE event_class = 'AUDIO_ALARM')    AS audio_events,
       AVG(confidence_score) AS avg_confidence
FROM TUMBLE(safety_events, event_time, INTERVAL '1 MINUTE')
GROUP BY zone_code, window_start, window_end;

CREATE MATERIALIZED VIEW multi_signal_threat_alerts AS
SELECT zone_code, window_start AS alert_time, 'MULTI_SIGNAL_THREAT' AS alert_type, peak_occupancy, audio_events, motion_events, total_events
FROM zone_safety_summary_1m
WHERE audio_events >= 1 AND motion_events >= 2 AND peak_occupancy > 50;

CREATE MATERIALIZED VIEW dispatch_response_live AS
SELECT d.dispatch_id, d.zone_code, d.incident_type, d.call_time, d.response_time_s, d.status,
       s.peak_occupancy, s.total_events AS concurrent_sensor_events,
       d.response_time_s > 480 AS sla_breach
FROM dispatch_events d
LEFT JOIN zone_safety_summary_1m s ON d.zone_code = s.zone_code AND d.call_time >= s.window_start AND d.call_time < s.window_end;

Crowd density above a per-zone threshold can drive automated gate control or a public address announcement through a sink, and a rolling hotspot map built from the one-minute summary updates every 30 seconds rather than nightly.

Emergency Response: Unit Availability, Response Performance, and SLA Risk

Fire, EMS, and police each publish incidents, unit locations, and dispatch assignments. The latest ping per unit gives availability by zone and type; joining incidents to dispatch in 15-minute windows gives average and p90 response time and counts priority 1 and 2 calls that breached eight minutes or are still pending past it.

CREATE SOURCE incident_stream (
    incident_id VARCHAR, zone_code VARCHAR, call_time TIMESTAMPTZ, event_class VARCHAR,     -- 'FIRE','EMS','POLICE_PRIORITY1'
    priority_level SMALLINT, lat DOUBLE PRECISION, lon DOUBLE PRECISION, status VARCHAR
) WITH (connector = 'kafka', topic = 'cad.incidents', properties.bootstrap.server = 'kafka:9092', scan.startup.mode = 'latest')
FORMAT PLAIN ENCODE JSON;

CREATE SOURCE unit_location_stream (
    unit_id VARCHAR, unit_type VARCHAR,       -- 'AMBULANCE','FIRE_ENGINE','PATROL'
    zone_code VARCHAR, ping_time TIMESTAMPTZ, lat DOUBLE PRECISION, lon DOUBLE PRECISION,
    status VARCHAR,                           -- 'AVAILABLE','DISPATCHED','AT_SCENE','OUT_OF_SERVICE'
    speed_kmh DOUBLE PRECISION
) WITH (connector = 'kafka', topic = 'avl.units', properties.bootstrap.server = 'kafka:9092', scan.startup.mode = 'latest')
FORMAT PLAIN ENCODE JSON;

CREATE SOURCE dispatch_log (
    dispatch_id VARCHAR, incident_id VARCHAR, unit_id VARCHAR, dispatch_time TIMESTAMPTZ,
    on_scene_time TIMESTAMPTZ, clear_time TIMESTAMPTZ, response_time_s INTEGER
) WITH (connector = 'kafka', topic = 'cad.dispatch.log', properties.bootstrap.server = 'kafka:9092', scan.startup.mode = 'latest')
FORMAT PLAIN ENCODE JSON;

CREATE MATERIALIZED VIEW unit_availability_live AS
SELECT zone_code, unit_type,
       COUNT(*) FILTER (WHERE status = 'AVAILABLE')      AS available_units,
       COUNT(*) FILTER (WHERE status = 'DISPATCHED')     AS dispatched_units,
       COUNT(*) FILTER (WHERE status = 'AT_SCENE')       AS on_scene_units,
       COUNT(*) FILTER (WHERE status = 'OUT_OF_SERVICE') AS oos_units,
       COUNT(*) AS total_units
FROM (SELECT DISTINCT ON (unit_id) unit_id, unit_type, zone_code, status FROM unit_location_stream ORDER BY unit_id, ping_time DESC) latest
GROUP BY zone_code, unit_type;

CREATE MATERIALIZED VIEW response_performance_15m AS
SELECT i.zone_code, i.event_class, window_start, window_end,
       COUNT(DISTINCT d.dispatch_id) AS total_dispatches,
       AVG(d.response_time_s) AS avg_response_time_s,
       PERCENTILE_CONT(0.9) WITHIN GROUP (ORDER BY d.response_time_s) AS p90_response_time_s,
       COUNT(*) FILTER (WHERE d.response_time_s > 480 AND i.priority_level <= 2) AS p1_p2_sla_breaches
FROM TUMBLE(incident_stream, call_time, INTERVAL '15 MINUTES') i
JOIN dispatch_log d ON i.incident_id = d.incident_id
GROUP BY i.zone_code, i.event_class, window_start, window_end;

CREATE MATERIALIZED VIEW pending_sla_at_risk AS
SELECT i.incident_id, i.zone_code, i.event_class, i.priority_level, i.call_time,
       EXTRACT(EPOCH FROM (NOW() - i.call_time)) AS seconds_open
FROM incident_stream i
LEFT JOIN dispatch_log d ON i.incident_id = d.incident_id AND d.on_scene_time IS NOT NULL
WHERE d.dispatch_id IS NULL AND i.priority_level <= 2 AND i.call_time < NOW() - INTERVAL '6 MINUTES';

CREATE MATERIALIZED VIEW emergency_alerts AS
SELECT zone_code, unit_type AS detail, 'LOW_UNIT_AVAILABILITY' AS alert_type, available_units AS metric
FROM unit_availability_live WHERE available_units = 0 AND total_units > 0
UNION ALL
SELECT zone_code, event_class, 'SLA_BREACH', p1_p2_sla_breaches FROM response_performance_15m WHERE p1_p2_sla_breaches > 0
UNION ALL
SELECT zone_code, incident_id, 'SLA_AT_RISK', seconds_open::INT FROM pending_sla_at_risk;

The pending-risk view uses NOW() in the filter, so an incident enters it at six minutes and leaves when a unit arrives, which is a two-minute head start on the eight-minute target. Nearest-available-unit selection is the equirectangular distance from the incident to every available unit of the right type, ordered and limited to one, and multiple 911 calls for the same event cluster by zone and a short time window to size the initial response. The same views serve after-action reports.

Routing Alerts to the Systems That Act

CREATE SINK incident_alerts_sink AS SELECT * FROM incident_candidates WHERE incident_confidence IN ('HIGH','MEDIUM')
WITH (connector = 'kafka', topic = 'traffic.alerts.incidents', properties.bootstrap.server = 'kafka:9092') FORMAT PLAIN ENCODE JSON;

CREATE SINK congestion_alerts_sink FROM congestion_alerts
WITH (connector = 'kafka', topic = 'traffic.alerts.congestion', properties.bootstrap.server = 'kafka:9092') FORMAT PLAIN ENCODE JSON;

CREATE SINK bunching_alerts_sink FROM bunching_alerts
WITH (connector = 'kafka', topic = 'transit.alerts.bunching', properties.bootstrap.server = 'kafka:9092') FORMAT PLAIN ENCODE JSON;

CREATE SINK near_capacity_sink FROM near_capacity_alerts
WITH (connector = 'kafka', topic = 'parking.alerts.capacity', properties.bootstrap.server = 'kafka:9092') FORMAT UPSERT ENCODE JSON;

CREATE SINK health_alerts_sink FROM health_alerts
WITH (connector = 'kafka', topic = 'aq.alerts.health', properties.bootstrap.server = 'kafka:9092') FORMAT PLAIN ENCODE JSON;

CREATE SINK safety_alerts_sink FROM multi_signal_threat_alerts
WITH (connector = 'kafka', topic = 'city.safety.alerts', properties.bootstrap.server = 'kafka:9092') FORMAT PLAIN ENCODE JSON;

CREATE SINK emergency_alerts_sink FROM emergency_alerts
WITH (connector = 'kafka', topic = 'cad.alerts', properties.bootstrap.server = 'kafka:9092') FORMAT PLAIN ENCODE JSON;

CREATE SINK facility_occupancy_sink FROM facility_occupancy
WITH (connector = 'jdbc', jdbc.url = 'jdbc:postgresql://city-db:5432/parking', table.name = 'facility_occupancy', type = 'upsert', primary_key = 'facility_id');

Adaptive signal controllers poll zone_congestion_5min over PostgreSQL. Grafana connects with the standard Postgres data source. Variable message signs read the parking upsert table. Each domain's views are independent, so a city can start with traffic and add transit, parking, air, and safety without touching what already runs.

Batch Reports vs Streaming SQL for City Operations

DomainBatch practiceStreaming SQL (RisingWave)
TrafficQuarterly timing plans, 5 to 15 minute historian lagFive-minute flow and congestion score, incident signature on the window
TransitOvernight headway reportsHeadway per stop arrival, bunching alert under two minutes
ParkingOccupancy counts refreshed by pollingLatest state per space, zone and facility rollups on every event
Air quality1 to 24 hour reference station reportsHourly smoothed AQI per sensor and neighborhood, spike detection
Urban safetyManual video monitoring, 15-minute summariesOne-minute zone summaries, correlated multi-signal alerts
Emergency responseAfter-action statisticsUnit availability, p90 response, SLA risk before the breach

Frequently Asked Questions

Can one RisingWave cluster serve all six domains? Yes. Each domain is its own set of sources and views, and the cluster scales compute and state independently. Start with the domain that has the clearest operational owner and add the rest; nothing in the traffic views depends on the transit ones.

How do loop detectors and GPS probes get reconciled? Join traffic_flow_5min and segment_travel_time_5min on zone and window. Detectors give count and occupancy, probes give travel time on segments without detectors. Where both exist, a divergence between them flags a faulty detector.

Why do AQI calculations start with an hourly average? The EPA PM2.5 index is defined over averaged concentrations, and the NowCast variant weights recent hours. The hourly view is the common input; a NowCast weighting is a second view over the last twelve hourly rows per sensor.

How is a bunching alert turned into a holding instruction? The bunching and headway variance views sink to a Kafka topic that transit dispatch consumes. The dispatch system decides the hold or express action; RisingWave supplies the signal and the route KPIs to judge whether the action helped.

How do I find the nearest available ambulance to an incident? Join open incidents to the latest position per available unit of the required type, compute the distance with an equirectangular approximation, and keep the smallest with DISTINCT ON (incident_id) ... ORDER BY incident_id, distance. Travel time from a routing service can replace straight-line distance as an enrichment field.

The engine for real-time streaming data.
Analyze, search, and decide.
GitHubXLinkedInSlackYouTube
Sign up for our to stay updated.