Design a ride-sharing service (like Uber)
Design a ride-sharing service like Uber or Lyft: riders request a ride, the system finds a nearby available driver, both see each other's live location, and the trip is priced and paid at the end.
A typical framing: "10 million rides a day across many cities. Drivers send their location every few seconds. A rider should be matched within seconds, a driver must never get two rides at once, and the system must handle rush hour and big events."
TL;DR
The two hard parts are location and matching.
- Location: drivers send GPS updates every ~4 seconds. Keep only the latest position of each available driver in an in-memory geospatial index (geohash, Google's S2 cells or Uber's H3 hexagons), partitioned by city or cell. Write the location stream to a log for trip history and analytics, not to the main database on every ping.
- Matching: query nearby cells for available drivers, rank by ETA (road distance, not straight-line), and offer the ride to one driver with a timeout. Claim the driver atomically (a conditional update or a lock with a TTL) so a driver can't be matched twice.
Trips follow a state machine (requested → matched → driver arriving → in progress → completed, or canceled) in a strongly consistent store. Live tracking during the trip flows over WebSockets or push. Pricing (including surge from supply and demand per area) and payments run as separate services.
1. Requirements and estimates
Functional
- Rider requests a ride (pickup, destination), sees price estimate and ETA.
- System matches a nearby driver; driver accepts or declines.
- Both see live location; trip starts, ends, is priced and paid.
- Ratings and trip history.
Non-functional
- Matching within a few seconds; location freshness within seconds.
- Consistency for trip and driver state (no double assignment); availability for location updates (a dropped ping is fine).
- Scales per city; one city's rush hour doesn't affect others.
Estimates
- 10M rides / day ≈ 120 ride requests per second, peaks several times that.
- 2M active drivers sending a location every 4 s → 500,000 location updates per second. This is the dominant load.
- Latest positions only: 2M drivers × ~100 bytes = 200 MB, easily held in memory, partitioned for throughput.
2. API
POST /v1/rides/estimate { pickup, dropoff } -> { price, surge, etaSec }
POST /v1/rides { pickup, dropoff, estimateId } -> 201 { rideId, status: "requested" }
GET /v1/rides/{id} -> status, driver, positions
POST /v1/rides/{id}/cancel
# Driver app
POST /v1/drivers/me/status { available: true }
WS /v1/drivers/me/stream -> sends { lat, lng, heading, ts } every few seconds
<- receives { type: "offer", rideId, pickup, expiresIn: 15 }
POST /v1/offers/{rideId}/accept
POST /v1/rides/{id}/start | /complete3. Data model
drivers (id, vehicle, rating, status: offline | available | offered | on_trip, city_id, version)
driver_location in-memory geo index: cell_id -> { driverId: (lat, lng, ts) } (latest only)
rides (id, rider_id, driver_id, status, pickup, dropoff, requested_at, price, surge, version)
location_log append-only stream: (driver_id, ts, lat, lng, ride_id?) -> object storage / OLAP4. High-level architecture
5. Deep dives and scaling
The geospatial index
- Geohash encodes a location as a string where a shared prefix means nearby; a nearby search checks the user's cell and its 8 neighbors. Simple, but cells are rectangles of uneven size.
- H3 (Uber) uses hexagons: every neighbor is the same distance away, which makes "drivers within k rings" and surge areas clean. S2 (Google) uses cells on a sphere projection, with good hierarchy.
- Quadtrees adapt to density (small cells downtown, big cells in the countryside) but are harder to update at 500k writes per second.
Store cellId → set of drivers in memory (Redis with geo commands, or a custom service), sharded by city or by cell. On each update, if the driver moved to a new cell, remove them from the old one and add them to the new one.
Location update throughput
500k writes per second is fine for an in-memory index spread across shards, but terrible for a relational database. Only the latest position is needed for matching; the full trail goes to a log (Kafka) for trip reconstruction, fare disputes and analytics. Clients batch updates when the network is poor, and the server drops stale updates (older timestamp than what it has).
Matching without double booking
- Find available drivers in nearby cells (expanding rings until enough candidates).
- Rank by ETA from the routing service: a driver 500 m away across a river can be 15 minutes away.
- Claim the best driver:
UPDATE drivers SET status = 'offered', offer_ride = ? WHERE id = ? AND status = 'available'(or a RedisSET NXwith a TTL). If it fails, someone else got them; try the next. - Send the offer with a timeout (~15 s). On decline or timeout, release the driver and offer to the next candidate.
At very high demand, batch matching (collect requests for a second or two and solve the assignment for all of them) gives better global results than first-come greedy matching.
Trip state machine and consistency
The ride record is the source of truth, updated with conditional transitions (WHERE status = 'matched' AND version = ?). Accept and cancel can race: whichever transition commits first wins, and the other gets a clear error. Payments run after completed, idempotently keyed by ride id.
Surge pricing
Per H3 cell (or zone) and time window, compare open requests with available drivers. When demand exceeds supply, raise a multiplier (with smoothing and caps). The estimate the rider accepted is locked in by estimateId for a few minutes.
Partitioning and failure
Partition almost everything by city: geo index, matching and even ride storage can be regional. A failure in one region stays there. If a location shard fails, drivers re-send their positions within seconds, so the index rebuilds itself.
Common follow-ups
- "Why not just store locations in PostgreSQL with PostGIS?" It's great for queries, but 500k updates per second of constantly changing points would overwhelm it. Keep live positions in memory, history in a log, and use PostGIS for analytics or slower queries.
- "How do you show the car moving smoothly?" The server forwards the driver's updates every few seconds; the rider app interpolates between points and snaps them to the road.
- "What if the driver's app loses connection mid-trip?" The trip continues; the app buffers locations and uploads them on reconnect, so the route and fare can be computed from the full trail.
What interviewers look for
- Estimates showing location updates dominate the load.
- A geospatial index choice (geohash, H3, S2, quadtree) with trade-offs, kept in memory for latest positions only.
- Atomic driver claiming and an offer flow with timeouts.
- A trip state machine in a consistent store, separate from the high-volume location path.
- ETA-based ranking, surge pricing and partitioning by city.