Design a Public Transportation System
0%
Editorial Solution
System requirements
Capacity estimation
Traffic
API design
Database design
High-level design
Request flows
Vehicle location ingestion flow
Detailed component design
RAPTOR: multi-modal trip planning
Trade-offs and tech choices
MQTT vs HTTP for vehicle telemetry
Failure scenarios and bottlenecks
GPS signal loss
Future improvements
Machine learning ETA predictions
Table of Contents
System requirements
Capacity estimation
Traffic
API design
Database design
High-level design
Request flows
Vehicle location ingestion flow
Detailed component design
RAPTOR: multi-modal trip planning
Trade-offs and tech choices
MQTT vs HTTP for vehicle telemetry
Failure scenarios and bottlenecks
GPS signal loss
Future improvements
Machine learning ETA predictions
A public transportation system serves millions of daily riders across buses, trains, and trams. Riders need to know when the next vehicle arrives, how to get from A to B with transfers, how much the trip costs, and whether any disruptions affect their route. Behind the scenes, thousands of vehicles broadcast GPS positions every few seconds, and the system must turn that raw location data into useful, real-time information.
Think about a typical commuter's morning. She opens the app at 7:50 AM, checks when the next bus arrives at her stop (ETA query). It says 3 minutes (live prediction from GPS). She walks to the stop. The bus is running 2 minutes late due to construction (live delay from map matching + historical model). She boards, taps her transit card (fare calculation), rides 15 stops, and transfers to the subway (trip planner computed this route). At the subway entrance, the display board shows her train arriving in 4 minutes (WebSocket-pushed ETA). Everything she touches depends on a real-time system processing thousands of data points per second.
The core challenge is blending two fundamentally different data models: static GTFS schedule data (routes, stops, timetables published weekly by the transit agency) and live GPS telemetry (vehicle positions arriving every 5 seconds over cellular networks). Every feature depends on reconciling these two sources. A trip planner that ignores live data suggests routes on cancelled lines. An ETA display that ignores the schedule has no baseline when GPS drops out in a tunnel. The system must always know both what should be happening (schedule) and what is actually happening (live positions).
Traffic
Start with the vehicles. 5,000 vehicles, each sending a GPS ping every 5 seconds, produces 1,000 pings/sec on average. But not all vehicles are active simultaneously. During off-peak hours (10 PM - 5 AM), only 20% of the fleet operates, dropping ingestion to 200 pings/sec. During morning rush (7-9 AM) and evening rush (5-7 PM), all vehicles are active and many routes run additional service, pushing throughput to 8,000 pings/sec for approximately 4 hours per day. The traffic pattern is sharply bimodal, not uniform.
Now the rider side. 2M daily riders across the network, of whom 500K are DAU on the mobile app (the rest use physical arrival boards or do not check digitally). Each app user generates approximately 5 queries per session (check arrivals at home stop, plan a trip, check arrivals at transfer stop, check return trip, check arrivals going home) = 2.5M queries/day. Queries concentrate during rush hours: peak query load of ~100 requests/sec for ETA lookups and ~30 requests/sec for trip planning.
The API surface serves three audiences with fundamentally different communication patterns: vehicles reporting positions (high-frequency, fire-and-forget), riders querying information (request-response and streaming), and operators managing the network (low-frequency CRUD). Each audience gets the protocol suited to its access pattern.
Vehicle telemetry (MQTT)
Vehicles publish GPS pings over MQTT, a lightweight publish-subscribe protocol designed for constrained devices on unreliable cellular connections. Why MQTT over HTTP? A bus sending a position every 5 seconds would need to establish a new TCP connection 17,280 times per day with HTTP. MQTT maintains one persistent connection for the entire operating day. At 5,000 vehicles, that is the difference between 86 million daily TCP handshakes and 5,000 persistent connections. MQTT also handles cellular dead zones gracefully: when a bus enters a tunnel, the connection drops, but MQTT QoS 1 guarantees that queued messages are delivered after reconnection without application-level retry logic.
This system has four distinct data profiles, each calling for a different storage technology. Using a single database for everything would force compromises that degrade performance across all access patterns.
PostgreSQL: schedule and configuration data (GTFS)
GTFS (General Transit Feed Specification) data is inherently relational: routes have trips, trips have stop_times, stop_times reference stops, fares depend on zones. This data is updated weekly by the transit agency and queried with complex joins during trip planning. PostgreSQL is the natural fit.
The architecture splits into three layers: ingestion (getting GPS data in), processing (turning raw data into useful information), and serving (delivering information to riders and operators). The layers communicate through Kafka, which provides temporal decoupling: each layer processes at its own pace.
Ingestion layer
Let's walk through the five most important flows to see how components interact end to end. Each flow highlights a different architectural pattern: ingestion uses fire-and-forget streaming, trip planning uses synchronous request-response, ETA updates use event-driven pub/sub, alert propagation uses fan-out, and fare taps use latency-critical synchronous lookups.
Vehicle location ingestion flow
This flow runs continuously, processing 1,000 GPS pings per second (8,000 at rush hour). It is the foundation of the entire system: every other feature depends on fresh vehicle positions.
RAPTOR: multi-modal trip planning
RAPTOR (Round-bAsed Public Transit Optimized Router) is the industry-standard algorithm for public transit trip planning. Understanding why RAPTOR exists requires understanding why simpler approaches fail for this problem.
Why not Dijkstra on a graph? The naive approach models every stop as a node and every route segment as a weighted edge, then runs Dijkstra to find the shortest path. Two problems make this impractical for transit:
Every technology choice in this system involves a genuine trade-off. An interviewer who hears "we use Redis because it is fast" will push back. The stronger answer explains what you give up and why the trade-off favors your choice for this specific workload.
MQTT vs HTTP for vehicle telemetry
MQTT wins on three dimensions for this use case. First, a persistent connection eliminates 17,280 daily TCP handshakes per vehicle (one per 5-second ping over an 18-hour operating day). Second, a 2-byte fixed header versus ~500-byte HTTP headers reduces cellular data usage by 98%, which matters for 5,000 vehicles on metered data plans. Third, QoS 1 with session resumption handles tunnel disconnections gracefully: the broker queues messages during the outage and delivers them when the vehicle reconnects, with no application-level retry logic needed.
GPS signal loss
This is not an edge case. Urban transit vehicles lose GPS signal for 5-15% of their route in cities with tunnels, bridges, and urban canyons formed by tall buildings. Consider New York City: the MTA subway system operates mostly underground, and even surface buses lose GPS under the elevated railways in Queens and the Bronx. In London, vehicles entering the Thames Tunnel or the Underground lose signal for minutes. The system must treat GPS gaps as a normal operating mode, not an exceptional failure.
Detection: if no ping arrives from a vehicle for 30 seconds (6 missed pings at the 5-second interval), the Vehicle Tracking Service marks it as stale. After 120 seconds, it escalates to offline. Both states are written to the vehicle's Redis metadata.
Machine learning ETA predictions
The current weighted-average ETA model is interpretable and reliable but cannot capture non-linear feature interactions. A gradient-boosted tree model trained on 2 years of historical position data could incorporate weather (rain adds 15% to travel time on surface routes), local events (a baseball game at 7 PM increases congestion near the stadium by 40% starting at 5:30 PM), school schedules (September weekday mornings have 20% more boarding delay than July), and road construction (ongoing projects that shift traffic patterns for months).
The key is to not replace the current model but to A/B test against it. ML models can overfit to training data and produce confidently wrong predictions for conditions not in the training set (a new holiday, a rare weather event, a route that just changed). Start with the weighted model as the control, deploy the ML model on 5% of routes, and compare mean absolute error over 4 weeks across normal days, weekends, holidays, and disruptions before expanding.
Try this problem yourself
Reading a solution is not the same as producing one under interview pressure. Design it on the whiteboard and get scored feedback.
0%
Editorial Solution
System requirements
Capacity estimation
Traffic
API design
Database design
High-level design
Request flows
Vehicle location ingestion flow
Detailed component design
RAPTOR: multi-modal trip planning
Trade-offs and tech choices
MQTT vs HTTP for vehicle telemetry
Failure scenarios and bottlenecks
GPS signal loss
Future improvements
Machine learning ETA predictions
Table of Contents
System requirements
Capacity estimation
Traffic
API design
Database design
High-level design
Request flows
Vehicle location ingestion flow
Detailed component design
RAPTOR: multi-modal trip planning
Trade-offs and tech choices
MQTT vs HTTP for vehicle telemetry
Failure scenarios and bottlenecks
GPS signal loss
Future improvements
Machine learning ETA predictions