Design ride matching
Read first: Partitioning and sharding, Design nearby search
Drivers report location constantly, and that stream is allowed to be a little stale. The match itself is a conditional write on one driver row so two trips cannot take the same person. If nobody accepts before the deadline, the trip ends unmatched and every offer lease expires.
Matching a rider to a driver is a small write with an ugly failure mode. The location stream is the high-rate path. The assignment is the path that must not hand the same driver two trips. Those are different stores. The geospatial index answers “who looks close.” The driver row answers “who is actually free.” Trusting the index for the second question is how you double-book.
Requirements
Two users. A rider wants a car from a pickup point. A driver wants one trip at a time and a chance to say no.
It must:
- Take a pickup location and offer the trip to a nearby driver whose last point is fresh.
- Guarantee that one driver is assigned at most one live trip. An offer counts. A driver sitting on an unanswered offer is not free.
- Stop if nobody accepts. The rider sees a clear “no” at a deadline you stated, not a spinner.
- Survive a retry of the request button and a retry of the accept button without creating a second trip or a second assignment.
Non-goals:
- The price, the surge formula, and the marketplace essay. A price can be attached to the trip row. You are not designing the economy.
- Turn-by-turn navigation. The pickup point is a coordinate.
- Payments. The trip has a fare later. Charging is a different design, with a different failure (a double charge). Do not bolt a card capture onto the match.
- A durable history of every GPS tick. Nearby search already keeps the latest point. This product consumes that index.
Latency assumption: the rider sees “offered to a driver” within about a second of the request, and has an answer, yes or no, within 30 seconds. Those 30 seconds are the product, not a timeout you hide in a client library.
Estimation
Assumptions:
- 500,000 drivers are online at the peak you care about. Each reports location every 4 seconds. This peak population is the sizing number. It is not an average, and it is a smaller, more specific fleet than the generic million-entity example on the nearby-search page.
- 20 million trip requests per day.
- Peak trip rate is 4 times the average, inside the 2x to 5x band. The peak is lumpy: Friday night in a few cities, not a flat global multiplier. You still write the multiplier down.
- A location update is 40 bytes. A driver row is 200 bytes. A trip row is 500 bytes, kept for a year. Replica factor 3 on the durable rows.
- An airport surge is 2,000 requests in 10 minutes, concentrated on a handful of cells. That is a scenario assumption, so you can see local contention.
- You offer up to 5 drivers, 8 seconds each, and you stop at 30 seconds even if you have not offered 5.
A day is 86,400 seconds.
peak location updates = 500,000 / 4 = 125,000 per second
location bandwidth = 125,000 * 40 bytes = 5e6 bytes/s = 5 MB/s
trip requests, average = 20e6 / 86,400 = 231 per second
shortcut / 1e5 = 200 per second, a bit low
peak trips, assumption 4x = about 930 per second
airport cell = 2,000 / 600 seconds = about 3 requests per second
driver rows at peak = 500,000 * 200 bytes = 100 MB
trip storage per day = 20e6 * 500 bytes = 10 GB
one year of trips = about 3.7 TB, times 3 replicas = about 11 TB
Read the two rates next to each other. Location updates are 125,000 per second. Match attempts, even at the assumed peak, are under 1,000 per second worldwide, and the airport that feels like the whole product is a few requests per second. You do not build a thousand match workers because the map looks busy. You build a location path that can take the writes, and a match path whose write is correct under contention.
Storage of current locations is tens of megabytes if you keep the latest point only. Eleven terabytes of trip history is a normal database, partitioned by trip id or by rider, and it is not on the match hot path except for the single row you are creating. Bandwidth of locations is 5 MB/s. Stop designing the network. A million requests a day would be about 12 per second. Trip requests are above that. Location updates are far above it. They are still small writes.
High-level design
flowchart LR
rider[Rider]
matcher[Matcher]
cells[Geospatial index]
driverRow[Driver row]
offer[Offer push]
driver[Driver]
rider --> matcher
matcher --> cells
matcher --> driverRow
driverRow --> offer
offer --> driver
driver --> matcher
The matcher is stateless. It creates a trip row, asks the geospatial index for candidates, and then tries a conditional update on the driver row. The push tells the driver. The accept comes back as a second conditional update. If the matcher process dies, the rows are still there, with deadlines on them. Nothing about “who is offered” lives only in memory.
The index is the one from nearby search: cell id, neighbor ring, distance rank, timestamp filter. Candidates older than 15 seconds are dropped. Assumption, and it sits inside the freshness window that lesson already uses for moving points. A candidate can be slightly wrong. The driver row is not allowed to be wrong.
Deep dive
The write that assigns
A driver is in one state: free, offered, or on a trip. A trip is requested, offering, assigned, or unmatched. The transition that matters is free to offered, and it is one conditional write: set this driver to offered for this trip, and set an expiry, only if the driver is free. If the write matches zero rows, someone else took them. Try the next candidate.
Walk two riders and one driver, because this is the bug you are designing against.
Both matchers read the index and see the driver as free. The point is 3 seconds old. Matcher A commits the conditional update for trip T1. Matcher B issues the same update for trip T2 and matches nothing. B moves on. The index was stale or simply concurrent, and it did not matter, because the index is not the lock. The driver row is.
Then A pushes the offer. The driver accepts. The accept is a second conditional write: set the trip to assigned for this driver, only if the trip is still offering and the driver is still offered for this trip. Both checks, one transaction. A lost response is a retry. The retry finds the trip already assigned to the same driver and returns success. That is an idempotent accept. A retry that created a second trip would be the failure.
The rider’s request button is the same shape. The client generates a key and stores it before the call. A double tap returns the trip that already exists. If you skip that, two matchers will offer two drivers to one human who tapped twice, and you will have invented a different double-book, this time of the rider.
Order of operations: reserve the driver, then push. If you push first, the driver can accept an offer you never won, and a second matcher can win the row while the first driver is already on the way. The push can fail after the reserve. The driver never sees it. The lease is what gives the driver back.
The lease and the timeout
Offered is not a permanent state. The row carries offered-until, 8 seconds from the reserve. Assumption. If the matcher dies after the reserve and before the push, the driver is stuck only until that timestamp. A sweeper, or the next matcher that touches the row, sets the driver back to free only when the state is still offered, the trip id is still this trip, and the deadline has passed. The trip id in the condition is the fence. Without it you can free a driver who has moved on to a newer offer you did not mean to cancel.
The rider’s deadline is 30 seconds or five declined offers, whichever comes first. Then the trip becomes unmatched. That is a successful outcome of the system. You persist it. You do not keep offering past the deadline because a sixth driver might say yes. You told the rider 30 seconds.
Each offer that expires returns that driver to free under the same conditional write. A driver who taps accept a second after expiry loses the race. The accept matches zero rows, and the client is told the offer is gone. Do not then assign them anyway. The trip may already be talking to someone else, or it may be unmatched. Either way the late tap is a no.
If the location pipeline stalls, candidates go stale together and the index returns nobody fresh. Stop matching. Widening the 15-second rule during the incident dispatches drivers who left. An empty match is the honest failure. The nearby-search page makes the same call for a stale moving point, and this is the product that pays for it.
Where the geospatial index fits, and where it does not
Reuse the cell. Do not invent a second spatial structure. A pickup queries the cell and the neighbor ring, filters timestamps, ranks by distance, and returns a short list. Assumption: ask for 15 candidates so that a few stale or already-offered ones still leave you a driver. The list is a hint ordered by distance.
What the index is allowed to get wrong: the driver has drifted a block, or the driver was offered a moment ago and the cell has not caught up, or the driver appears in two cells because the old cell delete has not landed. Insert-then-delete, with the newest timestamp winning, is that lesson’s write path. You inherit the ghost. The conditional update ignores a ghost who is not free.
What the index is not allowed to decide: that the driver is yours. Cache a candidate list for a second if a hot cell demands it. Do not cache “this driver is free” as a value you act on without the write. A cache of freeness is a second lock that does not lock.
Partitioning follows the write. Driver rows are partitioned by driver id, so two drivers in the same airport cell do not share a row lock, and a hot plaza does not pile its conditional updates onto one key. The cell index can still be hot as a read. More partitions of the driver table do not cool the cell. Split or cache the cell, which is the nearby-search answer, and keep the assignment write on the driver id. A hot key is not fixed by more partitions. Here the hot read and the contested write are different keys on purpose.
The offer push goes to whatever connection the driver currently holds. A held socket is stateful. When that machine dies, the driver reconnects and asks for the current offer. The offer they get is the row, not a message that lived on the dead machine. Same rule as any realtime hint: the durable state is in the database, the push is a nudge. If the nudge never arrives, the lease expires and the rider tries the next driver. You lost 8 seconds, not a car.
At the airport, watch the rate of conditional updates that match zero rows. If it is high, you are out of cars or the index is too stale to propose free ones. Retrying harder raises load and does not create drivers. Tell the rider unmatched, early, once you can see the candidate list is empty of free rows. That is load shedding: refuse the request you cannot satisfy.
Tradeoffs
| Choice | What you gain | What you spend |
|---|---|---|
| Conditional update on the driver row | Two matchers cannot both win the same driver | A lost race costs a round trip, and the rider waits on the next candidate |
| Trust the geospatial index as the assignment | One read, no contention | Double booking the moment two riders see the same free dot |
| Offer one driver, then the next | At most one person is held, and the state machine stays small | The rider may wait through several 8-second leases |
| Reserve first, push second | Nobody accepts an offer you do not own | A failed push burns the lease and the rider waits it out |
| Lease with a trip id in the release | A crashed matcher cannot stick a driver in offered | A slow phone can lose the offer at the deadline, which you have to show clearly |
| Partition drivers by driver id | Airport contention spreads across driver rows | The cell index is still a hot read and needs its own treatment |
| Stop at 30 seconds with unmatched | The rider can leave and try another product | You will say no to a driver who would have accepted at second 40 |
Failure modes
- Two matchers, one driver, and no conditional write. Symptom: two riders get the same car, or one rider is stranded when the driver takes the other app’s view of the trip. The zero-row update is the fix, and it has to be the write, not a check you did earlier.
- Accept is retried and the handler is not idempotent. Symptom: a second trip, or an error shown to a driver who did accept. Same driver, same trip, already assigned, is success.
- Reserve, crash, no lease. Symptom: the driver stays offered until a human notices, and the rider hangs. The expiry is on the row so a dead process is irrelevant.
- Release writes “set free” with no trip id. Symptom: you clear a driver who just accepted a newer trip, or you clear the wrong offer. The condition is the whole fix.
- Location stream stalls and you stretch the freshness window. Symptom: pickups that are empty curbs. Return unmatched.
- Push service is down. Symptom: offers expire unused, match rate collapses, driver rows churn through leases. The trip still ends unmatched at 30 seconds. Do not loop offers faster to compensate. You will burn the whole candidate list on pushes nobody can see.
- Rider retries create new trips. Symptom: one person, several drivers, several cars en route. The idempotency key on the request is the fix, and the client has to persist it before the first send.
- A hot cell and a retry storm. Symptom: the index and the handful of driver rows in that plaza time out, and clients retry the whole match. Bound the retries. A match that is still offering is the same trip, not a new one. Adding shards does not split the cell id or a single popular driver id.
Durability: the assignment is the row commit. If that commit is only on an async replica and the primary dies, you can lose the offer or, worse, forget that the driver was taken. Acknowledge the match state only after the write is durable on a majority. A slow replica stalls a match. A lost assignment double-books after failover. Take the stall.
In the interview
Open with the two rates. “Locations are on the order of 10^5 updates a second under my peak-driver assumption. Matches are hundreds per second. I will not spend the design on match throughput.” Then the sentence that matters: candidates come from the geospatial index, the assignment is a conditional write on the driver, and an unanswered offer expires.
Skip pricing, maps, and a re-derivation of geohash. Point at the cell, the neighbor ring, and the timestamp, and move on.
The question that follows is the double assignment, or the driver who never answers. Draw the two matchers and the zero-row update. Then draw the lease, including the crash between reserve and push. If they ask what you do when the conditional update keeps failing, say you are out of drivers and you return unmatched. Do not invent a queue of hopeful riders against one car without saying that the car is the scarce row.
Check yourself
Two matchers read that driver D is free and both try to assign a trip. What is stored, and which write decides?
The geospatial index can say free to both. That read is allowed to be stale. The decision is an update that sets D to offered for a trip only if D is still free. One update matches a row. The other matches nothing and moves to the next candidate. Whichever matcher read the index first does not matter.
The matcher reserves a driver and dies before the push. How does the driver become free, and what must the release condition include?
The offer row has an expiry, 8 seconds in this design. A sweeper sets the driver back to free only if the state is still offered, the deadline has passed, and the trip id is still the trip that reserved them. Without the trip id you can release a driver a newer offer already owns.
Peak location updates are 125,000 per second and peak match attempts are under 1,000. Where do you spend the design, and where do you refuse to?
You spend it on an ingestion path for the latest point and on the correctness of the assignment write. You do not spend it on a huge matcher tier. The airport scenario is a few requests a second of real contention on a small set of driver rows. Scale of the fleet and heat of one plaza are different problems.
The rider taps request twice and the driver taps accept twice, both because a response was lost. What must be true so you still have one trip and one assignment?
The rider’s client reused one idempotency key it stored before the first call, so the second call returns the same trip. The driver’s accept finds the trip already assigned to that driver and returns success. A new key on the rider, or an accept handler that inserts a fresh assignment, is a second booking.
Based on: Designing Data-Intensive Applications, Kleppmann and Riccomini; Alex Xu, ByteByteGo volumes.