GOAT EngineerPreparing your learning space…

System Design · Interview breakdown · Free article

Design a Ride-Hailing Service (Uber, Lyft)

Take 200,000 driver pings a second, find the free cars near one rider, and give each trip exactly one driver. Built one step at a time, with experiments you can run.

A ride-hailing service matches a rider who wants a car now with a nearby driver, then tracks the trip until it ends and the fare is charged. Drivers’ phones send their position every few seconds into an in-memory geo index for each city, where a newer ping replaces the old one. A ride request searches the index’s cells around the rider for free drivers and ranks a short list by road time. The trip is offered to one driver at a time, with a write that succeeds only if that driver is still free. A driver who does not answer in ten seconds is replaced by the next.

Difficulty: Hard. Reported in interviews at Amazon, Google, Meta, Salesforce, Visa. Also asked as Design Uber, Design Lyft, Design a proximity service, Design a taxi dispatch system, Design food delivery dispatch.

How do you design a ride-hailing service like Uber?

A ride-hailing service matches a rider who wants a car now with a driver close enough to pick them up. Then it follows the trip until it ends and the fare is paid. Uber and Lyft are the famous ones. The hard part is doing that matching in a couple of seconds, from a map of drivers that is moving while you read it.

  1. Quote: Airport · €18 · 4 min. The price and the 4 minutes both depend on which drivers are near her right now.
  2. Finding a car: Finding your driver…. A million drivers are online. A handful are near the station, and only some are free.
  3. Driver’s offer: New trip · 3 min · 10 s. Two riders can want the same driver in the same second. Only one may get them.
  4. On the way: D2 · 3 min away. The car on her map must move every few seconds, sent from a phone on a weak signal.
  5. Arrived: Trip done · €18 charged. The fare is charged once, even when the payment reply gets lost.
Meera sees five screens. Behind them, one service tracks a million moving drivers.

Picture Meera leaving a train station at 18:04 with a suitcase. She opens the app, types the airport, and sees €18 with a car 4 minutes away. She taps Request. Twelve seconds later a driver called D2 is on the way, and she watches a small car move toward her on the map.

On her screen that is one tap. Behind it, a million drivers’ phones are each reporting their position every five seconds. The service has to find the few free ones near the station and pick the one that can reach her soonest. It also has to make sure nobody else is promised the same car.

Interviewers like this problem because the first drawing is easy. The rest of the round is about a firehose of writes, a search on a map, and two people racing for one driver.

Here is the design in four sentences. Every driver’s phone sends its position every five seconds into an in-memory geo index for its city, where a newer ping replaces the old one. When Meera requests a ride, a matching service looks in the index’s cells around her for free drivers and ranks a short list by road time. The ride service offers the trip to the best driver with a write that succeeds only if that driver is still free. A driver who does not answer within ten seconds loses the offer, and the next one on the list gets it.

The rest of this page is about the moments that design has to survive.

Here is the first one. At 18:04:00 Meera and Tom, a block away, both tap Request. Both matchers find driver D2 free. If each one writes “D2 is yours” and tells its rider, two people are waiting for one car.

Here is the second. D2’s phone sits in a cup holder on a weak signal. D2 taps accept on Meera’s offer at 18:04:09, one second before it expires. The tap reaches the server at 18:04:12. By then the offer has expired and D2 has been offered to Tom. A design that lets the late tap through has double-booked D2 anyway.

What is the interviewer testing?

Most candidates draw a rider app, a driver app, a location service, a matching service and a trips database in the first ten minutes. That drawing is right. A mid-level answer often stops there.

The interviewer then pushes on six questions. A million drivers ping every five seconds: where do those writes go? How do you find the drivers near Meera without looking at all of them? Two riders want the same driver: what stops a double booking? The driver ignores the offer: how long does Meera wait? A concert ends and twenty thousand people ask for a car from one block: what breaks? Meera’s phone loses signal in a tunnel: what does she see when it comes back?

A senior answer handles the first three well. A staff answer also handles the unanswered offer, the crowd, and what happens when a city’s servers fail.

Spend most of the deep-dive time on the location writes, the nearby search and the double booking. The unanswered offer and the crowd are the usual follow-ups. How to run a round has the time plan for a 45 to 60 minute round and a 15-minute screen.

What should you ask before drawing anything?

Four questions change the design. Ask them in the first two minutes. If the interviewer leaves one open, say your assumption out loud.

How big, and how many cities?
A service in one city with 2,000 drivers can keep everything in one database. A service in hundreds of cities with a million drivers online cannot. Assume a million drivers online at the busiest hour, ten million rides a day, and cities that mostly do not share drivers.
One rider per car, or shared rides?
A shared ride puts two strangers in one car and has to check that the second pickup does not wreck the first rider’s trip. That is a routing problem of its own. Assume one rider party per car. Shared rides are out of scope.
Do we assign the driver, or do drivers pick trips?
Picture a driver at a red light with a list of ten nearby requests. The best trips go to whoever taps fastest. Assume the service offers each trip to one driver at a time, and the driver has about ten seconds to accept or decline.
How fresh must the map be?
A car drawn where it was five seconds ago is fine; it is still coming. A car drawn that went offline two minutes ago is a lie. Assume positions up to about ten seconds old are acceptable, and a driver silent for fifteen seconds disappears from search.

Functional requirements

On the board: Functional requirements
1. Rider: fare + pickup time for A → B
2. Rider: request; matched to a nearby driver
3. Driver: accept or decline within 10 s
4. Both see each other move until pickup
5. Trip ends; the fare is charged once
out: shared rides, scheduling, ratings

Say it, don’t write it: The rule that never bends is that one driver is never promised to two riders.

Two people use the service: a rider who wants a car now, and a driver who is online and wants trips.

  1. A rider enters a pickup and a destination and sees a price and how soon a car can arrive.
  2. A rider requests a ride and is matched to a nearby driver who is free.
  3. The driver sees the offer and accepts or declines it within 10 seconds.
  4. Until pickup, the rider sees the car move on the map, and the driver sees where to go.
  5. The driver marks arrival, the start and the end of the trip, and the fare is charged once.

Out of scope

  • Shared rides, where one car carries several riders
  • Rides booked for later
  • Ratings, tips and driver sign-up
  • Building the road map and the routing engine; we call one
  • How the price is computed, beyond the surge multiplier the crowd section needs

Two words need pinning down now. An offer is one driver being asked to take one trip, with a deadline. A trip is Meera’s request from the moment she taps until the fare is charged. One trip can go through several offers before a driver accepts. Keeping the two apart is most of this design.

Non-functional requirements

On the board: Non-functional requirements
• First offer out < 2 s after request (p99)
• A driver is never double-booked
• Map position ≤ 10 s old; approximate is OK
• An accepted request is never lost
• 200k pings/s without slowing matching
• One busy block must not stall its city

Say it, don’t write it: Positions can be a little wrong. Assignments cannot be wrong at all.

A driver’s position is out of date five seconds after it arrives, and a slightly wrong one costs nothing. The promise that D2 is coming for Meera is the opposite. It must be exactly right, and it must never be lost. So the service holds two kinds of data that deserve opposite treatment. The design spends its care on the promises and its speed on the positions. The targets are illustrative interview numbers, not measurements of any real service.

  • 99% of ride requests send their first offer to a driver within 2 seconds.
  • A driver is never committed to two trips, and a trip never has two drivers.
  • A driver on the map is at most about 10 seconds out of date. An approximate position is fine.
  • A ride request the API has accepted is never lost.
  • 200,000 driver pings a second do not slow matching down.
  • A crowd in one block does not stall the rest of its city.

The numbers on this page come from one made-up workload. A million drivers are online at the busiest hour, each phone sends its position every five seconds, and riders take 10 million rides a day. 1,000,000 phones ÷ one ping every 5 seconds is 200,000 pings a second. Each deep dive below works out the other numbers it needs from these.

