A ride-hailing app lets a rider tap one button and have a nearby driver on the way within seconds. Behind that tap, millions of phones report their GPS position every few seconds, the system finds the closest free drivers, offers the ride to one of them, makes sure two riders never get the same driver, and then keeps both people updated until the trip ends and the card is charged. This lesson is hard for a specific reason: the load is not "lots of reads". It is a constant firehose of tiny location writes plus a matching step that must be correct under races. We follow the eight-step interview framework and spend most of the deep dive on location ingestion, the geospatial index, and dispatch.
Detailed Notes
How to use this lesson
Treat this as a 45-minute interview. The numbers are assumptions you state out loud, not facts about any real company. The interviewer checks that your estimates drive your design, and that you can explain the two hard parts: finding nearby drivers fast, and assigning a driver to exactly one rider.
Step 1: Clarify Requirements
Open with: "Before I design, I'd like to agree on what the rider and driver can do, how big the system is, and what I can leave out."
Functional requirements
A rider enters a pickup and a destination and sees a fare estimate and an arrival time.
A rider requests a ride. The system finds a nearby available driver and offers the ride.
A driver can go online or offline, and while online reports their location continuously.
A driver can accept or decline an offer.
Rider and driver see each other's live location and the ride status (driver coming, driver arrived, trip started, trip finished).
Either side can cancel under defined rules.
At the end of the trip the rider is charged and both sides can see the trip history.
Extended requirements
Mention these and ask whether to include them. Do not design them unless asked.
Surge pricing: a higher price multiplier when demand is higher than supply in an area.
Ride types: economy, XL, shared rides (pooling several riders into one car).
Fast matching: after a rider requests a ride, the first driver offer should go out in under 1 second at p99 (99 of 100 requests faster than that), and a driver should be found within 10 to 15 seconds for most requests.
Fresh locations: the position used for matching should be less than 5 seconds old. A driver shown 30 seconds ago at the wrong corner is useless.
High availability: 99.99% for request, match and trip tracking (about 52 minutes of downtime a year). A rider stranded mid-trip is the worst outcome.
Correctness of assignment: a driver is never assigned two rides at once, and a ride never has two drivers. This is a hard guarantee, not a best effort.
Scalability: millions of drivers online and hundreds of ride requests per second globally, with local spikes (a stadium emptying).
Durability for money and trips: once a ride is accepted or a payment is taken, we must not lose or double-charge it.
Consistency decision. Driver locations can be slightly stale and lost occasionally, so we use eventual consistency and keep them in memory. Ride state and payments must be strongly consistent, so we use a database with transactions. Saying "different data, different guarantees" early shows maturity.
Out of scope
Map rendering, turn-by-turn navigation, driver onboarding and background checks, in-app chat, pooled rides, and the machine-learning models behind pricing and ETA. We will treat routing and ETA as a service we call.
Interview tip. Weak candidates start with "I'll store drivers in a database and query by latitude and longitude." Interviewers want you to notice early that location updates are a write-heavy stream that a normal database should not absorb directly.
Step 2: Estimate Scale
Back-of-the-envelope estimation means rough calculations that show which part of the system will be hard. Round everything so the arithmetic can be done aloud.
Assumptions to state
20 million rides per day worldwide.
3 million drivers online at the busiest time of day.
Each online driver sends a GPS update every 4 seconds.
One location update is about 100 bytes (driver id, latitude, longitude, heading, speed, timestamp, status).
An average trip lasts 20 minutes, which is 1,200 seconds.
A day has about 100,000 seconds (the real value is 86,400, but 100,000 makes mental math easy).
Peak traffic is 3x the average.
Ride request load
text
20M rides / 100,000 seconds = 200 rides per second (average)
200 rides x 3 peak factor = 600 ride requests per second at peak
600 requests per second is small by internet standards. A handful of servers could take the HTTP traffic. So what: the ride request path is not about raw volume. It is about correctness and latency of matching.
Driver location update load
text
3M online drivers / 4 seconds = 750,000 location updates per second
750,000 x 100 bytes = 75 MB per second incoming
This is the real load: 750,000 writes per second is 1,250 times the 600 ride requests per second. Few relational databases take that on durable disk writes without heavy sharding, and the data is worthless after a few seconds anyway. So what: location updates must go into an in-memory store that keeps only the latest position per driver. We do not write each update to a disk database.
Storage
text
Live driver positions: 3M drivers x 100 bytes = 300 MB (fits in memory)
Trip trail (GPS points kept only during trips):
20 min x 60 s / 4 s per point = 300 points per trip
20M trips x 300 points = 6 billion points per day
6 billion x 100 bytes = 600 GB per day
600 GB x 30 days = 18 TB hot, older data archived
Ride records: 20M rides x 1 KB = 20 GB per day = about 7 TB per year
The live position set is tiny (300 MB), so the "current location" index is cheap to hold in memory. The trail is the only big data set, and it is append-only, so it belongs in cheap, write-friendly storage. So what: two stores with different jobs: a small in-memory store for "where is everyone now", and an append-only store for history.
Real-time connections
text
Concurrent trips (Little's law idea): 200 rides/s x 1,200 s = 240,000 active trips
Connections: 3M drivers + 240K riders = about 3.3M open connections
One gateway holds about 50,000 connections = about 70 gateway servers (100+ with headroom)
Pushes to riders: 240K riders / 4 s = about 60,000 pushes per second
A WebSocket is a long-lived two-way connection between app and server, so the server can push data without the client asking. So what: we need a fleet of gateways that hold persistent connections, and they must be stateless enough to be replaced.
Uber: Estimate the ScaleEstimation
Request load
20Mrides / day
given
200/srides (average)
÷ 100,000 s
600/srides at peak
× 3 peak factor
3Mdrivers online at peak
given
750K/slocation updates
÷ 4 s interval
Location updates
750K/s
3M drivers ÷ 4 s, about 75 MB/s at 100 bytes each
Keep only latest positions in memory
Ride requests
200/s avg
20M ÷ 100,000 s, 600/s at peak
Volume is small; focus on correctness
Storage
300 MB live
3M × 100 B live; 6B trail points = 600 GB/day
Memory for live, append-only store for trails
Matching latency
< 1 s
600 searches/s × 7 cells = 4,200 lookups/s
Cheap if the index is cell-based and in memory
Key point. Location writes dwarf ride requests by more than 1,000 to 1. Matching is a correctness problem, not a volume problem.
Ride requests are few, but every online driver reports a location every 4 seconds.
Matching work
text
600 requests/s at peak x 7 cells searched = about 4,200 cell lookups per second
Candidates per request after filtering = about 10 drivers
ETA lookups for the shortlist: 600 x 10 = about 6,000 per second
Both numbers are modest. So what: matching is not CPU-bound. The challenge is doing it in a few hundred milliseconds with fresh data, and doing it without assigning one driver twice.
Interview tip. State the verdict for each number: "750K writes per second means in-memory, not disk", "600 rides per second is small, so correctness matters more than throughput", "300 MB of live positions means one shard per city is easily enough."
Step 3: Define the APIs
An API is the contract between clients and the service. Riders and drivers use different endpoints. Most frequent traffic (locations and live updates) uses a persistent WebSocket instead of one HTTP call per message.
201 Created with status REQUESTED. Matching continues asynchronously and the result arrives over the WebSocket.
400 Bad Request for an invalid location or ride type.
402 Payment Required if the payment method fails validation.
409 Conflict if the rider already has an active ride.
410 Gone if the fare quote expired.
429 Too Many Requests if the rider is spamming requests.
Idempotency. An idempotent operation can be repeated safely with the same result. A rider on a weak connection may retry. The Idempotency-Key header makes the server return the first ride instead of creating a second.
Ride lifecycle
http
GET /v1/rides/{ride_id} # current status, driver, ETA
POST /v1/rides/{ride_id}/cancel # 200, or 409 if already in progress
POST /v1/rides/{ride_id}/arrived # driver: reached pickup
POST /v1/rides/{ride_id}/start # driver: rider is in the car
POST /v1/rides/{ride_id}/complete # driver: trip finished
Driver APIs
http
POST /v1/drivers/me/status # { "status": "ONLINE" | "OFFLINE" }
POST /v1/offers/{offer_id}/accept # 200, 409 if taken, 410 if the offer expired
POST /v1/offers/{offer_id}/decline # 200
Real-time channel
json
// driver to server, every 4 seconds over the WebSocket{"type":"location","lat":37.7751,"lng":-122.4183,"heading":90,"speed":8.3,"ts":1772359500}// server to driver{"type":"offer","offer_id":"o_77","ride_id":"r_01HX9Q","pickup":{"lat":37.7749,"lng":-122.4194},"expires_in":10}// server to rider{"type":"driver_location","ride_id":"r_01HX9Q","lat":37.7760,"lng":-122.4170,"eta_seconds":180}{"type":"status","ride_id":"r_01HX9Q","status":"ARRIVED"}
Why a WebSocket and not HTTP? From the real-time lesson: polling would mean 750,000 new HTTP requests with headers every second, while a WebSocket sends a small frame over a connection that is already open. It also lets the server push offers to drivers instantly.
Interview discussion. "Driver location updates go over a persistent connection because they are small and frequent. Ride creation, accept and cancel are normal HTTP calls with idempotency keys, because they change state and may be retried."
Step 4: Define the Data Model
Start from access patterns. We have two very different kinds of data.
Hot, ephemeral data (live driver locations):
Upsert the latest position of a driver (750K per second).
Find available drivers near a point (about 4,200 cell lookups per second).
Forget drivers that stopped reporting.
Durable data (trips, payments, history):
Create a ride and move it through states safely, with no lost updates.
Look up a ride by id and a rider's or driver's recent rides.
Store the GPS trail of each trip for receipts, disputes and analytics.
Record each payment exactly once.
Fields and why each exists
rides.status: where the ride is in its life cycle. The most important field; every update is a conditional update on it.
rides.version: a counter incremented on every change, so concurrent writers cannot silently overwrite each other (optimistic concurrency).
rides.pickup_cell / city_id: which shard and which cell this ride belongs to, so dispatch can run per city.
rides.fare_estimate and surge_multiplier: locked at request time so the price shown is the price charged.
rides.driver_id: null until a driver accepts. The conditional update that sets it is how we avoid two drivers on one ride.
driver_location.cell_id: which geographic cell the driver is in, derived from latitude and longitude, used to find neighbours quickly.
driver_location.status: AVAILABLE, OFFERED, ON_TRIP. Matching only considers AVAILABLE.
payments.idempotency_key: unique per ride so a retried charge cannot charge twice.
trip_locations: one row per GPS point, partitioned by ride_id, sorted by time.
The Data ModelData model
driver_locationIn-memory store (TTL 15 s)
PKdriver_iduuid
one record per online driver
lat, lngfloat, float
latest GPS position
IDXcell_iduint64
H3-style cell; indexes the cell set
statusAVAILABLE | OFFERED | ON_TRIP
only AVAILABLE is matchable
updated_attimestamp
score in the cell sorted set
Overwritten every 4 seconds; expires if the phone goes silent.
ridesRelational DB (sharded by city)
PKride_idbigint
time-sortable id, includes city
FKrider_iduuid
who asked for the ride
FKdriver_iduuid
null until accepted
IDXstatusenum
state machine position
versionint
optimistic concurrency counter
pickup, dropofflat/lng pairs
pickup_celluint64
drives dispatch region
fare_estimate, surgeint, decimal
locked at request time
requested_attimestamp
Accept is UPDATE ... WHERE status = 'REQUESTED', so only one driver can win.
trip_locationsAppend-only store
PKride_idbigint
partition key
SKtstimestamp
sort key: points in time order
lat, lngfloat, float
About 300 points per trip; written in batches off the hot path.
paymentsRelational DB
PKpayment_iduuid
FKride_idbigint
UQidempotency_keyvarchar
makes retries safe
amountint
minor units (cents)
statuspending | paid | failed
Unique key per ride means a retry can never create a second charge.
Key point. Every ride change is a conditional update on status. That is how the system stays correct under races.
Live locations are ephemeral and in memory. Rides and payments are durable and transactional.
Which databases?
Live locations: in-memory key-value store (like Redis). Access is by driver id and by cell, the data fits in 300 MB, and it expires by itself. We explain the structure in the deep dive.
Rides and payments: relational database, sharded by city. A trip changes state with conditional updates (WHERE status = 'REQUESTED'), and payments need transactions. A relational database gives both. At 7 TB per year, a few shards per region are plenty. A key-value store with conditional writes would also work; what matters is that you need atomic compare-and-set on a single ride.
Trip trail: append-only, wide-column or time-series store, backed by object storage for old data. 600 GB per day of writes keyed by ride and time fits the log-structured write pattern from the indexing lesson.
Trade-off thinking. Putting everything in one database is simpler to operate, but the location stream would drown the transactional data. Splitting stores by access pattern costs more components, and gives each store the guarantees it actually needs.
Step 5: High-Level Design
Separate three jobs with different shapes: tracking (huge volume of tiny writes), matching (small volume, needs correctness) and trip management (small volume, durable).
High-Level ArchitectureArchitecture
Key point. Location data is huge and disposable. Ride data is small and precious. They get different stores.
Tracking, matching and trip management are separate services with separate stores.
Components and why each exists
Gateway fleet (WebSocket + REST): terminates TLS, authenticates, holds the long-lived connections for riders and drivers, and routes messages. It is stateless apart from the connection itself, so a dead gateway only means clients reconnect to another.
Location service: receives driver updates, validates them, computes the geographic cell, and updates the location store. It scales horizontally with the number of drivers.
Location store: in-memory, holds the latest position per driver and a per-cell index of drivers. It answers "who is near here?".
Dispatch (matching) service: takes a ride request, queries nearby drivers, ranks them, offers the ride, and handles accept, decline and timeout.
Ride service and Ride DB: the source of truth for ride state and the state machine.
Pricing and ETA service: computes fare estimates, surge multipliers and travel time from a road network with live traffic.
Payment service: charges the rider when a trip completes. Treated as separate because it talks to external card processors.
Request flow
The driver app sends a location every 4 seconds over its WebSocket. The gateway forwards it to the location service, which updates the in-memory store.
The rider requests a ride. The ride service creates a REQUESTED ride in the database and hands it to dispatch.
Dispatch searches nearby cells, picks the best candidate, claims that driver atomically, and sends the offer through the driver's gateway.
The driver accepts. The ride service moves the ride to ACCEPTED only if it is still REQUESTED. The rider is told through their WebSocket.
During the trip, driver locations flow to the rider's screen. At completion, a payment is created exactly once.
From Ride Request to Driver AssignedRequest flow
Rider appDispatchLocation storeDriver app1request rideride saved as REQUESTED2drivers in 7 cells312 candidatesrank by ETA, keep top 104claim driverAVAILABLE to OFFERED, atomic, 15 s lease5offer (10 s)6acceptUPDATE ... WHERE status = REQUESTED7driver assigned + ETA
Key point. If the driver declines or the offer times out, dispatch releases the claim and tries the next candidate.
The claim protects the driver. The conditional update on accept protects the ride.
Step 6: Deep Dive
Interviewers usually pick one of three: finding nearby drivers, matching without double assignment, or how location updates survive the load. We cover each, then the supporting parts.
6.1 Driver location ingestion
Every 4 seconds each of 3 million phones sends a position. That is 750,000 messages per second, and we must not write them to a normal disk database.
Location Ingestion PathArchitecture
Driver appevery 4 sGatewayWebSocketLocationservicevalidate, cell idLocation storelatest, TTL 15 sRider pushonly if on tripTrail queuedurable logRider appmoving dotTrail storeappend-onlylat, lngupsertif on tripbatch write
Key point. Losing one update is harmless because the next arrives in 4 seconds, so we never block on disk.
Every update takes the fast path into memory. Trip history is written off the critical path.
Phones batch nothing but stay light. Each message is about 100 bytes. The app sends less often when the driver is stationary or offline, and more often during a trip (a 4 second period is a reasonable compromise between battery and freshness).
Gateway to location service by driver id. Messages from one driver are routed to the same location-service instance (or shard), so updates arrive in order and there is no write race on one driver.
Reject bad data. Drop updates with an old timestamp (out-of-order delivery) or an impossible jump (speed above 200 km/h), which protects against GPS glitches and spoofing.
Latest position only. The location store overwrites the previous position. We never keep history here.
Archive trips asynchronously. If the driver is on a trip, the same message is also appended to a durable log (a message queue: a buffer producers append to and consumers read from later). A consumer writes the points to the trail store in batches. If that pipeline lags, matching and live tracking are unaffected.
Push to the rider. If the driver is on a trip, the location service also forwards the update to the rider's gateway, which pushes it down the rider's WebSocket (60,000 pushes per second across all trips).
Trade-off thinking. We accept losing a few location updates, since the next one arrives 4 seconds later. That is exactly why in-memory and eventual consistency are the right choices here. Losing a payment, in contrast, is never acceptable.
6.2 Finding nearby drivers: the geospatial index
"Find the 10 closest available drivers to this point" cannot be answered by scanning 3 million rows, and a normal index on latitude and a separate index on longitude do not help much (two range filters in two dimensions). The standard idea is to cut the map into cells, give each cell an id, and keep a list of drivers per cell. Then "nearby" means "the rider's cell plus its neighbour cells".
Three Ways to Index LocationsComparison
Geohash
square cells, string ids
1
Encode lat/lng as a string
6 chars = about 1.2 × 0.6 km
2
Look up that cell
map or prefix scan
3
Add the 8 neighbours
edges can split close points
4
Filter by distance
rank the survivors
Easy to store in any database
Prefix scans work
Edge effect needs 9-cell search
Corner neighbours are farther
Good and simple, widely known
Quadtree
tree that splits when dense
1
Start with the whole map
one root rectangle
2
Split into 4 at 100+ drivers
dense areas go deeper
3
Walk down to the leaf
then check adjacent leaves
4
Rebalance on moves
split and merge nodes
Adapts to uneven density
Few drivers per leaf
Pointer tree in one machine's memory
Moves cost tree updates
Strong for static or uneven data, harder to shard
H3-style cells
hexagons, 64-bit ids
1
Pick a resolution
edge about 460 m
2
cell_id(lat, lng)
constant time
3
Cell + ring 1 = 7 cells
ring 2 = 19 cells
4
Move = remove and add
to a hash map of cells
Equal distance to all neighbours
Trivial to shard by cell
Fixed size, tune per city
Needs a library
Our pick for the live index
Key point. Fixed cells in a hash map are simplest to update and shard. Quadtrees adapt to density but are harder to distribute.
All three answer 'who is near this point' by looking at a cell and its neighbours.
Geohash. A geohash converts latitude and longitude into a short string by repeatedly halving the world. Each extra character makes the cell smaller. A 6-character geohash is a cell about 1.2 km by 0.6 km. Nearby places share a prefix, so a database prefix scan or an in-memory map keyed by the string works. Pitfall: two points very close to each other can lie on opposite sides of a cell edge and have completely different geohashes, so you must always search the cell and its 8 neighbours.
Quadtree. A quadtree is a tree where each node covers a rectangle and splits into 4 children when it holds too many drivers (for example more than 100). Dense downtown areas become deep trees with small cells, empty areas stay coarse. It adapts to density, which is its strength. The cost is that it is a pointer-based structure in one machine's memory, so moves must update the tree and sharing it across servers is harder.
H3-style hexagonal cells. Uber open-sourced a system called H3 that divides the globe into hexagons at fixed resolutions. Every neighbour of a hexagon is the same distance from its centre, which makes "within about 2 km" much cleaner than with squares (squares have corner neighbours that are farther). A cell id is just a 64-bit number. At a resolution where a cell has an edge of about 460 m, the cell plus its first ring is 7 cells, and the second ring takes it to 19 cells.
What we choose. Fixed cells in a hash map win for a live location index: the cell id is computed from latitude and longitude in microseconds, a move is "remove from old cell, add to new cell", and sharding by cell id is trivial. We use H3-style cells (a geohash gives the same design with square cells and 9 neighbours). A quadtree is a strong answer if the interviewer pushes on very uneven density, but we can also handle density by choosing a finer resolution in dense cities.
Nearby search.
text
1. cell = cell_id(rider.lat, rider.lng) // one cell id
2. cells = cell + ring 1 // 7 cells
3. candidates = drivers in those cells with status AVAILABLE and updated in the last 15 s
4. if fewer than 5 candidates, widen to ring 2 (19 cells), then ring 3
5. sort by straight-line distance, keep the closest 10
6. ask the ETA service for real driving time for those 10, then re-rank
Why two distance steps? Straight-line distance is cheap and removes most drivers. Road distance is accurate but expensive, so we only compute it for a shortlist. A driver 300 m away across a river can be 15 minutes by road.
6.3 The in-memory location store
A key-value store such as Redis has two structures we need.
text
driver:{driver_id} -> { lat, lng, cell_id, status, heading, updated_at } (TTL 15 s)
cell:{cell_id} -> sorted set of driver_id, score = last update time
On each location update the service does:
Read the driver's old cell_id from driver:{id}.
If the cell changed, remove the driver from the old cell set.
Add the driver to the new cell set with the current time as the score.
Write the driver:{id} record and reset its TTL (time to live, a timer after which the key deletes itself) to 15 seconds.
The steps are one script executed atomically on the store, so a crash cannot leave a driver in two cells.
Why TTL? If a driver's phone dies or loses signal, no one tells us. The driver:{id} key simply expires after 15 seconds (about 3 missed updates). A key's TTL cannot remove a member from a set, so when reading a cell we only take members whose score is within the last 15 seconds, and a background sweeper trims old members. A driver who vanished is automatically excluded from matching without any explicit "logout" event.
Sizing and replication. 300 MB of live data, but 750,000 writes per second, so it is the write rate that forces us to partition. Each city (or group of cells) is its own shard. Each shard has a replica for failover; if a shard loses all its data, drivers repopulate it within 4 seconds as they send their next update. That is an unusual and nice property: the location store is self-healing, because its entire content is re-sent by the phones.
6.4 Matching and dispatch
Dispatch decides which driver gets which ride. The danger is a race condition (two actions interleaving with a wrong result): at a stadium two riders request at once, both searches pick the same closest driver, and both offer the ride to that driver. Without protection, that driver is offered two rides, or worse, both accepted.
We need two guarantees:
A driver has at most one active offer or ride.
A ride has at most one driver.
Two Layers That Prevent Double AssignmentComparison
Naive matching
check, then offer
1
Dispatch A reads driver D
status AVAILABLE
2
Dispatch B reads driver D
also AVAILABLE
3
Both send an offer to D
two riders, one driver
4
D accepts both?
one rider is stranded
Race between read and offer
Stranded rider, angry driver
Never check and act in two steps
Claim, then accept
two atomic operations
1
Atomic claim on driver
AVAILABLE to OFFERED, one winner
2
Loser tries next driver
claim failed, no offer sent
3
Offer with 10 s timeout
claim lease 15 s
4
Conditional update on ride
WHERE status = REQUESTED
Exactly one winner per driver and per ride
Crash safe: leases expire
Needs an atomic operation in the store
Correct under races and crashes
Key point. Atomic claim on the driver, conditional update on the ride. Leases make both safe if a worker crashes.
Naive matching lets two dispatchers pick the same driver. We guard the driver and the ride separately.
Step A: claim the driver before offering. Before sending an offer, dispatch performs an atomic claim on the driver: set status from AVAILABLE to OFFERED and attach the ride id, in one compare-and-set operation on the location store (for example a script that checks status == AVAILABLE and sets OFFERED with a 15-second expiry). If two dispatchers race, exactly one wins. The loser sees the claim fail and immediately tries the next driver on its list. A lock with a lease (a lock that expires on its own) is the same idea: the claim expires after 15 seconds, so a dispatch crash cannot leave a driver stuck forever.
Step B: send the offer with a timeout. The offer is pushed to the driver over the WebSocket with a 10-second countdown. The offer record stores expires_at.
Step C: handle the response.
Accept: the ride service runs a conditional update: UPDATE rides SET driver_id = ?, status = 'ACCEPTED' WHERE ride_id = ? AND status = 'REQUESTED'. If the row changed, we have a match. If it did not (rider cancelled, or another driver already took it), the driver gets 409.
Decline or timeout: release the claim (status back to AVAILABLE) and try the next candidate. After about 3 to 5 failed offers or 30 seconds, widen the search ring or tell the rider no cars are available (EXPIRED).
Step A protects the driver, step C protects the ride. Using both means a bug in one layer does not lead to double assignment.
Which driver is best? Rank by estimated time to pickup first, because that is what the rider feels. Break ties with other signals such as driver rating, acceptance rate, and whether the driver is heading toward the pickup. Offer to one driver at a time (sequential). Offering to several at once is faster but wastes driver attention and makes "first to accept wins" logic harder, so a common compromise is sequential offers with short timeouts.
Interview discussion. "I make the claim on the driver atomic in the location store, then make the acceptance a conditional update on the ride row. The claim has a lease so a crashed dispatcher can't strand a driver, and the conditional update means even a duplicate accept can't create a second assignment."
6.5 Ride state machine
A state machine lists the allowed states of a ride and the only legal moves between them. It stops impossible things, like completing a ride that was never started or cancelling after the trip finished.
Ride State MachineArchitecture
REQUESTEDsearchingEXPIREDno driver foundACCEPTEDdriver on the wayARRIVEDat pickupCANCELLEDfee may applyIN_PROGRESStrip runningCOMPLETEDtrip finishedPaymentidempotent chargetimeoutacceptcancelno-showstartcompleteoutbox
Key point. States are written to the ride event log, which gives an audit trail and a replay for disputes.
Every arrow is a conditional update on the current status. Illegal moves are rejected.
Legal transitions:
REQUESTED to ACCEPTED (a driver accepted), EXPIRED (no driver found) or CANCELLED (rider cancelled).
ACCEPTED to ARRIVED (driver at pickup) or CANCELLED (rider or driver cancels; a fee may apply).
ARRIVED to IN_PROGRESS (rider got in) or CANCELLED (rider no-show).
IN_PROGRESS to COMPLETED. Cancelling mid-trip is handled as a special case that ends the trip at the current location.
COMPLETED triggers payment. PAID (or PAYMENT_FAILED) is tracked on the payment record, not by reopening the ride.
Every transition is a conditional update on the current status (and version), and every transition is written to a ride event log. The log gives an audit trail for disputes and lets us replay what happened.
6.6 ETA and pricing (high level)
ETA. Routing needs a road graph (intersections as nodes, roads as edges with travel times) and live traffic. A routing service runs shortest-path searches over it. For the hot, repeated queries (for example popular airport trips) we cache results by cell pair. We call this as a black box in the interview and mention that it is cached and approximate.
Surge pricing. For every cell (or cluster of cells) the pricing service tracks, over a sliding window of one to two minutes:
text
demand = ride requests in the cell
supply = available drivers in the cell
ratio = demand / supply
multiplier = bucket(ratio), for example 1.0, 1.2, 1.5, 2.0, capped at 3.0
Smooth the multiplier over time so the price does not flicker, and quote it to the rider in the fare estimate, then lock it into the ride record. That way the price shown is the price charged. Surge also pulls supply toward busy areas because drivers see the higher earnings.
6.7 Real-time updates to riders
Every active trip gives the rider two things: the ride status and the driver's moving dot. Both travel through the rider's WebSocket.
A status change (accepted, arrived, started) is published by the ride service to a pub/sub channel (many subscribers receive each message) keyed by ride id. The gateway that holds the rider's connection is subscribed and pushes it to the app.
A location update for a driver on a trip is routed the same way, at most one push every 4 seconds.
If the WebSocket is down (app in the background), fall back to a push notification through the phone vendor's service for important status changes, and let the app fetch GET /v1/rides/{id} on reconnect. The ride state in the database is always the truth, the WebSocket is only a fast pipe.
A connection registry (a small key-value store mapping user id to gateway id) tells services which gateway to send each message to. Entries expire with the connection.
6.8 Sharding by city
All of this partitions naturally by geography.
Shard key: city or region. A ride in Mumbai never needs a driver in Paris. Each region has its own location store shard, dispatch workers and ride database shard, so traffic and failures stay local.
Big cities. The busiest city might hold 5% of global traffic, about 37,500 location updates per second at 750K globally, which is fine for a few nodes. If one city outgrows a shard, split it by cell: shard by a coarse parent cell (for example a cell of about 50 km across) instead of by city name.
Boundaries. A rider near the edge of a shard may have the best driver on the other side. Dispatch queries the neighbouring shard too when the search ring crosses the boundary.
Hot spots. Stadiums and airports create sudden local spikes. Smaller cells there, and extra dispatch workers for those regions, absorb them. Use a queue partitioned by region for ride requests, so one overloaded region only builds a backlog in its own partition.
Trade-off thinking. A global index would find the best driver anywhere, but it would be a single hot, slow system for a benefit nobody needs. Geographic sharding gives locality, fault isolation and simple scaling.
Step 7: Bottlenecks and Failure Handling
Bottlenecks
Location write rate.Cause: 750K updates per second. Mitigation: in-memory store, sharded by region, small messages, adaptive update interval, and no per-update disk writes.
Hot cells.Cause: a stadium empties and thousands of requests and drivers gather in one cell. Mitigation: finer cell resolution in dense areas, more dispatch workers per region, and rate limiting new requests with a "high demand" response.
Gateway connections.Cause: 3.3 million persistent connections. Mitigation: about 100 gateways with headroom, load balancing by least connections, and gradual reconnects after a deployment so clients don't reconnect all at once (a thundering herd, where many clients retry together).
ETA service latency.Cause: shortest-path searches on the critical path. Mitigation: only run for the top 10 candidates, cache results, and fall back to straight-line distance if the service is slow.
Trail pipeline backlog.Cause: 600 GB per day of points. Mitigation: scale consumers by queue depth. Live matching is not affected.
Failures
Driver disconnects. If the driver was idle, the TTL expires and they leave the available pool in 15 seconds. If a driver has a pending offer, the offer simply times out and the claim lease expires. If the driver is on a trip, the ride stays IN_PROGRESS and continues when they reconnect; the app buffers recent GPS points and sends them on reconnect. The rider is shown "connection lost, trying to reconnect" instead of an error.
Dispatch worker crashes mid-match. The ride is already REQUESTED in the database, and the offer record has an expires_at. A supervisor (or another worker consuming the same region partition) notices the stuck ride and restarts matching. The claimed driver's lease expires on its own, and the conditional update on accept prevents a duplicate assignment even if two workers both continue the same ride.
Location store shard fails. Fail over to its replica. If everything is lost, the shard is repopulated by drivers' next updates within about 4 seconds. Matching is briefly worse (fewer candidates) rather than down.
Ride database node fails. Promote a replica. Ride requests in that shard pause briefly; trips already running keep their state in memory on the apps and recover once the leader returns.
Duplicate payment. A retry after a timeout must not charge twice. The payment record has a unique idempotency_key derived from the ride id, and the same key is sent to the card processor, so a retry returns the original result. The payment is started from the ride event log (an outbox: the event is written in the same transaction as the ride change, then a worker sends it), so a ride cannot complete without the payment being scheduled.
Region outage. Riders and drivers in that region fail over to a standby region with data replicated across regions. Drivers re-announce themselves through their next update.
Graceful degradation. If dispatch is slow, widen timeouts and tell the rider "finding your driver" instead of failing. If surge pricing is down, fall back to the last known multiplier or 1.0.
Interview tip. Pick two or three failures, say what the user sees, and name the monitoring: match time p99, offer acceptance rate, location store lag, gateway connection count, fraction of rides in REQUESTED for more than 30 seconds, payment failures, and cells with demand/supply above 3.
Solid arrows are synchronous calls. Dashed arrows are asynchronous or background paths.
Request flow
Driver location: driver app, gateway, location service, location store (cell index with TTL). Ride request: rider app, gateway, ride service (creates REQUESTED), dispatch, nearby search in the location store, ETA ranking, atomic claim, offer to the driver, accept as conditional update, status pushed to the rider. Trip: driver locations flow to the rider through the gateway until completion.
Data flow
Live positions live only in the in-memory store and are rebuilt by phones if lost. Rides and ride events live in the sharded relational database, the source of truth. GPS points for trips flow through a queue into the trail store. Payments are created from completed rides and stored with their idempotency keys.
Background processing
Consumers write trip trails and clean up old points. A sweeper trims stale cell members and restarts stuck matches. Workers compute surge multipliers per cell every minute. A payment worker charges completed rides with retries. Analytics jobs build driver earnings and demand heat maps.
Critical design decisions
In-memory store with TTL for locations, because 750K writes per second of short-lived data does not belong on disk.
Cell-based geospatial index (H3-style) with neighbour search, for constant-time "who is near me" queries.
Atomic driver claim plus conditional ride update, so no double assignment even with races and crashes.
A ride state machine with conditional updates, so every change is legal and auditable.
Sharding by city or region, for locality and failure isolation.
WebSockets plus a push-notification fallback, for live updates with a durable source of truth.
Idempotent payments through an outbox, so money is never lost or doubled.
If time remains, discuss shared rides (matching a second rider onto an existing trip with a detour limit), batched matching (collect requests for 2 seconds and solve a global assignment to reduce total wait time), and multi-region failover.