Priya steps out of Pune railway station with a suitcase and opens the Uber app. The map already shows a handful of small cars crawling along the streets around her. She sets the airport as her destination, taps Request, and within a couple of seconds the screen says that Ravi, in a white hatchback, is three minutes away. She watches the little car turn two corners and pull up beside her.

It looks like a simple lookup, "find the nearest car", but almost every word in that phrase hides a problem. The cars are moving, so wherever the system thinks Ravi is, he was there a few seconds ago. There are millions of them worldwide, so checking every car for every request is out of the question. "Nearest" in a straight line can mean a car on the far side of a river, ten minutes away by road. And picking the nearest car for Priya might leave the rider who taps Request one second later with a car twice as far away, when a slightly different pairing would have suited both.
In this case study we'll design the system that answers Priya's request, the way an engineer would: start with the most obvious design, find exactly where it breaks, and fix it, step by step. The question we'll keep coming back to is this: when Priya taps Request, how does Uber pick the right car out of millions of moving ones, in a second or two? Along the way we'll go from boxes on a diagram down to hexagonal grids, 64-bit cell IDs, road graphs and an assignment problem.
01What we're building, and how big
1.1What it has to do
The core of Uber, the part that moves people, comes down to a short list:
- Show nearby cars on the rider's map as soon as the app opens.
- Match a request to a driver, and get the driver to accept it.
- Estimate times: how long until the car arrives, and how long the trip will take.
- Price the trip, including raising prices where demand outruns supply (surge).
- Track the trip live for both rider and driver, from pickup to drop-off.
- Charge the rider and pay the driver once the trip ends.
And the qualities it needs while doing that:
- Fresh: the system's idea of where each car is should be seconds old, not minutes.
- Fast: a match within a couple of seconds of tapping Request.
- Correct where it matters: one driver can't be assigned to two riders at once, and a trip that has started must never be forgotten.
- Available: a failing data centre mustn't strand riders mid-trip.
This list differs from WhatsApp's in one important way. WhatsApp's hard problem was delivering messages to the right place; Uber's is a question about space: which of the moving things are close to this point, and in what sense of close. Most of this case study is about answering that question quickly.
1.2How big is it?
Uber's own filings give the scale. In the quarter that ended in June 2026, the platform handled about 3.9 billion trips and had 208 million people using it each month. A record 10.2 million drivers and couriers earned money on it that quarter. Across 2025, Uber completed about 13.6 billion trips, more than 40 million a day. (These "trips" include food and package deliveries, not only rides.) It operates in over 70 countries and more than 15,000 cities.
The number that shapes the design most, though, is how often each car reports where it is. Every driver's phone works out its position from GPS satellites and sends it to Uber's servers every few seconds. Uber described this in 2015 as every four seconds, and its partner API still delivers driver locations at a four-second interval by default.