Suppose the trips database cannot confirm a write. Then the API refuses the request, and the app says so. It never shows “Finding your driver” for a trip nobody recorded.

Core entities

On the board: Core entities
Driver(id, city, status, offer, trip)
Location(driver, lat, lng, seen_at) memory
Quote(id, pickup, drop, price, expires)
Trip(id, rider, driver, state, version)
Offer(id, trip, driver, expires, outcome)

Say it, don’t write it: A location can be lost and nobody notices. A trip’s driver can never be lost or doubled.

Follow one request through the system. Meera asks for a price, and gets quote Q9: €18, valid for two minutes. She taps Request, which creates trip T1 in the state searching. The ride service offers T1 to D2 as offer O1. D2 does not answer, so O1 expires. Offer O2 goes to D3, who declines. Offer O3 goes to D4, who accepts. T1 now has a driver.

Each of those records holds a few fields.

The driver record holds the driver’s city and status: offline, available, offered or on_trip. While an offer is open, it also holds that offer’s ID and deadline. Once the driver accepts, it holds the trip’s ID. The status is the truth about who may be offered a trip.

The location holds a latitude, a longitude, the time the phone read them, and a counter. It is replaced every five seconds.

The quote holds the rider, the pickup, the drop-off, the price with its surge multiplier, and an expiry. It is the price Meera agreed to.

The trip holds the rider, the quote, the driver once one accepts, its state, a version and the fare. It is the one record every step checks.

The offer holds the trip, the driver, when it was sent, its deadline and its outcome. Every offer is kept, so support can explain a long wait.

Look at where each record lives. Driver, quote, trip and offer rows are in the trips database, because they carry promises. That database is PostgreSQL, one per city, because each promise is a row that changes only under a condition. The location is in memory, because it is replaced every five seconds and a lost one is refilled by the next ping.

A ping says where D4 is. It never says whether D4 is free. Suppose a late ping could set D4 back to available. Then D4 could be offered a second trip halfway through the first. So a driver’s status and position are different things, and mixing them is a classic mistake.

API

On the board: API
POST /quotes {pickup, dropoff} → price
POST /trips {quoteId, requestId} → trip
socket: ping {lat, lng, capturedAt, n}
POST /offers/:id/accept · /decline
POST /trips/:id/arrive|start|end {version}
GET  /trips/:id → state, driver, version

Say it, don’t write it: A request ID makes a retried request return the same trip, not a second car.

The rider app and the driver app each keep one connection open to a socket gateway. Pings go up it, and offers and positions come down it. Everything that changes a trip goes through ordinary HTTP calls, so it can be retried and checked.

RequestResponseRule it enforces
POST /quotes201 with price, pickup minutes and expiryA quote reserves no driver
POST /trips201 with the trip in state searchingThe same request ID returns the same trip; the quote must not have expired
ping over the socketNothing backOnly the driver’s own session may send it; an older counter is dropped
POST /offers/{id}/accept, /decline200 with the trip, or 409 if the offer is goneOnly the driver it was sent to; only while the row still holds it
POST /trips/{id}/arrive, /start, /end200 with the new version, or 409Carries the version the app read, so a late message cannot move the trip backward
POST /trips/{id}/cancel200 with any feeRaces with acceptance through the same row
GET /trips/{id}State, version, driver and positionOnly the trip’s rider and driver
Concrete exchangeMeaning
POST /trips with {"requestId":"r-5c1","quoteId":"Q9"}201 {"tripId":"T1","state":"searching","version":1}
Driver ping over the socket: {"lat":38.7223,"lng":-9.1406,"capturedAt":"18:03:58.2","n":4812}The location service keeps it only if 4812 is higher than the counter it holds for D2
POST /trips/T1/start with {"version":4}200 {"state":"in_progress","version":5}

Three fields exist for a reason. The request ID makes a request that timed out in a tunnel safe to send again: Meera’s app retries, and gets T1 back instead of a second car. The counter n goes up with every ping, so a packet that arrives late cannot move the car backward. The version makes each trip change conditional on the state the app last saw.

The driver’s exact position is shown to one rider, and only during their trip. Before Meera requests, the map of cars around her shows approximate icons. That way nobody can follow one driver around the city through the API.

Step 1: drivers report where they are

Before any rider can be matched, the service has to know where the drivers are. D2 goes online. D2’s phone opens a connection to the socket gateway and sends a ping every five seconds: latitude, longitude, the time the phone read its GPS, and a counter.

The gateway passes each ping to the location service. The location service drops a ping whose counter is lower than the one it already holds for D2. Otherwise it writes the position into the geo index for D2’s city. The geo index keeps one position per driver. A new ping overwrites the old one.

The interactive version of this example is available when JavaScript loads.

This path carries 200,000 pings a second, and none of them is precious. The first deep dive shows why they go to memory and not to a database.

Step 2: quote a fare

Meera enters the airport. The app calls POST /quotes. The ride service asks the matching service for the free drivers nearest the station and their road time to her, which gives the “4 min” on her screen. It asks the maps service for the road distance and time from the station to the airport. It prices the trip, stores quote Q9 with a two-minute expiry, and returns €18.

The quote reserves no driver. It is a snapshot of the market. If Meera waits five minutes before tapping Request, the quote expires, and she sees a fresh price.

The interactive version of this example is available when JavaScript loads.

Matching only searches and ranks. It writes nothing. That keeps the one component that must be exactly right, the ride service and its database, small.

Step 3: request, match and offer

Meera taps Request. The ride service writes trip T1 in the state searching, and answers her app. Then it asks matching for a ranked shortlist: D2 at 3 minutes, D3 at 5, D4 at 6.

The ride service offers T1 to D2 with one conditional write on D2’s row. The write sets the status to offered, holding offer O1, but only if D2 is still available. If the write changes a row, O1 is D2’s. The ride service pushes the offer to D2’s phone through the socket gateway. If the write changes nothing, another rider got D2 first, and the ride service tries D3.

D2 taps accept. The accept is another conditional write: set D2 to on_trip and T1 to assigned, in one transaction, but only if D2’s row still holds O1. Meera’s app gets “D2 is on the way.”

The interactive version of this example is available when JavaScript loads.

The third deep dive shows why the write has to name the offer, and not just check that the driver is free.

Step 4: pickup, the trip and the fare

From now on Meera’s app also holds a socket. While D2 drives to her, the location service forwards each of D2’s pings to Meera’s connection, and her map moves. D2 marks arrival, then starts the trip, then ends it at the airport. Each of those is a trip change carrying the version D2’s app last saw.

Trip stateMoves toAllowed when
searchingassigned, or cancelledA driver’s accept wins the row; or the rider cancels first
assignedarrived, or cancelledThe assigned driver arrives; either side cancels under the fee rules
arrivedin_progressThe assigned driver starts the trip
in_progresscompletedThe assigned driver ends the trip
completednothingPayment and support change their own records, not the trip’s state

A delayed “arrived” that reaches the server after “started” carries an old version, so the server refuses it. The trip never moves backward because a message came in late.

At the end, the ride service computes the fare from the trip and the quote. It records the fare and asks the payment provider to charge it, keyed by the trip ID and the charge type. The payment follow-up after the deep dives covers the reply that never comes.

The interactive version of this example is available when JavaScript loads.

On a quiet evening this design already works. The deep dives below are six moments it has to survive. They are 200,000 pings a second, a search on a moving map, two riders racing for one driver, an offer nobody answers, a stadium emptying and a tunnel.

A million drivers ping every 5 seconds. Where do 200,000 writes a second go?

It is 18:00 on a Friday in Lisbon. D2 is parked in a side street south-west of the station, with the app open. Every five seconds, D2’s phone reads its GPS and sends one small message: latitude, longitude, the time it read them, and a counter. Call it 100 bytes. Across every city, a million drivers are online, and every phone does the same.

