Design ride-sharing with geo-indexing
Ingest a quarter of a million driver locations a second into an in-memory geospatial index, answer nearby-driver queries, and dispatch each driver to exactly one trip.
The problem
Uber launched in San Francisco in 2010 with a simple promise: press a button and a car arrives. Behind the button is a question no ordinary database index answers well: which available drivers are near this point right now?
Picture the first version. A drivers table has lat and lng columns, each driver’s phone updates its row every few seconds, and matching runs WHERE lat BETWEEN ... AND lng BETWEEN .... With 500 drivers in one city it works. With a million drivers it fails twice over. The write load is 250,000 row updates a second, each one also rewriting index entries. And the query is slow, because a B-tree orders rows along one dimension. The database can use the index to find a band of latitude, but that band circles the planet and every row in it must be checked for longitude.
The data is also odd. A position is worthless 10 seconds after it was written, yet the system must never send two riders the same driver. One part of the problem wants a fast, forgetful store. The other wants strict correctness.
Requirements
Functional
- Drivers go online and report their location continuously.
- A rider requests a ride from a pickup point to a destination and sees an ETA.
- The system finds nearby available drivers and offers the trip to one of them, who can accept or decline.
- Rider and driver each see the other’s position during pickup and the trip.
- The trip moves through its states to completion or cancellation.
Out of scope unless asked: payments (see the payment system), ratings, shared rides, driver onboarding. Surge pricing is an extension.
Non-functional
- Location freshness: positions used for matching are under about 10 seconds old.
- Match latency: a driver is offered the trip within a few seconds of the request.
- Correctness of dispatch: a driver is on at most one trip, and a trip has at most one driver.
- Availability: 99.99% for requesting and matching. This is a real-time service where an outage strands people.
- Durability: trip records are never lost. Live locations may be.
- Scale: 1 million drivers online at peak, 10 million trips a day.
Capacity estimates
| Quantity | Working | Result |
|---|---|---|
| Location writes | 1M drivers / 4 seconds | 250,000 per second |
| Ride requests | 10M a day / 86,400 | about 115 per second, 600 at a 5x peak |
| Live index size | 1M drivers x 100 bytes | about 100 MB |
| Location history | 250,000 x 100 bytes | 25 MB per second, about 2 TB a day |
| Trip records | 10M a day x 1 KB | 10 GB a day |
The live index would fit in the memory of a laptop. Its difficulty is the write rate and the need to stay available, not its size. Location writes outnumber ride requests by more than 400 to 1, so the two paths should share nothing. Trips are few and valuable, and belong in a transactional database.
API
POST /v1/rides
Idempotency-Key: 5d2e...
{ "pickup": { "lat": 51.5033, "lng": -0.1196 },
"dropoff": { "lat": 51.4700, "lng": -0.4543 },
"product": "standard", "quote_id": "q_81f" }
202 Accepted
{ "ride_id": "r_7c1", "status": "MATCHING" }
GET /v1/rides/{ride_id}
POST /v1/rides/{ride_id}/cancel
POST /v1/offers/{offer_id}/accept driver
POST /v1/rides/{ride_id}/events driver: arrived, started, completed
Drivers hold a persistent connection (a WebSocket or a gRPC stream) and send location messages on it. The same connection carries offers back to them.
{ "type": "location", "seq": 1841, "ts": 1767268800123,
"lat": 51.5033, "lng": -0.1196, "heading": 270, "speed": 8.4 }
The sequence number lets the server drop updates that arrive out of order. The request returns 202 because matching takes seconds; the rider’s app learns the outcome by push on its own connection.
Data model
Trips live in a relational or other transactional store:
| Column | Type | Notes |
|---|---|---|
trip_id |
string, primary key | |
rider_id, driver_id |
string | driver is null until assigned |
status |
enum | the state machine below |
version |
integer | incremented on every transition |
The row also holds pickup, drop-off, the price quote and timestamps for each transition.
REQUESTED → MATCHING → DRIVER_ASSIGNED → DRIVER_ARRIVED → IN_PROGRESS → COMPLETED
MATCHING → NO_DRIVERS any state before IN_PROGRESS → CANCELLED
Driver status (offline, available, offered, on trip) is a small durable record per driver, updated only by conditional writes.
The live location index is two in-memory maps per shard:
driver_id → { cell, lat, lng, heading, status, updated_at }
cell_id → set of driver_ids
Location history is an append-only log, keyed by driver, that ends up in cheap storage for fare calculation, disputes and traffic models.
High-level architecture
Location path. The driver app sends a position every 4 seconds over its connection to the gateway, which forwards it to the location service. The service computes the cell id, updates the two maps on the shard that owns that region, and appends the update to the location log without waiting for it. Nothing on this path touches a disk synchronously.
Request path. The rider app posts a ride request. The trip service writes the trip row in state MATCHING and calls the matching service. Matching asks the geo index for available drivers in the cells around the pickup point, asks the ETA service for road travel times, reserves the best driver and sends the offer through the gateway. When the driver accepts, the trip service moves the trip to DRIVER_ASSIGNED and notifies the rider.
Stream path. Workers consume the location log to write trip traces to storage, estimate traffic speeds on road segments and count supply per cell for surge.
Deep dives
Ingesting locations and indexing them
All four common geospatial indexes do the same job: turn a two-dimensional position into a one-dimensional key, so “nearby” becomes “has one of these few keys”.
| Index | How it divides space | Watch out for |
|---|---|---|
| Geohash | Interleaves longitude and latitude bits, base-32 string, nested rectangles | Neighbours across a boundary share no prefix; cells narrow towards the poles |
| Quadtree | Splits a square into four whenever it holds too many points | A tree to rebalance as points move |
| S2 | Cube faces divided as quadtrees to level 30, ordered on a Hilbert curve, 64-bit ids | More complex library; cells are quadrilaterals, not exact squares |
| H3 | Hexagons at 16 resolutions, 64-bit ids | Children do not nest exactly; 12 pentagons per resolution |
Geohash, published by Gustavo Niemeyer in 2008, is the simplest and works in any store with sorted keys. Redis geospatial commands (GEOADD, and GEOSEARCH since Redis 6.2) store a 52-bit geohash as a sorted-set score. Always search the target cell and its eight neighbours.
Quadtrees adapt to density, which suits static points such as restaurants. For a million moving points the constant splitting and merging is a cost with little benefit.
S2 is Google’s library. Its Hilbert curve keeps cells that are close in space close in id order more reliably than geohash’s Z-order curve, and its region coverer returns a set of cells that covers any circle or polygon. MongoDB’s 2dsphere indexes are built on it.
H3 was open-sourced by Uber in 2018. Every hexagon has six neighbours at the same distance, so “all cells within k rings” approximates a circle well, and per-cell statistics such as demand smooth evenly across neighbours. Resolution 8 cells average about 0.74 square kilometres and resolution 9 about 0.1.
I would choose H3 at resolution 8 or 9 in a custom in-memory service. A query computes the pickup cell, takes the ring of cells around it and unions the driver sets, widening the ring if there are too few candidates. An update usually leaves the driver in the same cell, so it overwrites one map entry. Only a cell change touches the sets.
Sharding. Shard by a coarse parent cell, roughly a city district, using consistent hashing on the cell id. A nearby query then touches one or two shards. Sharding by driver id would balance writes perfectly but force every query to ask every shard. Dense city centres become hot shards, so let the hottest regions map to finer cells and more shards.
Staleness. Each entry has an updated_at. Queries ignore entries older than about 15 seconds, and a sweeper removes them. Redis sorted sets have no per-member expiry, so on Redis you write that sweeper yourself.
Durability. There is none, deliberately. Each shard has a replica receiving the same writes. If both are lost, a new shard is complete again within 4 seconds, because every driver reports in.
Matching and dispatch
- Candidates. Take available, fresh drivers from the cells around the pickup point, perhaps the 20 closest by straight-line distance.
- Rank. Ask the ETA service for road travel time from each candidate to the pickup. The closest driver in a straight line may be across a river.
- Reserve. Atomically change the best driver’s status from
availabletoofferedwith the trip id and a 15-second expiry. This is a conditional write: it succeeds only if the status is stillavailable. If it fails, another request got there first, so take the next candidate. - Offer. Push the offer to the driver. On accept, the trip service runs
UPDATE trips SET status = 'DRIVER_ASSIGNED' ... WHERE trip_id = ? AND status = 'MATCHING'and the driver becomeson_trip. On decline or timeout, release the driver and try the next. - Give up after a time limit and move the trip to
NO_DRIVERS.
The reserve step is what prevents double dispatch. The geo index holds only a copy of the status as a filter. The conditional write on the durable driver record is the truth, the same idea as a short-lived distributed lock with an expiry.
Every trip transition has the same shape: a conditional update on the current status. If the rider cancels while an offer is out, the trip is already CANCELLED when the acceptance arrives, the update matches no rows, and the driver is released and told the trip has gone. Each committed transition also writes an event (through an outbox table) that drives notifications, receipts and billing.
ETA and surge
ETA is a shortest-path query on the road network: intersections are nodes, road segments are edges, and each edge weight is its current travel time. Preprocessing techniques such as contraction hierarchies make continent-scale queries take milliseconds. Edge weights come from recent driver traces in the location log, and many teams add a learned correction on top. For ranking candidates, cache ETAs between pairs of cells for a minute or so.
Surge is a stream job. For each cell it counts open requests and available drivers over a sliding window of a few minutes, turns the ratio into a multiplier and smooths it across neighbouring cells and over time so prices do not flicker. The quote shown to the rider is stored with an expiry, so the fare charged is the fare that was displayed.
Bottlenecks and failure modes
- An index shard dies. Queries go to its replica. A replacement starts empty and refills from live updates in seconds.
- A driver’s phone loses signal. The entry goes stale and is filtered out, so the driver stops receiving offers. During a trip the app buffers points and uploads them later for the fare.
- A gateway node restarts. Tens of thousands of connections drop and reconnect together. Clients need jittered exponential backoff or the reconnect storm takes down the next node.
- A stadium empties. One cell has thousands of requests and few drivers. Requests queue in matching, the search ring widens, and surge draws supply in. Per-region shards keep the rest of the city unaffected.
- The location log lags. Traffic and surge go stale. Matching is unaffected because it reads the in-memory index directly.
- Trip database failover. In-flight transitions fail and are retried. Conditional updates and idempotency keys make the retries safe.
- Noisy GPS. Raw points jump between parallel streets. Snap positions to the road network before using them for ETA or fares.
Trade-offs
| Decision | Chosen | Alternative | Why |
|---|---|---|---|
| Geo index | H3 cells in memory | Geohash on Redis | Equidistant neighbours and full control of expiry; more to build |
| Live locations | Memory only, async log | Durable write per update | Data is replaced in 4 seconds; avoids 250,000 disk writes a second |
| Index sharding | By region | By driver id | Queries stay on one or two shards; dense cities run hot |
| Matching | Greedy with compare-and-set | Batched assignment | Simple and immediate; not globally optimal |
| Driver transport | Persistent connection | Polling over HTTP | Pushes offers instantly; gateways hold state |
45-minute interview script
A pacing guide. Interviewers differ, so treat the timings as a default and follow their lead.
- 0:00 to 5:00
Requirements 5 min
Confirm the core loop (request, match, pick up, drop off). Ask how often drivers report location, how many are online at peak and how fast a match must be. Put pricing, payments and ratings out of scope, with surge as an extension.
- 5:00 to 9:00
Capacity estimates 4 min
Derive location writes per second, ride requests per second and the size of the live index. Say the conclusion, which is that the index is tiny but written constantly, while trips are few and must be durable.
- 9:00 to 12:00
API 3 min
Request a ride with an idempotency key, the driver's location stream over a persistent connection, accept an offer, and trip events. Mention that updates reach the rider by push.
- 12:00 to 16:00
Data model 4 min
The durable trip row with its status, and the two in-memory maps of the location index. Draw the trip states and say each transition is a conditional update.
- 16:00 to 24:00
High-level design 8 min
Draw the location path first because it carries the traffic, then the request and matching path, then the asynchronous stream. Narrate one ride request from tap to driver assigned.
- 24:00 to 32:00
Deep dive: location ingestion and geo-indexing 8 min
Why a B-tree on latitude and longitude fails, then geohash, quadtree, S2 and H3 with one strength and one weakness each. Pick one, size the cells, and explain sharding by region.
- 32:00 to 39:00
Deep dive: matching and dispatch 7 min
Candidates from the index, ranking by road ETA, reserving the driver with a compare-and-set, offer timeouts, and what happens when the rider cancels mid-offer. Mention batched matching.
- 39:00 to 43:00
Failure modes and trade-offs 4 min
Losing an index shard, stale drivers, a gateway restart and the reconnect storm, a stadium emptying. Explain surge in two sentences if asked.
- 43:00 to 45:00
Wrap-up 2 min
Summarise in three sentences and name what you would build next, such as batched matching or shared rides.
Key takeaways
- Treat live driver locations as ephemeral. Each one is replaced within seconds, so keep them in memory and send a copy to a log for history.
- A geospatial index turns "nearby" into "has one of these few cell ids", which a hash map answers in constant time.
- Geohash and S2 use square-ish cells on a space-filling curve, H3 uses hexagons, and a quadtree adapts cell size to density. Know one strength and one weakness of each.
- Rank candidate drivers by road ETA, not straight-line distance.
- Prevent double dispatch with an atomic compare-and-set on the driver's status, not with a check followed by a write.
- Every trip transition is a conditional update on the current status, so retries and races cannot move a trip backwards.
Check yourself
0 of 5 answered
Flashcards
These 6 cards are in your review deck. Tap a card to see the answer.
How does a geohash work?
It interleaves the bits of longitude and latitude and writes them in base 32. A longer string is a smaller rectangle, and a shared prefix means a shared enclosing cell. Six characters is roughly 1.2 km by 0.6 km at the equator.
What is S2?
Google's library that projects the Earth onto the six faces of a cube, divides each face as a quadtree to 30 levels and numbers the cells along a Hilbert curve, giving a 64-bit cell id.
What is H3?
Uber's hexagonal grid, open-sourced in 2018. Sixteen resolutions, 64-bit ids, six equidistant neighbours per cell. Children only approximately fit their parent, and every resolution has 12 pentagons.
When is a quadtree a good geospatial index?
When points are fairly static and unevenly dense, such as restaurants. It splits crowded areas into small cells and leaves empty areas large. Constant movement means constant restructuring.
How do you stop one driver being dispatched to two trips?
Reserve the driver with an atomic conditional update of their status (available to offered) before sending the offer. The request that loses the race tries the next candidate.
Why rank drivers by ETA and not distance?
The closest driver in a straight line may be across a river, on a motorway heading away or on the wrong side of a one-way system. Road travel time is what the rider experiences.