1. Functional requirements
- Get a fare estimate for a pickup and a destination.
- Request a ride on that estimate and get matched with a nearby driver.
- Drivers accept or decline a request and navigate to the pickup.
Below the line: payments, ratings, scheduled rides, pooling, surge pricing, trip history.
Scale: 6M active drivers reporting location every 5 s, about 1M location writes/s; 20M rides a day, about 250 requests/s, 10x at rush hour in one city. Ride requests are cheap. The design is driven by the 1M location writes a second, which must be searchable within seconds.
2. Non-functional requirements
- High throughput for location updates: 1M writes/s
- Matching under a minute end to end
- Consistency for matching: a driver never holds two rides
- No ride request dropped: declines, timeouts and crashes
3. Core entities
- Riders
- Drivers: available | offered | on_trip
- Locations
- Fares
- Rides: requested → accepted → in_progress → completed | cancelled
4. API routes
Auth is a header on all four. The offer and the match arrive by push, not by a route. Simple enough to start; the location route changes store in the first deep dive.
Fare estimate
POST /fares
body: pickup, destination
returns: fareId, price, eta, expiresAt
Request a ride
POST /rides Idempotency-Key: fareId
body: fareId
returns: rideId, status requested
Location heartbeat
POST /drivers/location every 5 s
body: lat, lng
returns: ok
Accept or decline
PATCH /rides/:rideId
body: action accept | decline
returns: status, pickup, destination, or 409
5. High-level design
The simplest system that satisfies the four routes. Two clients, one gateway, a ride service, a matching service, a location service, one database. The deep dives change this picture.
Boxes, drawing order: rider app, driver app · gateway · ride service, matching service, location service · Postgres · Maps API beside ride, push beside matching.
Data model:
Driver id, status
Location driverId, lat, lng, updatedAt
Fare id, riderId, pickup, destination, price, expiresAt
Ride id, riderId, driverId, fareId, status
Postgres, one primary: conditional updates and one transaction for accept, unique on fareId for retries; 250 ride writes/s is nothing. Heartbeats are the one thing that does not belong here, which is the first deep dive.
6. Deep dives
Order in the room: 6.1 must · 6.3 if time · 6.2 and 6.4 one line each, only if asked. Each deep dive opens with three spoken sentences: Problem, Pick, Cost. Everything under them is what you say when the interviewer digs.
6.1 Location updates at 1M writes/s: Redis GEO per cell
Problem. Every heartbeat is an UPDATE on the one database, a million a second, logged and indexed, for a value that is stale five seconds later; one primary does tens of thousands, not a million.
Pick. An in-memory Redis geospatial index, one key per ~40 km cell, written with GEOADD, a 15 s liveness window per driver, spread over a Redis Cluster so the busiest key sees ~10K writes/s; Postgres never sees a heartbeat.
Cost. Positions live only in memory and a lost node refills from heartbeats within one interval; a sweeper per cell to expire drivers, since GEO members cannot expire on their own. Rejected: writing heartbeats to Postgres, because it is both too slow and the wrong durability for data that is stale in seconds.
Draw: a Redis GEO box per cell beside the location service; the arrow from the location service to Postgres goes away.
Flow
- Heartbeat:
POST /drivers/location→ Location service →cell = geohash4(lat, lng)→ one pipeline:GEOADD drivers:{cell} lng lat driverId,ZADD seen:{cell} now+15s driverId. Each cell is its own key, so Redis Cluster spreads cells across nodes and no node sees more than a few busy cities. - TTL: a GEO member cannot expire on its own, so a sweeper per cell runs every 5 s:
ZRANGEBYSCORE seen:{cell} -inf now→ZREMthose ids from both keys. A driver whose app dies is gone from search within 15 s. - Cell change: the service keeps
cell:{driverId}(SET … EX 15); when the new cell differs itZREMs the driver from the old keys first, so a driver is in exactly one cell. Going offline removes the driver at once.
Follow up: 1M writes a second is still a lot of Redis. Can you cut it?
Answer: Report on change, not on a clock: the app sends when it has moved more than 50 m or turned, otherwise every 30 s as a liveness ping, so parked and queued drivers go nearly silent and writes drop by half or more. The server sets the interval per driver state: 5 s on a trip or heading to a pickup, 10 s available and moving, 30 s parked. The seen score becomes now + 3 × interval, so the sweeper threshold follows the interval and two lost heartbeats never drop a live driver. Staleness grows only for drivers who are not moving, which is exactly when it does not matter. If one cell still outgrows its node, key by geohash 5 instead of 4 so the writes spread over more hash slots.
6.2 Nearby drivers: GEOSEARCH, ranked by ETA
Problem. Finding drivers is a bounding-box scan on the database that also takes heartbeats, ranked by straight-line distance, which across a river is the slowest driver.
Pick. GEOSEARCH on the cell’s key, 2 km radius, nearest 10, then one Maps distance-matrix call to rank those 10 by ETA; widen to 5 and 10 km when fewer than 3 remain.
Cost. One external call of about 200 ms on the matching path, the only one; a cell border costs one extra key lookup.
6.3 No double dispatch: a lock per driver
Problem. The matcher reads status = available and pushes an offer, and nothing stops a second request from reading the same row a moment later; two riders get the same driver.
Pick. A Redis lock per driver, SET lock:driver:{id} {rideId} NX EX 10, held while the offer is out, and on accept one Postgres transaction with conditional updates on both the driver row and the ride row; either touching 0 rows is a 409.
Cost. Two stores agreeing, with the database as the last word, and a compare-and-delete on release so a late decline cannot drop a newer ride’s lock. Rejected: a status = offered row in Postgres, because the offer window needs an expiry and Redis gives it for free.
Draw: a lock key in Redis between the matching service and the driver push; the accept path gets a conditional update box in Postgres.
Flow
- Offer: the matcher takes the first candidate and runs
SET lock:driver:{driverId} {rideId} NX EX 10.nilmeans another ride holds this driver → skip to the next candidate;OK→ push the offer with a 10 s countdown. - Accept:
PATCH /rides/:rideId {accept}→ Ride service:GET lock:driver:{driverId}must equalrideId, else 409. Then one transaction:UPDATE driver SET status = 'on_trip' WHERE id = ? AND status = 'available'andUPDATE ride SET driver_id = ?, status = 'accepted' WHERE id = ? AND status = 'requested'; either touches 0 rows → rollback, 409. - After commit:
SET trip:driver:{driverId} {rideId},DEL lock:driver:{driverId}, push the match to the rider. Trip end deletes thetripkey and setsstatus = available. - Decline or timeout: release with a compare-and-delete (Lua:
if GET == rideId then DEL), so a late decline for an old offer cannot drop a newer ride’s lock. The driver is offerable again at once.
Follow up: The driver taps accept and the app loses connectivity. What does each side see?
Answer: Accept is idempotent on rideId, so the app retries the PATCH until it gets an answer. If the first try never arrived, the lock expires at 10 s, the deadline worker (6.4) offers the next driver, and the late accept gets a 409 the app shows as “offer expired”. If it committed, the retry finds ride.driver_id already set to this driver, returns the same accepted ride, and the app resumes navigation. A committed accept with a dead app would strand the rider, so the Ride service watches the heartbeat (6.1): 30 s without one on an accepted ride puts the ride back to requested, the driver to offline, and republishes the request. The rider sees “finding you a new driver”, never a car that is not coming.
6.4 Request to match: one offer at a time
Problem. The ride service calls the matcher inline and offers once; a decline or a silent app leaves the ride requested forever, and a crashed instance drops requests. Pick. The request is durable in Kafka, partitioned by cell; the matcher offers to one driver at a time with a 10 s deadline in a Redis sorted set, moves to the next on decline or timeout, and gives up after 5 offers or 60 s. Cost. Up to 50 s for a ride nobody wants, bounded by giving up, and about a second of latency from the queue. Rejected: broadcasting to the nearest five, because four drivers lose a race they already turned toward.
Final design
Trade-offs, the two to say:
- Redis GEO over Postgres for locations: 1M writes/s only fit in memory, the data is stale in seconds anyway, and a lost node refills itself within one interval.
- A Redis lock with a TTL over a
status = offeredrow: the offer window needs an expiry and Redis gives it for free; the conditional update on accept stays the last word.
Study only, not for the room: full flows for 6.2 and 6.4, and the 6.2 follow-up.
6.2 flow and follow-up
- Search:
GEOSEARCH drivers:{cell} FROMLONLAT lng lat BYRADIUS 2 km ASC COUNT 10 WITHDIST, repeated for each neighbor cell the radius crosses (at most 4 keys), merged nearest first. - Filter: one
MGETover the candidates’lock:driver:{id}andtrip:driver:{id}keys (6.3) drops drivers who are offered or on a trip. Fewer than 3 left → widen to 5 km, then 10 km. - Rank: one Maps API distance-matrix call, 10 origins → the pickup, with traffic; sort by ETA. About 200 ms, and the only external call on the matching path.
- Hand off: the ranked ids become
candidates:{rideId}(Redis list,EXPIRE 300); the offer loop (6.4) pops from it, so a decline needs no second search.
Follow up: How far do you search before giving up?
Answer: The cap is an ETA, not a distance: a rider waits about 15 min, which is ~10 km in a city and more in the suburbs, so rings of 2, 5 and 10 km, then stop. Each ring is one GEOSEARCH per touched cell with COUNT 10, so widening costs microseconds, not a scan. Three empty rings mean supply is the problem, not search: return no drivers nearby within seconds instead of a silent wait, and let the rider retry. The real lever at that point is surge pricing (below the line), which pulls drivers toward the hot area. Dense cities stop at the first ring most of the time, so the wide search is rare and cheap.
6.4 flow
- Request:
POST /rides→ Ride service inserts the ride asrequested(unique onfareId, so a retry returns the samerideId) → publishes{rideId, pickup, cell}to Kafkaride-requests, key = cell →rideId. The rider app waits for the match push. - Offer: the consumer for that cell’s partition searches and ranks (6.2), pops the first of
candidates:{rideId}, locks the driver (6.3), pushes the offer with a 10 s countdown, thenZADD offer_deadline:{cell} now+10s rideIdand commits the offset. - Next: a decline sets the deadline to
now; the same consumer’s worker pollsZRANGEBYSCORE offer_deadline:{cell} -inf nowevery second, releases the lock and repeats step 2 with the next candidate. An empty list triggers one wider search (6.2). - Give up: after 5 offers (
INCR attempts:{rideId}) or 60 s since the request, ride →cancelled, reasonno_drivers, push the rider “no drivers nearby, try again”. An accept (6.3) removes the ride fromoffer_deadline:{cell}and deletes its candidates.