1,000,000 phones ÷ one ping every 5 seconds is 200,000 pings a second. In bytes that is small. 200,000 × 100 bytes is 20 MB a second, which any network carries. The count is the problem. Each ping is a separate write, and five seconds later the next ping makes it worthless.

The first design most people draw keeps latitude and longitude as two columns on the drivers table, in the trips database, with an index on them. Every ping becomes one UPDATE of D2’s row. In a small city with 2,000 drivers, that is 2,000 ÷ 5 = 400 updates a second. One database takes that without noticing.

Now do the Friday arithmetic for the busiest city, which has a trips database of its own. Say it holds 50,000 drivers online, 5% of the million. 50,000 ÷ 5 is 10,000 pings a second into its trips database.

The same database records that city’s rides. Across the service, 10 million rides a day is 10,000,000 ÷ 86,400, about 116 a second. Say the evening peak runs at ten times the average: about 1,160 ride requests a second. The busiest city’s 5% share is about 58. Each ride writes the database about ten times: the quote, the trip, an offer or two with their expiries, the accept, arrival, start and end. So 58 rides make about 580 writes a second. 10,000 ÷ (10,000 + 580) is about 95%. Nineteen of every twenty writes are pings.

Each of those updates is expensive in ways the data does not need. The database writes a new version of the row. It updates the index on the two columns. It appends a record to its log and flushes it to disk before confirming, so the update survives a crash. Replay a crash to see what all that protects. The database restarts and restores D2’s last position from its log. D2’s phone sends a newer one within five seconds anyway. The one database that must never lose a trip is spending most of its effort protecting data that is stale on arrival.

The next idea moves positions out of the trips database, into a spatial database of their own, one per city. PostGIS stores each position as a geography value with a spatial index. Now the pings no longer compete with the trips. The busiest city’s 10,000 pings a second land on a database of their own.

This works. But look at what each ping still pays for. It is logged to disk, the spatial index is updated, and the change is copied to a replica. That buys durability for a fact the phone will repeat in five seconds. Across all cities, at 200,000 pings a second, most of that effort protects nothing.

So keep only the newest position, and keep it in memory. Each city gets one Redis geo set, a structure that stores members with coordinates and can search them by distance. D2’s ping becomes GEOADD drivers:lisbon -9.1406 38.7223 D2. Adding a member that already exists replaces its position. So the set holds at most one entry per driver, and it never grows. The next deep dive trims it further, to available drivers only.

An entry costs more in memory than the 100 bytes it took on the wire. Say 100 to 150 bytes, and two entries per driver, because a second set appears below. That estimates 200 to 300 MB for all million drivers. Every online driver still fits in one machine’s memory.

A write here is a change in memory. Switch Redis persistence off, and nothing is written to disk. Redis also copies a write to its replica after confirming it, so no write waits for a copy either. Replay the crash. The Redis node for Lisbon restarts and comes back empty. Within five seconds, every phone in Lisbon has sent its next ping, and every driver is back. Nothing in the set was the only copy of anything. The phones hold the truth about where they are, and they repeat it every five seconds. Losing the set costs one ping cycle of search results, and no promise. Data like this, rebuilt by its sources, is called soft state.

A replica still helps, because it makes a failover faster. It needs one precaution. With persistence off, a primary that restarts on its own comes back empty, and its replica then copies the empty set. The Redis replication docs warn about exactly this. So turn off automatic restart, and let the replica be promoted first.

The widget below shows a large city split into three zones, each its own key on its own node. Guess how long a restarted node takes to fill again, then restart it. The three tabs are the guesses.

The interactive version of this example is available when JavaScript loads.

The ten Station drivers come back one at a time, each with its phone’s next ping, and the last lands after 4.8 seconds.

Memory brings two problems that the database had hidden.

The first is order. D4 is driving along the river road. D4’s phone sends ping 3301 at 18:03:53, then ping 3302 at 18:03:58, 60 metres further on. Ping 3301 gets stuck behind a weak cell signal and arrives after 3302. A set that keeps the last arrival moves D4’s car 60 metres backward. So every ping carries the counter the phone increases, and a ping whose counter is lower than the last one kept is dropped.

Many location-service machines take pings, so the highest counter has to live where all of them see it. Keep it in Redis, in a hash for the city, beside the positions. A short Lua script handles each ping as one step. It compares the counter and, only if the new one is higher, stores it and moves the driver. Redis runs a script without interleaving other commands. So two scripts cannot both read the old counter and then both write, which is how a late ping could slip past. The other way is to send every ping from one driver to the same location-service machine, which then keeps the counter in its own memory.

The counter has one gap. After the Redis node restarts, it has forgotten every driver’s counter. A late packet that lands in that moment is accepted, and a car jumps back once. The next ping corrects it five seconds later. Nothing here decides who drives whom, so that trade is fine.

The second problem is silence. D5 drives into a tunnel, and the pings stop. The geo set still holds D5’s last position. So search keeps finding D5 and keeps offering trips that D5’s phone cannot receive. Each one wastes a rider’s ten-second offer. A geo set is a sorted set underneath, and a sorted set has no expiry per member. So the same script also writes a second sorted set, seen:lisbon, recording when each driver last pinged. Every few seconds a sweeper removes any driver silent for 15 seconds from both sets. Fifteen seconds is three missed pings. The code aside in the third deep dive shows the commands.

One key per city also decides the sharding. Redis Cluster puts each key on one shard, chosen from a hash of its name. So on a cluster, a city’s keys share a hash tag: drivers:lisbon becomes drivers:{lisbon}, beside seen:{lisbon}. That puts them on the same shard, and lets one script touch them all. A search in Lisbon then asks one machine.

Now size that shard for the busiest city. Its 10,000 pings a second are 10,000 script runs, each a few commands, so call it 30,000 to 40,000 commands a second. Its searches are far fewer. About 58 ride requests a second at the peak, plus their quotes, each make one or two radius searches. The sweeper adds one scan every few seconds. As an illustrative figure, take one Redis shard at about 100,000 simple commands a second, and measure your own. The busiest city then fits one shard with room to spare. A city far bigger splits into areas, each its own key, like the zones in the widget above. A rider near a boundary between areas searches both keys.

Nothing above keeps a history, and receipts, disputes and arrival-time models need one. Keeping every ping would take 200,000 × 100 bytes × 86,400 seconds, about 1.7 TB a day. So the location service sends only what is needed to a Kafka topic, off the path to matching. Receipts and disputes need the route of every trip, so every ping of a driver on a trip goes. Say half the online drivers are on a trip or heading to one: 100,000 pings a second. 100,000 × 100 bytes × 86,400 is about 0.86 TB a day, or about 26 TB over 30 days. A small sample of the other pings is added for arrival-time models. The topic keeps 30 days.

Location history is personal data. Only the people who need it can read it. Logs carry trip and driver IDs, never exact coordinates.

The interactive version of this example is available when JavaScript loads.

The hot path now writes memory only. The trips database, which carries every promise, never sees a ping.

The gap: A ping is worth something for five seconds, and 200,000 of them arrive every second.

Option 1: Update the driver’s row in the trips database

Latitude and longitude are indexed columns on the driver row, updated on every ping.

Works when: One small city, where 400 pings a second sit easily beside the trips.

Breaks when: In the busiest city about 95% of the trips database’s writes are pings, each one logged and indexed.

Option 2: A spatial database per city

Positions live in PostGIS with a spatial index, apart from the trips, about 10,000 writes a second in the busiest city.

Works when: A market whose pings would crowd the trips database but fit a spatial database of their own.

Breaks when: Every ping is still logged, indexed and copied, to protect a fact the phone repeats in five seconds.

