Design Ride Matching
When a rider taps request, the app must find a nearby, available driver within seconds, offer the trip, and make sure two riders never get the same driver. This lesson designs the matching core of a ride-hailing app: a stream of driver locations, an in-memory geospatial index, a dispatch service that offers trips one driver at a time, and a trip state machine that keeps everything consistent.
What you will learn
- Driver locations are a firehose of small, short-lived updates: keep them in memory, not in a database.
- Index locations with a grid of cells (geohash or similar) and search the rider's cell and its neighbours.
- Rank candidates by estimated time to pickup, not straight-line distance.
- Offer to one driver at a time with a short timeout; claim the driver atomically.
- A trip state machine, persisted durably, is the source of truth for the ride.
- Partition everything by city or region: matching is local.
In this lesson
- The question
- Step 1: Clarify the requirements
- Step 2: Back-of-the-envelope estimates
- Step 3: The API
- Step 4: The location pipeline
- Step 5: Indexing locations
- Step 6: Estimating time to pickup
- Step 7: Dispatch and offers
- Step 8: Never assigning a driver twice
- Step 9: The trip state machine
- Step 10: One ride, from tap to pickup
- Step 11: Scaling by region
- Step 12: Supply, demand and surge
- Step 13: Failures
- Step 14: The follow-up questions
- Recap
The question
Welcome to lesson sixteen of the InterviewDryRun system design course. Today we design the heart of a ride-hailing app: matching a rider who wants a ride with a nearby driver who can take it.
It is a favourite interview question because it is location-based, real-time and full of concurrency problems. Millions of drivers send their position every few seconds. Riders expect to be matched in seconds. Two riders must never be given the same driver. And everything about it is local: a driver in one city is irrelevant to a rider in another. Seeing that last point, and using it, is what makes the design scale.
Max asks
“Design the part of a ride-hailing app that matches riders to nearby drivers.”
That is how Max, our AI interviewer, asks it. Notice the scope: the part that matches. Not payments, not maps, not the rating system. So be explicit early that you will focus on driver locations, finding nearby drivers, and the dispatch flow, and that you will treat routing, pricing and payments as services you call.
The plan: requirements and numbers, then the API, then the location pipeline. Then the geospatial index, which is the core technical piece, then dispatch and offers, the trip state machine, preventing double assignment, scaling by region, surge, failures, and the follow-up questions.
Step 1: Clarify the requirements
- 01Drivers share locationEvery few seconds while online
- 02Rider requests a ridePickup, destination, ride type
- 03MatchFind a nearby available driver; offer the trip
- 04Driver accepts or declinesThen the next driver is tried
- 05Track the tripBoth see each other's location until pickup
Start with questions.
Drivers who are online send their location every few seconds. A rider requests a ride with a pickup point, a destination, and a ride type, like standard or large.
The system finds a suitable nearby driver and offers them the trip. Ask how offers work: does one driver get the offer at a time, or do several see it and the fastest wins? The common answer is one at a time, with a short time to accept, which is fairer to drivers. If a driver declines or does not answer, try the next one.
After a match, rider and driver see each other's live location until pickup. Ask about shared rides, where several riders share a car. Say they are an extension, and that we will design single rides first.
- 01Fast matchingA driver offered within a few seconds
- 02Never double-assignOne driver, one trip at a time
- 03High write rateMillions of location updates
- 04AvailableRiders stranded if matching is down
- 05Good matchesShort pickup times, fair to drivers
The qualities. Matching must be fast: the rider should see a driver on the way within a few seconds. And there is a hard correctness rule: a driver must never be assigned two trips at once. That is our key invariant.
The location write rate is high, and each update is only useful for a few seconds. That is a very unusual data profile: lots of writes, very short lifetime. It suggests memory, not a database.
Availability matters, because a matching outage strands people at night. And match quality: short pickup times for riders, and a fair share of trips for drivers. State that we optimise mainly for pickup time, and keep fairness as a secondary signal.
Step 2: Back-of-the-envelope estimates
Let us size it.
Say two million drivers online at peak, each sending an update every four seconds. That is five hundred thousand location updates a second. Each is tiny, about a hundred bytes, so the bandwidth is modest. The rate is what matters. Writing half a million rows a second to a database, only to overwrite them four seconds later, would be wasteful and expensive.
Ride requests are far fewer: twenty million a day, about a thousand a second at peak. Each one triggers a nearby search and a dispatch. And the biggest single city might have a hundred thousand drivers online, so twenty-five thousand updates a second in one place.
So the shape is: a firehose of location writes that only need to be current, a much smaller stream of requests that need a fast spatial search, and trips that must be stored durably and correctly. Three different kinds of data with three different treatments, which is a nice thing to say out loud before drawing.
And memory: two million drivers, each with a position, a status and a cell, at around a hundred bytes, is about two hundred megabytes for the whole world. Even the largest city's drivers fit comfortably in one server's memory. That number makes the in-memory design an easy decision rather than a bold one.
Step 3: The API
driver app → PUT /v1/drivers/me/location (or over a socket)
{ lat, lng, heading, speed, ts }
driver app → POST /v1/drivers/me/status { online | offline }
rider app → POST /v1/rides
{ pickup, destination, type } → { rideId, status: searching }
server → driver app: offer { rideId, pickup, eta, expiresIn: 15 }
driver app → POST /v1/offers/{rideId}/accept | /decline
server → rider app: matched { driver, car, eta }, driver locationsThe API has two clients, the driver app and the rider app, and a lot of it flows from the server to the apps, so both apps keep a persistent connection open while active.
Drivers send location updates and go online or offline. Riders create a ride request and immediately get back a ride id with the status searching. Matching then happens asynchronously, and the result arrives over the connection: an offer to a driver, and a matched message to the rider, followed by a stream of the driver's location.
Making the ride request asynchronous is an important choice. Matching can take several seconds, with offers and declines, and we do not want an HTTP request hanging for that long. The ride id is the handle for everything that follows, and every call that changes the ride carries it, which also makes retries safe.
Step 4: The location pipeline
Location updates arrive from driver apps over persistent connections to a gateway tier, like the one we designed for chat.
Gateways forward each update to the location service responsible for that driver's city. Partitioning by city, or by region within big cities, means each location server handles a manageable share, and every search for a rider in that city hits the same servers that hold all of its drivers.
The location service updates an in-memory geospatial index: driver seventy-seven is now at this point, in this cell, available. It keeps only the latest position for each driver, with a timestamp. If a driver's updates stop for, say, thirty seconds, they are treated as offline and removed from search.
The updates are also written asynchronously to a location log, for things that need history: drawing the route of a trip, calculating the distance for the fare, and analytics. Those consumers read the log at their own pace; the matching path never waits for them. And notice: no database write on the hot path. If a location server dies, we lose at most a few seconds of positions, which are rebuilt within seconds as drivers send their next update.
The driver app can help reduce load too. When a driver is parked and waiting, their position barely changes, so the app can send updates less often, say every fifteen seconds, and speed up again when the car moves. Updates can also be batched with other small messages on the same connection. Smart clients often remove a third or more of the write load at no cost to match quality.
Step 5: Indexing locations
| Approach | How | Notes |
|---|---|---|
| Scan all drivers | distance to each | fine for 100, not 100,000 |
| Database spatial index | R-tree on lat, lng | good for static places; heavy for 25,000 writes a second |
| Geohash grid | string prefix = area | simple, works in any key-value store |
| Hierarchical cells | hexagons or squares at levels | even areas, easy neighbours |
| Quadtree | split busy areas finer | adapts to density; harder to update |
Now the core technical piece: how do we find drivers near a point, quickly, when they all move every few seconds?
Scanning every driver in the city and computing distances works for a few hundred drivers, but not a hundred thousand, a thousand times a second. A database's spatial index is excellent for places that do not move, like restaurants, but rebalancing a tree structure twenty-five thousand times a second is heavy.
The simplest effective idea is a grid. A geohash divides the world into cells and gives each cell a short string; longer strings mean smaller cells, and nearby cells share prefixes. At a length of six characters, a cell is roughly a kilometre across. We keep, for each cell, the set of available drivers in it. Moving a driver means removing them from one cell's set and adding them to another, only when they cross a cell boundary.
Hierarchical cell systems, for example ones based on hexagons, improve on geohashes: cells have more even areas, and every cell has the same number of neighbours, which makes searching rings around a point easy. Quadtrees adapt cell size to density, which is great for static data. For moving drivers, a fixed grid with cheap updates is the usual answer. Name the trade-off, and pick the grid.
cell = cellOf(pickup, level = ~1 km) candidates = drivers in cell + its neighbouring cells if fewer than 10: widen to the next ring of cells filter: available, right car type, fresh location rank: estimated time to pickup (routing service) take top 5
A search then looks like this. Find the pickup's cell. Collect available drivers from that cell and its neighbours, because a driver just across the boundary may be the closest. If there are too few, widen to the next ring of cells. Filter by availability, car type and how fresh the location is.
Then rank. Straight-line distance is misleading: a driver two hundred metres away across a river, or going the wrong way on a one-way road, might be ten minutes away. So for the top few dozen candidates, ask a routing service for the estimated time to the pickup, and rank by that. That small detail, time rather than distance, is one interviewers notice.
Choosing the cell size is a small but real decision. Cells that are too large return hundreds of drivers to filter and rank; cells that are too small mean searching many cells to find enough drivers. A cell of around a kilometre suits a dense city, and suburban or rural areas can start the search at a coarser level. Hierarchical cells make that easy, because a coarse cell is just the parent of the fine ones.
Step 6: Estimating time to pickup
- 01Road graphPrecomputed routing graph per region
- 02Live speedsUpdated from the location stream of all drivers
- 03Many-to-one queriesTimes from 30 drivers to one pickup in one call
- 04Cache by cell pairRough ETAs reused for a minute
Ranking by time to pickup needs estimated times of arrival, and lots of them: dozens per request, a thousand requests a second. A routing service holds a road graph for the region, preprocessed so that shortest-path queries take milliseconds rather than seconds.
Road speeds come from our own drivers. The same location stream we already have tells us how fast cars are moving on each road segment right now, which is a nice reuse: the matching system's raw data improves its own ranking.
For matching, use many-to-one queries: the times from all candidate drivers to one pickup point, computed together, which is much cheaper than separate queries. And cache rough estimates between pairs of cells for a minute; dispatch only needs exact times for the final few candidates. If the routing service is slow, fall back to straight-line distance with a speed factor, so matching never stops.
Step 7: Dispatch and offers
Now the dispatch flow. The rider's request creates a ride record in the ride service, in the state searching. That record is stored durably, because it is the source of truth for this trip.
The ride service hands the request to the dispatch service for that city. Dispatch asks the geo index for nearby available drivers, asks the routing service for their pickup times, and builds a ranked list.
Then it offers the trip to the best driver, with a timer of, say, fifteen seconds. While the offer is out, that driver is reserved: they will not be offered any other trip. If the driver accepts, the trip is assigned. If they decline or the timer runs out, the reservation is released, and dispatch offers to the next driver on the list, refreshing the list if it has become stale.
A refinement worth mentioning: instead of matching each request the moment it arrives, a dispatch system can collect requests for a second or two and solve them together, assigning drivers to riders to minimise total pickup time across all of them. Greedy one-at-a-time matching can give a driver to the first rider when a second rider, a moment later, was a much better fit. Batch matching improves overall pickup times noticeably in busy areas. Mention it as an optimisation once the basic flow is clear.
Step 8: Never assigning a driver twice
// driver status lives with the driver's location shard reserve(driver 77, ride r1): if status == AVAILABLE: status = OFFERED(r1, until now+15s) else: fail // atomic on one key accept(driver 77, ride r1): if status == OFFERED(r1): status = ON_TRIP(r1) ride r1: SEARCHING → ACCEPTED only if still SEARCHING
Here is the key invariant: one driver, one trip. In a busy area, two dispatch decisions for two riders may both pick driver seventy-seven, the closest one, at the same moment. Only one can win.
So reserving a driver is an atomic compare-and-set on that driver's status: change it from available to offered for this ride, only if it is currently available. The driver's status lives on the single shard that owns that driver, so the operation is atomic without any distributed locking. The losing dispatch sees the failure and moves to its next candidate.
Acceptance is atomic too, on both sides. The driver's status changes from offered for this ride to on trip, and the ride changes from searching to accepted, only if it is still searching. Why check the ride as well? Because a rider might cancel while the offer is out, or a retry might have matched the ride with someone else. Each check is a conditional update, the same pattern we used for ticket seats and payments. Once you have seen it three times, say so: it is the standard tool for invariants under concurrency.
And offers must expire reliably. The offered status includes an expiry time, so even if the dispatch server that made the offer crashes, the driver becomes available again on their own after fifteen seconds. Like ticket holds, put the expiry in the data rather than in a timer that can die with a process.
Step 9: The trip state machine
| State | Entered when | Next |
|---|---|---|
| Searching | rider requests | Accepted, Cancelled, No drivers |
| Accepted | driver accepts | Arrived, Cancelled |
| Arrived | driver at pickup | In progress, Cancelled (no-show) |
| In progress | rider picked up | Completed |
| Completed | drop-off | payment, ratings |
Once matched, the trip follows a state machine stored durably in the ride service's database, which, unlike locations, must never lose data. Every transition is a conditional update with the expected current state, and every transition is also published as an event.
The states are searching, accepted, arrived at pickup, in progress, and completed, with cancellation possible from the early states. Completion triggers the fare calculation from the recorded route in the location log, then payment, and ratings, each in its own service, reacting to the trip completed event.
During pickup and the trip, rider and driver see each other's location. The location service forwards the driver's updates for an active trip to the rider's connection, and vice versa, a few times a second at most. That forwarding is a lightweight subscription keyed by the trip, not a database poll.
Step 10: One ride, from tap to pickup
| Time | What happens |
|---|---|
| 0.0 s | rider taps request; ride stored as searching |
| 0.1 s | dispatch finds 14 drivers in 7 cells |
| 0.3 s | ETAs ranked; driver 77 reserved, offer sent |
| 6 s | driver 77 declines; reservation released |
| 6.2 s | driver 31 reserved, offer sent |
| 9 s | driver 31 accepts; rider sees car and ETA |
Let us walk one ride through the whole system, second by second, because it shows how the pieces fit.
The rider taps request. The ride service stores a new ride, searching, and replies with its id in a few tens of milliseconds, so the app can show a searching screen right away. Dispatch for the rider's city takes the request, looks up the pickup's cell and its neighbours in the in-memory index, and finds fourteen available drivers of the right car type within a hundred milliseconds.
It asks the routing service for pickup times for those fourteen, ranks them, and atomically reserves the best, driver seventy-seven. The offer goes over the driver's connection, with fifteen seconds to respond. Under half a second has passed since the tap.
Driver seventy-seven declines; perhaps they are about to end their shift. The reservation is released, dispatch refreshes the list, because six seconds have passed and drivers have moved, and reserves driver thirty-one. Three seconds later, thirty-one accepts. In one transaction-like step, thirty-one becomes on trip and the ride becomes accepted, and the rider sees the car, the driver's name and an arrival time. Nine seconds in total, with one decline. Every promise we made, fast matching, one trip per driver, durable ride state, held throughout.
Step 11: Scaling by region
- 01Shard by city or regionLocation, geo index and dispatch together
- 02Split big citiesBy area; search crosses into neighbours near borders
- 03Global servicesAccounts, payments, trip history
- 04Regional deploymentEach region's cities served from nearby data centres
Now scale. The beautiful thing about this problem is that matching is local. A rider in one city only ever needs drivers in that city. So partition location tracking, the geo index and dispatch together by city. Each city's shard holds all its drivers in memory and handles all its searches, without talking to other shards.
The largest cities may be too big for one shard, so split them by area. A rider near a boundary needs drivers on both sides, so a search near a border queries the neighbouring shard too. With hexagonal cells, the boundary is just a set of cells, and the shard for each cell is known.
Other services are global or regional and scale like ordinary web services: accounts, payments and trip history in sharded databases. Deploy each region's matching close to its cities, so the latency from phone to server is low. If the interviewer asks about one city having a big event, say a stadium emptying, that is a hot area within a shard; batch matching and surge pricing both help, which leads to the next point.
Step 12: Supply, demand and surge
- 01Measure per cellOpen requests versus available drivers
- 02Surge multiplierRaises price, lowers demand, attracts drivers
- 03Show it before bookingRider accepts the price up front
- 04Smooth itAvoid prices jumping every few seconds
Matching works only if there are drivers. When a concert ends, thousands of requests arrive in one area with few drivers. A streaming job counts, per cell and per minute, open requests and available drivers.
When demand clearly exceeds supply, a surge multiplier raises prices in those cells. Higher prices reduce demand from riders who can wait, and attract drivers from nearby areas. It is a pricing decision, but the system needs the supply and demand data that the matching system already has.
Show the price to the rider before they confirm, and lock it for that request, so it does not change during matching. And smooth the multiplier over a few minutes, so prices do not flicker every few seconds, which feels unfair to riders and confusing to drivers. You do not need to design the pricing model; mentioning how it plugs in is enough.
Step 13: Failures
- 01Location shard diesRebuilt from the next round of updates in seconds
- 02Dispatch crashes mid-offerOffer expires; ride is re-dispatched from its state
- 03Driver phone loses signalStale drivers drop out of search; trip continues
- 04Ride DB failoverSynchronous replica; requests retried by ride id
If a location shard dies, a replacement starts empty, and within one update interval, four seconds, every driver has reported in again. Matching in that city pauses for a few seconds at most. Because location data is ephemeral, we deliberately do not replicate it; rebuilding it is faster and simpler.
If a dispatch server crashes while an offer is out, the driver's reservation expires on its own, and a recovery loop finds rides that have been searching too long with no active offer and dispatches them again. The ride's durable state makes this safe.
Drivers lose signal in tunnels and car parks. Their location becomes stale, so they drop out of new searches, but an active trip is not cancelled; the app keeps working offline and reports when it reconnects. And the ride database uses synchronous replication with failover, so an acknowledged trip is never lost, and clients retry using the ride id, which makes retries safe.
Step 14: The follow-up questions
Max asks
“How would you add shared rides, where two riders going the same way share a car?”
The candidate search changes: besides available drivers, consider drivers already on a shared trip whose route passes near the new pickup, and whose detour for the existing rider stays under a limit. Ranking becomes a small optimisation over detour time for everyone in the car. The state machine gains multiple pickups and drop-offs. Batch matching becomes much more valuable here, because pairing riders well is the whole point.
Max asks
“A driver's app is hacked to report fake locations. What can you do?”
Check plausibility on the server: speed between updates, jumps across the city, positions matching roads, and agreement with other signals from the phone. Flag drivers whose tracks look impossible and remove them from matching while reviewed. Fare calculation should also use server-side checks of the route, so faking a longer trip does not pay.
Max asks
“Why not store driver locations in a geospatial database and query it?”
For half a million updates a second, mostly overwriting values that are useless after a few seconds, a durable database spends most of its effort on work we do not need: logging, indexing and replicating every update. An in-memory grid per city does the job with simple set operations, and losing it is harmless because it rebuilds in seconds. Use a database for what must persist: trips.
Max asks
“No driver accepts after five offers. What do you do?”
Widen the search radius and include drivers who are about to finish a trip nearby, since they may be the fastest option. Tell the rider honestly that it is taking longer, with an option to keep waiting or cancel without a fee. If there is still nobody, end the search with no drivers available. Feed the event into supply and demand data, so surge and driver incentives can respond to areas that keep running out.
Recap
- 010 to 5: requirementsLocations, request, offer, accept; never double-assign
- 025 to 10: estimates500,000 updates a second, short-lived; 1,000 requests
- 0310 to 20: locations and geoIn memory per city; grid cells and neighbours; rank by ETA
- 0420 to 35: dispatchOne offer at a time; atomic reserve and accept
- 0535 to 45: trip and scaleDurable state machine; shard by city; surge; failures
On the clock: five minutes of requirements, with the invariant one driver, one trip. Five minutes of numbers, which show locations are a short-lived firehose that belongs in memory.
Ten minutes on the location pipeline and the geo index: per-city shards, grid cells, neighbour searches and ranking by time to pickup.
Fifteen minutes on dispatch: offers one at a time with timeouts, atomic reservation and acceptance, and batch matching as an improvement. And ten minutes on the trip state machine, sharding by city, surge and failures. If you separate ephemeral locations from durable trips, and explain why, you will stand out.
Geospatial indexing and concurrency in one question is a lot to explain clearly in forty-five minutes. Practicing out loud is how you find the right order. You can practice this exact question with Max, our AI interviewer, at interview dry run dot com. It is free to start, and you get a scored report with what to fix. The written lesson, with every diagram, is on the site too. See you in lesson seventeen.
Now say it out loud
Watching an answer is not the same as giving one. Max asks this exact question, pushes back when an answer is vague and keeps time, then scores you per skill.
Practice with MaxFree: a 5-minute voice round and unlimited typed drills, with scored feedback. No card, and your camera is never recorded.