Architecting a Real-Time Car Dispatch Backend
System DesignModel answerLast updated
Design the backend for an on-demand car service: live driver positions, sub-second nearest-driver matching, a reliable trip lifecycle, and no double bookings at city scale.
Build the Backend for an On-Demand Car Service
You are asked to design the server side of a mobile app that connects people who need a car with nearby drivers. The platform must work for a very large user base and react in real time.
What the system must do
- Live driver positions: Each driver's phone reports its GPS location every few seconds. The platform must ingest these reports and use them to show riders which drivers are nearby.
- Dispatch: When a rider asks for a trip, find a suitable close-by available driver and send that driver an offer.
- Trip lifecycle: Track each trip through its states (requested, accepted, in progress, completed) and make sure transitions are applied reliably.
- Load profile: The system must cope with a read-heavy workload (riders looking at the map) and a write-heavy workload (continuous location reports) at the same time.
Scale and quality targets
- Peak load: about 500,000 active drivers and 2 million active riders.
- Finding a driver for a request should complete in under 500 ms.
- Once a driver accepts a trip, that assignment must be consistent everywhere. A driver must never end up committed to two trips.
What your answer should cover
- API design: the endpoints or channels that riders and drivers use.
- Spatial indexing: how you store driver positions and answer "who is near this point?" (for example grid cells, geohashes, quadtrees, or a specialized store).
- Data storage: which databases you choose for trips, user profiles, and live location data, and why.
- Architecture: the main components and message flow, including load balancers, caching, and publish/subscribe messaging.
- Trade-offs: how consistency, availability, and partition tolerance apply to location data versus driver assignment.
Start with back-of-the-envelope numbers and state any assumptions you make.
Hints
Hint 1
Do the arithmetic first: 500K drivers reporting every ~4 seconds is about 125K writes/s, and the whole live map is only on the order of 100 MB. Ask what that implies about where live data should be kept and why you would still shard.
Hint 2
Split the system into two workloads with different needs: a huge, short-lived, loss-tolerant stream of locations, and a small, durable, strongly consistent stream of trips and assignments. Choose storage and consistency separately for each.
Hint 3
To prevent double assignment, think of a temporary reservation on the driver with a timeout, followed by a conditional (versioned or compare-and-set) write that moves the driver to busy and the trip to accepted in one atomic step.
Hint 4
For the spatial index, think about what happens at cell borders: a query must cover neighboring cells, not just the one containing the pickup point. Also consider how a very dense downtown cell would be handled.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Scale estimates and framing
- Location writes: 500K drivers / 4 s gives about 125K writes/s, roughly 12 MB/s at ~100 bytes each.
- Live state size: 500K x ~200 B is about 100 MB. It fits on one machine, so we shard for throughput, fault isolation, and locality, not capacity.
- Nearby-driver reads: 2M riders refreshing every ~5 s gives about 400K reads/s. These tolerate a few seconds of staleness.
- Trip requests: about 1-5K/s at peak, each needing strong consistency.
The central idea is two separate pipelines:
- Location pipeline: high volume, ephemeral, favors availability (AP).
- Trip and assignment pipeline: low volume, durable, favors consistency (CP).
Out of scope: payments, pricing, and routing internals (treated as dependencies).
2. APIs
Driver side
- A persistent WebSocket
/v1/drivers/stream: the driver sends{lat, lng, heading, ts}every ~4 s, and the server pushes trip offers down the same channel. POST /v1/drivers/{id}/statuswithavailableoroffline.POST /v1/trips/{id}/accept,/decline,/start,/complete.
Rider side
GET /v1/drivers/nearby?lat=&lng=&radius=returns approximate positions.POST /v1/tripswith{pickup, dropoff, product}and anIdempotency-Keyheader. It returns a trip ID in stateREQUESTEDimmediately.GET /v1/trips/{id}or a socket subscription for updates;POST /v1/trips/{id}/cancel.
WebSockets avoid per-request HTTP overhead at 125K msgs/s and give a push channel for offers. Idempotency keys make client retries safe on unreliable mobile networks.
3. Spatial index
Use a hierarchical cell system such as S2 or H3 (for example S2 level ~12, a few km² per cell). Maintain two in-memory maps:
cellId -> set of driverIdsdriverId -> {lat, lng, cellId, status, ts}
Update: compute the new cell; if it changed, move the driver between sets. O(1).
Query: cover a circle around the pickup with 4-9 cells, union their drivers, filter on available and freshness (for example last update under 15 s old), rank by straight-line distance, then re-rank the top ~10 by road-based ETA.
Sharding: by city or region first, then by cell range inside very large cities. Neighbor lookups rarely cross shards. Hot downtown cells can be split to a finer level.
Alternatives: Redis GEO (geohash in a sorted set, GEOSEARCH) works well, but you must query neighboring prefixes because close points can have different geohash prefixes. Quadtrees adapt to density but are harder to rebalance when everything moves constantly; fixed cell IDs make sharding and caching simpler.
4. Storage
| Data | Store | Reason |
|---|---|---|
| Live locations/status | In-memory index (Redis Cluster or custom service) | High write rate, ephemeral, ms reads |
| Location history | Kafka, then Cassandra or object storage | Append-only; analytics, ETA models, disputes |
| Trips | Relational (Postgres sharded by city, or a distributed SQL store) | State machine, transactions, conditional updates |
| Profiles | Relational/document store plus read cache | Low write rate, read-heavy |
Trip row: trip_id, rider_id, driver_id, state, pickup, dropoff, fare, timestamps, version.
Driver assignment row: driver_id, status, current_trip_id, version. This row is the single source of truth for "is this driver busy?".
5. Architecture and request flow
Components: API gateway / L7 load balancer for riders; a WebSocket gateway fleet for drivers; Kafka topic driver-locations keyed by city; a Location Service (in-memory index, sharded); a Dispatch Service; a Trip Service backed by the trips database; and a change-data-capture stream into a trip-events topic feeding notifications, billing, and surge logic.
Flow:
- The rider calls
POST /trips; the Trip Service storesREQUESTEDand emits an event. - Dispatch asks the Location Service for candidates (~10-50 ms) and ranks them by ETA.
- Dispatch reserves the best driver atomically (a short-TTL lock) and pushes an offer via the WS gateway with a 10-15 s timeout.
- On accept, a conditional transaction sets the trip to
ACCEPTEDand the driver toON_TRIPonly if the driver is still reserved for this trip (version check). On decline or timeout, release the reservation and try the next candidate. - State changes fan out through Kafka to the rider's socket, push notifications, and billing.
Push vs. pull: push for offers, since polling by hundreds of thousands of drivers adds load and seconds of delay. Keep pull as a reconnect fallback (fetch pending offers). Offer to one driver at a time, or a small batch with first-accept-wins enforced by the reservation.
Caching: cache nearby-driver responses per cell for 1-2 s. Riders in the same area share a result, absorbing most of the 400K reads/s. Snap or jitter displayed positions to protect driver privacy.
6. CAP trade-offs
- Locations and nearby views: AP. Slightly stale positions are harmless. A crashed shard can rebuild from incoming updates within about one reporting interval, so heavy replication is unnecessary.
- Assignment: CP. Double-assigning a driver strands a rider. During a partition, prefer refusing or delaying a match over risking two trips for one driver. Keep the assignment write in a single consistent partition (by driver or city) with a strongly consistent store.
7. Common mistakes
- Putting location updates through the transactional database (125K writes/s is unnecessary durability cost).
- Forgetting neighbor cells at borders, causing missed nearby drivers.
- Relying on "check then write" without an atomic conditional update, which allows races and double assignment.
- Not handling driver offer timeouts, app disconnects, or duplicate requests (no idempotency).
- Ignoring hot spots such as airports or events at cell boundaries.
- Cross-region matching that needs distributed transactions; keep each city self-contained.
8. Follow-ups to be ready for
Surge pricing from per-cell supply/demand counters, batched matching to optimize globally rather than greedily, multi-region failover for a city, and how to degrade gracefully (serve cached nearby views, queue requests) when the Location Service is overloaded.