Option 3: Newest position only, in memory, per city (start here)

A Redis geo set per city holds one entry per driver, overwritten by each ping, a few hundred megabytes for a million drivers.

Works when: Any city whose pings fit one shard, with bigger cities split into areas.

Watch for: A late packet can move a car backward, and a silent phone stays searchable.

Fix within it: A Lua script drops any ping with an older counter, and a sweeper removes drivers silent for 15 seconds.

In the interview: Open with option 3, and give the number that forces it: 200,000 writes a second, each stale five seconds later. Name option 1 as the right start for one small city, and say where pings start to crowd out the trips.

Say this: A million drivers pinging every five seconds is 200,000 writes a second, and each is stale five seconds later. So I keep only the newest position per driver, in an in-memory geo set per city. If a node restarts, the phones refill it within five seconds, so it needs no disk. For one small city I would keep positions as indexed columns in the trips database, and move them to memory when pings crowd them out.

Meera stands at the taxi rank outside the station. A river runs just east of her, and the only bridge is far up the map, to the north. Four free drivers are within 650 metres of her. The matcher has to find them, then decide which one to ask first.

The simplest search keeps every driver in one table, with no split by city and no spatial index. It measures the distance from Meera to each driver and keeps the closest. In a service with 2,000 drivers, that is 2,000 small sums per request, and it costs nothing.

At the Friday peak the arithmetic changes. The last deep dive put the peak at about 1,160 ride requests a second. Each one facing a million drivers is 1,160 × 1,000,000, over a billion distance checks a second.

Splitting by city helps. The busiest city then scans 58 × 50,000, about 2.9 million a second, which memory can afford. Yet each search still reads 50,000 positions to find the handful near one rider.

A range query on two indexed columns is the next thing people reach for, and it is little better. Ask for a latitude between two values and a longitude between two others. The index on latitude finds a thin band that runs across the whole city, east to west. Every driver in that band is then checked on longitude, one at a time. The index has cut the city in one direction only.

The fix indexes the map instead of the drivers. Cut the map into cells and give each position the ID of its cell. Geohash does this by interleaving the bits of latitude and longitude into a short string, so nearby points usually share a prefix. Store drivers by cell, and a search reads one cell instead of a city.

Replay Meera’s search against her own cell only. It finds D3, 502 metres away and 5 minutes by road. It misses D1, only 244 metres away, because D1 is over the cell line to the east. Meera stands 40 metres from her cell’s edge, and a one-cell search is blind to anyone just over it.

So search her cell and the eight around it. On a grid of squares, the nine cells contain every point within one cell width of her, wherever she stands in her own cell. Most geohash cells are rectangles, and there the promise holds only for the shorter side. If the ring finds no free driver, or too few to choose from, widen by one more ring, up to a limit such as 5 km.

The ring finds four drivers. Ranked by distance on the map, D1 comes first at 244 metres. But D1 is across the river. The only bridge is near the top of the map, so D1 needs 9 minutes to reach her. D2, at 615 metres, is on her side and needs 3. A straight line knows nothing about rivers, one-way streets or traffic.

So the matcher sends its shortlist, up to about 20 drivers, to the routing service and asks for each one’s road time to Meera. Routing services answer that as one matrix request: one rider, twenty drivers, one reply. At the peak, 1,160 requests × 20 drivers is 23,200 road times a second, carried in 1,160 calls. That is expensive, and it is affordable only because the cells cut a million drivers down to twenty first.

The widget has both halves. The Search chips compare her cell alone with her cell and the eight around it. The Rank by chips switch a straight line for road time.

The interactive version of this example is available when JavaScript loads.

Ranked by road time, D2 comes first at 3 minutes, although it is 615 metres away on the map. The routing service ran on four drivers, not on the city.

Cells bring two problems of their own.

A fixed cell is the wrong size somewhere. In the city centre on a Saturday night, one 600-metre cell can hold hundreds of free drivers waiting for fares. A search reads all of them to rank twenty. In a suburb at 03:00, nine cells hold nobody, and the search widens ring after ring. Two schemes let the cell size follow the crowd. A quadtree splits a square into four whenever it holds too many drivers, so cells are small downtown and large in the suburbs. H3 is a grid Uber built and released as open source. It covers the earth almost entirely in hexagons, at 16 resolutions. A service can search fine hexagons downtown and coarse ones in the suburbs.

The index also lags the truth by a moment. D3 may have accepted another trip a second ago while the index still lists D3 near Meera. So the index keeps only available drivers. When the ride service changes a driver’s status, it publishes the change on a stream. The location service reads that stream and keeps a small cache of each driver’s status. When D3 leaves available, it removes D3 from the searchable set. While the cache says busy, D3’s pings reach the rider tracking D3, but not the searchable set. A search can still read the set in the moment before the removal lands. So the offer write in the next deep dive checks again that the driver is free. The search proposes, and only that write decides.

Which kind of cell to use is a common follow-up, so know the three.

SchemeHow a cell is foundGood atWeak at
GeohashInterleave the bits of latitude and longitude into a short string; a longer string is a smaller cellWorks in any store that sorts strings. Redis geo sets use it underneathCells are fixed in degrees, so they narrow east to west away from the equator. Most are rectangles, and two cells that touch can have very different strings
QuadtreeSplit a square into four, again and again, until each holds few enough driversFollows density: small cells downtown, big ones in the suburbsDrivers move, so the tree keeps splitting and merging. It is also harder to share across machines
H3 hexagonsA library maps a point to a hexagon at one of 16 resolutionsEvery neighbour is the same distance from the centre, which keeps rings evenA parent hexagon only roughly contains its seven children, so counts rolled up to a coarser level are approximate

Uber describes building H3 for ride pricing and dispatch, and measuring supply and demand in hexagons to set surge pricing (H3). It gives the reason for hexagons. A hexagon has one distance from its centre to every neighbour, where a square has two.

Redis gives you the geohash version ready made, as a radius search. GEOSEARCH takes a centre and a radius, reads the geohash cells that cover that circle, and keeps the members inside it. Widening by a ring becomes searching again with a larger radius. With COUNT and ASC it returns the nearest few. Without the ANY option, its work grows with the number of members in the area, even if you ask for five (GEOSEARCH). That is one more reason to keep the radius small and widen it only when needed.

Any of the three schemes works in an interview. Name one, explain the neighbour search, and say how the cell size follows density.

The gap: A million drivers must shrink to a short list, and the nearest dot is not always the nearest car.

Option 1: Measure the distance to every driver

Compute the rider’s distance to every driver in one table, or run a range query on two indexed columns.

Works when: A few thousand drivers, where a scan costs almost nothing.

Breaks when: With one table at the peak, a scan is over a billion distance checks a second, and a range query still reads a band across the city.

Option 2: Search her cell only

Store drivers by cell ID, as geohash does, and read the rider’s cell.

Works when: The rider stands well inside a cell that holds enough free drivers.

Breaks when: D1 is 244 metres away, over the cell line, and the search never sees it.

Option 3: Nine cells, nearest on the map first

Read her cell and the eight around it, widen by rings, and offer the closest dot.

Works when: Open streets, where distance on the map tracks driving time.

Breaks when: The nearest dot is across the river, 9 minutes away.

Option 4: Nine cells, then rank a shortlist by road time (start here)

Send up to 20 of the ring’s nearest drivers to the routing service in one call, and offer the fastest.

Works when: Any city, since routing runs on 20 drivers, never on a million.

Watch for: Fixed cells are the wrong size somewhere, and the index can list a driver who was taken a moment ago.

Fix within it: Let cell size follow density with a quadtree or H3, keep only available drivers searchable, and let the offer write check again.

In the interview: Open with option 4, and draw the ring of nine cells first. Explain the ring with the rider near an edge, and the road time with the river. If the interviewer asks which cells, name one scheme from the table and say how its size follows density.