Suppose a million drivers are online at the same moment, each sending a location every four seconds. How many location updates arrive per second, and how long is each one worth keeping?
APIThe API the two phones callPlain HTTPS for actions that happen once (estimate, request, accept), each with an idempotency key, and one long-lived connection per phone for everything that streams (locations up, trip updates down).OpenClose
In an interview, the API comes straight after the requirements, because it pins down what the rest of the design must serve. Uber's internal API isn't public, so this is the shape a design needs, split by how often each call happens:
| Call | Who | How often | Transport |
|---|---|---|---|
GET /v1/fare-estimate?pickup=…&dropoff=… | rider | a few times per trip | HTTPS |
POST /v1/rides with an Idempotency-Key header | rider | once per trip | HTTPS |
POST /v1/offers/{offer_id}/accept | driver | once per offer | HTTPS |
location {lat, lng, heading, speed, ts} | driver | every 4 s | the open connection, upstream |
| trip updates (driver assigned, car position, ETA) | server → both | every few seconds | the open connection, downstream |
Two things in that table trip people up. Locations don't go over a fresh HTTPS request each time. Think about it: a TLS handshake every four seconds from millions of phones costs more than the forty-odd bytes of position it carries, so the update rides the same long-lived connection the server pushes on (section 8.1 is about that channel). And the rider's POST /v1/rides carries an idempotency key, a random ID the phone generates once and resends on every retry. Priya is on patchy station Wi-Fi; if her first request reaches the server but the reply is lost, the phone retries, and the server sees the same key and returns the ride it already created instead of booking a second car.
-- the server's side of an idempotency key: the UNIQUE constraint does the work
CREATE TABLE ride_requests (
idempotency_key UUID PRIMARY KEY,
rider_id BIGINT NOT NULL,
trip_id BIGINT, -- filled in once matched
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
-- INSERT ... ON CONFLICT (idempotency_key) DO NOTHING RETURNING trip_id;02Version 1: a table of drivers
2.1The obvious design
The most obvious design is a database table with one row per driver: driver ID, latitude, longitude, and whether they're free. Each location update overwrites the driver's row. When Priya requests a ride, the server asks for the free drivers ordered by distance from Priya and takes the closest.
Both halves break at Uber's scale. Writes are the first problem: a quarter of a million updates a second to a database on disk, each one written durably even though it will be useless four seconds later. Reads are the second: "order by distance from Priya" means computing the distance from Priya to every free driver and sorting. An ordinary database index can't help, because an index sorts by one value, and distance from Priya isn't a value stored in any row; it depends on where Priya is.
So we need two things: a place to keep the latest positions that can absorb constant overwrites, and a way to find the drivers near a point without looking at all of them. Keeping positions is the easy part. Since only the latest position matters and it's replaced every few seconds anyway, it can live in memory. The rest of this section's trouble, finding nearby drivers without scanning everyone, takes the whole of the next section.
IndexWhich index would Postgres use, and why isn't it enough?A B-tree on (lat, lng) only narrows one coordinate; a PostGIS GiST index can answer 'nearest 10' properly, but Postgres can't absorb 250,000 updates a second to indexed rows.OpenClose
Try the obvious index first. A composite B-tree on (lat, lng) sorts drivers by latitude, and by longitude only among drivers with exactly the same latitude. A box query like this one can use the index for the latitude range, but then has to check the longitude of every driver in that horizontal strip. Across a whole country, that strip holds most of them:
CREATE INDEX drivers_lat_lng ON drivers (lat, lng);
SELECT id FROM drivers
WHERE lat BETWEEN 18.52 AND 18.54 -- the index narrows this
AND lng BETWEEN 73.86 AND 73.89 -- this is checked row by row
AND state = 'available';A B-tree is a one-dimensional structure, so no ordering of two columns makes "close in both" cheap. Postgres's answer is a different kind of index. With the PostGIS extension, a GiST index stores an R-tree, a tree of nested bounding boxes, and supports a distance operator <-> that walks the tree nearest-first. This query really does find the ten closest drivers without scanning everyone:
CREATE INDEX drivers_geo ON drivers USING GIST (location);
SELECT id FROM drivers
WHERE state = 'available'
ORDER BY location <-> ST_MakePoint(73.8743, 18.5286)::geography
LIMIT 10;So the read side is solvable inside a database. Writes are what kill it. In Postgres an UPDATE doesn't change a row in place; it writes a new version of the row, logs it to the write-ahead log, and updates the indexes to point at the new version, leaving the old one for VACUUM to clean up. At 250,000 updates a second that's 250,000 new row versions, WAL records and index changes a second, all made durable for data that's worthless four seconds later. A single Postgres primary probably handles a few tens of thousands of writes like that a second, maybe more on very good hardware, but nowhere near 250,000.
| Option | Finds nearest quickly? | Takes 250k updates/s? | Survives a crash? |
|---|---|---|---|
| B-tree on (lat, lng) | No: one coordinate only | No | Yes |
| PostGIS GiST (R-tree) | Yes | No: MVCC + WAL per update | Yes |
| In-memory cells, sharded | Yes | Yes | No, but drivers resend in 4 s |
Look at the last column. Durability is the expensive thing here, and it's exactly what this data doesn't need. (PostGIS is still what I'd reach for with slow-changing shapes: city boundaries, airport pickup zones, restaurant locations.)
03Finding what's nearby: indexing space
3.1Chop the map into cells
Here's an idea you'd probably come up with yourself. Divide the city into a grid of squares, say 500 metres on a side, and keep a list of the drivers currently inside each square. When Ravi's update arrives, compute which square he's in (divide his coordinates by 500 and round down) and move him into that square's list if he's crossed a line. When Priya requests, look only in her square and the eight squares around it.
This program tries it with a million drivers scattered over a 40 km by 40 km city, comparing it with checking every driver:
brute force: 1,000,000 drivers checked, 81.7 ms
grid index: 1,456 drivers checked, 0.327 ms
same driver found: True, 24 m awaySo the grid found the same driver after looking at 1,456 drivers instead of a million, about 250 times faster (the exact times vary from run to run). There's a deliberate shortcut in the program: it assumes the nearest driver is within one cell of Priya, which is true here because the city is evenly packed with drivers. With sparse drivers, the search has to widen ring by ring until it finds someone.
That last caveat is the grid's real weakness, because real cities are not evenly packed. At 6 pm a 500-metre square in central Mumbai might hold hundreds of cars while one on the outskirts holds none. A single cell size is too coarse downtown, where every cell holds too many cars, and too fine in the suburbs, where Priya's search has to step through many empty cells. The fixes are smarter ways to cut space into cells, and there are four well-known ones.
3.2Geohash: a cell you can write as a string
A geohash turns a location into a short string, by repeatedly halving the world. The first step asks "is the point east or west of the middle longitude?" and records a 1 or a 0. The next asks "north or south of the middle latitude?", and so on, alternating, halving the remaining box each time. Every five of those bits become one character from a 32-character alphabet. Each extra character makes the box 32 times smaller.
Pune station tek93j1
Koregaon Park tek93qr
Mumbai CST te7g9rvPune station and Koregaon Park, about two kilometres apart, share the first five characters, tek93. Mumbai, 120 km away, shares only te. That's the property that makes geohashes useful: nearby places usually share a long prefix, so "drivers near Priya" becomes "drivers whose geohash starts with tek93", a prefix search that any ordinary sorted index, in Redis, Postgres or Cassandra, can answer.

The word "usually" in that paragraph is the catch. Halving like this traces a zig-zag path through space called a Z-order curve, and where the curve jumps, two points a few metres apart on either side of a cell boundary can have completely different prefixes. A geohash search therefore always has to check the eight neighbouring cells too, just like the grid. Geohash cells also get narrower towards the poles, so a "cell" isn't the same size everywhere.
3.3Quadtrees and S2: cells that adapt
A quadtree fixes the density problem directly. Start with one square covering the city. Whenever a square holds more than some limit of drivers, split it into four equal squares, and keep splitting until every square is below the limit. Busy downtown streets end up covered by many small squares, and empty suburbs by a few big ones.

Google's S2 library takes the hierarchy of squares and makes it global and fixed. It projects the Earth onto the six faces of a cube and divides each face into a quadtree of cells, 31 levels deep. Each cell gets a 64-bit ID, numbered along a Hilbert curve, a path that winds through every cell without the big jumps of the Z-order curve. Cells that are close on the curve are close on the ground, so a range of IDs covers a compact area, which suits a sorted index well. According to write-ups of a 2015 Uber talk, Uber's dispatch system used S2 cells at level 12, each a few square kilometres, to organise its driver index at the time.

3.4H3: hexagons
In 2018 Uber open-sourced its own grid system, H3, and it isn't made of squares at all. H3 covers the Earth with hexagons.
It's about the neighbours. Look at a square cell: four neighbours share an edge with it, and four more touch it only at a corner, about 1.4 times further away. Any calculation that spreads out from a cell, such as "demand in this area and the areas around it", has to treat those two kinds of neighbour differently. A hexagon has six neighbours, all sharing an edge and all at the same distance. Uber's 2018 post puts it plainly: hexagons have only one distance between a cell's centre and its neighbours', where squares have two.


H3 offers 16 resolutions, from cells the size of continents down to cells under a square metre. Each finer resolution has cells about a seventh the area of the one above:
| Resolution | Average cell area | Average edge | Cells on Earth |
|---|---|---|---|
| 0 | 4,357,449 km² | 1,281 km | 122 |
| 7 | 5.16 km² | 1.41 km | about 99 million |
| 8 | 0.74 km² | 0.53 km | about 692 million |
| 9 | 0.11 km² | 0.20 km | about 4.8 billion |
| 15 | 0.9 m² | 0.58 m | about 570 trillion |
A city-scale question uses resolutions around 7 to 9: a resolution-8 hexagon is roughly a neighbourhood, half a kilometre across. Which resolution Uber uses for each job isn't published; my guess would be somewhere around 7 or 8 for surge, but nobody outside Uber can say for sure.
"Find drivers near Priya" in H3 becomes: find Priya's cell, then ask for every cell within k steps of it. That operation is called gridDisk (it was named kRing in earlier versions). With k = 1 it returns Priya's cell and its 6 neighbours, 7 cells. In general it returns 3k² + 3k + 1 cells, so 19 for k = 2, and the search widens ring by ring until enough drivers turn up.

Hexagons have one drawback, and it's built into geometry: you can't divide a hexagon exactly into seven smaller hexagons. H3's children cover their parent only approximately, slightly rotated, where S2's four children tile their parent square exactly.

3.5Inside an H3 cell ID
An H3 cell is identified by a single 64-bit integer, so it's cheap to store, hash and compare. The bits are laid out like this:
| Bits | Field | What it holds |
|---|---|---|
| 1 | reserved | always 0 |
| 4 | mode | 1 means "this is a cell" (other modes encode edges and vertices) |
| 3 | reserved | |
| 4 | resolution | 0 to 15 |
| 7 | base cell | which of the 122 resolution-0 cells it descends from |
| 45 | 15 digits × 3 bits | one digit (0 to 6) per resolution, choosing one of seven children at each step; unused digits are set to 7 |
So an ID is literally a path: start from one of the 122 base cells and take one of seven turns at each resolution. Finding a cell's parent means setting the resolution field one lower and blanking the last used digit, a couple of bit operations. That's also what makes compaction possible: when all seven children of a parent are in a set, replace them with the parent. Uber's 2018 post gives the example of California: 10,633 cells at resolution 6, or 901 cells once compacted into a mix of resolutions.
Which way of cutting the map into cells?
- A plain string: works with any sorted index
- Easy to implement
- Neighbours across boundaries have unrelated prefixes
- Cells shrink towards the poles
- Exact parent-child containment
- Hilbert order keeps ID ranges compact
- Two kinds of neighbour: edge and corner
- Every neighbour at the same distance
- Smooth for spreading and aggregating values
- One 64-bit ID per cell
- Children only approximately fill their parent
- 12 pentagons at every resolution need special care
Uber built H3 because its most demanding spatial questions were about areas, not points: demand and supply per neighbourhood, smoothed across adjacent neighbourhoods for surge pricing, and analysed across a whole city. Equal-distance neighbours make that smoothing simple and unbiased. For pure "which drivers are near this point" lookups, the choice matters less; any of the four works with a neighbour search. Uber's 2015 dispatch system used S2 cells and got along fine.
- The map is cut into cells (H3 hexagons), and each cell keeps a list of the drivers inside it
- Finding nearby drivers means looking at a ring of cells (gridDisk) instead of a million rows
- A cell ID is a 64-bit integer, so it's cheap to hash, store and compare
Check yourself: Why does a geohash search still have to check the eight neighbouring cells?
Two points a few metres apart can sit on opposite sides of a cell boundary where the Z-order curve jumps, so their prefixes share nothing. If you only searched the prefix, you'd miss a driver right next to Priya.
04Keeping the live map of drivers
4.1Too much for one machine
We now know how to find nearby drivers in a grid. So where does that grid live? Holding the latest position of a few million drivers takes only a few hundred megabytes, which fits on one machine easily. The problem is the traffic: a quarter of a million updates a second, plus every rider's search, plus the fact that one machine is one machine, and when it fails, nobody can get a ride anywhere.
So the index is split across many machines, and the natural way to split it is by cell. Each machine owns some set of cells and holds the drivers currently inside them. Ravi's location update goes to whichever machine owns his current cell. Priya's search goes to the machines that own the cells in her gridDisk, usually just one or two, since nearby cells tend to be on the same machine.
One property of this workload makes failures far less painful than usual. Because every driver resends their position every four seconds, a node that crashes and restarts empty is fully repopulated within a few seconds, without any backup or replica. The data heals itself. That's a big part of why it can live in memory at all.
CacheCould the location index just be Redis?For most companies, yes: Redis GEO sets keyed by city or coarse cell work well. Uber built its own in 2015 because matching needs more than position: state, vehicle type, and drivers about to finish a trip.OpenClose
Redis is the usual interview answer for "latest location of every driver", and it's a good one. Redis keeps everything in memory, executes each command on one thread so commands never interleave, and has GEO commands built in. Under the hood, GEOADD turns a position into a 52-bit geohash and stores it as the score of a sorted set member, so a radius search is a handful of score-range lookups, the prefix trick from section 3.2.
# one sorted set per coarse area, so no key gets too big or too hot
GEOADD drivers:pune:avail 73.8743 18.5286 driver:ravi
GEOSEARCH drivers:pune:avail FROMLONLAT 73.8750 18.5290 BYRADIUS 2 km ASC COUNT 20
# a sorted-set member can't expire on its own, so track freshness separately
ZADD drivers:pune:seen 1762850000 driver:ravi # score = last update, unix seconds
ZRANGEBYSCORE drivers:pune:seen 0 1762849970 # sweeper: anyone silent for 30 sA few design choices hide in those lines. The key is per area, not one global set, because a single key lives on one Redis node; Mumbai's set and Pune's set can then sit on different shards of a Redis Cluster. Availability is part of the key (:avail), so a search never has to filter out busy drivers; when Ravi accepts a trip he's removed from that set in the same step. And because Redis can't expire one member of a set, a second sorted set records when each driver last reported, and a small sweeper removes drivers whose phones went quiet.
Capacity math is reassuring here. A sorted-set entry with a short member name probably costs on the order of 100 bytes (it depends on the encoding Redis picks), so a million drivers comes to roughly 100 MB. That fits in memory with room to spare. One Redis node handles somewhere around 100,000 simple commands a second, so 250,000 updates a second needs a few primary shards plus replicas. Small cluster.
So why didn't Uber just use it? Its 2015 talks describe a custom supply service in Node.js, sharded with Ringpop, and I think the answer is in what dispatch actually asks: not "who's within 2 km" but "who's within a few minutes, is free or about to be free, drives the right vehicle type, and hasn't just declined". That's a query over position plus several other fields, evaluated thousands of times a second, and it's easier to answer in a service that holds driver objects in memory than in a key-value store holding points. If you're designing this in an interview, Redis GEO is a sound first answer; the custom service is what you move to when the query outgrows it.
4.2Who owns which cells: Ringpop
Something has to decide which node owns each cell, and keep every node and gateway in agreement as nodes join, crash and restart. Uber built and open-sourced a library for this in 2015 called Ringpop, and the motivating case was exactly this driver-location service.
Ringpop combines two ideas from chapters 29 and 30. The first is a consistent hash ring: each node is placed at several points on a circle of hash values, and each key, here a cell ID, belongs to the first node clockwise from the key's hash. When a node leaves, only its keys move, to its neighbours on the ring; everyone else's stay put. Ringpop keeps the ring in a red-black tree, so finding a key's owner takes a logarithmic number of steps.
The second is SWIM gossip for membership: nodes ping each other at random, ask others to ping a node that doesn't answer, mark it suspect and then faulty, and spread those changes by piggybacking them on their pings. So there's no central coordinator; every node keeps its own copy of the membership list and the copies converge.
When a request arrives at a node that doesn't own the key, that node forwards it to the owner. Uber called this "handle or forward". Any node can take any request, which keeps clients simple.
How do nodes agree on who owns which cells?
- One source of truth
- Easy to reason about
- Another critical system to run
- Every membership change goes through it
- No central component
- Only a failed node's keys move
- Membership views can briefly disagree
- Gossip traffic grows with cluster size
Ringpop fitted 2015's Uber: services written in Node.js, growing fast, without an existing coordination layer. It didn't last everywhere. By 2017 Uber's push platform had replaced Ringpop with Netty, ZooKeeper and Apache Helix, and in 2021 Uber's engineers cited Ringpop's peer-to-peer protocol as one of the limits that led them to rebuild the trip-handling platform. Gossip is excellent at "roughly who is alive"; it's a poor fit when an assignment must be exactly right, which is the subject of section 5.3.
05Choosing a driver
5.1Nearest isn't quickest
Dispatch now has a list of candidate drivers near Priya. The next mistake to avoid is picking the closest one in a straight line. Pune has a river running through it, and the nearest car in a straight line might be across a bridge that's twenty minutes away at rush hour, while a car twice as far away is on Priya's side of the river and three minutes from her.
So matching is done on estimated time of arrival (ETA), computed along the actual road network, not on straight-line distance. Uber's own description of its marketplace says it directly: closest doesn't always mean quickest, because of traffic, overpasses, rivers and other geography. The straight-line search from section 3 still has a job, though. It cheaply narrows millions of drivers down to a few dozen, and only those few dozen get the expensive road-based ETA calculation, which section 6 covers.
5.2One rider at a time, or a batch?
There's a second, subtler mistake. Suppose two riders request within a second of each other, and two free drivers are nearby.
Priya requests first, then Sam a second later. Ravi is 2 minutes from Priya and 3 from Sam. Meena is 4 minutes from Priya and 9 from Sam. If each rider in turn takes the nearest free driver, what's the total waiting time? Can you do better?
This short program does both: greedy in order of request, and a search over every possible pairing for the lowest total wait.
greedy {'Priya': 'Ravi', 'Sam': 'Meena'} waits {'Priya': 2, 'Sam': 9} total 11 min
batched {'Priya': 'Meena', 'Sam': 'Ravi'} waits {'Priya': 4, 'Sam': 3} total 7 minPairing riders with drivers to minimise the total cost is a classic problem called bipartite matching, or the assignment problem. Trying every pairing, as the program does, works for two riders and two drivers, but the number of pairings grows factorially, so real solvers use algorithms such as the Hungarian algorithm, which solves it in polynomial time, or min-cost flow. Uber hasn't published which solver it uses. At that size it's probably something closer to min-cost flow than a textbook Hungarian, but that's a guess.
Should each request be matched the moment it arrives?
- The fastest possible answer for each rider
- Trivial to implement
- Early riders can take drivers that later riders needed far more
- Total waiting across everyone is higher
- Lower waiting time across everyone
- Can count drivers who are about to finish a nearby trip
- Each rider waits a few seconds longer for the match
- A heavier computation per batch
Uber's marketplace page describes exactly this: waiting just a few seconds after a request lets it pair riders and drivers to reduce the average wait for everyone, "not just the closest pair". The same window lets the dispatcher consider a driver who is about to drop someone off around the corner, who would be invisible to a search for free drivers only; Uber's dispatch rewrite in 2015 was built to plan ahead in this way.
5.3One driver, one trip
The batch gives Ravi to Sam. Dispatch sends Ravi an offer, Ravi's phone shows it with a countdown, and Ravi taps Accept. If Ravi ignores it, the offer expires and Sam goes back into the next batch.
Here, for the first time, correctness matters more than speed. Two dispatch processes, perhaps handling neighbouring areas, must never offer Ravi to two riders at once, and once Ravi accepts, the trip must exist and be remembered whatever fails. Think of each driver and trip as a small state machine, where only certain moves are allowed, and each move must happen at most once:
These state names are illustrative; Uber's internal ones aren't public. What is public is how its thinking changed. Uber's original trip platform was built, in its engineers' words, on the premise of trading consistency for availability and latency, using Node.js, Ringpop, Cassandra and Redis. In 2021 Uber described rebuilding it in Java on Google Cloud Spanner, a database that offers transactions across shards, and modelling each driver, rider and trip as a hierarchical state machine. The rebuilt platform served over a million concurrent users in over 10,000 cities.
For driver and trip state, favour availability or consistency?
- Keeps working through partitions and node failures
- Low latency
- Rare double assignments and lost updates to clean up
- Hard-to-reason-about edge cases as products multiply
- A driver can't be in two trips
- Simpler code for complex flows
- A distributed database with higher write latency
- Depends on the database's availability
Location index and trip state ended up with opposite answers, and that's the right outcome: locations are overwritten every four seconds and heal themselves, so losing one costs nothing; a trip is a promise to a rider and a driver, so losing or doubling one costs a great deal. Chapter 19 covers what "transactions across shards" requires, and chapter 31 what it costs.
ConsistencyHow do you stop two dispatchers offering Ravi at once?Make the claim a single compare-and-set: change Ravi from available to offered only if he's still available, and treat 'zero rows changed' as losing the race. A lease (TTL) on the offer cleans up after crashes.OpenClose
Here's the race. Dispatcher A reads Ravi's row, sees available, and decides to offer him to Sam. Dispatcher B reads the same row a millisecond later, also sees available, and offers him to someone else. Both write offered. If you read first and write second, no amount of care in the code fixes this, because the gap between the read and the write is where the other dispatcher gets in.
So don't read first. Put the check inside the write, and let the database do both in one step:
UPDATE drivers
SET state = 'offered', offer_id = :offer, offer_expires = now() + interval '15 seconds'
WHERE driver_id = :ravi AND state = 'available';
-- 1 row updated → you own Ravi
-- 0 rows updated → somebody else got him; pick the next candidateThat's a compare-and-set: the WHERE state = 'available' is the compare, and the database's row lock makes the compare and the set one atomic thing. The same idea in Redis is SET lock:driver:ravi offer123 NX PX 15000, which only succeeds if the key doesn't exist yet and deletes itself after 15 seconds.
Why the expiry? Say dispatcher A claims Ravi and then crashes before sending the offer. Without a timeout, Ravi sits in offered forever and never gets another ride. With one, the claim is really a lease: it's yours for 15 seconds, and a sweeper (or the next claim, checking offer_expires < now()) frees it after that.
When Ravi taps Accept, two rows have to change together: his state goes to en_route, and a trip row is created. On one database that's an ordinary transaction. Once drivers and trips live on different shards, it's a distributed transaction, and that's a big part of why Uber moved this platform onto Spanner in 2021: Spanner does multi-row, multi-shard transactions natively, so "driver is busy" and "trip exists" can't end up disagreeing.
| Approach | Stops the double offer? | Cleans up after a crash? | Where it fits |
|---|---|---|---|
| Read, then write | No | No | Nowhere, honestly |
| Conditional UPDATE | Yes | With an expiry column + sweeper | One SQL database |
Redis SET NX PX | Yes, mostly | Yes, the key expires | Fast claims, if a rare double offer is tolerable |
| Spanner / multi-shard transaction | Yes | Yes | Claim and trip creation as one step across shards |
Why "mostly" for Redis? With a single Redis primary and async replication, a failover can lose a lock that was just granted, so the new primary hands it out again. For an offer that a driver can still decline that's survivable. For money it isn't.
- Locations live in memory, split across nodes by cell, with a hash ring deciding who owns what
- Dispatch batches requests for a few seconds and solves the assignment problem for everyone at once
- Claiming a driver is one atomic compare-and-set, so nobody gets offered twice
Check yourself: Dispatcher A reads Ravi as available, then dispatcher B does too. What stops both offering him?
Neither of them should be reading first. Each one runs UPDATE … SET state = 'offered' WHERE driver_id = ravi AND state = 'available', and the database runs those one at a time on the row. Whoever goes first changes one row; the other changes zero and moves on to the next candidate.
06How long will it take?
6.1The road network as a graph
Matching needs an ETA for each candidate driver, and the app shows ETAs all the time: for the car to arrive, for the trip, for the price estimate. To compute one, Uber models the road network as a graph: every intersection is a node, every stretch of road between two intersections is an edge, and each edge's weight is how long it takes to drive. Turn restrictions and the cost of turning are modelled too. An ETA is then the length of the shortest path between two nodes.


For shortest paths, the textbook algorithm is Dijkstra's algorithm, which explores outward from the start in order of distance until it reaches the destination. On a city graph with millions of edges, that exploration touches a large part of the city for every query. A* speeds it up by preferring nodes in the direction of the destination, and Uber's 2015 post on its routing engine measured a city-scale A* query with live traffic at about 120 milliseconds. That sounds fast, but it's far too slow when every request needs dozens of ETAs and the whole platform asks for hundreds of thousands a second.
The standard trick for fast routing is to precompute. Contraction hierarchies rank the nodes by importance and add "shortcut" edges that skip over unimportant nodes, so a query can climb quickly onto major roads and come back down near the destination, answering in milliseconds. Precomputation is the catch, though: Uber's post notes that building the contracted graph for all the roads of the world takes about 12 hours, which makes folding in live traffic, which changes by the minute, very hard.
How should ETAs be computed?
- Always uses the latest traffic
- Nothing to precompute
- About 120 ms per query: too slow at scale
- Very fast queries
- About 12 hours to rebuild for the world
- Live traffic is hard to apply
- Fast queries with fresh traffic
- Learns what the graph can't see
- Two systems to build and keep consistent
Uber's in-house routing engine, Gurafu, launched in 2015 and divides the graph into a hierarchy of cells, so that small sections can be preprocessed independently and in parallel, aiming for single-digit-millisecond answers at hundreds of thousands of requests a second. On top of it, since 2022, a model called DeepETA predicts the difference between the routing engine's estimate and the real arrival time, learning effects such as pickups at airports or slow drop-offs that a sum of road segments can't know about.
DeepETA is worth a moment, because it's a neat design pattern. The routing engine computes an ETA as a sum of segment travel times. Then a neural network, which Uber says replaced one of the largest gradient-boosted tree ensembles in the world, predicts how wrong that sum will be, given the time of day, the type of request and other features. Learning only the correction keeps the model's job small and lets the routing engine keep doing what it's good at. Uber's ETAs feed fares, pickup estimates, matching and delivery planning, and Uber describes DeepETA as its highest-traffic model.
07Surge pricing, per hexagon
7.1Supply and demand on a map
It's raining, a concert has just ended, and two hundred people near the stadium open the app at once. There are thirty drivers nearby. If prices stay normal, most of those people get no car and the drivers stay put. Raising the price in that area does two things at once: some riders decide to wait or walk, and drivers from nearby areas head towards the stadium. That's surge pricing, and it's computed per area.
Uber's 2018 H3 post says it plainly: surge is calculated by measuring supply and demand in hexagons in each city. A later post on Uber's real-time analytics system, Gairos, describes the calculation as querying the number of requests and the number of available drivers for a hexagon, with over a million events a second flowing into that system. This is where hexagons earn their keep: smoothing a surge value across a hexagon and its six equidistant neighbours avoids sharp price cliffs at cell edges, and treats every direction the same.
Uber's 2021 paper on its real-time data infrastructure describes surge's choices directly: the pipeline favours fresh data and availability over consistency, and events that arrive late for their window are dropped. It runs in several regions at once, and if one region fails, the surge calculation fails over to another. A price computed from slightly incomplete counts a few seconds ago is far better than no price at all.
Queue / streamWhy Kafka for the event log, and not RabbitMQ, SQS or Redis Streams?Because many teams read the same events for different jobs, at different speeds, and sometimes need to replay yesterday. Kafka keeps the log on disk for days and lets each reader keep its own position; a queue deletes a message once it's handled.OpenClose
Start with who reads these events. Surge counts requests per hexagon. Fraud looks for drivers whose GPS jumps impossibly. The ETA team wants every completed trip to train DeepETA. Analytics wants all of it in the warehouse. That's four consumers of one stream, and they don't run at the same speed: surge is seconds behind, the warehouse load might be an hour behind, and when someone ships a bug in the fraud job, they'll want to rewind to this morning and run it again.
A traditional queue like RabbitMQ or SQS is built for a different job. A message goes to one worker, the worker acknowledges it, and it's gone. You can fake multiple readers by copying every message into one queue per consumer, but replaying last Tuesday is off the table, because last Tuesday was deleted.
Kafka is a log, not a queue. Producers append to the end of a partition, an ordered file on disk; each consumer group remembers its own offset (how far it has read); messages stay for as long as the retention setting says, whether anyone has read them or not. Adding a fifth consumer costs nothing on the producer side, and replay means resetting an offset.
| Kafka | RabbitMQ | SQS | Redis Streams | |
|---|---|---|---|---|
| Many independent readers | Yes, consumer groups | Copy per queue | Copy per queue (SNS fan-out) | Yes, consumer groups |
| Replay old events | Yes, until retention | No | No | Only while it fits in memory |
| Ordering | Per partition | Per queue | FIFO queues only, lower throughput | Per stream |
| Throughput | Millions/s per cluster | Tens of thousands/s per node | Managed, scales, per-call cost | High, memory-bound |
| Good at | Event logs, pipelines | Task queues, routing rules | Simple managed work queues | Small, fast streams |
Uber is about as committed to Kafka as a company gets. Its 2021 SIGMOD paper describes Kafka carrying trillions of messages and petabytes of data a day, feeding Flink jobs like surge, Pinot for real-time analytics, and the Hive warehouse.
The partition key matters more than the broker
Within a topic, Kafka only keeps order inside a partition, and each partition is read by one consumer in a group. So the key you partition by decides what a single Flink task gets to see. For surge, partition by hexagon (a coarse H3 cell, say resolution 6 or 7): every request and every free-driver event for one area lands on the same partition, so one task can count them without talking to anyone. Partition by driver_id and each driver's events stay in order, but a hexagon's events end up spread across every partition, and counting them needs a shuffle.
The hexagon key has its own failure mode, and it shows up at exactly the wrong time. When a concert ends, one hexagon's partition gets a flood while the rest idle. Usual fixes are a coarser key that mixes busy and quiet areas, or salting the hot key (hex:8a2a1072b59ffff:3) across a few partitions and summing the pieces afterwards. I don't know which, if either, Uber does; the paper doesn't say.
Windows and late events
Flink counts per tumbling window, back-to-back non-overlapping buckets of, say, one minute. Phones on bad networks send events late, so Flink tracks a watermark, its estimate of "everything before time T has arrived", and closes a window when the watermark passes its end. An event that turns up after its window closed is late; the surge job simply drops it, as the 2021 paper describes. Being a few events short beats publishing the price late.
CacheWhere the surge multiplier lives, and why it has a TTLIn a key-value store keyed by hexagon, overwritten every window, with an expiry slightly longer than the window, so a dead pipeline fails back to no surge rather than freezing a stale 3x price.OpenClose
Reads here are tiny and hot: given Priya's hexagon, what's the multiplier? Every fare estimate in a city asks that, many times a second, so it lives in memory, in Redis or an equivalent:
SET surge:8a60145b2a4ffff 1.8 EX 120 # written by the Flink job each window
GET surge:8a60145b2a4ffff # read by the pricing service
# (nil) → no surge, charge 1.0xThe EX 120 is the important part. If the stream job dies, nobody refreshes these keys, and without an expiry the last value would stay forever: a hexagon that surged to 3x during a storm would still charge 3x at 4 am. With a two-minute expiry, a stalled pipeline means surge quietly disappears. That's the failure you want, because undercharging for a few minutes is cheap and overcharging makes the news.
There's a second, separate store in the flow. Once Priya sees a fare and taps Request, the price she saw is the price she pays (Uber calls these upfront fares), even if surge changes a second later. So the estimate is saved as a quote: quote:{id} → {fare, surge, expires} with a short TTL, and POST /v1/rides passes the quote ID. The pricing service charges what the quote says, and an expired quote means showing her a new price.
08During the trip: live updates and storage
8.1Pushing updates to phones
While Ravi drives to Sam, Sam's app shows the car moving and the ETA counting down, and Ravi's app shows directions. The simple way to build this is for each app to ask the server every few seconds for updates. Uber did exactly that at first, and by its own account, at one point 80% of the requests to its API gateway were these polling calls, most of them answering "nothing new".
Uber's fix, described in 2020, was a push platform called RAMEN: each app keeps one long-lived connection open, and the server pushes updates down it when something changes, with a heartbeat every four seconds to keep the connection alive and detect failures. It handled over 1.5 million concurrent connections and over 250,000 messages a second. In 2022 Uber moved it to bidirectional gRPC streams, because with the earlier one-way design the server couldn't tell for up to 30 seconds whether a message had arrived.
That's the same decision WhatsApp made in its section 2, for the same reason: when the server knows first that something has changed, it should tell the phone, not wait to be asked.
Real-timePolling, SSE, WebSockets or gRPC streams?Uber went polling → Server-Sent Events (RAMEN, one-way) → bidirectional gRPC streams in 2022. Honestly, the protocol isn't the hard part; it's knowing which of thousands of gateway servers holds Sam's connection.OpenClose
There are four ways to get "Ravi is 2 minutes away" onto Sam's screen:
| Option | How it works | Cost | Problem |
|---|---|---|---|
| Polling | Phone asks every few seconds | A request per phone per interval, mostly "nothing new" | 80% of Uber's gateway traffic, at one point |
| Long polling | Phone asks, server holds the request open until there's news | One open request per phone, re-opened after each answer | Fiddly with proxies and timeouts |
| Server-Sent Events | One HTTP response that never ends; server writes events into it | One connection per phone | One-way: the phone can't acknowledge on it |
| WebSocket / gRPC stream | One connection, both directions | One connection per phone, plus your own heartbeats | Stateful servers; you need routing |
Uber's RAMEN was built on Server-Sent Events. That's how you end up with the 30-second blind spot from the section above: acks had to come back some other way, so the server couldn't tell for a while whether a message had landed. Moving to bidirectional gRPC in 2022 put the ack on the same stream.
Whichever protocol you pick, the same question comes next, and it's the one interviewers actually push on. Sam's phone is connected to one gateway server out of thousands. When dispatch wants to tell Sam something, which server does it send to? You need a connection registry: when Sam connects, the gateway writes conn:sam → gateway-417 to a fast store (Redis, or a consistent hash ring of gateways so the mapping is computable). Dispatch looks it up and sends the message to gateway 417, which writes it down Sam's socket. When Sam's phone reconnects to a different gateway after going through a tunnel, the entry is overwritten, and anything sent in between needs to be held and replayed, so messages carry sequence numbers and the phone says "I last saw 1,204" when it reconnects.
8.2Where trips are stored
A trip, once accepted, is a record that must never be lost: it's the basis of the fare, the driver's pay, receipts, disputes and safety investigations. In 2014 Uber outgrew a single Postgres database and built Schemaless, a layer on top of many MySQL databases. Its data model was an append-only map from (row ID, column name, version) to an immutable JSON value. A trip's row had columns such as BASE for the trip itself, STATUS, NOTES and FARE ADJUSTMENTS, and every change wrote a new version instead of updating in place. The data was split across 4,096 fixed shards, each a primary MySQL database with two replicas.
That design later evolved into Docstore, which added Raft-based replication within each partition and strict consistency per partition, at a scale of tens of millions of queries a second. And as section 5.3 described, the trip-handling platform itself moved onto Spanner in 2021 for transactions across shards.
SchemaThe trips table: keys, shard key and indexesShard by trip_id so writes spread evenly; then 'Priya's last 20 trips' needs a secondary index keyed by rider_id, which on a sharded store lives on different shards and is updated asynchronously, exactly what Schemaless did.OpenClose
Here's the table you'd sketch on a whiteboard. Uber's real schema isn't public, so this is the logical shape, not their columns:
Each index exists because a screen or a job asks a specific question. (rider_id, requested_at DESC) is a composite index: the B-tree is sorted by rider, then by time within a rider, so "Priya's 20 most recent trips" is one seek and a short forward scan, with no sort. The partial index only holds the few percent of trips that are still live, so the operations dashboard doesn't drag billions of finished rows through memory.
Then you shard it, and the indexes get hard
One machine can't hold every trip, so the table is split across shards. Which column decides the shard? trip_id spreads writes evenly and makes "fetch trip X" a one-shard lookup. But now Priya's trips are scattered across all 4,096 shards, and trips_by_rider can't be a local index any more, since a local index on each shard only knows that shard's rows. Asking all 4,096 shards for every "my trips" screen doesn't scale.
You fix it with a global secondary index: a separate table, sharded by rider_id, holding (rider_id, requested_at) → trip_id. That's what Schemaless did. Its 2016 design post describes indexes declared on fields inside the JSON cells, sharded by the indexed field, and updated asynchronously after the main write, so an index can lag the data briefly. For a trip history screen that's fine. Priya probably won't even notice her trip showing up a second late.
| Shard key | Fast | Slow or awkward |
|---|---|---|
trip_id | Writes spread evenly; fetch by trip ID | Anything by rider or driver needs a global index |
rider_id | Rider history is one shard | Driver earnings need a global index; a few heavy users make hot shards |
city_id | City-wide operations | Mumbai's shard is enormous and Shimla's idle |
DatabasePostgres, then MySQL + Schemaless, then Spanner. Why each move?Postgres ran out of headroom for Uber's update-heavy, index-heavy workload in 2014–16; MySQL's index layout and replication suited it better; Spanner arrived in 2021 when cross-shard transactions mattered more than raw write latency.OpenClose
Uber published unusually candid reasons for each move, so this one's a good story to have ready for an interview.
Postgres → MySQL (2014–2016). Uber's 2016 post "Why Uber Engineering Switched from Postgres to MySQL" mostly comes down to how each database points its indexes at rows. In Postgres, every secondary index stores the row's physical location. An update writes a new copy of the row somewhere else, so every index on the table has to be updated too, even indexes on columns that didn't change. (Postgres has an optimisation called HOT updates that sometimes avoids this, but only when no indexed column changes and the new version fits on the same page.) In MySQL's InnoDB, secondary indexes store the primary key instead, so updating status doesn't touch the index on rider_id at all. For a table with several indexes and a stream of status updates, that's a big difference in write amplification. The post also lists replication: Postgres replicated the physical write-ahead log, all those index changes included, across data centres, and that cost bandwidth.
Why not Cassandra? Uber used Cassandra elsewhere, and it takes huge write volumes. But trips need things Cassandra makes hard: conditional updates on a row, secondary indexes that work, and an operational model the team already trusted. Uber's Schemaless post says it chose to build on MySQL partly because MySQL was what its engineers knew how to run.
MySQL + Schemaless → Spanner (2021). Schemaless gave Uber scale and append-only history but no transactions across shards. The 2021 fulfilment rewrite needed "driver is busy" and "trip is created" to happen together, even though drivers and trips live on different shards. Spanner does that with synchronised clocks (TrueTime) and two-phase commit, and pays some write latency for it, likely a few milliseconds more per commit than a single MySQL primary.
| Postgres (single) | Cassandra | MySQL + Schemaless | Spanner | |
|---|---|---|---|---|
| Scales writes horizontally | No | Yes | Yes, 4,096 shards | Yes |
| Transactions across rows on different shards | n/a | No (lightweight transactions are per partition) | No | Yes |
| Secondary indexes | Local, rich | Limited | Global, asynchronous | Global, consistent |
| What it cost Uber | Write amplification, replication | Weak conditional updates | Hand-built consistency | Latency, cloud dependency |
If an interviewer asks "SQL or NoSQL for trips?", Uber's history is a decent answer in itself: a relational engine underneath every step, and the layer on top changed as the consistency needs did.
- ETAs come from a partitioned road graph plus DeepETA's learned correction
- Surge is counted per hexagon by Flink reading Kafka, and served from a key-value store with a TTL
- Phones get pushed updates over one long-lived connection, found through a connection registry
- Trips sit in a sharded, transactional store with global indexes by rider and driver
Check yourself: Why does the surge key in the cache have an expiry at all, if Flink rewrites it every window?
In case Flink stops rewriting it. Without an expiry, a crashed pipeline would freeze the last multiplier in place, maybe a storm-time 3x, for hours. With one, surge falls back to 1.0x within a couple of minutes, and undercharging briefly is the cheaper mistake.
09When a data centre fails mid-trip
9.1The phone remembers the trip
Sam is halfway to the airport when the data centre handling Pune goes dark. The trip is in progress, Ravi is driving, and the servers that knew about the trip are unreachable.
Uber's 2016 description of its stack says that each city is assigned to the closest data centre and backed up in another, and that if one data centre fails, trips fail over to another. What's interesting is how that works for trips already in progress. According to write-ups of a 2015 Uber talk, the dispatch system periodically sent each driver's phone an encrypted digest of the trip's state. If the data centre failed, the phone's next request would land in the backup data centre, which wouldn't recognise the trip, ask the phone for its digest, and rebuild the trip's state from it. The phone, which is present for the whole trip anyway, acts as a backup of its own trip.
On the app side, Uber described in 2020 a small state machine in its mobile client with four states, primary, failover, backup and recovery, that decides which network path to use and moves back only after test requests succeed.
10The whole system
10.1Every box, and why it's there
| Component | What it does | Added because |
|---|---|---|
| Location index | Latest position of every driver, by cell, in memory | A table scan can't find nearby drivers fast (§2, §3) |
| Cell system (S2, H3) | Turns positions into cell IDs; neighbour searches | Density varies; neighbours must be found cheaply (§3) |
| Consistent hashing + membership | Splits cells across nodes; survives node loss | Too much traffic for one machine (§4) |
| Dispatch | Collects requests and drivers, solves the assignment | Greedy matching wastes everyone's time (§5) |
| ETA service | Shortest paths on the road graph, corrected by ML | Straight-line distance misleads (§5, §6) |
| Surge pipeline | Supply and demand per hexagon, as a stream | Prices must react to local demand within seconds (§7) |
| Push channel | One long-lived connection per app | Polling was 80% of API traffic (§8) |
| Trip store | Durable, transactional record of every trip | A trip is a promise that can't be lost or doubled (§5.3, §8) |
Here's the same design one level down: the actual technology at each layer, what it beat, and a link to the box that argues it.
10.2From top to bottom
| Level | The choice | Data structure or algorithm |
|---|---|---|
| System | Split data by how wrong it can afford to be | In-memory index for locations, streams for surge, transactions for trips |
| Location index | Bucket drivers by cell | Hash map from cell ID to the set of drivers in it |
| Cells | Hexagons for areas, squares where containment matters | H3 64-bit IDs (base cell + 15 three-bit digits); S2 Hilbert-ordered IDs |
| Neighbour search | Widen ring by ring | gridDisk: 3k² + 3k + 1 cells within k steps |
| Sharding | Cells to nodes | Consistent hash ring in a red-black tree; SWIM gossip |
| Matching | Batch for a few seconds | Bipartite assignment (Hungarian algorithm, min-cost flow) |
| ETA | Road graph plus correction | Weighted directed graph; A*, partitioned precomputation; residual neural network |
| Surge | Per hexagon, per window | Windowed counts in a stream processor; hexagon → multiplier map |
| Trips | One state change at a time | Hierarchical state machines; append-only versioned cells; Spanner transactions |
11What goes wrong, and what it cost
11.1Failures this design has to survive
| What happens | What the user sees | What the design does |
|---|---|---|
| A location index node crashes | Nothing, or a car briefly missing from the map | Its cells move to other nodes; drivers' next updates refill them within seconds |
| GPS is wrong between tall buildings | The car jumps across the map | Positions are snapped to roads and smoothed over successive updates |
| Two dispatchers pick the same driver | The driver gets two offers | Driver state changes atomically, so the second assignment fails |
| A driver ignores the offer | The rider waits longer | The offer times out and the rider joins the next batch |
| A sudden crowd in one hexagon | Long waits, no cars | Surge raises prices there and draws drivers in |
| A data centre fails mid-trip | A brief stall | The city fails over; in-progress trips are rebuilt from state the phones carry |
11.2The tradeoffs, in one table
| Decision | Chosen | Given up | Why it was worth it |
|---|---|---|---|
| Where locations live | Memory, sharded by cell | Durability | They're overwritten every 4 s and heal themselves |
| How to cut space | Hexagons (H3) for areas | Exact parent-child containment | Equal neighbours make area statistics fair and smooth |
| Who owns which cells | Consistent hashing + gossip (2015) | Exact agreement at every instant | No central coordinator; only a dead node's cells move |
| Matching | Batch for a few seconds | The fastest possible answer for each rider | Lower total waiting for everyone |
| Closeness | Road-network ETA | Cheap straight-line distance | Rivers, bridges and traffic decide real wait times |
| Surge data | Freshness over consistency | Exact counts | A slightly wrong price now beats a perfect price late |
| Trip state | Consistency over availability (2021) | Some write latency | A driver can't be in two trips; trips are never lost |
12Summary
- The workload is mostly locations: every driver every four seconds, a quarter of a million writes a second for a million drivers, of which only the latest per driver matters.
- A table ordered by distance can't scale: every query would compute the distance to every driver, and an ordinary index can't sort by distance from a moving point.
- Cut the map into cells and keep drivers in per-cell lists, so a search looks at a few cells, not everyone.
- Geohash, quadtrees, S2 and H3 are four ways to cut it: prefix strings, density-adaptive squares, Hilbert-ordered squares, and hexagons with equidistant neighbours.
- An H3 cell is a 64-bit path: a base cell and one of seven children per resolution, so parents, neighbours and compaction are bit operations.
- The location index lives in memory, sharded by cell, and heals itself after a crash because drivers resend their positions.
- Match on road-based ETA, not straight-line distance, using the cheap cell search to narrow millions of drivers to a few dozen candidates.
- Batch requests for a few seconds and solve the assignment problem, so everyone waits less in total.
- ETAs come from a road graph plus a learned correction: fast precomputed routing, with a model that predicts how wrong it will be.
- Surge is computed per hexagon from streams of events, favouring freshness over exactness.
- Sort data by the cost of being wrong: approximate and self-healing for locations and surge, transactional for trips and payments.
13Build this
A dispatch simulator.
- Install the
h3Python package. Simulate 10,000 drivers moving along random straight lines in a city-sized box, each reporting a position every four seconds of simulated time, and keep a dictionary from resolution-8 cell to the set of drivers in it. - For each simulated request, use
grid_diskwith increasing k until at least 10 free drivers are found. Count how many cells and drivers each search touched. - Match greedily, then match in two-second batches using
scipy.optimize.linear_sum_assignment(an implementation of the assignment problem). Compare average and worst rider wait. - Put all the drivers in one part of the box and none elsewhere, and watch the search cost change; then try a coarser and a finer resolution.
- Compute "surge" as requests divided by free drivers per cell, smooth it over each cell's
grid_disk(1), and draw it.
14Interview questions
beginnerWhy can't you find the nearest driver with an ordinary database index?›
An ordinary index sorts rows by a stored value, but the distance from a rider to a driver isn't stored anywhere; it depends on where the rider is, which changes with every request. Without a spatial index, the database has to compute the distance to every driver and sort them. A spatial index, a grid of cells, geohashes, a quadtree, S2 or H3, groups drivers by area so a search only looks at the few cells around the rider.
beginnerWhy does Uber use hexagons?›
Every neighbour of a hexagon shares an edge with it and is the same distance away, while a square has four edge neighbours and four corner neighbours that are further away. When you compute something over an area and its surroundings, like supply and demand for surge pricing, hexagons treat every direction alike and avoid artefacts at corners. The cost is that hexagons can't be split exactly into smaller hexagons, so moving between resolutions is approximate.
intermediateDriver locations arrive 250,000 times a second. Where do you store them, and what happens when a node dies?›
Only each driver's latest position matters, so keep it in memory, partitioned by cell across many nodes, with a consistent hash ring deciding which node owns which cells. Updates are routed to the owner of the driver's current cell. When a node dies, its cells move to other nodes on the ring, and because every driver resends a position within a few seconds, the new owners are repopulated almost immediately without any backup.
intermediateWhy would you delay matching a rider by a few seconds on purpose?›
Matching each rider greedily the moment they request can give an early rider a driver that a later rider needed far more. Collecting the requests and free drivers in an area for a few seconds and solving the assignment for all of them together lowers the total waiting time. In a two-rider example, greedy gives waits of 2 and 9 minutes, and the batched assignment gives 4 and 3. Uber describes doing this to reduce the average wait for everyone.
deepWhich parts of a ride-hailing system should be eventually consistent, and which must be strongly consistent?›
Sort the data by the cost of being wrong. Driver locations are overwritten every few seconds and heal themselves, and surge counts are statistics where a slightly stale value is fine, so both can be in-memory or streaming and prefer availability. Driver assignment and trip state must be exactly right: a driver mustn't be offered to two riders, and an accepted trip mustn't be lost, so those changes need atomic transitions in a transactional store. Uber moved its trip platform from an availability-first design to Spanner transactions in 2021 for exactly this reason.
deepHow do you compute ETAs fast enough for matching at scale?›
Model the road network as a weighted graph and compute shortest paths, but plain Dijkstra or A* is too slow at city scale with hundreds of thousands of requests a second. Precomputation helps: contraction hierarchies add shortcut edges for millisecond queries, but rebuilding them for the world takes hours, which makes live traffic hard, so engines like Uber's Gurafu partition the graph into cells that can be precomputed independently. Then a learned model, like Uber's DeepETA, predicts the residual error of the routing estimate from features such as time of day and pickup type.
15Go deeper
A location index node crashes. What's lost, and how long until it's back?›
The latest positions of the drivers in its cells. Its cells move to other nodes on the hash ring, and since every driver resends a position every few seconds, those nodes have a complete picture again within seconds. Nothing needs restoring from a backup.
Two points 10 metres apart have geohashes with no common prefix. How?›
They're on opposite sides of a cell boundary where the Z-order curve jumps. That's why a geohash search always checks the neighbouring cells as well as the cell matching the prefix.
How many H3 cells does gridDisk(k = 3) return around a cell away from pentagons?›
3k² + 3k + 1 = 27 + 9 + 1 = 37: the centre cell, 6 in the first ring, 12 in the second and 18 in the third.
Why hexagons, how the hierarchy works, and how surge uses them. The h3geo.org documentation has the resolution table and the bit layout.
How Uber's routing engine models the road graph, why contraction hierarchies didn't fit live traffic, and the residual model on top.
Consistent hashing plus SWIM gossip for application-level sharding, with the driver-location service as the motivating example.
Why the trip platform moved from availability-first to Spanner transactions, and how state machines model trips.
Kafka, Flink and the surge pipeline, including which properties it trades away and why.
The dispatch system as it was in 2015: supply and demand services, S2 cells, Ringpop, and failover with state kept on drivers' phones.
16Related chapters
The same push-over-polling decision, and a contrasting system built around delivering messages. Chapter 49.
Consistent hashing and how keys move when nodes join and leave. Chapter 29.
SWIM, suspicion and gossip, the membership half of Ringpop. Chapter 30.
What it takes to make "one driver, one trip" hold under concurrency. Chapter 19.
The event log under the surge pipeline. Chapter 23.