Guide / System design Most asked
Design: ride-hailing (Uber/Ola)
Driver location ingestion, geospatial indexing (geohash, H3), matching one driver to one rider, trip state machine, ETA and surge pricing, and real-time updates.
Ride-hailing combines write-heavy location streams, geospatial search, matching with strict consistency and real-time push.
Fundamentals (the design)#
1. Requirements#
Functional: rider requests a ride; nearby drivers are found and offered the trip; driver accepts; live tracking, ETA and fare; payments; ratings. Non-functional: matching within a few seconds, a driver gets one trip at a time and a trip gets one driver, location freshness of ~4 s, high availability, global scale by city.
2. Estimates#
1M active drivers sending a location every 4 s ≈ 250K writes/s (small, ~100 B each ≈ 25 MB/s). 10M rides/day ≈ 115 rides/s average, peak several times higher. The location stream dominates writes; ride requests are comparatively few but need low latency and correctness.
3. Architecture#
Driver app ──(WebSocket/HTTP every ~4s)──► Location service ──► Redis geo index (current positions)
└──► Kafka → trip history / analytics / ETA models
Rider app ──► API gateway ──► Trip service ──► Matching service ──► query nearby drivers, rank, offer
│ │
▼ ▼
Trip DB (state) Dispatch (push offer → driver app; timeout → next driver)
Pricing/surge service, ETA/routing service (maps), Payment service, Notification service, WebSocket gateway
4. Geospatial indexing#
You need “drivers within 3 km of this point” in milliseconds.
| Method | Idea | Notes |
|---|---|---|
| Geohash | Interleaves lat/long bits into a string; shared prefix means nearby | Simple, works in Redis; edge effects: query the cell and its 8 neighbours |
| H3 (Uber) | Hexagonal hierarchical grid | Uniform neighbour distances, good for surge cells and aggregation |
| Quadtree | Recursively split dense areas | Adaptive density; in-memory structures |
| S2 (Google) | Spherical cells | Used by many mapping systems |
Redis GEOADD / GEOSEARCH | Sorted-set backed geohash | Fast for a city-sized in-memory set of current driver positions |
Design: shard the live location index by city/region (or by H3 cell range); each driver’s latest position is an upsert (not history). Old positions go to Kafka for analytics. Expire drivers that stop reporting (TTL).
5. Matching#
- Rider requests → trip created
REQUESTED(idempotent request ID). - Query candidate drivers in the rider’s cell + neighbours; filter by availability, vehicle type, rating; rank by ETA (road distance via routing service), not straight line, plus fairness and acceptance probability.
- Send an offer to the best driver with a timeout (10–15 s). Accept/decline/timeout → try next (or batch-match across many riders and drivers every couple of seconds using an assignment algorithm for global efficiency).
- Atomic assignment:
UPDATE drivers SET status='ON_TRIP', trip_id=:t WHERE id=:d AND status='AVAILABLE'(compare-and-set) andUPDATE trips SET driver_id=:d, status='MATCHED' WHERE id=:t AND driver_id IS NULL. Only one succeeds; losers retry with another candidate. This guarantees one driver per trip and one trip per driver even with concurrent matchers.
6. Trip state machine#
REQUESTED → MATCHED → DRIVER_ARRIVING → IN_PROGRESS → COMPLETED (or CANCELLED, NO_DRIVER). Transitions are conditional updates and emit events (outbox). Payment is triggered on completion with idempotency (Payment system).
7. Real-time tracking#
Driver positions flow to the rider during a trip through a WebSocket gateway (pub/sub topic per trip); clients reconnect with backoff and resume from the last sequence (Networking). Smooth the map with client-side interpolation and send updates only when position changed meaningfully.
8. ETA, pricing and surge#
ETA from a routing engine (graph shortest path with live traffic) cached by origin-destination cell pairs. Surge: aggregate demand (requests) and supply (available drivers) per H3 cell in a stream job over a sliding window; multiplier = f(demand/supply), smoothed and capped; shown to the rider before confirm and locked for the trip (price quote ID with expiry).
9. Failure handling#
Driver app disconnects mid-offer → timeout and next candidate; matching service crash → trips in REQUESTED are recovered from DB and re-dispatched; location service down → use last known positions with staleness cutoff; region failover with city-level cells; idempotency on trip creation and payment.
Most asked questions#
1. How do you find nearby drivers fast? An in-memory geospatial index (geohash/H3 in Redis) sharded by region, querying the cell and neighbours then ranking by ETA.
2. How do you handle 250K location updates/s? Lightweight updates over persistent connections, upsert into a sharded in-memory store, write history asynchronously to Kafka, batch and compress.
3. How do you guarantee one driver per trip? Atomic compare-and-set on driver and trip state with conditional updates.
4. How is surge pricing computed? Per-cell demand/supply over sliding windows in a stream processor, smoothed multiplier, quoted and locked.
5. How do riders see live driver positions? WebSocket topic per trip with sequence numbers and reconnect/resume.
Senior-level questions#
1. “Matching is greedy per rider and drivers sit idle while riders wait.” Batch matching in short windows with global assignment (Hungarian/min-cost flow approximations), considering ETA and idle time; trades a few seconds of latency for efficiency.
2. “A stadium event creates a hot cell.” Hierarchical cells with adaptive resolution, replicate/shard hot cells, pre-position drivers via incentives, scale the matching shard for that region, rate-limit requests with queueing.
3. “GPS noise causes cars to jump on the map.” Map matching (snap to road network), Kalman or similar smoothing, reject impossible speeds, client interpolation.
4. “Handling a driver accepting two offers at once.” The atomic driver status update ensures only one succeeds; the second receives “no longer available”; offers are serialised per driver.
5. “Design for a city-level outage.” Cell/region isolation, per-city deployment units, failover of control plane but keeping city data local, static fallback behaviours (e.g. allow cash trips), graceful degradation of pricing.
Quiz#
1. Why query neighbouring geohash cells?
Nearby points can lie in adjacent cells across a boundary even if prefixes differ, so querying only one cell misses close drivers.
2. Why rank by road ETA rather than straight distance?
Rivers, one-way streets and traffic make a nearby driver far in travel time.
3. How is double assignment prevented?
Conditional updates on both trip and driver rows (compare-and-set), so only one concurrent matcher wins.
4. What do you store for driver locations in the live index?
Only the latest position per driver (an upsert), with a TTL; history goes to a log/analytics store.
5. What is the advantage of H3 over geohash?
Hexagons have uniform neighbour distances and no extreme edge/pole distortion, making aggregation and neighbour queries more consistent.