Say this: Scanning one table of a million drivers is a billion checks a second at the peak, so I store drivers by map cell. I search the rider’s cell and the eight around it, because she may stand near an edge, and widen by a ring if too few turn up. Then one routing call ranks a shortlist of about 20 by road time, because the nearest dot can be across a river. The offer write checks again that the driver is still free.

Two riders get the same driver at the same moment. What stops a double booking?

At 18:04:00 Meera and Tom, a block apart, both tap Request. Two matchers run at the same moment, one for each rider, and both put D2 at the top of their lists. Offers last 10 seconds. D2’s phone sits in a cup holder on a weak signal.

On a quiet night, two riders reaching one free driver in the same second is rare. At the Friday peak, 1,160 requests a second draw on the same few free cars around each station. The bug is the same. It happens far more often.

The obvious code reads D2’s row, sees available, and writes D2 as assigned to its rider. Replay it with two matchers. Meera’s matcher reads available at 18:04:00.00. Tom’s matcher reads available a moment later, before anything has changed. At .03 Meera’s matcher writes D2 as hers and tells her a car is coming. At .04 Tom’s matcher writes D2 as his and tells him the same. Tom’s write replaced Meera’s in the row. The database records one assignment, and two riders are waiting for one car. Nothing even logs that it happened.

Reading that D2 is free and promising D2 to a rider are two steps. Another matcher fits between them.

The next idea is a lock. Before offering D2, a matcher takes a lock on D2 in Redis that expires after 10 seconds, the length of an offer. A matcher that cannot take the lock moves on. Replay the race. At 18:04:00 Meera’s matcher takes the lock and offers D2 her trip, offer A. At 18:04:02 Tom’s matcher tries, fails, and leaves D2 alone. So far the lock works.

Now add the weak signal. D2 taps accept on offer A at 18:04:09, one second before it expires. The tap takes three seconds to reach the server. At 18:04:10 the lock expires, and Meera’s matcher gives up on D2. Tom’s matcher has found nobody better. At 18:04:11 it takes the lock and offers D2 Tom’s trip, offer B. At 18:04:12 the late tap on offer A arrives. The accept handler checks that D2 is locked. D2 is locked, by Tom’s matcher, so the handler assigns D2 to Meera. D2’s screen now shows offer B, and at 18:04:14 D2 accepts that too. Both riders are told D2 is coming.

The lock answered the question “is anyone holding D2?” The question that mattered was “is this the offer D2 is holding?” The two differ exactly when one offer ends and the next begins, which is when late taps arrive. A Redis lock has a second weakness. By default Redis copies a write to its replica after confirming it. Suppose the Redis primary dies a moment after granting Meera’s lock. The replica it fails over to never heard of that lock, so Tom’s matcher takes one at once.

The fix makes D2’s row in the trips database the only place a promise is made, and makes every write name its offer. The offer is one conditional write: set D2 to offered, holding offer A, only where D2 is available. If it changes one row, offer A is D2’s. If it changes none, another matcher got there first, and this one tries its next driver.

The accept names the offer too. It sets D2 to on_trip only where the row still holds offer A. The expiry is the same kind of write. It sets D2 back to available only where the row still holds offer A.

Replay the race. At 18:04:00 Meera’s offer write changes the row. At 18:04:02 Tom’s changes nothing, and Tom’s matcher moves on. At 18:04:10 the expiry frees D2, because the row still holds offer A. At 18:04:11 Tom’s offer write puts offer B on the row. At 18:04:12 the late tap on offer A needs the row to hold A. It holds B, so nothing changes, and D2’s phone says that offer has gone. At 18:04:14 D2 accepts B, and D2 is Tom’s. Meera’s matcher is already asking D3.

Notice what the accept does not check: the clock. The database applies the accept and the expiry one after the other on the same row. Whichever arrives first changes what the row holds, and the other then matches nothing. A tap that lands a moment after 18:04:10, before the expiry write, still wins. That is harmless, because nobody else holds D2 yet.

The expiry has to name the offer too. Suppose it freed D2 by driver ID alone, and the expiry for offer A ran a second time, at 18:04:11.5, after Tom’s offer. It would free D2 from offer B, and a third matcher could offer D2 again. A write that succeeds only while the row still holds the value it expects is a compare-and-set. The offer ID works like the fencing token a lock hands out. It checks the current holder rather than a number that only rises. The effect is the same: a writer holding an old one changes nothing.

The three tabs below replay the race. The first reads and then writes, the second takes a lock, and the third writes only while the row holds its offer.

The interactive version of this example is available when JavaScript loads.

The accept changes two rows. D2 becomes on_trip, and Meera’s trip moves from searching to assigned with D2 as its driver. Both changes happen in one transaction. The trip write has its own condition: only while the trip is still searching. Suppose Meera cancelled a second earlier. Her cancel changed the trip first, so the accept’s trip write changes no row. The ride service sees that and rolls the whole transaction back. D2 is never left driving to a trip that no longer exists.

This is an ordinary local transaction, because both rows live in the same city’s database. Riders and drivers are told only after the commit. A notification sent earlier could announce a write that then rolled back.

Here are the three writes that decide who drives whom: the geo index commands, the offer and accept, and a small-city version in one database.

The interactive version of this example is available when JavaScript loads.

Every database write in it carries a condition. None holds a lock while a person decides. A driver takes up to ten seconds to answer, and no database lock should last that long.

Uber describes the same problem in its own dispatch system. Its older design favoured availability, so consistency was best effort. When a driver accepts, all the related records have to change together, all or nothing. Uber moved that state to Spanner, a database that runs transactions across machines (Fulfillment platform). That pays off when a trip’s records cannot share one machine. Every commit then coordinates several machines. With one relational database per city, a driver and a trip already share a machine, so a local transaction does the same job.

The gap: Reading that D2 is free and promising D2 are two steps, and D2’s answer can arrive after the offer has ended.

Option 1: Read, then assign

Read the driver’s row and, if it says available, write the driver as assigned.

Works when: One matcher handles the city, one request at a time.

Breaks when: Two matchers both read available, both write, and both riders are told D2 is coming.

Option 2: A Redis lock with a 10-second expiry

Take a lock on the driver before offering, and skip the driver if another matcher holds it.

Works when: Every tap reaches the server before its offer ends, and Redis never fails over during an offer.

Breaks when: A late tap on an expired offer finds D2 locked by the next offer, and gets through.

Option 3: A conditional write that names the offer (start here)

The offer, the accept and the expiry each change the driver’s row only where it holds the expected status or offer.

Works when: Any number of matchers, since the database orders every write on the row.

Watch for: A write that forgets to name the offer, such as an expiry by driver ID alone, frees the driver from a newer offer.

Fix within it: Name the offer in every write, the expiry included, change both rows in one transaction, and notify only after the commit.

Option 4: One transactional store across machines

A database such as Spanner runs one accept across rows that live on different machines.

Works when: A trip’s records cannot share one machine.

Watch for: Every commit coordinates several machines.

Fix within it: Reach for it only when one database per city cannot hold a trip’s records.

In the interview: Open with option 3, and say the two conditions that carry it: “only if available” and “only if the row still holds this offer”. Bring up option 2 to show why a lock answers the wrong question. Reach for option 4 only if the interviewer puts a trip’s records on different machines, and say what each commit then costs.

Say this: The bug is a check-then-act race: two matchers both read D2 as free. I make D2’s row the only place a promise is made, with a write that offers D2 only if D2 is available. The accept and the expiry each change the row only where it still holds that offer, so a late tap matches nothing. The driver and trip rows share one city database, so the accept is one local transaction.

The driver ignores the offer. How long does Meera wait?

