Real-time supply chain and logistics monitoring with streaming SQL means shipment status, delays, warehouse stock alerts, supplier scorecards, carrier on-time rates, cold chain excursions, port berth and crane state, and intermodal dwell are all maintained as materialized views that update the moment a tracking scan, GPS ping, warehouse transaction, temperature reading, AIS report, or leg event arrives. This guide builds the full visibility layer on RisingWave, a PostgreSQL-compatible streaming database, starting from a verified monitoring tutorial and extending it to freight tracking, carrier performance, cold chain, ports, and multi-modal transport.
Why Nightly ETL Fails Supply Chain Visibility
Supply chain disruptions cost businesses an average of $184 million a year, according to Interos, and the root cause is rarely the disruption itself. It is the hours between the carrier flagging a shipment as delayed at 2 PM and the dashboard showing it the next morning, after the SLA is already breached. Batch architectures fail in four specific ways: the data is stale, delay detection happens after the SLA, teams fight fires instead of preventing them, and shipments, inventory, and supplier data run through separate pipelines so nobody sees that a delayed shipment from Supplier A will cause a stockout at Warehouse East.
The same gap appears at every node. A consignment that goes dark for 30 minutes forces dispatch decisions on stale positions. A carrier whose on-time rate collapses on one lane shows up in a monthly scorecard after thousands of deliveries. A reefer that spiked above range for ten minutes is discovered when the logger is downloaded at delivery. A crane breakdown or berth delay reaches the port coordinator several dashboard refreshes late. A container sitting at a rail transfer for 14 hours is found in tomorrow's exception report.
RisingWave treats each of these events as it arrives and maintains the views as incrementally updated query results, recomputing only the affected shipment, SKU, carrier, asset, berth, or leg. Results serve over the PostgreSQL protocol to Grafana and operations dashboards and through Kafka sinks to alerting, procurement, and carrier management systems. RisingWave is open source under Apache 2.0, written in Rust, and checkpoints state to S3.
Tutorial: Shipments, Inventory, and Suppliers in Three Views
Model the three core streams as tables for the walkthrough; in production each is a Kafka source or a CDC table fed by the transportation management system, the warehouse management system, and the ERP.
CREATE TABLE shipments (
shipment_id VARCHAR PRIMARY KEY,
order_id VARCHAR,
supplier_id VARCHAR,
origin_warehouse VARCHAR,
destination VARCHAR,
status VARCHAR, -- 'shipped', 'in_transit', 'delayed', 'delivered'
shipped_at TIMESTAMPTZ,
estimated_arrival TIMESTAMPTZ,
actual_arrival TIMESTAMPTZ,
carrier VARCHAR,
weight_kg DOUBLE PRECISION
);
CREATE TABLE warehouse_inventory (
warehouse_id VARCHAR,
product_id VARCHAR,
product_name VARCHAR,
quantity INT,
reorder_threshold INT,
last_updated TIMESTAMPTZ,
PRIMARY KEY (warehouse_id, product_id)
);
CREATE TABLE supplier_deliveries (
delivery_id VARCHAR PRIMARY KEY,
supplier_id VARCHAR,
supplier_name VARCHAR,
promised_date TIMESTAMPTZ,
actual_date TIMESTAMPTZ,
quantity_ordered INT,
quantity_delivered INT,
quality_score DOUBLE PRECISION
);
The shipment status view enriches each row with transit time and a delivery classification. When the carrier pushes a status change from in_transit to delivered with an arrival time, the view recalculates within seconds.
CREATE MATERIALIZED VIEW mv_shipment_status AS
SELECT shipment_id, order_id, supplier_id, origin_warehouse, destination, status, carrier, shipped_at, estimated_arrival, actual_arrival,
CASE WHEN actual_arrival IS NOT NULL THEN EXTRACT(EPOCH FROM (actual_arrival - shipped_at)) / 3600.0 END AS transit_hours,
CASE WHEN status = 'delivered' AND actual_arrival <= estimated_arrival THEN 'on_time'
WHEN status = 'delivered' AND actual_arrival > estimated_arrival THEN 'late'
WHEN status = 'delayed' THEN 'delayed'
ELSE 'in_progress' END AS delivery_performance
FROM shipments;
CREATE MATERIALIZED VIEW mv_shipment_delays AS
SELECT shipment_id, order_id, supplier_id, carrier, destination, estimated_arrival, status,
CASE WHEN status = 'delayed' THEN 'ACTION REQUIRED' ELSE 'DELIVERED LATE' END AS alert_level,
CASE WHEN status = 'delivered' THEN ROUND((EXTRACT(EPOCH FROM (actual_arrival - estimated_arrival)) / 3600.0)::NUMERIC, 1) END AS hours_late
FROM shipments
WHERE status = 'delayed' OR (status = 'delivered' AND actual_arrival > estimated_arrival);
Stockouts are among the most expensive failures. The inventory alert view classifies stock against the reorder threshold and tells procurement exactly how many units to order, not just that it needs to:
CREATE MATERIALIZED VIEW mv_warehouse_alerts AS
SELECT warehouse_id, product_id, product_name, quantity, reorder_threshold,
CASE WHEN quantity <= reorder_threshold * 0.5 THEN 'CRITICAL' ELSE 'LOW' END AS stock_status,
reorder_threshold - quantity AS units_below_threshold
FROM warehouse_inventory
WHERE quantity <= reorder_threshold;
The supplier scorecard weights quality at 40 percent, because defective components cascade into returns, rework, and line stops, and fill rate and on-time delivery at 30 percent each:
CREATE MATERIALIZED VIEW mv_supplier_performance AS
SELECT supplier_id, supplier_name,
COUNT(*) AS total_deliveries,
ROUND(AVG(quality_score)::NUMERIC, 2) AS avg_quality_score,
ROUND((SUM(quantity_delivered)::DOUBLE PRECISION / NULLIF(SUM(quantity_ordered), 0) * 100)::NUMERIC, 1) AS fill_rate_pct,
ROUND((COUNT(*) FILTER (WHERE actual_date <= promised_date)::DOUBLE PRECISION / COUNT(*) * 100)::NUMERIC, 1) AS on_time_pct,
ROUND((AVG(quality_score) * 0.4
+ SUM(quantity_delivered)::DOUBLE PRECISION / NULLIF(SUM(quantity_ordered), 0) * 10 * 0.3
+ COUNT(*) FILTER (WHERE actual_date <= promised_date)::DOUBLE PRECISION / COUNT(*) * 10 * 0.3)::NUMERIC, 2) AS composite_score
FROM supplier_deliveries
GROUP BY supplier_id, supplier_name;
With a few sample rows, Beta Electronics leads at 8.38 on near-perfect quality and fill rate while Central Parts Co trails at 5.57 with zero on-time deliveries. The payoff is correlation. One query joins the three views: this shipment is delayed, it is bound for a warehouse already critical on the same product, and its supplier is on time half the time. That cross-signal picture is what siloed batch pipelines cannot produce.
CREATE MATERIALIZED VIEW mv_supply_chain_risk AS
SELECT d.shipment_id, d.carrier, d.alert_level, d.destination, a.warehouse_id, a.product_name, a.stock_status, p.supplier_name, p.on_time_pct, p.composite_score
FROM mv_shipment_delays d
JOIN shipments s ON d.shipment_id = s.shipment_id
JOIN mv_warehouse_alerts a ON s.destination = a.warehouse_id
JOIN mv_supplier_performance p ON d.supplier_id = p.supplier_id;
Freight Tracking: Live Positions and Dark Shipments
Vehicle and container telematics give the position layer. The latest ping per shipment joined to the manifest is the live map; a shipment that has been silent for ten minutes while not delivered is a GPS failure, a breakdown, or a deviation, and it should page someone.
CREATE SOURCE vehicle_telemetry (
vehicle_id VARCHAR,
shipment_id VARCHAR,
latitude DOUBLE PRECISION,
longitude DOUBLE PRECISION,
speed_kmh DOUBLE PRECISION,
heading_deg DOUBLE PRECISION,
status VARCHAR,
event_time TIMESTAMPTZ
) WITH (connector = 'kafka', topic = 'vehicle-telemetry', properties.bootstrap.server = 'kafka:9092', scan.startup.mode = 'latest')
FORMAT PLAIN ENCODE JSON;
CREATE MATERIALIZED VIEW live_shipment_positions AS
SELECT t.shipment_id, s.origin_warehouse, s.destination, s.estimated_arrival, s.carrier,
t.latitude, t.longitude, t.speed_kmh, t.status, t.event_time AS last_seen, NOW() - t.event_time AS data_age
FROM (SELECT DISTINCT ON (shipment_id) * FROM vehicle_telemetry ORDER BY shipment_id, event_time DESC) t
JOIN shipments s ON t.shipment_id = s.shipment_id;
CREATE MATERIALIZED VIEW stale_shipment_alerts AS
SELECT shipment_id, origin_warehouse, destination, carrier, last_seen,
EXTRACT(EPOCH FROM (NOW() - last_seen)) / 60 AS minutes_since_update
FROM live_shipment_positions
WHERE NOW() - last_seen > INTERVAL '10 MINUTES' AND status NOT IN ('DELIVERED', 'CANCELLED');
CREATE MATERIALIZED VIEW shipment_speed_5m AS
SELECT shipment_id, window_start, window_end, AVG(speed_kmh) AS avg_speed_kmh, MIN(speed_kmh) AS min_speed_kmh, COUNT(*) AS ping_count
FROM TUMBLE(vehicle_telemetry, event_time, INTERVAL '5 MINUTES')
GROUP BY shipment_id, window_start, window_end;
A five-minute average speed near zero on a shipment that should be moving, combined with a fresh last_seen, is a stopped truck rather than a dark one, which is a different call to make. Geofence arrival at the destination, from the companion fleet telematics guide, is how actual_arrival gets stamped automatically when the carrier's own feed lags.
Carrier Performance: On-Time Rate, SLA Breaches, and Claims
Shippers using several carriers need to know who is underperforming now, not who had a bad week last quarter. Carrier tracking events from API webhooks or EDI 214 messages give a delivery outcome per shipment; hourly tumbling windows give on-time rate per carrier and service level; a four-hour window with a minimum volume is the SLA breach alert, and claims joined to deliveries give the damage rate.
CREATE SOURCE carrier_tracking (
tracking_number VARCHAR,
shipment_id VARCHAR,
carrier_code VARCHAR,
service_level VARCHAR, -- 'GROUND', 'EXPRESS', 'OVERNIGHT', 'FREIGHT'
origin_zip VARCHAR,
dest_zip VARCHAR,
event_type VARCHAR, -- 'PICKED_UP', 'IN_TRANSIT', 'OUT_FOR_DELIVERY', 'DELIVERED', 'EXCEPTION', 'RETURNED'
exception_code VARCHAR,
committed_delivery TIMESTAMPTZ,
event_ts TIMESTAMPTZ
) WITH (connector = 'kafka', topic = 'logistics.tracking', properties.bootstrap.server = 'kafka:9092', scan.startup.mode = 'latest')
FORMAT PLAIN ENCODE JSON;
CREATE SOURCE carrier_claims (
claim_id VARCHAR, shipment_id VARCHAR, carrier_code VARCHAR, claim_type VARCHAR, claim_amount DECIMAL, filed_ts TIMESTAMPTZ
) WITH (connector = 'kafka', topic = 'logistics.claims', properties.bootstrap.server = 'kafka:9092', scan.startup.mode = 'latest')
FORMAT PLAIN ENCODE JSON;
CREATE MATERIALIZED VIEW delivery_outcomes AS
SELECT DISTINCT ON (shipment_id)
shipment_id, carrier_code, service_level, origin_zip, dest_zip, committed_delivery, event_ts AS outcome_ts,
CASE WHEN event_type = 'DELIVERED' AND event_ts <= committed_delivery THEN 'ON_TIME'
WHEN event_type = 'DELIVERED' THEN 'LATE'
ELSE 'EXCEPTION' END AS delivery_status,
EXTRACT(EPOCH FROM (event_ts - committed_delivery)) / 3600.0 AS variance_hours
FROM carrier_tracking
WHERE event_type IN ('DELIVERED', 'EXCEPTION', 'RETURNED')
ORDER BY shipment_id, event_ts DESC;
CREATE MATERIALIZED VIEW carrier_hourly_kpis AS
SELECT window_start, window_end, carrier_code, service_level,
COUNT(*) AS total_outcomes,
COUNT(*) FILTER (WHERE delivery_status = 'ON_TIME') AS on_time_count,
COUNT(*) FILTER (WHERE delivery_status = 'LATE') AS late_count,
COUNT(*) FILTER (WHERE delivery_status = 'EXCEPTION') AS exception_count,
ROUND(100.0 * COUNT(*) FILTER (WHERE delivery_status = 'ON_TIME')
/ NULLIF(COUNT(*) FILTER (WHERE delivery_status IN ('ON_TIME', 'LATE')), 0), 2) AS on_time_rate_pct,
AVG(variance_hours) FILTER (WHERE delivery_status = 'LATE') AS avg_late_hours
FROM TUMBLE(delivery_outcomes, outcome_ts, INTERVAL '1 HOUR')
GROUP BY window_start, window_end, carrier_code, service_level;
CREATE MATERIALIZED VIEW carrier_sla_breaches AS
SELECT window_start, window_end, carrier_code, service_level, total_deliveries, late_count, on_time_rate_pct
FROM (
SELECT window_start, window_end, carrier_code, service_level,
COUNT(*) FILTER (WHERE delivery_status IN ('ON_TIME', 'LATE')) AS total_deliveries,
COUNT(*) FILTER (WHERE delivery_status = 'LATE') AS late_count,
ROUND(100.0 * COUNT(*) FILTER (WHERE delivery_status = 'ON_TIME')
/ NULLIF(COUNT(*) FILTER (WHERE delivery_status IN ('ON_TIME', 'LATE')), 0), 2) AS on_time_rate_pct
FROM TUMBLE(delivery_outcomes, outcome_ts, INTERVAL '4 HOURS')
GROUP BY window_start, window_end, carrier_code, service_level
) w
WHERE on_time_rate_pct < 95 AND total_deliveries >= 20;
CREATE MATERIALIZED VIEW daily_claim_rate AS
SELECT c.window_start, c.window_end, c.carrier_code,
COUNT(DISTINCT c.claim_id) AS claims_filed, SUM(c.claim_amount) AS total_claim_value,
COUNT(DISTINCT d.shipment_id) AS deliveries_in_day,
ROUND(100.0 * COUNT(DISTINCT c.claim_id) / NULLIF(COUNT(DISTINCT d.shipment_id), 0), 3) AS claim_rate_pct
FROM TUMBLE(carrier_claims, filed_ts, INTERVAL '1 DAY') c
LEFT JOIN delivery_outcomes d ON d.carrier_code = c.carrier_code AND d.outcome_ts >= c.window_start AND d.outcome_ts < c.window_end
GROUP BY c.window_start, c.window_end, c.carrier_code;
Grouping the breach view by origin and destination zip prefix as well as carrier turns a network-wide number into a lane-level one, which is where the real conversation with the carrier happens. Hourly KPIs sink to the analytics database behind the formal scorecard, so the monthly document and the live dashboard agree.
Cold Chain: Excursions, Exposure, and Compliance
Vaccines, blood products, produce, and frozen goods each have a temperature band, and traditional monitoring finds an excursion when the logger is downloaded at delivery. IoT sensors over MQTT or Kafka make every reading evaluable on arrival, with the acceptable range per asset in a zone table, a stale-sensor check in the same view, and rolling windows for the exposure metrics behind mean kinetic temperature.
CREATE SOURCE cold_chain_readings (
sensor_id VARCHAR,
asset_id VARCHAR, -- truck, container, room, pallet
temperature_c DOUBLE PRECISION,
humidity_pct DOUBLE PRECISION,
door_open BOOLEAN,
battery_pct DOUBLE PRECISION,
event_time TIMESTAMPTZ
) WITH (connector = 'kafka', topic = 'cold-chain-sensors', properties.bootstrap.server = 'kafka:9092', scan.startup.mode = 'latest')
FORMAT PLAIN ENCODE JSON;
CREATE TABLE monitoring_zones (
asset_id VARCHAR PRIMARY KEY,
asset_name VARCHAR,
asset_type VARCHAR, -- 'REEFER_TRUCK', 'COLD_ROOM', 'FREEZER', 'PALLET'
cargo_type VARCHAR, -- 'FROZEN_FOOD', 'PHARMA_2_8', 'PHARMA_15_25'
shipment_id VARCHAR,
min_temp_c DOUBLE PRECISION,
max_temp_c DOUBLE PRECISION,
min_humidity_pct DOUBLE PRECISION,
max_humidity_pct DOUBLE PRECISION
);
CREATE MATERIALIZED VIEW live_cold_chain_status AS
SELECT r.asset_id, z.asset_name, z.asset_type, z.cargo_type, z.shipment_id,
r.temperature_c, r.humidity_pct, r.door_open, r.battery_pct, r.event_time AS last_reading, NOW() - r.event_time AS reading_age,
r.temperature_c BETWEEN z.min_temp_c AND z.max_temp_c AS temp_in_spec,
r.humidity_pct BETWEEN z.min_humidity_pct AND z.max_humidity_pct AS humidity_in_spec,
GREATEST(z.min_temp_c - r.temperature_c, r.temperature_c - z.max_temp_c, 0) AS temp_deviation_c,
z.min_temp_c, z.max_temp_c
FROM (SELECT DISTINCT ON (asset_id) * FROM cold_chain_readings ORDER BY asset_id, event_time DESC) r
JOIN monitoring_zones z ON r.asset_id = z.asset_id;
CREATE MATERIALIZED VIEW active_excursion_alerts AS
SELECT asset_id, asset_name, cargo_type, shipment_id, temperature_c, min_temp_c, max_temp_c, temp_deviation_c, door_open, last_reading, reading_age,
CASE WHEN reading_age > INTERVAL '15 MINUTES' THEN 'SENSOR_STALE'
WHEN NOT temp_in_spec THEN 'TEMPERATURE_EXCURSION'
ELSE 'HUMIDITY_EXCURSION' END AS alert_type
FROM live_cold_chain_status
WHERE NOT temp_in_spec OR NOT humidity_in_spec OR reading_age > INTERVAL '15 MINUTES';
CREATE MATERIALIZED VIEW temperature_rolling_30min AS
SELECT window_start, window_end, r.asset_id, z.cargo_type,
AVG(r.temperature_c) AS avg_temp_c, MAX(r.temperature_c) AS max_temp_c, MIN(r.temperature_c) AS min_temp_c,
COUNT(*) AS reading_count,
COUNT(*) FILTER (WHERE r.temperature_c > z.max_temp_c OR r.temperature_c < z.min_temp_c) AS excursion_readings,
COUNT(*) FILTER (WHERE r.door_open) AS door_open_readings
FROM TUMBLE(cold_chain_readings, event_time, INTERVAL '30 MINUTES') r
JOIN monitoring_zones z ON r.asset_id = z.asset_id
GROUP BY window_start, window_end, r.asset_id, z.cargo_type;
CREATE MATERIALIZED VIEW compliance_summary AS
SELECT window_start, window_end, z.cargo_type,
COUNT(DISTINCT r.asset_id) AS monitored_assets,
COUNT(DISTINCT r.asset_id) FILTER (WHERE r.temperature_c BETWEEN z.min_temp_c AND z.max_temp_c) AS compliant_assets,
ROUND(100.0 * COUNT(DISTINCT r.asset_id) FILTER (WHERE r.temperature_c BETWEEN z.min_temp_c AND z.max_temp_c)
/ NULLIF(COUNT(DISTINCT r.asset_id), 0), 1) AS compliance_rate_pct
FROM TUMBLE(cold_chain_readings, event_time, INTERVAL '5 MINUTES') r
JOIN monitoring_zones z ON r.asset_id = z.asset_id
GROUP BY window_start, window_end, z.cargo_type;
A reefer door opening correlates with a temperature rise two readings later, and the door-open count in the 30-minute view explains an excursion that would otherwise look like a compressor fault. Mean kinetic temperature itself is an exponential over the readings and is best computed in a service or a user-defined function reading the rolling view; the view supplies the inputs. The raw readings in Kafka are the audit-ready log regulators ask for.
Port Operations: Vessels, Berths, Cranes, and Gates
A vessel call coordinates arrival, pilots and tugs, berth allocation, crane deployment, yard trucks, rail, and gates against a window that affects the next vessel in the queue. AIS positions, terminal operating system events, and gate transactions give a live port state view at every level.
CREATE SOURCE ais_positions (
mmsi VARCHAR, vessel_name VARCHAR, vessel_type VARCHAR, latitude DOUBLE PRECISION, longitude DOUBLE PRECISION,
speed_knots DOUBLE PRECISION, nav_status VARCHAR, -- 'UNDERWAY', 'AT_ANCHOR', 'MOORED'
destination VARCHAR, eta TIMESTAMPTZ, event_time TIMESTAMPTZ
) WITH (connector = 'kafka', topic = 'ais-positions', properties.bootstrap.server = 'kafka:9092', scan.startup.mode = 'latest')
FORMAT PLAIN ENCODE JSON;
CREATE SOURCE terminal_events (
event_id VARCHAR, event_type VARCHAR, -- 'BERTH_ALLOC', 'BERTH_RELEASE', 'CRANE_CYCLE', 'EQUIP_STATUS'
vessel_id VARCHAR, berth_id VARCHAR, crane_id VARCHAR, container_id VARCHAR, value DOUBLE PRECISION, event_time TIMESTAMPTZ
) WITH (connector = 'kafka', topic = 'terminal-events', properties.bootstrap.server = 'kafka:9092', scan.startup.mode = 'latest')
FORMAT PLAIN ENCODE JSON;
CREATE SOURCE gate_transactions (
transaction_id VARCHAR, gate_id VARCHAR, truck_plate VARCHAR, container_id VARCHAR, direction VARCHAR, queue_wait_sec INTEGER, event_time TIMESTAMPTZ
) WITH (connector = 'kafka', topic = 'gate-transactions', properties.bootstrap.server = 'kafka:9092', scan.startup.mode = 'latest')
FORMAT PLAIN ENCODE JSON;
CREATE TABLE berths (berth_id VARCHAR PRIMARY KEY, berth_name VARCHAR, terminal_id VARCHAR, max_loa_m DOUBLE PRECISION, quay_cranes INTEGER);
CREATE MATERIALIZED VIEW live_vessel_positions AS
SELECT DISTINCT ON (mmsi) mmsi, vessel_name, vessel_type, latitude, longitude, speed_knots, nav_status, destination, eta, event_time AS last_ais_report, NOW() - event_time AS ais_age
FROM ais_positions
ORDER BY mmsi, event_time DESC;
CREATE MATERIALIZED VIEW approaching_vessels AS
SELECT mmsi, vessel_name, vessel_type, speed_knots, nav_status, eta, last_ais_report,
111.0 * SQRT(POWER(latitude - 1.2647, 2) + POWER((longitude - 103.820) * COS(RADIANS(latitude)), 2)) / 1.852 AS distance_nm_to_port
FROM live_vessel_positions
WHERE nav_status = 'UNDERWAY'
AND 111.0 * SQRT(POWER(latitude - 1.2647, 2) + POWER((longitude - 103.820) * COS(RADIANS(latitude)), 2)) / 1.852 < 20;
CREATE MATERIALIZED VIEW berth_state AS
SELECT DISTINCT ON (berth_id) berth_id, event_type AS last_event, vessel_id, event_time
FROM terminal_events
WHERE event_type IN ('BERTH_ALLOC', 'BERTH_RELEASE')
ORDER BY berth_id, event_time DESC;
CREATE MATERIALIZED VIEW berth_occupancy AS
SELECT b.berth_id, b.berth_name, b.terminal_id, b.quay_cranes,
CASE WHEN s.last_event = 'BERTH_ALLOC' THEN s.vessel_id END AS occupied_by,
CASE WHEN s.last_event = 'BERTH_ALLOC' THEN s.event_time END AS occupied_since
FROM berths b
LEFT JOIN berth_state s ON b.berth_id = s.berth_id;
CREATE MATERIALIZED VIEW crane_productivity AS
SELECT window_start, window_end, crane_id, COUNT(*) AS moves_per_hour, AVG(value) AS avg_cycle_time_sec, MIN(value) AS min_cycle_time_sec
FROM TUMBLE(terminal_events, event_time, INTERVAL '1 HOUR')
WHERE event_type = 'CRANE_CYCLE'
GROUP BY window_start, window_end, crane_id;
CREATE MATERIALIZED VIEW gate_throughput AS
SELECT window_start, window_end, gate_id,
COUNT(*) FILTER (WHERE direction = 'IN') AS trucks_in, COUNT(*) FILTER (WHERE direction = 'OUT') AS trucks_out,
AVG(queue_wait_sec) FILTER (WHERE direction = 'IN') AS avg_wait_sec_in, MAX(queue_wait_sec) FILTER (WHERE direction = 'IN') AS max_wait_sec_in
FROM TUMBLE(gate_transactions, event_time, INTERVAL '1 HOUR')
GROUP BY window_start, window_end, gate_id;
CREATE MATERIALIZED VIEW stale_ais_alerts AS
SELECT mmsi, vessel_name, nav_status, last_ais_report, ais_age
FROM live_vessel_positions
WHERE ais_age > INTERVAL '15 MINUTES' AND nav_status NOT IN ('AT_ANCHOR', 'MOORED');
The operations center summary, vessels at berth and at anchor, berths occupied and free, vessels approaching, is a handful of counts over these views. Crane moves per hour falling while a vessel is at berth is the signal that a crane needs attention before the vessel's departure window slips. Gate wait times by hour drive appointment scheduling.
Multi-Modal Transport: Legs, Transitions, Dwell, and Schedule Adherence
An intercontinental shipment touches ocean, rail, road, and sometimes air, each tracked by a different system at a different cadence. A normalization layer upstream writes one event stream keyed by shipment and leg sequence. The current leg per shipment is a DISTINCT ON; joining each leg's arrival to the next leg's departure gives intermodal dwell, the hours cargo sits at a transfer point, which is where multi-modal shipments lose their schedule.
CREATE SOURCE transport_events (
shipment_id VARCHAR,
booking_ref VARCHAR,
transport_mode VARCHAR, -- 'OCEAN', 'RAIL', 'ROAD', 'AIR', 'PORT_DWELL', 'WAREHOUSE_DWELL'
leg_sequence INTEGER,
event_type VARCHAR, -- 'DEPARTED', 'IN_TRANSIT', 'ARRIVED', 'CUSTOMS_HOLD', 'EXCEPTION'
carrier_code VARCHAR,
container_id VARCHAR,
location_name VARCHAR,
planned_arrival TIMESTAMPTZ,
event_ts TIMESTAMPTZ
) WITH (connector = 'kafka', topic = 'logistics.transport_events', properties.bootstrap.server = 'kafka:9092', scan.startup.mode = 'latest')
FORMAT PLAIN ENCODE JSON;
CREATE MATERIALIZED VIEW shipment_current_leg AS
SELECT DISTINCT ON (shipment_id) shipment_id, booking_ref, transport_mode AS current_mode, leg_sequence AS current_leg, event_type AS current_event,
carrier_code, container_id, location_name, planned_arrival, event_ts AS last_event_ts, NOW() - event_ts AS event_age
FROM transport_events
ORDER BY shipment_id, event_ts DESC;
CREATE MATERIALIZED VIEW shipment_leg_transitions AS
SELECT a.shipment_id, a.booking_ref, a.transport_mode AS from_mode, b.transport_mode AS to_mode, a.location_name AS handoff_location,
a.event_ts AS leg_end_ts, b.event_ts AS leg_start_ts,
EXTRACT(EPOCH FROM (b.event_ts - a.event_ts)) / 3600.0 AS intermodal_dwell_hours
FROM transport_events a
LEFT JOIN transport_events b ON b.shipment_id = a.shipment_id AND b.leg_sequence = a.leg_sequence + 1 AND b.event_type = 'DEPARTED'
WHERE a.event_type = 'ARRIVED';
CREATE MATERIALIZED VIEW intermodal_dwell_alerts AS
SELECT shipment_id, booking_ref, handoff_location AS stuck_at, from_mode, to_mode, leg_end_ts AS arrived_at_transfer,
COALESCE(intermodal_dwell_hours, EXTRACT(EPOCH FROM (NOW() - leg_end_ts)) / 3600.0) AS dwell_hours
FROM shipment_leg_transitions
WHERE intermodal_dwell_hours > 12 OR (leg_start_ts IS NULL AND NOW() - leg_end_ts > INTERVAL '12 HOURS');
CREATE MATERIALIZED VIEW schedule_adherence AS
SELECT shipment_id, transport_mode, carrier_code, location_name, planned_arrival, event_ts AS actual_arrival,
EXTRACT(EPOCH FROM (event_ts - planned_arrival)) / 3600.0 AS delay_hours,
CASE WHEN event_ts <= planned_arrival THEN 'ON_TIME'
WHEN event_ts <= planned_arrival + INTERVAL '4 HOURS' THEN 'MINOR_DELAY'
ELSE 'SIGNIFICANT_DELAY' END AS adherence_status
FROM transport_events
WHERE event_type = 'ARRIVED' AND planned_arrival IS NOT NULL;
CREATE MATERIALIZED VIEW hourly_in_transit_by_mode AS
SELECT window_start, window_end, transport_mode, COUNT(DISTINCT shipment_id) AS shipment_count
FROM TUMBLE(transport_events, event_ts, INTERVAL '1 HOUR')
WHERE event_type = 'IN_TRANSIT'
GROUP BY window_start, window_end, transport_mode;
A container that arrived at the port 14 hours ago with no rail departure scanned is in intermodal_dwell_alerts now, not in tomorrow's exception report. schedule_adherence by mode and carrier, archived to Iceberg, becomes the long-run carrier analysis, and the same leg events feed mv_shipment_status so the customer-facing tracker and the operations view agree.
Routing Alerts and Serving Dashboards
CREATE SINK shipment_delay_sink FROM mv_shipment_delays
WITH (connector = 'kafka', topic = 'ops.alerts.shipment_delays', properties.bootstrap.server = 'kafka:9092') FORMAT UPSERT ENCODE JSON;
CREATE SINK warehouse_alert_sink FROM mv_warehouse_alerts
WITH (connector = 'kafka', topic = 'procurement.alerts.low_stock', properties.bootstrap.server = 'kafka:9092') FORMAT UPSERT ENCODE JSON;
CREATE SINK stale_shipment_sink FROM stale_shipment_alerts
WITH (connector = 'kafka', topic = 'ops.alerts.dark_shipments', properties.bootstrap.server = 'kafka:9092') FORMAT PLAIN ENCODE JSON;
CREATE SINK carrier_sla_breach_sink FROM carrier_sla_breaches
WITH (connector = 'kafka', topic = 'ops.alerts.carrier_sla', properties.bootstrap.server = 'kafka:9092') FORMAT PLAIN ENCODE JSON;
CREATE SINK cold_chain_alert_sink FROM active_excursion_alerts
WITH (connector = 'kafka', topic = 'ops.alerts.cold_chain', properties.bootstrap.server = 'kafka:9092') FORMAT UPSERT ENCODE JSON;
CREATE SINK dwell_alert_sink FROM intermodal_dwell_alerts
WITH (connector = 'kafka', topic = 'ops.alerts.dwell_exceeded', properties.bootstrap.server = 'kafka:9092') FORMAT PLAIN ENCODE JSON;
CREATE SINK carrier_kpi_sink FROM carrier_hourly_kpis
WITH (connector = 'jdbc', jdbc.url = 'jdbc:postgresql://analytics-db:5432/logistics', table.name = 'carrier_hourly_kpis',
type = 'upsert', primary_key = 'window_start,carrier_code,service_level');
CREATE SINK schedule_adherence_sink FROM schedule_adherence
WITH (connector = 'iceberg', type = 'append-only', catalog.type = 'rest', catalog.uri = 'http://iceberg-catalog:8181',
database.name = 'logistics', table.name = 'schedule_adherence');
Grafana, the supplier portal, and the port operations center read the status views directly over PostgreSQL. Partition Kafka topics by carrier or region so ingestion parallelizes, keep temporal filters on views that would otherwise grow with history, and build risk views on top of signal views rather than re-aggregating raw events.
Batch Visibility vs Streaming SQL Across the Chain
| Node | Batch practice | Consequence | Streaming SQL (RisingWave) |
|---|---|---|---|
| Shipment delay | Next-morning dashboard | SLA already breached | Alert view on the status change |
| Stockout | Nightly inventory extract | Expedited shipping | Threshold view on every warehouse scan, with units to reorder |
| Supplier quality | Quarterly scorecard | Repeat problem next shipment | Composite score per delivery, joined to delays and stock |
| Dark shipment | Noticed by the customer | Stale dispatch decisions | Ten-minute silence alert |
| Carrier SLA | Monthly scorecard | Thousands of late deliveries | Four-hour on-time rate per carrier and lane |
| Cold chain excursion | Logger downloaded at delivery | Spoiled cargo, liability | Per-reading range check plus stale sensor alert |
| Port coordination | Dashboard every 5 to 15 minutes | Berth and crane delays compound | Live vessel, berth, crane, and gate state |
| Intermodal dwell | Overnight join | Containers stranded for a day | Arrival to next departure per leg, alert at 12 hours |
Frequently Asked Questions
Can RisingWave read the TMS, WMS, and ERP directly instead of through Kafka? Yes, through PostgreSQL and MySQL CDC connectors. The shipments, inventory, and deliveries tables above can be CDC tables with primary keys, and the views are unchanged. Kafka remains the right choice for high-volume telemetry and for fan-out to other consumers.
How do I keep the shipment status view from growing forever?
Add a temporal filter such as shipped_at > NOW() - INTERVAL '30 DAYS' and archive completed shipments to Iceberg through a sink. Windowed views retain state only for open windows plus allowed lateness.
How are late-arriving tracking events handled?
Views are keyed by event time, so a scan that arrives late is attributed to the window it belongs to, and delivery_outcomes picks the latest event per shipment regardless of arrival order. Define a watermark on the source timestamp to bound how long windows wait.
Can mean kinetic temperature be computed in SQL?
The inputs, readings per asset per window, come from temperature_rolling_30min. The exponential formula itself is best in a Python user-defined function or a small service that reads the view and writes the result back as a table for the compliance dashboard.
How do I correlate a port delay with downstream inventory risk?
Join shipment_current_leg on container or booking reference to shipments, then to mv_warehouse_alerts on the destination warehouse and product. A container stuck in port dwell whose destination is already at critical stock is the highest-priority expedite, and it is one view.
