"Design Uber" tends to turn into "design a geospatial index" within five minutes. The candidate draws a grid over a city, picks geohash or a quadtree, and spends the next twenty minutes on finding the drivers near a rider. That part has a known answer, worked through in geospatial indexing. It's also the part of the system that is allowed to be wrong.
A driver's position is up to 4 seconds old when dispatch reads it, and the car has moved since. The cars on the rider's map, the pickup estimate and the surge price are all estimates built from those positions. If one of them is a few seconds out of date, or a ping goes missing, nothing breaks, because the next ping replaces it within 4 seconds.
Then a driver taps accept, and the rules change. This driver now has this trip and no other. This rider has this driver and no other. The price the rider saw is the price, and the card is charged once. None of those may be wrong even once, and the requirements below put them at about 200 a second.
Ride-hailing is a fast search over data that is allowed to be wrong, followed by a commitment that is not.
The two halves want opposite things. The search needs throughput and freshness, and it can lose data. The commitment needs transactions, and it can afford to be slow by computer standards, because the person on the other end takes seconds to tap a button. Most of this design is keeping the two apart and putting the line between them in the right place.
Understanding the problem
The general method for this part of the interview is in The First Five Minutes: Requirements.
A rider opens the app and sees cars nearby and a price for the trip. They tap request, and a few seconds later a driver's phone shows an offer. The driver accepts. The rider watches the car approach on the map, gets in, and is taken to the destination. The card is charged when the trip ends.
"Uber" covers at least five systems, and each needs a different design. Split them before you draw anything.
- Dispatch. Matching each ride request to one driver, and getting that driver to accept. This is the core of the question.
- Live location. Taking every online driver's position every few seconds, finding the drivers near a point, and showing a rider where their driver is. The volume is huge, and each position is useful for seconds.
- Pricing. An upfront fare, plus surge: a multiplier on the fare that rises where riders outnumber available drivers.
- Maps and routing. Road graphs, traffic, directions and driving time estimates. A large system of its own.
- Payments. Charging riders, paying drivers, refunds and fraud.
This design covers the first three, plus enough of payments to charge each trip once.
Functional requirements
Core:
- See nearby cars and an upfront fare before requesting a ride.
- Request a ride and get exactly one driver, who can accept or decline the offer.
- Track the trip. The rider sees the driver approach, then the trip's progress. The driver sees the pickup and the destination.
- End the trip and charge the rider the agreed fare, once.
Out of scope, deliberately:
- Routing and driving time estimates. We call a routing service and use its answer.
- Shared rides, scheduled rides and food delivery. Shared rides put several riders in one car, which makes matching a different problem.
- Driver onboarding, ratings, fraud, and paying drivers.
- Navigation inside the driver's app.
Non-functional requirements
- Scale. 500,000 drivers online at peak, each sending its position every 4 seconds. That's 125,000 position updates a second, the load the geospatial indexing page designs for.
- Fresh enough positions. Dispatch and the rider's map see a driver's new position within about 5 seconds. A lost position is fine, because the next one arrives 4 seconds later.
- A fast first offer. When a driver is free nearby, their phone shows the offer within 3 seconds of the rider's tap.
- Exact commitments. A driver never holds two trips at once, a request never gets two drivers, and a trip is charged once.
- Trips survive failures. A trip in progress survives the loss of a server or of a whole region. It doesn't disappear, and it doesn't get a second driver.
Requirements 2 and 4 carry the design. Requirement 2 is measured in seconds and accepts loss. Requirement 4 accepts no loss at all. Write both down in those words. If requirement 2 says "accurate" instead, the positions start to look like data that needs a durable database. Then 125,000 writes a second end up in the same data store as the trips.
The question is whether positions and trips can share a
data store. Size each one's write rate and how long its
data stays useful.
Positions
drivers online at peak 500,000
one ping every 4 s 500,000 / 4 = 125,000 writes/s
life of one position until the next ping = 4 s
Commitments
drivers busy at peak, assumed 60% = 300,000
a trip holds a driver ~25 min, 5 to reach
the rider and 20 for the ride 25 × 60 = 1,500 s
trips starting 300,000 / 1,500 = 200/s
writes per trip, request to charge, ~10
200 × 10 = 2,000 writes/s
life of one trip record = years
─────────────────────────────────────────────────────────
Positions arrive about 600 times faster than trips start,
and each one is useless 4 seconds later. Trips are few,
and each one is kept for years. One data store cannot be
good at both.The ratio is the time a trip holds a driver over the ping interval and the busy share, 1,500 / 4 / 0.6, about 625, so it stays the same at any fleet size.
The set up
Core entities
- Rider. An account with a payment method.
- Driver. An account and a vehicle, plus a session while they're online. The session has a state,
AVAILABLE,EN_ROUTEorON_TRIP, and a position. It can also hold a claim for one offer, and one trip queued behind the current one. The position changes every 4 seconds. The rest changes a few times per trip. - Trip. One record from the rider's tap to the charge: pickup, destination, the quote, the driver and a state. The trip is the entity whose changes are commitments, and most of the design is about who may change its state, and when.
- Offer. A proposal of one trip to one driver, with a deadline.
- Quote. A fare shown before the request, with the surge multiplier inside it and an expiry time.
How do offers and positions travel?
Pick the transports before the interface. Four flows cross the network.
- Positions, up from every driver's phone, every 4 seconds.
- Offers, down to one driver at a time, and the server must know they arrived.
- The cars on a rider's map, before the trip.
- Trip events and the driver's position, down to one rider, during the trip.
The rule from push against polling settles most of this. Push when updates are rarer than the delay the client accepts, and poll when they're more frequent.
The cars on the map: poll. Each car moves every 4 seconds, and the rider accepts a 5 second delay, so the updates are more frequent than the delay. A poll every 5 seconds is cheaper than a push per car, and riders in the same area can share one answer (section 1).
Offers: push, with an acknowledgement on the same connection. An offer is rare and urgent. Dispatch needs to know within seconds whether it arrived, so it can offer the trip to someone else if it didn't.
Uber's push platform first batched its acknowledgements, which left an offer's delivery unknown for up to 30 seconds. It moved to gRPC streams that acknowledge each message, as the trip offer example describes. Here, the driver's app holds one gRPC bidirectional stream, and its pings go up the same stream the offers come down.
Trip events: push. "Driver assigned" and "driver arrived" each happen once and must arrive within seconds. So the rider's app opens a push stream when it requests a ride, and the driver's position travels on the same stream. A phone in the background holds no stream at all (section 3).
System interface
RIDER → SERVER, over HTTPS
POST /v1/quotes
{ "pickup": { "lat": 40.7580, "lng": -73.9855 },
"dropoff": { "lat": 40.7484, "lng": -73.9857 },
"product": "standard" }
→ { "quote": { "quote_id": "q_5c1e", "rider_id": "r_7",
"product": "standard",
"pickup": { "lat": 40.7580, "lng": -73.9855 },
"dropoff": { "lat": 40.7484, "lng": -73.9857 },
"fare": "18.40", "multiplier": 1.3,
"expires_at": "2026-11-01T18:04:00Z" },
"signature": "9f1c..." }
POST /v1/trips
{ "quote": { ...exactly as returned... }, "signature": "9f1c...",
"payment_method": "pm_31" }
→ 202 { "trip_id": "t_19", "state": "REQUESTED" }
DRIVER ↔ SERVER, one gRPC bidirectional stream
↑ { "ping": { "lat": 40.7612, "lng": -73.9776, "state": "ON_TRIP",
"trip_id": "t_12", "dropoff": { ... },
"dropoff_eta_s": 140, "ts": 1761999843000 } }
↓ { "offer": { "offer_id": "o_88", "trip_id": "t_19",
"pickup": { ... }, "expires_in_s": 15 } }
↑ { "ack": "o_88" }
↑ { "accept": "o_88" }
Four things to note.
The quote is signed whole, and it can be used once. The signature covers the rider, the product, the pickup, the drop-off, the fare, the multiplier and the expiry. So the request service can trust the quote without looking anything up, and nobody can reuse it for another rider or another route. The trip stores quote_id in a unique column, so one quote creates at most one trip.
Requesting a ride returns a trip, not a driver. Matching takes seconds, and it can take several offers. So the call returns 202 Accepted with a trip ID, and the rider's app learns the outcome over its push stream.
The driver's app acknowledges an offer separately from accepting it. The ack means the phone has the offer. The accept means the person agreed. They're different events, seconds apart, and the gap between them is where dispatch decides whether to wait or move on.
A driver on a trip says where it ends. The ping carries the drop-off point and the app's estimate of the time to reach it, so dispatch can see which drivers are about to be free.
High-level design
1. Show nearby cars and an upfront fare
Where do 125,000 positions a second go?
Geospatial indexing builds this index step by step, and this design uses it as it is. In short:
- A ping rewrites one Redis key per driver,
driver:{id}. It holds the position, the driver's cell and the state the app reports. For a driver on a trip, it also holds the drop-off point and the estimated time of arrival (ETA) there. A 30 second expiry on the key resets with every ping. - Each cell, a square about 1 km on a side, has a Redis set of the drivers in it,
cell:{cellId}. The cell sets are spread across shards by a hash of the cell ID. - A ping changes a cell set only when the driver crosses into a new cell, about 4,200 times a second at city speeds, and each crossing is two writes. Every driver is also re-added to its cell once a minute, 500,000 / 60, about 8,300 writes a second. Together the cell sets take about 16,700 writes a second.
- Nothing is written to disk or copied to a replica. A lost shard refills its driver keys from the next round of pings within 4 seconds, and its cell sets from the re-adds within a minute.
This design adds one thing. The location service also appends every ping to Kafka, a partitioned log, keyed by driver ID. Quotes and ride requests go to Kafka too. That's 125,000 records a second of about 100 bytes each, around 12.5 MB a second.
The index answers one question: which drivers are near this point now. The log feeds everything that may run a little late: each trip's route trace, the surge counts in deep dive 3, and analytics. A log, rather than a direct call to each reader, lets every reader keep its own place. A reader that falls behind delays its own output and never slows the index.
The state in the driver key comes from the app, so it can be a few seconds behind. A driver who accepted a trip a moment ago can still show as available. That's acceptable, because nothing is committed from the index.
The cars on the rider's map
The rider's app asks for the cars around it every 5 seconds. The service reads the 3 by 3 block of cells around the rider, fetches each driver key, drops the drivers who aren't available, and returns the nearest ten or so. Downtown, thousands of riders ask about the same few cells. So the instance that owns a cell builds one list a second, and every rider in that cell shares it. Geospatial indexing works through that case with its numbers.
The map is approximate on purpose. It shows that cars exist and roughly where they are. Dispatch doesn't use it.
The fare quote
When the rider enters a destination, the quote service works out a fare from four inputs. The routing service gives the route's distance and driving time. The city's rate card and the product set the base price. And the surge multiplier for the pickup's hexagon comes from Redis, which the surge job in deep dive 3 fills.
It returns a quote with an expiry a few minutes away, signed with a key only the servers hold. The signature is a hash-based message authentication code (HMAC), a keyed hash over every field of the quote. The request service checks the signature and the expiry. If the quote has expired, the app asks for a new one and shows the new price before the rider confirms.
The quote is where the first approximate number becomes a commitment. The multiplier came from counts that may be a minute old. Once the rider requests, the trip's fare starts from the quote, whatever surge does next.
2. Match the rider with one driver
The rider taps request. The request service checks the quote and writes the trip row in state REQUESTED. In the same transaction it writes an outbox row, an event that starts the card authorization (section 4). Then it tells the dispatcher for the pickup area. A dispatcher is a process that owns matching for one area of the map, a group of cells.
Two questions remain: which driver gets the offer, and how to make sure that driver goes to only one rider.
Offer the nearest available driver, straight away
The index can already sort candidates by distance, so the obvious match is the first available driver, offered the moment the request arrives. Uber says it used to match riders this way: immediately, to the closest available driver.
It breaks on what "nearest" measures. The index measures a straight line. A driver 300 m away on the other side of a river can be 15 minutes away by road, while a driver 1.5 km away on the same avenue arrives in 3. The rider cares about the wait, not the distance.
The straight line still has a job. It's the filter that turns 500,000 drivers into a few dozen candidates. It just can't be the ranking.
Rank the candidates by driving time, and offer one at a time
Take the available drivers within a couple of kilometres, about 30 in a busy area. Ask the routing service for each one's driving time to the pickup, in one batched call. Offer the trip to the driver with the shortest time. If they decline, or don't answer within 15 seconds, offer it to the next.
This is the standard answer, and it's correct.
Its cost shows up when requests arrive close together. Each request takes the best driver for itself at the moment it arrives, and that choice can be bad for the request that arrives one second later.
Match in short batches, and count drivers who are about to be free
Question the premise that each request is matched alone, the moment it arrives, against drivers who are free right now.
Collect the requests in an area for a short window, 2 seconds here. Ask the routing service for the driving time from every candidate to every pickup in the batch. Then pick the set of pairs with the lowest total wait, instead of the best driver for each request in turn. This is the assignment problem, and the Hungarian algorithm solves it exactly, in milliseconds for a batch of a few dozen requests.
Uber describes its own matching this way. In the seconds after a request, it evaluates nearby riders and drivers in one batch, to cut the average wait for everyone.
Widen the candidates in time as well as in space. A driver who will drop off a passenger 300 m from the pickup in 2 minutes can be a better match than a free driver 8 minutes away. Uber's 2015 dispatch system did this. Matt Ranney, Uber's chief systems architect, said in a talk that picking a driver who is on a trip can cut both the rider's wait and the extra driving. The drop-off point and ETA in the driver key show dispatch who these drivers are.
The trade, sized. The window adds up to 2 seconds before any offer goes out, on a pickup that takes minutes. In the example it saves 4 minutes of total waiting. And deep dive 4 assumes that a driver takes longer than 2 seconds just to read an offer.
What you give up. A dispatcher has to see every request in its area at once, which is why areas have owners. Batches grow in a shortage, so the solve gets slower when the area is busiest. And one rider's match is harder to explain, because the best driver for them may have gone to someone else.
Getting the offer to the driver
The dispatcher sends the offer down the driver's gRPC stream, and the app acknowledges it as soon as it arrives, before the driver has decided anything. Two timers run.
- The acknowledgement: 2 seconds. If no ack comes back, the phone probably never got the offer. The dispatcher releases the driver and offers the trip to the next one, without waiting out the whole window. This is the case batched acknowledgements couldn't handle.
- The answer: 15 seconds on screen, 20 on the server. The driver sees a 15 second countdown. The server accepts an answer for 20 seconds, so a tap at 14.9 seconds still counts after a slow trip across the network.
A decline releases the driver at once, and the trip goes into the next batch with that driver left out.
What stops two riders getting the same driver?
The dispatcher chose its pairs from the index, and the index can be a few seconds behind. So each pair has to be checked against the database before an offer goes out.
Two things can go wrong. Two dispatchers can offer the same driver at the same time, near the edge of their areas or after one of them restarts. And an accept changes two records, the trip and the driver, which can end up disagreeing. This is requirement 4, so the answer can't depend on timing.
Trust the index, and update both records when the driver accepts
The dispatcher checks that the driver key says available, sends the offer, and on accept marks the trip as accepted and the driver as busy. It's tempting, because the state is right there in the key the dispatcher has already read.
That state is the app's own report, up to 4 seconds old. Two dispatchers read "available" within the same second, and both send offers. The driver taps accept on both, nothing checks either one, and both trips commit driver 8812. Two riders now wait for the same car, and nothing in the design notices.
Lock the driver in Redis for the length of the offer
Before offering, the dispatcher takes a lock on the driver: SET lock:driver:8812 o_88 NX PX 20000. The key is written only if it doesn't exist, so exactly one dispatcher gets the lock, and the others pick another driver. It expires after 20 seconds, the offer window, so a dispatcher that crashes frees the driver on its own. On accept, the trip service marks the trip accepted, and the driver service marks the driver busy.
This is a common answer, and it stops the double offer in normal running. It has two costs.
The lock lives in Redis and the trip lives in a database, so two systems each hold part of the truth. Redis copies writes to its replica asynchronously, so a failover can lose a lock granted a moment earlier, and a second dispatcher takes the same driver.
And the accept still writes two records in two services. If the trip service commits and the call to the driver service fails, you need a saga to retry or undo it. Until the saga finishes, the two records disagree.
Uber's fulfillment platform ran this way, with a saga across separate trip and supply services, until a rewrite from about 2019 to 2021. Its write-up says the system was internally inconsistent between the operations that made up one logical transaction.
Make the claim a row change, and accept in one transaction
Question two premises together: that the claim needs its own lock service, and that the trip and the driver belong in different databases.
Put both rows in one transactional database, Postgres to start with, and make the claim a change to those rows. The offer is one transaction. It writes the same offer_id and deadline, offer_until, onto the trip row and the driver row, and only if both are free. The accept is one transaction that moves both rows, and only if both still carry that offer_id and the deadline hasn't passed.
An expired claim counts as free, so no job has to clean up after a crashed dispatcher. The dispatcher runs both transactions, because it made the offer. This is the pending state from distributed transactions and sagas, with a name, an owner and a deadline, written onto two rows at once.
The number that makes this affordable comes from the requirements. About 200 trips start a second, and all their writes, from request to charge, come to about 2,000 a second. One transactional database handles that with room to spare, so there's no throughput reason to split trips from drivers.
Uber reached the same conclusion. Its write-up says accepting an offer has to change both the trip and the driver's session. Uber rebuilt the platform on Spanner for strong consistency across rows and tables.
What you give up. The database is now on the path of every offer and every accept, so it has to stay up through a region failure, which deep dive 5 pays for. Every offer waits for a commit, tens of milliseconds against a 15 second window. And trips and drivers can no longer scale as separate services with separate databases. At 2,000 writes a second, they don't need to.
Which data store, and what actually forces it
Section 1 sent positions to Redis and Kafka. Trips, offers, drivers and riders still need a home. Two numbers decide it: how fast the data is written, and how much of it is still live.
One Postgres for trips, drivers and riders
Everything that isn't a position goes in one Postgres primary, with replicas for reads. At 2,000 writes a second, one primary is comfortable, and the two-row transactions above are ordinary. It's the right starting point, and it stays right for a long time.
Its cost sits in one table. The trips table holds two different kinds of data. A trip in progress is read often and written about ten times in half an hour, by dispatch, the apps and payments. A finished trip never changes again and is read by receipts, support and driver earnings, for years. The table grows with the second kind, and the first kind does all the work.
Partition the trips table by month
Keep one Postgres, but partition the trips table by month. Recent months stay on fast disks, and old months are detached and moved to cheaper storage. This is the standard fix for a table that grows forever, and every query and transaction stays as it was.
Its cost arrives with requirement 5. The trips in progress must survive a region, so the database that holds them has to commit across regions, and that is expensive per byte. With every month of history in the same database, the history pays that price too.
Split the live trip from the finished one
Question the premise that a trip is one kind of data, and keep two databases.
The live database holds only trips in progress, offers and driver sessions. The trip archive holds finished trips and their route traces. When a trip completes, the same transaction writes an outbox row. A mover reads it, copies the trip into the archive, and deletes it from the live database a few minutes later. Uber's fulfillment platform works this way: a trip's data stays in Spanner until the finished trip has been copied to long-term storage.
The question is whether one database should hold both
trips in progress and finished trips. Size each part.
Live: what dispatch and the apps read now
trips in progress ≈ busy drivers = 300,000
trip rows 300,000 × ~2 KB = 600 MB
driver sessions 500,000 × ~0.5 KB = 250 MB
total < 1 GB
History: what receipts, support and earnings read later
trips a day 200/s at peak, daily
average a third of it ≈ 6M
trip records 6M × 2 KB = 12 GB/day
route traces, one point per 4 s ping
a 20 minute ride 1,200 s / 4 s = 300 points
× ~30 B a point 300 × 30 B = 9 KB a trip
all trips 6M × 9 KB = 54 GB/day
a year 66 GB × 365 ≈ 24 TB
─────────────────────────────────────────────────────────
Under a gigabyte, each trip written about ten times in
half an hour, against 24 TB a year, written once and
rarely read. Those are two different databases.The split changes what each side has to be. The live database is under a gigabyte, so all of it fits in memory, and making it survive a region costs little in absolute terms. Uber's write-up puts a multi-region Spanner configuration at 3 to 4 times the cost of a single region. That multiplier is cheap on a gigabyte and expensive on 24 TB a year.
The archive needs none of it. Its rows are written once and never updated, and they're read by trip ID, or by rider with the newest first. A wide-column store such as Cassandra, or DynamoDB, keyed that way, fits.
What you give up. A trip lives in two places for a few minutes after it ends, so a receipt read in that window checks the live database first. The mover is a job you own, and the archive is a second database to run.
| data store | what goes in it | the requirement that forces it |
|---|---|---|
| Redis, in memory, no persistence | driver keys and cell sets | 125,000 writes a second, each one worthless 4 seconds later |
| Kafka | every ping, quote and request, and trip events | readers that may lag: traces, surge, analytics |
| live database, Spanner or CockroachDB across three regions | trips in progress, offers, driver sessions, the outbox | two-row transactions at 2,000 writes a second, and surviving a region (deep dive 5) |
| trip archive, Cassandra or DynamoDB | finished trips and route traces | 24 TB a year, written once, read by trip or by rider |
| Redis | surge multipliers per hexagon | read on every quote, rewritten every minute |
| Postgres | rider and driver accounts, vehicles, payment methods | small and relational, and it changes rarely |
The tables
-- Live database. Small, transactional, replicated across regions.
driver_sessions (
driver_id bigint primary key,
state text not null, -- AVAILABLE, EN_ROUTE, ON_TRIP
offer_id uuid, -- the offer this driver is claimed for
offer_until timestamptz, -- when that claim lapses
trip_id bigint, -- the trip in progress
next_trip_id bigint, -- a trip accepted behind it
updated_at timestamptz not null
)
trips (
trip_id bigint primary key,
rider_id bigint not null,
quote_id text not null unique, -- one quote, one trip
state text not null, -- REQUESTED ... COMPLETED, CANCELLED
quote jsonb not null, -- as signed at quote time
pickup_cell bigint not null, -- picks the dispatcher
offer_id uuid,
offer_until timestamptz,
driver_id bigint,
auth_id text, -- set once the card hold succeeds
fare numeric, -- the final fare
created_at timestamptz not null
)
index (pickup_cell) where state in ('REQUESTED', 'OFFERED')
outbox (
event_id uuid primary key,
trip_id bigint not null,
kind text not null, -- TRIP_REQUESTED, TRIP_COMPLETED, ...
payload jsonb not null,
created_at timestamptz not null
)
-- Trip archive. Wide-column, written once per finished trip.
trips_by_rider (
rider_id bigint, -- partition key
completed_at timestamp, -- clustering key, newest first
trip_id bigint,
summary blob,
primary key ((rider_id), completed_at, trip_id)
) WITH CLUSTERING ORDER BY (completed_at DESC);
trip_records (
trip_id bigint primary key,
record blob, -- the final trip row
trace blob -- the route, from Kafka
);
Four things to note.
The claim sits on both rows. offer_id and offer_until give the claim an owner and a deadline on each side, and every claim checks both. If a dispatcher dies in the middle of an offer, its claim lapses and frees the driver and the trip within 20 seconds. The claim doesn't change the driver's state, so a driver on a trip can be claimed too.
The quote is stored as the rider saw it. The fare at the end of the trip starts from quote, not from whatever surge says by then. It changes only when the rider changes the destination, with a new quote and a new card hold (section 4).
Open requests are indexed by area. The partial index covers only REQUESTED and OFFERED rows, by pickup_cell. A dispatcher reads its area's open requests at the start of every batch, and the index stays small because nearly every row is in some other state.
No table holds a position. Positions live in Redis and Kafka. A trip's trace reaches the archive from Kafka after the trip ends.
The queries that carry the product
-- 1. A ping. 125,000 a second, in Redis, never SQL.
-- One script: SET driver:{id} ... EX 30, returning the old cell,
-- then SREM and SADD only if the cell changed.
-- 2. Claim a trip and a driver for one offer. Both rows or neither.
-- A retry of the same offer matches its own claim.
BEGIN;
UPDATE trips
SET state = 'OFFERED', offer_id = $offer,
offer_until = now() + interval '20 seconds'
WHERE trip_id = $trip
AND (state = 'REQUESTED'
OR (state = 'OFFERED' AND (offer_until < now() OR offer_id = $offer)));
UPDATE driver_sessions
SET offer_id = $offer, offer_until = now() + interval '20 seconds'
WHERE driver_id = $driver
AND (state = 'AVAILABLE' OR (state = 'ON_TRIP' AND next_trip_id IS NULL))
AND (offer_id IS NULL OR offer_until < now() OR offer_id = $offer);
COMMIT; -- if either UPDATE matched no row: ROLLBACK, try the next pair
-- 3. Accept, for a free driver. Only the offer that still holds both
-- rows, and only once the card hold has succeeded.
BEGIN;
UPDATE driver_sessions
SET state = 'EN_ROUTE', trip_id = $trip, offer_id = NULL, offer_until = NULL
WHERE driver_id = $driver AND state = 'AVAILABLE'
AND offer_id = $offer AND offer_until > now();
UPDATE trips
SET state = 'ACCEPTED', driver_id = $driver, offer_id = NULL, offer_until = NULL
WHERE trip_id = $trip AND offer_id = $offer AND offer_until > now()
AND auth_id IS NOT NULL;
COMMIT; -- if either UPDATE matched no row: ROLLBACK, then read the trip
-- 4. At the start of every batch, a dispatcher reads its open requests.
SELECT trip_id, quote, pickup_cell
FROM trips
WHERE pickup_cell = ANY($cells)
AND (state = 'REQUESTED' OR (state = 'OFFERED' AND offer_until < now()));
-- 5. Complete a trip. The driver moves to the queued trip, if any.
BEGIN;
UPDATE trips SET state = 'COMPLETED', fare = $fare
WHERE trip_id = $trip AND state = 'IN_PROGRESS';
UPDATE driver_sessions
SET trip_id = next_trip_id, next_trip_id = NULL,
state = CASE WHEN next_trip_id IS NULL THEN 'AVAILABLE' ELSE 'EN_ROUTE' END
WHERE driver_id = $driver AND trip_id = $trip;
INSERT INTO outbox (event_id, trip_id, kind, payload, created_at)
VALUES ($event, $trip, 'TRIP_COMPLETED', $payload, now());
COMMIT;
Query 1 runs 125,000 times a second, and query 3 about 200. Query 2 matches its own claim, offer_id = $offer. So a dispatcher that lost the reply can run it again, instead of leaving both rows claimed for 20 seconds by an offer it never sent.
A driver on a trip is accepted with the same checks, but the accept sets next_trip_id and leaves the state at ON_TRIP. Query 5 then moves that trip into trip_id with the state EN_ROUTE, so the driver never shows as AVAILABLE in between, and query 2 can't claim them twice.
Query 3 is the one an interviewer pushes on, and three cases come up. An accept that reaches the database at 19.9 seconds commits, because the deadline is checked against the database's clock, not the phone's. A tap after the dispatcher has released the driver matches no row, because the release cleared offer_id. And a second tap on the same offer also matches no row, because the first accept cleared it.
So when an accept matches nothing, the dispatcher reads the trip before replying. If the trip already names this driver, the earlier tap won, and the app is told the trip is theirs. If the card hold hasn't come back yet, the accept waits for it and runs again.
3. Track the driver to the pickup, and the trip to the end
After the accept, the dispatcher hands the trip to the trip service, which owns every later step. It moves the trip to ARRIVED when the driver reaches the pickup, and to IN_PROGRESS when the rider gets in.
The rider sees the driver's car move. The driver's pings already carry the trip ID. When it takes over the trip, the trip service writes a small Redis entry, watch:{trip_id}, naming the rider. For each ping with a trip ID, the location service reads that entry, from its own cache after the first ping. It sends the position to the push service, which holds the rider's stream. If the region's Redis is lost, the location service reads the rider from the trip row in the live database instead.
Only the newest position matters, so each one replaces any position still waiting to go out. At peak that's up to 300,000 trips, each sending a position every 4 seconds, or 75,000 messages a second.
Trip events are different. "Driver assigned", "driver arrived" and "trip started" happen once each, and a rider who misses one is confused. The trip service sends them at a higher priority, and the push service retries them until each is acknowledged or its lifetime runs out.
A phone in the background has no stream. Then the push service sends the alert through the Apple Push Notification service (APNs) or Firebase Cloud Messaging (FCM), set up as in "Your driver is arriving". Its lifetime is about 5 minutes, because the alert is false after that. Its collapse key is the trip ID, so each status replaces the one before it.
Neither provider promises order, so a late "driver assigned" can replace a "driver arrived" that is still waiting. When the rider opens the app, it reads the trip's state from the server. The push was only a hint.
The pings of a driver on a trip also become the trip's route. A trace writer reads them from Kafka, groups them by trip ID, and writes the route to the archive when the trip ends. A few lost pings leave small gaps, and the route between the points on either side fills them. The receipt's map and any later fare dispute read this trace.
4. End the trip and charge the rider
The charge starts at the request, not at the end. The request's transaction writes a TRIP_REQUESTED row to the outbox, and a relay passes it to the payment service. That service places an authorization hold on the card for the quoted fare: the card network reserves the money without moving it. The trip row records the hold in auth_id. Uber documents the same hold, from the request to the charge.
Matching doesn't wait for the hold. The offer goes out while the authorization runs, and query 3 commits an accept only once auth_id is set. Assume an authorization takes about a second. A driver takes 3 to 15 seconds to read an offer and tap, so the accept almost never waits. If the card is declined, the trip is cancelled and the claimed driver is released, which costs that driver one offer.
A new destination needs a new hold. When the rider changes the destination, the app gets a new quote, and the payment service authorizes the new fare before the trip takes the change. So the capture at the end is never larger than a hold that has already succeeded.
When the driver taps end trip, query 5 runs as one transaction in the live database. It marks the trip COMPLETED with its final fare, moves the driver to a queued trip or back to AVAILABLE, and writes a TRIP_COMPLETED row to the outbox.
That transaction is the pivot of the trip's saga, in the terms of distributed transactions and sagas. Everything before it can still be undone. Everything after it only moves forward.
A relay reads the outbox row and calls the payment service to capture the hold, with the trip ID as the idempotency key, so a retried capture charges once. The receipt, the driver's earnings and the move to the archive read the same event.
Cancellation follows the same line. Before the accept, a cancel removes the hold and costs nothing. After the accept, it's a commitment being undone. The trip moves to CANCELLED and the driver is released from it in one transaction: back to AVAILABLE, or, for a trip queued behind another, back to just the trip they are finishing. If the city's rules charge a cancellation fee, the relay captures that part of the hold instead of the fare.
Deep dives
Deep dives 1, 2 and 5 come up in most versions of this interview.
1. How many servers, and what actually needs scaling?
The question is which part of the system needs the
machines. Connections and pings first, then the rest.
Connections
drivers online 500,000
riders from the request to the drop-off
≈ busy drivers 300,000
total = 800,000
at ~100,000 per server, assumed
800,000 / 100,000 = 8 servers
doubled to survive losing a zone = 16 servers
Messages
pings in 125,000/s / 16 ≈ 7,800/s per server
positions out to riders 300,000 trips / 4 s = 75,000/s
Index, Redis
driver keys and cell sets 125,000 + 16,700 ≈ 142,000 writes/s
at 100k to 1M simple ops per node = 1 to 2 nodes
Dispatch
requests 200/s
driving times, ~30 candidates each 200 × 30 = 6,000/s
Live database
writes, from the requirements 2,000/s
─────────────────────────────────────────────────────────
The machines go to held connections and to pings. The
commitments run at 2,000 writes a second, the lightest
load in the design.2. Hot areas, and how dispatch is split
Demand is never even across a city, and the worst cases arrive on a schedule: a stadium empties, a concert ends, rain starts at rush hour.
The question is what runs out first: servers or drivers. All of these numbers are assumed. people leaving 20,000 share who request a ride 30% requests 20,000 × 0.3 = 6,000 spread over 15 min 6,000 / 900 s ≈ 6.7/s drivers who can reach the gates in 10 min ≈ 300 all of them claimed 300 / 6.7 per second ≈ 45 s a trip holds a driver ~25 min, so in the first 15 min each of them takes one trip ≈ 300 trips requests still waiting 6,000 − 300 = 5,700 ───────────────────────────────────────────────────────── 6,000 requests and 300 drivers. After the first minute, each batch is a long queue of requests against the few drivers who have just become free. The shortage is in cars, and no number of servers adds one.
The dispatcher caps each batch at the oldest few hundred open requests, so one solve stays small while the queue runs into thousands. So a hot area isn't a capacity problem for dispatch. It's a market problem.
The design has two answers to it. Surge raises the price around the stadium, which brings drivers in from farther away and makes some riders wait or walk. And the app shows the rider a wait based on the requests ahead of them and the drivers on their way, not on the nearest car on the map.
The split does matter in one place: the edges between areas. A dispatcher batches the requests in its area, so how should the map be divided between dispatchers?
One dispatcher per city
A city looks like the natural unit. It has its own rates and its own drivers, and its trips mostly stay inside it. Uber's old dispatch system was sharded by city, before the rewrite Matt Ranney described in 2015.
It breaks on the largest city. One city is one process, and you can't split it, so the busiest city's Friday night has to fit on one machine. This is the shard-by-city mistake from geospatial indexing, with dispatch on top.
One dispatcher per group of cells, each owning its area outright
Divide the map into areas, say 10 km squares made of cells, and assign each area to one dispatcher by a hash of its ID. A large city becomes dozens of areas on dozens of processes. Uber's rewritten system split its index of drivers the same way, by S2 cell ID.
The cost is the edges. A request near an edge has candidates on the other side, and they belong to another dispatcher. With 10 km areas and a 1 km search, 36 percent of requests are within 1 km of an edge, and with a 2 km search it's 64 percent. If a dispatcher ignores drivers across the edge, it makes worse matches for a third of requests or more. If it reads them, two dispatchers can offer the same driver.
Let the areas overlap, and let the claim settle it
Question the premise that ownership must be exclusive for the system to be correct.
Each dispatcher owns the requests in its area, and reads drivers from its neighbours too. When two dispatchers pick the same driver in the same window, the offer transaction from section 2 lets exactly one of them claim the driver. The other's transaction matches no row, and its request goes into its next batch with that driver left out.
Ownership can now move without stopping anything. During the stadium let-out, you split the busy area into smaller ones, or move it to an idle process. If two dispatchers both think they own the area for a few seconds, the cost is failed claims, not double bookings.
The trade, sized. A failed claim costs one request one batch, 2 seconds. In return, every request near an edge sees every nearby driver.
What you give up. Some work is wasted on driving times for drivers who went elsewhere. Each dispatcher reads a wider ring of cells. And at a busy edge, one request can lose two claims in a row and wait 4 seconds.
3. How does surge pricing work, and how fresh must it be?
Surge raises the price where riders outnumber available drivers, to bring drivers in and to spread demand out. A 2021 paper on Uber's real-time data infrastructure describes the pipeline. Trip data and rider and driver status flow through Kafka into a Flink job. The job computes a multiplier for each hexagon over a time window and writes it to a key-value store. A hexagon grid such as H3, which geospatial indexing describes, gives every cell neighbours at the same distance.
The obvious version computes the multiplier when a quote is requested. It counts the available drivers in the index around the pickup, counts the recent requests, and divides. That puts a scan of the area on every quote, and the price can jump between two quotes a second apart because one driver went offline. A job over a window does the counting once per hexagon per window, whatever the quote rate, and smooths out single drivers coming and going.
The version here, with its windows assumed:
- Every minute, a Flink job reads the last 5 minutes of pings and requests from Kafka.
- Demand in a hexagon is the requests and quotes with a pickup in it. Supply is the drivers whose latest ping in the window put them there as
AVAILABLE. - The multiplier comes from the ratio, smoothed with the neighbouring hexagons and capped per city.
- The job writes each hexagon's multiplier, with the time it was computed, to Redis, where the quote service reads it.
Surge sits on the search side of the line. The paper says the surge pipeline favours freshness and availability over consistency, and that messages arriving late don't count toward the window. A count that is a minute old and missing a few late pings is good enough for a price.
The quote moves it across the line. The multiplier becomes exact at one moment: when the rider requests with a quote. If surge rises from 1.3 to 1.8 while the request is being matched, the trip keeps 1.3.
4. Where does the time to a match go?
Requirement 3 gives 3 seconds. The question is how long the batch window can be. The timings are assumed. rider's tap reaches the request service 40 to 150 ms check the quote, write the trip, across regions ~50 ms wait for the next batch 0 to 2,000 ms candidates from the index ~5 ms driving times for the batch, one call ~20 ms solve the batch ~10 ms offer transaction, across regions ~50 ms offer down the driver's stream 40 to 150 ms ───────────────────────────────────────────────────────── worst case ≈ 2,440 ms the same, without the batch window ≈ 440 ms Running alongside, from the request: card authorization ~1 s After the offer is on screen: the driver reads it and taps 3 to 15 s accept transaction, once the hold is in ~50 ms "driver assigned" down the rider's stream 40 to 150 ms ───────────────────────────────────────────────────────── The servers take about 440 ms, plus a window of up to 2 seconds that we choose. The card authorization and the driver run at the same time, and the driver takes longer.
The batch window is the one large item, and it's a choice: requirement 3 caps it at about 2.6 seconds. The card authorization stays off this path, because section 4 makes the accept wait for it, not the offer.
The driver's reaction time is also why the cross-region commit is affordable. 50 ms is under 2 percent of the 3 seconds that even the fastest driver takes to read an offer and tap.
5. What fails, and what survives losing a region?
Take the parts in order of how often they fail.
A dispatcher. Its open requests are rows in the live database, not state in its memory, and every batch reads them afresh with query 4. Another process takes the area and carries on from its next batch. Offers the old one sent either get answered or lapse at their deadline, and a request whose offer lapsed shows up in the next batch's query 4. A rider whose request was in the dying dispatcher's batch waits a few seconds longer.
An offer lost on the way. No ack comes back within 2 seconds, so the dispatcher releases the driver and offers the trip to the next one. If the first phone shows the offer late and the driver taps accept, query 3 turns it away, and the app tells the driver the offer has gone.
A Redis shard of the index. It refills from pings and re-adds, as section 1 describes. Until it does, dispatch sees fewer candidates in some cells and makes slightly worse matches. No commitment depends on the index.
The routing service. Without driving times, dispatch ranks candidates by straight-line distance, scaled by a factor per city. Matches get worse, and they keep happening. Quotes are different. A quote is a promise, so without a route the quote service shows an error rather than a guessed price.
The surge job. The quote service checks the time on each multiplier. If the job stops, it keeps quoting with the last multiplier for each hexagon, capped at a limit per city, until the job recovers.
Losing a region
Requirement 5 says a trip in progress survives a whole region going down.
Each city is homed to one region. Its drivers, riders and dispatchers all connect to that region, and they fail over together to the same backup region. If a city's phones were spread across regions, each region's dispatchers would see only some of the city's drivers.
The search is rebuilt, not copied. Each region indexes only the cities homed to it, and no region holds a copy of another's index. When a region fails, its cities' apps reconnect to the backup region and keep pinging. Their drivers appear in its index the way section 1 describes, counted from each driver's first ping after reconnecting. Copying 125,000 writes a second across regions, to save that minute of slightly worse matching, is a bad trade.
Surge already runs in every region. The 2021 paper describes each region computing surge from the same aggregated Kafka input, so the regions arrive at the same multipliers.
The commitments are copied before anyone is told. A trip accepted in the lost region must still be accepted in the surviving one. Otherwise the next batch gives the rider a second driver. So the live database commits across three regions by quorum, in Spanner or CockroachDB. Every offer and accept pays a cross-region round trip, the 50 ms from deep dive 4, and the multi-region price from the data store section, on under a gigabyte.
The lost region's dispatchers start again in the backup region, and their next batch reads the open requests with query 4. Payments favour consistency too. The 2021 paper describes payment processing reading the log from one region at a time and failing over, rather than running in every region.
Uber's 2015 design, as Matt Ranney described it, took the other route. Dispatch sent an encrypted state digest to each driver's phone instead of copying trips to its backup datacenter. After a failover, the backup asked the phones for their digests.
6. How do you know it is working?
During an incident you need four answers quickly: how long riders wait, how many requests find no driver, whether the index is fresh, and whether any commitments are stuck.
- Time to accept and the unmatched rate, per city and per area. A sudden change means either a shortage or a broken dispatcher, and the next metric tells them apart.
- Ping age per area. If pings stop arriving in one area, dispatch there is matching against stale positions, and riders see cars that left.
- Claims that fail, as a rate. A few at area edges are normal. A rise means two dispatchers think they own the same area.
- Stuck states. Trips in
OFFEREDpast their deadline that nothing has picked up, tripsACCEPTEDfor over an hour without starting, andCOMPLETEDtrips whose capture hasn't happened. Each is a commitment that stopped halfway, and each needs an alarm on the age of the oldest one. - Don't label metrics by rider or driver. Every distinct label value is its own time series, and 500,000 drivers would overload the metrics backend. Aggregate by city and area, and trace one trip through logs.
Final design
One trip, end to end:
- The driver's app streams a ping every 4 seconds over gRPC. The location service rewrites the driver key, updates a cell set if the driver changed cells, and appends the ping to Kafka.
- The rider's app polls for nearby cars every 5 seconds, then asks for a quote. The quote service reads the index for the map, and the routing service and the surge multiplier for the price. It returns a signed, single-use quote with an expiry.
- The rider taps request. The request service checks the quote, writes the trip once per quote ID in state
REQUESTEDwith aTRIP_REQUESTEDoutbox row, and tells the area's dispatcher. The relay asks payments for a hold on the card. - Every 2 seconds, the dispatcher that owns the pickup area reads its open requests with query 4. It reads candidates from the index, including drivers about to finish a trip, gets driving times for the whole batch, and picks the pairs with the lowest total wait.
- For each pair, the dispatcher's transaction claims the trip and the driver for 20 seconds. The offer goes down the driver's stream, and the phone acknowledges it within 2 seconds or the dispatcher moves on.
- The driver accepts. Once the card hold is in place, the dispatcher's transaction moves both rows. The trip service takes over the trip, and the push service sends the rider "driver assigned", then the driver's position every 4 seconds.
- The driver ends the trip. One transaction completes it, moves the driver to a queued trip or frees them, and writes the outbox row. The relay captures the hold with the trip ID as the key, and the mover copies the trip into the archive, beside the route the trace writer built from Kafka.
- Every minute, the surge job counts drivers and requests per hexagon from Kafka and writes new multipliers. Every stage reports time to accept, unmatched requests, ping age, failed claims and stuck states.
The numbers behind the shape: 125,000 pings a second, about 600 times the 200 trips that start each second. The commitments come to 2,000 writes a second on a live database under a gigabyte, small enough to commit across three regions. A rider waits at most about 2.4 seconds for the offer to reach a driver.
What is expected at each level
How interviewers turn what they see into these levels is in How a System Design Interview Is Scored.
Mid-level
Breadth matters more than depth at this level, and it's fine to be led.
You should keep driver positions out of the main database, and find nearby drivers with a grid of cells and an exact distance check. You should offer a trip to one driver at a time, with a timeout. You should be able to draw the trip's states, and charge the rider at the end.
You aren't expected to raise batching, multi-region commits or surge without being asked. You are expected to answer sensibly when asked "what if two riders get the same driver?" A good answer names a check that only one of them can pass, and says where that check runs.
Senior
You drive the structure, and three things should come up without prompting.
The two rates. 125,000 position writes a second against about 200 trips. Say what each one does to storage: positions in memory with an expiry, trips in a transactional database.
The race on a driver. Say how two dispatchers are kept from offering the same driver, and how an accept changes the trip and the driver without a moment where they disagree. A lock in Redis is acceptable if you can name what it costs.
Offers that go missing. Say how the server learns an offer arrived, and what it does when the driver doesn't answer.
Two things are disqualifying: writing every ping to the trips database, and no answer to two riders getting one driver.
Staff+
A correct design is still the bar. A staff+ answer also decides what not to build.
State the line between the search and the commitment early, and use it. It keeps positions out of the transactional database, lets dispatch read stale data, and decides what a region failure has to preserve.
Match in batches, and say what it costs. Name the objective, the lowest total wait, size the window against requirement 3, and include drivers who are about to finish a trip.
Make the accept one transaction, and justify it with the rate. About 2,000 writes a second means there's no throughput reason to split trips from drivers.
Split live trips from finished ones. Under a gigabyte of live state can afford to commit across three regions. 24 TB a year of history can't, and doesn't need to.
Be able to say what you would not build. No location index copied across regions, and no durable storage for positions. No lock service for drivers, and no saga between a trip service and a driver service. No surge recomputed on every quote or at match time. No routing engine of your own. A team could spend a quarter on any one of these. Naming them as deliberate omissions is worth more than another box on the diagram.
Sources
Nearly every mechanism and real-world number above comes from what Uber has published about its own systems. Densities, fleet shares, timings and windows are assumptions, stated where they're used.
- HighScalability, How Uber Scales Their Real-Time Market Platform, 2015, a summary of Matt Ranney's QCon talk. Drivers reporting every 4 seconds, dispatch sharded by city before the rewrite, and the supply index sharded by S2 cell ID after it. Planning with drivers who are on a trip, and the encrypted state digest sent to driver phones for datacenter failover.
- Uber Marketplace, How does Uber match riders with drivers?. Matching that used to pick the closest available driver straight away. It now evaluates nearby riders and drivers in one batch, in the seconds after a request, to cut the average wait for everyone.
- Uber Engineering, Uber's Fulfillment Platform: Ground-up Re-architecture and Building Uber's Fulfillment Platform for Planet-Scale using Google Cloud Spanner, 2021. The old design's saga across trip and supply services, and its inconsistent states between steps. The accept that must change both entities, and the move to Spanner for transactions across regions. Data deleted once a trip is copied to long-term storage, and multi-region at 3 to 4 times the cost of one region.
- Yupeng Fu and Chinmay Soman, Real-time Data Infrastructure at Uber, SIGMOD 2021. The surge pipeline from Kafka through Flink to a key-value store per hexagon, and its preference for freshness over consistency, with late messages left out. The surge job running in every region, and payments consumed in one region at a time.
- Uber Engineering, Uber's Next Gen Push Platform on gRPC, 2022. The 30 second gap in batched acknowledgements that blocked resending driver offers, and the move to gRPC streams that acknowledge each message.
- Uber, What is an Authorization Hold?, 2022. The hold placed for the fare at request time, turned into the charge when the trip completes, and removed on cancel.