Take a different evening. Meera taps Request at 18:04:00 again, and her shortlist is D2 at 3 minutes, D3 at 5, D4 at 6 and D1 at 9. Tonight D2’s phone is in a pocket, and D2 will never see the offer. D3 will decline, because the airport is the wrong direction for going home. D4 will accept. D1, across the river, has the quickest thumb of the four tonight.

The matcher has to choose whom to ask, in what order, and what notices when nobody answers.

The fastest-looking answer sends the offer to all four at once, and the first to accept gets it. Replay it. All four phones ring at 0 seconds. D1 taps accept at 2 seconds, and the conditional write gives D1 the trip. Everyone at once looks fastest, matching at 2 seconds. Then Meera sees the car. D1 is across the river, 9 minutes away. D4 said yes at 5 seconds and was told the trip was gone.

Run it on a second night, when every driver answers differently. D4 declines at 2 seconds, D3 accepts at 3, D2 at 4 and D1 at 6. D3 wins, 5 minutes away instead of D2’s 3. D2 and D1 are told they are too late. Four phones rang for one trip. A driver told “too late” several times an hour tends to stop hurrying to answer, which makes every later offer slower. Sending to everyone turns the offer into a race of reflexes, and the fastest thumb is not the nearest car.

So ask one driver at a time, best first. Offer D2. If D2 has not answered in ten seconds, offer D3, then D4. The simplest place for that ten-second timer is memory: a timer set inside the ride service process that sent the offer.

Replay the pocket. At 0 seconds the offer reaches D2. At 4 seconds that process restarts for a deploy. The timer lived in that process, so it is gone. D2 never answers, and nothing else knows the offer should end. Nobody ever asks D3. Meera sits on “Finding your driver” with a trip nobody is working on.

The fix moves the deadline out of the process. The offer write stores offer_expires_at on D2’s row. Then a component that survives restarts owns the wake-up: a delay queue, or a workflow engine such as Temporal. It is set for that deadline, and at the deadline it wakes the ride service, on whichever machine is running. D2’s app counts down from the same value. A sweep also scans it, for any deadline that passed with no wake-up. The ride service runs the expiry write, which frees D2 only where the row still holds this offer. If that write changes a row, the offer really ran out, and the ride service offers the trip to D3. If it changes nothing, the offer already ended another way, and the wake-up stops there.

Replay the pocket with the stored deadline. D2 is silent, and at 10 seconds the timer fires. D3 is asked at 10 and declines at 13. D4 is asked at 13 and accepts at 18. Three phones rang, one at a time. Meera has the 6-minute driver 18 seconds after she tapped. A restart in the middle now costs her nothing, or at most one extra delivery of the wake-up. With a 30-second timeout, the same story ends at 38 seconds.

Pick a situation and a strategy below, and send the offers. The first tab asks one driver at a time, with the timeout chips setting its deadline. The second asks every driver at once.

The interactive version of this example is available when JavaScript loads.

On a night when the best driver answers, one at a time costs one second. D2 accepts at 4 seconds, and only one phone rang. Everyone at once matched at 3 seconds, with a car 2 minutes farther away.

The deadline and its wake-up now live outside the ride service’s memory.

The interactive version of this example is available when JavaScript loads.

The durable timer brings three new questions.

The first is a duplicate wake-up. A delay queue can deliver the same message twice, and a timer can fire late. A second firing finds the row no longer holding the offer, so its expiry write changes nothing. A late firing loses the same way to an accept that reached the row first. Either way the write changes no row, so the chain stops, and nobody offers D3 a trip that is already taken. Nothing checks the clock when a driver accepts, because the row decides.

The second is a stale list. The shortlist was ranked at 0 seconds. By the time D4 is asked at 13 seconds, D4 may have taken another trip. After 30 seconds, the drivers near Meera have moved. The offer write already finds out. If D4 is no longer available, it changes nothing, and the ride service skips to the next name. When the list runs out, it widens the ring and searches again, rather than retrying the same names.

The third is the length of the timeout. A long one lets one sleepy driver cost every rider behind them: 38 seconds instead of 18 on the same night. A short one takes trips from a driver reaching for the phone at a red light. This page uses ten seconds as an illustrative window. Set yours from how long your drivers really take to answer. A driver who times out several times in a row is set to away, so their phone stops ringing until they tap back in.

One more signal can shorten the wait. The offer travels down D2’s socket, and the app acknowledges it the moment it arrives. If no acknowledgement comes back within a second or two, D2’s phone is probably off the network. The ride service can then expire the offer early and ask D3. A phone in a pocket still acknowledges, so that case still costs the full window.

When free drivers are scarce and every timeout hurts, a service can offer the trip to the top two at once, each with its own stored deadline. The accept is still a conditional write, so only one wins. The other said yes and hears “too late”, so this is a lever to use sparingly.

The gap: An offer waits on a person who may never answer, and something must notice when the ten seconds are up.

Option 1: Offer every nearby driver at once

All four phones ring, and the first accept wins the row.

Works when: Every nearby driver is about as close as the next, so the fastest thumb costs nothing.

Breaks when: The fastest thumb wins: D1 matches at 2 seconds, 9 minutes away.

Option 2: One at a time, timer in process memory

Offer the best driver, and keep a ten-second timer in the process before asking the next.

Works when: The process never restarts while it waits.

Breaks when: A restart mid-wait kills the timer, and nobody ever asks the next driver.

Option 3: One at a time, stored deadline, durable timer (start here)

The deadline is on the driver’s row, and a delay queue or workflow engine wakes the ride service to expire it and ask the next driver.

Works when: Any night, since a restart costs a few seconds and never the ride.

Watch for: A timer can fire twice or late, and the shortlist goes stale while it waits.

Fix within it: An expiry that changes no row stops the chain, and an offer write that changes nothing skips to the next name or widens the search.

Option 4: Two at a time when drivers are scarce

Offer the top two at once, each with its own stored deadline.

Works when: Free drivers are scarce, and every timeout costs the rider dearly.

Watch for: One driver who said yes is told the trip has gone.

Fix within it: Use it sparingly, and keep the accept a conditional write so only one wins.

In the interview: Open with option 3, and give the timeout a number, such as ten seconds, tuned to how fast drivers answer. Mention option 2 only to show where the timer must not live. Offer option 4 if the interviewer says free drivers are scarce, and say it is used sparingly because of what it costs drivers.

Say this: I offer the trip to one driver at a time, best first, because the fastest thumb is not the nearest car. The deadline is stored on the offer, and a durable timer expires it. Only an expiry that changes the row moves on to the next driver. Each offer is a conditional write, so a driver who took another trip is skipped.

A concert ends and 20,000 people ask for a car from one block. What breaks?

It is 23:00. A stadium concert ends, and 20,000 people open the app within ten minutes. About 800 drivers are within reach of the stadium.

Do the arithmetic first. 20,000 requests in 600 seconds is about 33 a second. The whole service handles 1,160 a second at its evening peak, so the servers are fine. The block is out of cars, and no design makes an 801st driver.

The first design treats the crowd as 20,000 separate riders. Each takes the nearest free car the moment it asks. Two things go wrong.

The first is pairing. Take two riders and two drivers from the crowd. R1 asks first. D1 is 2 minutes from R1, so R1 takes D1. R2 asks a second later. The only car left is D2, 12 minutes away. That is 14 minutes in total, with one rider waiting 12.

The second arrives after the first 800 riders are matched. Every later request searches, finds nothing, widens its ring and searches again. The number of waiting apps grows all through the ten minutes, and by the end it is 19,200. If each retries every five seconds, that is 19,200 ÷ 5 = 3,840 searches a second at the peak of the storm. It is over three times the service’s whole evening peak. All of it aims at the same few cells, and none of it can succeed.

Better pairing comes from looking at requests together. Collect one area’s requests for about two seconds. Then assign the whole batch at once, choosing the pairs that keep the total pickup time lowest. That needs road times between riders and drivers. In the first minutes, while free cars still outnumber riders, a two-second batch holds the riders who arrived in it. At 33 requests a second that is about 66 riders. Price each against their 20 nearest free drivers, not every driver. 66 × 20 is 1,320 road times per batch, in one matrix call. Once a queue exists, a batch takes riders from its head, as many as there are free drivers nearby, and the matrix shrinks with it.

Replay the two riders. Seen together, a better pairing appears. R1 takes D2 and waits one minute more. R2 takes D1 and waits nine fewer. The total drops to 6 minutes, and the longest wait falls from 12 minutes to 3.

The first tab below matches each request as it arrives. The second collects two seconds of requests, then matches them together. The numbers on the lines are road minutes.

The interactive version of this example is available when JavaScript loads.

Every rider in a batch waits up to two seconds before matching starts. That window is the price of batching, and it is why batches are short.

Batching makes better pairs from the same 800 drivers. It cannot make more drivers. Four more pieces finish the job. Two answer the other 19,200 riders, one keeps the batches fair, and one protects the rest of the city.

Price shapes the crowd. The service counts requests and free drivers in each hexagon over the last few minutes. Where requests far outnumber drivers, the price rises. Some riders decide to wait, or walk to a quieter street. Drivers nearby see the higher fares and head toward the stadium. The quote records the multiplier, so the price a rider saw is the price they pay unless the trip itself changes. A new drop-off, an extra stop or a toll can still change it. The quote also expires after two minutes. A rider who taps Request after the quote expired sees the new price before any car is sent. Uber describes measuring supply and demand in hexagons to set surge pricing (H3). How the multiplier is chosen from those counts is a pricing question, and out of scope here.

A queue replaces the search storm. A rider who cannot be matched now joins the area’s waiting list, with a position and an estimated wait. The app stops searching and waits its turn. The 3,840 searches a second become one batch per area every two seconds. In the metrics, keep “no drivers nearby” apart from “the service failed”, so a stadium night does not look like an outage.

Now look at Priya, at the far gate, 9 minutes from every free car. Everyone else in her batch is 2 or 3 minutes from one. Giving Priya a car adds 9 minutes to the total, so the lowest-total pairing leaves her out. The next batch, two seconds later, does the same, and so does the one after. So a rider who has waited past a limit is matched first, whatever the totals say.

Across town, D7 ends a trip at 23:04 and taps End. That call reaches the same ride service that is taking the stadium’s requests. If it waits in the same queue, D7’s fare is charged late, and D7 gets no new offer. So arrivals, cancellations and trip ends get capacity of their own. Search work per request is capped too. A search stops at its ring limit, and routing prices at most 20 drivers per rider, whatever the crowd.

The servers were never the shortage. The design spends the cars well, and tells everyone else the truth about the wait.

The gap: Twenty thousand riders want 800 cars, and the riders who miss out must not flood the city with searches.

Option 1: Match each request on arrival

Each request takes the nearest free car the moment it arrives.

Works when: Free cars outnumber requests, as on a normal night.

Breaks when: Early riders take cars later ones needed, and 19,200 retrying apps send 3,840 searches a second.

Option 2: Collect for 2 seconds and match together

Assign each area’s requests as a batch that keeps the total pickup time low.

Works when: Riders and drivers are roughly in balance, so better pairs make the difference.

Breaks when: Better pairs from 800 drivers still leave 19,200 riders with no answer.

Option 3: Batch, price and queue (start here)

Batch per area, raise the price per hexagon where demand outruns supply, and queue the rest with a position and a wait.

Works when: Any crowd bigger than its supply.

Watch for: A batch can push one hard pickup back again and again, and the crowd can starve trips in progress.

Fix within it: Match anyone past a waiting limit first, cap search work, and give trip events their own capacity.

In the interview: Open with the arithmetic: 33 requests a second is nothing for the servers, and the block is out of cars. Then give option 3. Explain option 2 when the interviewer asks how batching helps, and say what its two-second window costs.

Say this: Twenty thousand requests in ten minutes is 33 a second, so the servers are fine and the block is out of cars. I batch requests per area for about two seconds to get better pairs from the 800 drivers. Surge pricing per hexagon shapes demand and pulls drivers in, and anyone left joins a queue with an honest wait. Search work per request is capped, and trips in progress keep their own capacity.

Meera’s phone loses signal in a tunnel. What does she see when it comes back?

D4 is on the way, and Meera watches the car creep toward her on the map. She walks through an underpass to reach the kerb, and her phone loses signal for 40 seconds. During those seconds, D4 pulls up and marks arrived.

One rider watching one car costs nothing. Now size the whole service. Say half the million online drivers are on a trip or on their way to one. Each of those has a rider whose app shows the car moving: 500,000 apps.

The simplest app asks the server for the trip and the driver’s position every 2 seconds, with GET /trips/T1. It recovers from any gap by itself, because the first poll after the tunnel returns “arrived”. For a small service that is a fine start.

At this size, 500,000 apps each polling every 2 seconds is 500,000 ÷ 2 = 250,000 requests a second. A driver’s position changes only every 5 seconds, so three polls in five return a position the app already has. The car also moves in jumps, one per poll.

So push instead. Meera’s app keeps one open connection to the socket gateway. The location service forwards each of D4’s pings down it. Trip changes such as assigned, arrived and started come down the same connection. One push per ping is 500,000 ÷ 5 = 100,000 pushes a second, and each one carries something new. The app animates the car between pings, so it glides.

Now replay the tunnel. The “arrived” push goes out while Meera’s phone has no signal. The connection is dead, and the message is lost. When the signal returns, her app opens a new connection and waits. Nothing tells it that it missed anything. So it shows a car still on its way, while D4 waits at the kerb.

The fix keeps the pushes and adds a way back to the truth. Every trip change carries the trip’s version, which goes up by one with each change. After any gap, the app reconnects and waits until the gateway confirms it is subscribed to trip T1. Only then does it read GET /trips/T1. Pushes that arrive before the read returns are held in a buffer. The read returns the state and its version, such as “arrived, version 3”. The app shows that state, applies any buffered change newer than version 3, and drops the rest. Positions are ordered by their ping counter instead, so the app ignores a position older than the one it shows.

Replay the tunnel. The signal returns. The app subscribes again, then reads the trip and gets “arrived, version 3”. Meera sees the car at the kerb, not a car two minutes away that suddenly jumps. The lost push cost nothing, because the read carried the same fact.

The order matters. Suppose the app reads first and subscribes second. Between the two, Meera gets in and D4 starts the trip. The “started” push goes to a socket that does not exist yet, and the read already said “arrived”. The app is stuck on the wrong screen. When the app subscribes first, every change reaches it, either in the read or down the socket. The version then sorts out any overlap.

Pushing brings two smaller problems. The first is finding Meera. Each of D4’s pings has to reach the rider on D4’s trip. The location service keeps a cache from driver to rider, filled from the same status stream that tells it who is busy. Then a small directory maps each connected user to a gateway machine. At 100,000 pushes a second, each push costs two lookups in memory.

The second is keeping that directory right. Each connection gets an ID. When Meera’s app reconnects to a different machine, her entry is replaced with the new machine and the new connection ID. The old machine may clean up its dead connection a few seconds later. So its delete runs only if the entry still holds the old connection ID. A push sent to the old machine in between is dropped, and the read on reconnect makes that harmless.

When the app is in the background, no socket is open at all, and Meera would never see “your driver has arrived”. So the big moments, such as arrival, also go by mobile push notification. Positions never go that way.

The same reasoning is the core of the chat system breakdown, where it carries the whole design. A pushed message can be lost, and the trip record cannot, so every gap ends with a read of the record.

The gap: A stream to a phone can drop messages, and the phone cannot tell what it missed.

Option 1: Poll for the trip every 2 seconds

The app reads the trip and the driver’s position every 2 seconds.

Works when: A small service, where the next poll recovers from any gap.

Breaks when: 500,000 apps make 250,000 requests a second, and the car moves in jumps.

Option 2: Push every change over a socket

Pings and trip changes come down one open connection, about 100,000 pushes a second.

Works when: The connection never drops.

Breaks when: The “arrived” pushed during a tunnel is lost, and the app never learns.

Option 3: Push, then read a snapshot after every gap (start here)

Every change carries a version, and after a reconnect the app subscribes, then reads the trip and applies only newer buffered pushes.

Works when: Any connection, since the read covers any push that was lost.

Watch for: An app in the background has no socket open.

Fix within it: Send the big moments by mobile push notification; positions never go that way.

In the interview: Open with option 3, and say the order out loud: listen, then read. Mention option 1 as a fine start for a small service, and give its cost at 500,000 riders. Option 2 is worth one sentence, because it is the design that forgets the tunnel.

Say this: Each rider’s app holds a socket, and the location service pushes the driver’s pings to it, which the app animates. Every trip change carries a version, so the app ignores anything older. After a gap, the app subscribes first and then reads the trip, so a push lost in a tunnel costs nothing. When the app is in the background, arrival goes by push notification.

That completes the design. The two sections below are shorter follow-ups that a senior or staff round often adds.

If they push: the trip ended. How is Meera charged exactly once?

D4 ends the trip at the airport. The ride service writes the trip as completed, with the fare, in one transaction. Then it asks the payment provider to charge €18. It passes an idempotency key made from the trip ID and the charge type, such as T1:fare. A tip or a cancellation fee later gets its own key, such as T1:tip.

Suppose the provider charges the card and the reply is lost. The ride service does not know whether Meera paid. So it asks again with the same key, and the provider returns the first result instead of charging a second time (idempotency). A new key for the retry would have charged her twice. The retry must also send the same amount, because the provider rejects a reused key whose request has changed.

The ride service can also crash between the commit and the charge. So a sweep finds completed trips with no payment result, and sends the charge again with the same key. The sweep must run well inside the time the provider keeps keys. Stripe keeps a key for at least 24 hours, and treats a key reused after it is removed as a new request.

The trip is completed whatever the payment does. A failed card is a problem for the payment record, not a reason to pretend the ride did not happen. Driver payouts, refunds and disputes belong to a payments system of their own. The payment system breakdown covers them.

If they push: what happens when a city’s servers fail?

Everything in this design is split by city. Each city has its own part of the geo index, its own matchers and its own trips database. Almost every trip starts and ends inside one city, so a trip never needs two databases. A trip that crosses a city line belongs to the city where it started.

A driver who crosses a city line during a trip stays with the old city until the trip ends. Then they are handed over. The old city stops offering them trips, and their status row moves to the new city’s database. While it moves, neither city offers them anything. The new city starts once the row has arrived and their pings do.

When a trips database machine fails, a replica takes over. Suppose the replica is missing an acceptance the old primary had confirmed. It shows that driver as available, and the next matcher offers them a second trip while they drive the first. So the trips database copies each write to a standby in the same region before confirming it, and a failover promotes that standby. Within one region that adds a few milliseconds to each offer and accept. Nobody notices that beside a driver’s ten seconds to answer. It has a cost of its own. With one synchronous standby, losing that standby stops every write. So run two, and let a commit wait for either one. PostgreSQL calls this quorum commit, written ANY 1 (s1, s2). The geo index needs none of that, because it refills in five seconds.

If a whole region is lost, the cities in it stop taking new requests until another region takes over their trips databases. The old region must be cut off first, so it cannot keep offering drivers. The database failover article explains why that order matters.

The copy in another region is usually asynchronous, so it can be seconds behind. An accept in those last seconds may be missing, and its driver then shows as available. The trip row for that accept may be missing too, still searching or with no driver. So before taking requests, the new region rebuilds both from the apps. Each driver app reports the trip it holds, and each rider app reports the trip it is waiting on. Where the two agree, the driver is marked on_trip and the trip assigned. Trips under way keep moving on the road, because the driver and the rider know where they are going. Ending them and charging the fare wait until those rows are rebuilt, and the apps retry those calls.

Walk one ride through the final design

At 18:03:58 D2’s phone sends ping 4812 from a side street south-west of the station. The location service keeps it, and D2’s entry in the Lisbon geo index moves.

At 18:04:00 Meera taps Request with quote Q9. The ride service writes trip T1 and asks matching for a shortlist. Matching searches Meera’s cell and its neighbours, finds four free drivers, and asks the routing service for their road times in one call. D2 comes first at 3 minutes. The ride service writes offer O1 on D2’s row, only where D2 is available, and sets a timer for 18:04:10.

D2 does not answer. At 18:04:10 the timer fires, the expiry write frees D2’s row, and O2 goes to D3, who declines. O3 goes to D4, who accepts at 18:04:18. One transaction sets D4 to on_trip and T1 to assigned. Meera’s app shows D4 on the way, and the car moves on her map with every ping. At the airport, the fare is charged once, keyed by T1:fare.

The interactive version of this example is available when JavaScript loads.

RequirementWhere it is metThe trade-off
FR1 quote a fareRide service, matching for nearby supply, maps for the route; quote stored with an expiryThe quote is a snapshot. It reserves no driver
FR2 match a nearby driverGeo index per city, cell ring search, a shortlist ranked by road timeThe index is a few seconds behind, so the offer write checks again
FR3 accept or declineConditional writes that name the offer; stored deadlines and durable timersOne driver at a time is slower when drivers ignore offers
FR4 see each other moveSockets, with the location service forwarding the assigned driver’s pingsA snapshot read after every reconnect, because pushes can be lost
FR5 finish and payVersioned trip changes; payment keyed by trip and charge typeA charge whose reply was lost is asked again, never repeated

How does the answer change for Uber, a proximity service or food delivery?

Interview variantWhat carries overWhat changes
Design Uber, or design LyftEverything on this pageNothing; these are the product names for the same question
Design a proximity service, or Yelp nearbyCells, rings and a nearest-first searchPlaces do not move and are not reserved. It is a read-heavy index, with no pings and no offers
Design nearby friendsPings, soft state and cell searchPeople move but are not reserved, and privacy settings decide who sees whom
Design food delivery dispatchOffers, conditional accepts and batchingThe courier’s arrival is timed to the food being ready, and one courier may carry several orders
Design a taxi dispatch systemTrips, offers and the driver’s status rowA dispatcher or a rank queue may assign drivers, instead of nearest first
Design airport pickupsOffers and conditional acceptsDrivers wait in a holding lot in a first-in, first-out queue, so the offer goes to the longest wait, not the nearest car
Design shared ridesEverything up to the offerA second rider can join a car already on a trip, so matching checks the detour for the first

What should an answer reach at each level?

LevelWhat the answer shows
Intern or mid-levelDerives 200,000 pings a second and keeps them out of the trips database. Finds drivers by cell, not by scanning. Offers a trip to one driver and records the result.
SeniorSearches the neighbouring cells and ranks by road time. Prevents double booking with a conditional write, and names the offer so a late accept fails. Keeps trip changes versioned.
StaffTreats positions as soft state and explains the restart. Stores offer deadlines with durable timers. Handles a crowd with batching, surge pricing, a queue and capped search work. Splits everything by city, and keeps a failover from offering a driver twice.
PrincipalSets the promises with the business: how stale the map may be, how long an offer lasts, what a surge may charge. Explains the failover order for a region, and what changes for delivery or shared rides.

Test yourself with the quiz, then pick another problem from the System Design interview breakdowns.

By GOAT Engineer. Back to all breakdowns. Privacy Policy · Contact.