KnowSys

Designing Uber

Priya taps Request outside Pune station, and within a couple of seconds a driver three minutes away is on the way. We'll design the system that makes that match, from millions of moving cars down to hexagons, bit layouts, road graphs and the assignment problem, and look at the tradeoffs Uber made along the way.

⏱ 55 min read◆ IntermediateAssumes: chapter 29 (partitioning), chapter 30 (failure detection) helps, the WhatsApp case study (chapter 49) helps
Start reading

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.

An Uber-branded car parked on a snowy city street
Every car on the platform is a moving point that reports where it is every few seconds. The whole design is about finding the right one quickly.Photo: Nickispeaki, CC BY-SA 4.0, via Wikimedia Commons

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:

  1. Show nearby cars on the rider's map as soon as the app opens.
  2. Match a request to a driver, and get the driver to accept it.
  3. Estimate times: how long until the car arrives, and how long the trip will take.
  4. Price the trip, including raising prices where demand outruns supply (surge).
  5. Track the trip live for both rider and driver, from pickup to drop-off.
  6. 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.

The Earth surrounded by the orbits of navigation satellites
Each driver's phone works out its position by timing signals from satellites like these. The fix is good to a few metres in the open, worse between tall buildings, and it's out of date the moment the car moves.Image: NASA Scientific Visualization Studio, public domain, via Wikimedia Commons
Your turn: design it before reading on

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).

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:

CallWhoHow oftenTransport
GET /v1/fare-estimate?pickup=…&dropoff=…ridera few times per tripHTTPS
POST /v1/rides with an Idempotency-Key headerrideronce per tripHTTPS
POST /v1/offers/{offer_id}/acceptdriveronce per offerHTTPS
location {lat, lng, heading, speed, ts}driverevery 4 sthe open connection, upstream
trip updates (driver assigned, car position, ETA)server → bothevery few secondsthe 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.

SQL
-- 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.

Version 1: every update and every request goes to one table
UPDATErequestDrivers' phonesGPS every 4 sAPI serverdrivers tableid, lat, lng, freePriya's phone
Simple, and wrong twice over: 250,000 overwrites a second hammer one table, and each request has to compute the distance to every driver to find 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.

Insight
An index can only sort by something stored in the row. Distance from Priya isn't stored anywhere, so no ordinary index can sort by it.

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.

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:

SQL
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:

SQL
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.

OptionFinds nearest quickly?Takes 250k updates/s?Survives a crash?
B-tree on (lat, lng)No: one coordinate onlyNoYes
PostGIS GiST (R-tree)YesNo: MVCC + WAL per updateYes
In-memory cells, shardedYesYesNo, 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:

Nearest driver: check everyone, or check a few grid cells
python
Python
import math, random, time
random.seed(1)
 
# 1,000,000 drivers scattered over a 40 km x 40 km city
N, SIZE = 1_000_000, 40_000.0
drivers = [(random.uniform(0, SIZE), random.uniform(0, SIZE)) for _ in range(N)]
rider = (21_345.0, 18_210.0)
 
def dist(a, b):
    return math.hypot(a[0] - b[0], a[1] - b[1])
 
# 1. brute force: look at every driver
t = time.perf_counter()
best = min(drivers, key=lambda d: dist(d, rider))
brute_ms = (time.perf_counter() - t) * 1000
 
# 2. grid index: 500 m cells, look only in the rider's cell and its neighbours
CELL = 500.0
grid = {}
for d in drivers:
    grid.setdefault((int(d[0] // CELL), int(d[1] // CELL)), []).append(d)
 
t = time.perf_counter()
cx, cy = int(rider[0] // CELL), int(rider[1] // CELL)
nearby = [d for dx in (-1, 0, 1) for dy in (-1, 0, 1)
          for d in grid.get((cx + dx, cy + dy), [])]
best_grid = min(nearby, key=lambda d: dist(d, rider))
grid_ms = (time.perf_counter() - t) * 1000
 
print(f"brute force: {N:,} drivers checked, {brute_ms:.1f} ms")
print(f"grid index:  {len(nearby):,} drivers checked, {grid_ms:.3f} ms")
print(f"same driver found: {best == best_grid}, {dist(best, rider):.0f} m away")
output
C++
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 away

So 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.

Encode three places as geohashes
python
Python
BASE32 = "0123456789bcdefghjkmnpqrstuvwxyz"
 
def geohash(lat, lon, length=7):
    lat_lo, lat_hi, lon_lo, lon_hi = -90.0, 90.0, -180.0, 180.0
    bits, even, out = 0, True, ""
    for i in range(length * 5):
        if even:                      # even bits split longitude
            mid = (lon_lo + lon_hi) / 2
            bit = lon >= mid
            lon_lo, lon_hi = (mid, lon_hi) if bit else (lon_lo, mid)
        else:                         # odd bits split latitude
            mid = (lat_lo + lat_hi) / 2
            bit = lat >= mid
            lat_lo, lat_hi = (mid, lat_hi) if bit else (lat_lo, mid)
        bits = bits * 2 + bit
        even = not even
        if i % 5 == 4:
            out += BASE32[bits]
            bits = 0
    return out
 
places = {
    "Pune station":   (18.5286, 73.8743),
    "Koregaon Park":  (18.5362, 73.8940),
    "Mumbai CST":     (18.9398, 72.8355),
}
for name, (lat, lon) in places.items():
    print(f"{name:14} {geohash(lat, lon)}")
output
C++
Pune station   tek93j1
Koregaon Park  tek93qr
Mumbai CST     te7g9rv

Pune 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.

A map of southern Brazil divided into 32 rectangles, each labelled with a two-character geohash beginning with 6g
The geohash cell 6g split into its 32 children, 6g0 to 6gz. Each child is a box 32 times smaller, and adjacent boxes usually share the prefix, but look at the edges: cells that touch across a boundary can have quite different strings.Image: Krauss, CC BY-SA 4.0, via Wikimedia Commons. Map data © OpenStreetMap contributors

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.

A square repeatedly divided into smaller squares wherever points cluster, leaving large empty squares where there are no points
A quadtree over a set of points. Squares split only where points cluster, so every leaf square holds only a few points however uneven the density. The cost is that the shape of the tree depends on the data, and moving points means splitting and merging squares as they go.Image: David Eppstein, public domain, via Wikimedia Commons

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.

Three Hilbert curves of increasing detail drawn on top of each other in red, blue and black
Hilbert curves of order 1 (red), 2 (blue) and 3 (black). Each order replaces every segment with a smaller copy of the U shape, and the path never jumps across the square. S2 numbers its cells in this order, so cells with nearby IDs are nearby on Earth.Image: Geoff Richards, public domain, via Wikimedia Commons

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.

A square grid with lines from the centre cell to its eight neighbours; the diagonal ones are longer and dashed
Squares: four edge neighbours, and four diagonal neighbours further away (dashed).Image: H3 project documentation, © Uber Technologies, Inc., Apache License 2.0
A hexagonal grid with lines from the centre cell to its six neighbours, all the same length
Hexagons: six neighbours, every one the same distance away.Image: H3 project documentation, © Uber Technologies, Inc., Apache License 2.0

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:

ResolutionAverage cell areaAverage edgeCells on Earth
04,357,449 km²1,281 km122
75.16 km²1.41 kmabout 99 million
80.74 km²0.53 kmabout 692 million
90.11 km²0.20 kmabout 4.8 billion
150.9 m²0.58 mabout 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.

A map of San Francisco with one large hexagon over the city centre and its six neighbouring hexagons shaded
One H3 cell over central San Francisco and its six neighbours, the result of gridDisk with k = 1. Each neighbour shares an edge with the centre cell, so a search or a sum over this ring treats every direction alike.Image: H3 project documentation, © Uber Technologies, Inc., Apache License 2.0. Map data © OpenStreetMap contributors

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.

Seven small hexagons over San Francisco Bay with a larger red hexagon outline around them that they don't fit exactly
Seven resolution-n+1 cells and their resolution-n parent (outlined). The children almost, but not exactly, fill the parent. That's the price of hexagons: containment across resolutions is approximate.Image: H3 project documentation, © Uber Technologies, Inc., Apache License 2.0. Map data © OpenStreetMap contributors

3.5Inside an H3 cell ID

zoomUberLocation indexH3 cell64-bit 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:

BitsFieldWhat it holds
1reservedalways 0
4mode1 means "this is a cell" (other modes encode edges and vertices)
3reserved
4resolution0 to 15
7base cellwhich of the 122 resolution-0 cells it descends from
4515 digits × 3 bitsone 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.

Decision

Which way of cutting the map into cells?

Geohash
Alternate halving of latitude and longitude, written as a string.
  • A plain string: works with any sorted index
  • Easy to implement
  • Neighbours across boundaries have unrelated prefixes
  • Cells shrink towards the poles
Quadtree / S2
Squares split four ways; S2 numbers them along a Hilbert curve.
  • Exact parent-child containment
  • Hilbert order keeps ID ranges compact
  • Two kinds of neighbour: edge and corner
chosen
H3 hexagons
Hexagons at 16 resolutions, each about a seventh of the one above.
  • 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.

Checkpoint 1: where the design stands
  • 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
Still broken: All of this sits on one machine, and 250,000 updates a second plus every rider's search is too much for it. If it dies, nobody gets a ride.
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.

Location updates and searches, routed by cell
SUPPLY INDEX, IN MEMORYRavi's phoneevery 4 sPriya's phoneLocation gatewaylat/lng → cellDispatchmatchingIndex node Acells 0–4,999Index node Bcells 5,000–9,999Index node Ccells 10,000+Ring membershipwho owns which cells
Step 1. Ravi's phone sends its position. The location gateway turns latitude and longitude into a cell ID and looks up which index node owns that cell.
1 / 5

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.

Insight
If every record gets resent every four seconds anyway, you don't need to back it up. A crashed node refills itself.
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.

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.

Output
# 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 s

A 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.

Decision

How do nodes agree on who owns which cells?

A central coordinator
ZooKeeper or a similar service holds the assignment; nodes watch it.
  • One source of truth
  • Easy to reason about
  • Another critical system to run
  • Every membership change goes through it
chosen
Gossip + consistent hashing (Ringpop)
Nodes gossip membership peer to peer and hash keys onto a ring.
  • 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.

Insight
Filter cheaply, then measure expensively. A straight-line cell search cuts millions of drivers to a few dozen, and only those few dozen get a real road ETA.

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.

Your turn: design it before reading on

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 matching versus matching a batch
python
Python
from itertools import permutations
 
# minutes for each driver to reach each rider
eta = {
    ("Ravi", "Priya"): 2, ("Ravi", "Sam"): 3,
    ("Meena", "Priya"): 4, ("Meena", "Sam"): 9,
}
riders, drivers = ["Priya", "Sam"], ["Ravi", "Meena"]
 
# Greedy: each rider, in order of request, takes the nearest free driver
free, greedy = set(drivers), {}
for r in riders:
    d = min(free, key=lambda d: eta[(d, r)])
    greedy[r] = d
    free.remove(d)
 
# Batched: try every assignment, keep the lowest total wait
best = min(permutations(drivers),
           key=lambda ds: sum(eta[(d, r)] for d, r in zip(ds, riders)))
batched = dict(zip(riders, best))
 
for name, plan in [("greedy", greedy), ("batched", batched)]:
    waits = {r: eta[(d, r)] for r, d in plan.items()}
    print(f"{name:8} {plan}  waits {waits}  total {sum(waits.values())} min")
output
C++
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 min

Pairing 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.

Decision

Should each request be matched the moment it arrives?

Greedy, immediately
Each request takes the best free driver as soon as 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
chosen
Batch for a few seconds
Collect the requests and free drivers in an area over a short window, then solve the assignment for all of them.
  • 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:

A driver's state through one trip
AvailableOffer pendingcountdownEn routeto pickupOn tripTrip completefare, paymentRavi
Step 1. Ravi is available: his position is in the supply index and he can be matched.
1 / 5

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.

Decision

For driver and trip state, favour availability or consistency?

Availability first (2014–2020)
Eventually consistent stores; resolve conflicts afterwards.
  • 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
chosen
Consistency first (2021 rebuild)
Transactions across shards; each state change happens exactly once.
  • 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.

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:

SQL
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 candidate

That'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.

ApproachStops the double offer?Cleans up after a crash?Where it fits
Read, then writeNoNoNowhere, honestly
Conditional UPDATEYesWith an expiry column + sweeperOne SQL database
Redis SET NX PXYes, mostlyYes, the key expiresFast claims, if a rare double offer is tolerable
Spanner / multi-shard transactionYesYesClaim 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.

Checkpoint 2: where the design stands
  • 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
Still broken: Matching runs on ETAs, and we haven't said where a fast, traffic-aware ETA comes from. Plain A* takes about 120 ms per query, and dispatch needs dozens per request.
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.

A street map of Midtown Manhattan showing its grid of avenues and streets
A real road network, Midtown Manhattan. Every intersection becomes a node, every block-long stretch of road an edge.Map: © OpenStreetMap contributors, CC BY 4.0, via Wikimedia Commons (cropped)
A graph of circles connected by lines labelled with numbers, with the shortest path between two highlighted circles drawn in red
The same idea as a graph: edge weights are travel times, and the ETA is the cheapest path (red) between two nodes.Image: Dimitris131, public domain, via Wikimedia Commons

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.

Decision

How should ETAs be computed?

Plain A* on live traffic
Search the graph for every query, with current edge weights.
  • Always uses the latest traffic
  • Nothing to precompute
  • About 120 ms per query: too slow at scale
Contraction hierarchies
Precompute shortcut edges over the whole graph; queries take milliseconds.
  • Very fast queries
  • About 12 hours to rebuild for the world
  • Live traffic is hard to apply
chosen
Partitioned graph, then ML correction
Precompute within small cells so pieces can be rebuilt quickly; correct the result with a learned model.
  • 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.

The surge pipeline
Rider + driver appsrequests, locationsEvent logKafkaStream jobper hexagon, per windowSurge valueshexagon → multiplierPricing servicePriya's phonefare estimate
Step 1. Every request, every driver location update and every trip state change is written to an event log.
1 / 4

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.

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.

KafkaRabbitMQSQSRedis Streams
Many independent readersYes, consumer groupsCopy per queueCopy per queue (SNS fan-out)Yes, consumer groups
Replay old eventsYes, until retentionNoNoOnly while it fits in memory
OrderingPer partitionPer queueFIFO queues only, lower throughputPer stream
ThroughputMillions/s per clusterTens of thousands/s per nodeManaged, scales, per-call costHigh, memory-bound
Good atEvent logs, pipelinesTask queues, routing rulesSimple managed work queuesSmall, 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.

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:

Output
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.0x

The 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.

There are four ways to get "Ravi is 2 minutes away" onto Sam's screen:

OptionHow it worksCostProblem
PollingPhone asks every few secondsA request per phone per interval, mostly "nothing new"80% of Uber's gateway traffic, at one point
Long pollingPhone asks, server holds the request open until there's newsOne open request per phone, re-opened after each answerFiddly with proxies and timeouts
Server-Sent EventsOne HTTP response that never ends; server writes events into itOne connection per phoneOne-way: the phone can't acknowledge on it
WebSocket / gRPC streamOne connection, both directionsOne connection per phone, plus your own heartbeatsStateful 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.

zoomUberTripsSchemaless(row, column, version) → JSON
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.

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:

SQL
CREATE TABLE trips (
  trip_id        BIGINT PRIMARY KEY,          -- time-ordered ID, e.g. Snowflake-style
  rider_id       BIGINT NOT NULL,
  driver_id      BIGINT,
  city_id        INT NOT NULL,
  status         TEXT NOT NULL,               -- requested / en_route / on_trip / completed / cancelled
  quote_id       UUID NOT NULL,               -- the fare Priya agreed to
  requested_at   TIMESTAMPTZ NOT NULL,
  pickup_h3      BIGINT, dropoff_h3 BIGINT,
  fare_paise     BIGINT,                      -- money as integers, never floats
  version        INT NOT NULL DEFAULT 1       -- for optimistic concurrency
);
 
-- "my trips" screen, newest first
CREATE INDEX trips_by_rider  ON trips (rider_id,  requested_at DESC);
-- the driver's earnings page
CREATE INDEX trips_by_driver ON trips (driver_id, requested_at DESC);
-- live operations only care about unfinished trips: a partial index stays small
CREATE INDEX trips_active    ON trips (city_id, status)
  WHERE status IN ('requested', 'en_route', 'on_trip');

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 keyFastSlow or awkward
trip_idWrites spread evenly; fetch by trip IDAnything by rider or driver needs a global index
rider_idRider history is one shardDriver earnings need a global index; a few heavy users make hot shards
city_idCity-wide operationsMumbai'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.

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)CassandraMySQL + SchemalessSpanner
Scales writes horizontallyNoYesYes, 4,096 shardsYes
Transactions across rows on different shardsn/aNo (lightweight transactions are per partition)NoYes
Secondary indexesLocal, richLimitedGlobal, asynchronousGlobal, consistent
What it cost UberWrite amplification, replicationWeak conditional updatesHand-built consistencyLatency, 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.

Checkpoint 3: where the design stands
  • 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
Still broken: Everything above assumes the data centre is up. What happens to Sam's trip, halfway to the airport, when it isn't?
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

Uber's ride flow, end to end
REAL-TIME, APPROXIMATEnearby?ETAscreate tripmultipliersPriya's phoneRavi's phoneGPS every 4 sAPI gateway+ push channelPricingsurge per hexagonDispatchbatch matchingLocation indexcells, in memoryETA serviceroad graph + DeepETATrip storetransactionalEvent streamKafka → Flink
Step 1. Ravi's phone sends its position every four seconds; the gateway routes it to the location index node that owns his cell.
1 / 6
ComponentWhat it doesAdded because
Location indexLatest position of every driver, by cell, in memoryA table scan can't find nearby drivers fast (§2, §3)
Cell system (S2, H3)Turns positions into cell IDs; neighbour searchesDensity varies; neighbours must be found cheaply (§3)
Consistent hashing + membershipSplits cells across nodes; survives node lossToo much traffic for one machine (§4)
DispatchCollects requests and drivers, solves the assignmentGreedy matching wastes everyone's time (§5)
ETA serviceShortest paths on the road graph, corrected by MLStraight-line distance misleads (§5, §6)
Surge pipelineSupply and demand per hexagon, as a streamPrices must react to local demand within seconds (§7)
Push channelOne long-lived connection per appPolling was 80% of API traffic (§8)
Trip storeDurable, transactional record of every tripA 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.

The engineering blueprint
API
Retries on bad networks mustn't book two cars; locations every 4 s can't pay a TLS handshake each
Driver locations
250k overwrites/s of data that heals itself in 4 s
Over: Postgres + PostGIS: right query, can't take the write rate
Spatial index
Equal-distance neighbours for area maths; 64-bit IDs
Over: B-tree on (lat, lng), geohash, S2
Driver claim
Two dispatchers must never offer one driver
Over: Read-then-write
Event log
Many consumers, own offsets, replay
Over: RabbitMQ, SQS: delete on ack, no replay
Stream processing
Fresh counts per hexagon; late beats never
Surge + quotes
Hot tiny reads; a dead pipeline fails to 1.0x
Push
Polling was 80% of gateway traffic; acks need a return path
Over: Polling, long polling
Trips
Durable, sharded, then cross-shard transactions
Over: Single Postgres, Cassandra
Trip indexes
Even writes, and history screens are still one lookup

10.2From top to bottom

LevelThe choiceData structure or algorithm
SystemSplit data by how wrong it can afford to beIn-memory index for locations, streams for surge, transactions for trips
Location indexBucket drivers by cellHash map from cell ID to the set of drivers in it
CellsHexagons for areas, squares where containment mattersH3 64-bit IDs (base cell + 15 three-bit digits); S2 Hilbert-ordered IDs
Neighbour searchWiden ring by ringgridDisk: 3k² + 3k + 1 cells within k steps
ShardingCells to nodesConsistent hash ring in a red-black tree; SWIM gossip
MatchingBatch for a few secondsBipartite assignment (Hungarian algorithm, min-cost flow)
ETARoad graph plus correctionWeighted directed graph; A*, partitioned precomputation; residual neural network
SurgePer hexagon, per windowWindowed counts in a stream processor; hexagon → multiplier map
TripsOne state change at a timeHierarchical state machines; append-only versioned cells; Spanner transactions

11What goes wrong, and what it cost

11.1Failures this design has to survive

What happensWhat the user seesWhat the design does
A location index node crashesNothing, or a car briefly missing from the mapIts cells move to other nodes; drivers' next updates refill them within seconds
GPS is wrong between tall buildingsThe car jumps across the mapPositions are snapped to roads and smoothed over successive updates
Two dispatchers pick the same driverThe driver gets two offersDriver state changes atomically, so the second assignment fails
A driver ignores the offerThe rider waits longerThe offer times out and the rider joins the next batch
A sudden crowd in one hexagonLong waits, no carsSurge raises prices there and draws drivers in
A data centre fails mid-tripA brief stallThe city fails over; in-progress trips are rebuilt from state the phones carry

11.2The tradeoffs, in one table

DecisionChosenGiven upWhy it was worth it
Where locations liveMemory, sharded by cellDurabilityThey're overwritten every 4 s and heal themselves
How to cut spaceHexagons (H3) for areasExact parent-child containmentEqual neighbours make area statistics fair and smooth
Who owns which cellsConsistent hashing + gossip (2015)Exact agreement at every instantNo central coordinator; only a dead node's cells move
MatchingBatch for a few secondsThe fastest possible answer for each riderLower total waiting for everyone
ClosenessRoad-network ETACheap straight-line distanceRivers, bridges and traffic decide real wait times
Surge dataFreshness over consistencyExact countsA slightly wrong price now beats a perfect price late
Trip stateConsistency over availability (2021)Some write latencyA driver can't be in two trips; trips are never lost

12Summary

  1. 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.
  2. 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.
  3. Cut the map into cells and keep drivers in per-cell lists, so a search looks at a few cells, not everyone.
  4. Geohash, quadtrees, S2 and H3 are four ways to cut it: prefix strings, density-adaptive squares, Hilbert-ordered squares, and hexagons with equidistant neighbours.
  5. 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.
  6. The location index lives in memory, sharded by cell, and heals itself after a crash because drivers resend their positions.
  7. Match on road-based ETA, not straight-line distance, using the cheap cell search to narrow millions of drivers to a few dozen candidates.
  8. Batch requests for a few seconds and solve the assignment problem, so everyone waits less in total.
  9. ETAs come from a road graph plus a learned correction: fast precomputed routing, with a model that predicts how wrong it will be.
  10. Surge is computed per hexagon from streams of events, favouring freshness over exactness.
  11. 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 h3 Python 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_disk with 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

check yourself
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.

H3: Uber's Hexagonal Hierarchical Spatial Index (Uber blog, 2018)

Why hexagons, how the hierarchy works, and how surge uses them. The h3geo.org documentation has the resolution table and the bit layout.

'ETA Phone Home' (Uber blog, 2015) and DeepETA (2022)

How Uber's routing engine models the road graph, why contraction hierarchies didn't fit live traffic, and the residual model on top.

Ringpop (Uber blog, 2016)

Consistent hashing plus SWIM gossip for application-level sharding, with the driver-location service as the motivating example.

Uber's Fulfillment Platform rearchitecture (Uber blog, 2021)

Why the trip platform moved from availability-first to Spanner transactions, and how state machines model trips.

Real-time Data Infrastructure at Uber (SIGMOD 2021)

Kafka, Flink and the surge pipeline, including which properties it trades away and why.

Matt Ranney, 'Scaling Uber's Real-time Market Platform' (QCon 2015)

The dispatch system as it was in 2015: supply and demand services, S2 cells, Ringpop, and failover with state kept on drivers' phones.

Designing WhatsApp

The same push-over-polling decision, and a contrasting system built around delivering messages. Chapter 49.

Partitioning

Consistent hashing and how keys move when nodes join and leave. Chapter 29.

Failure Detection

SWIM, suspicion and gossip, the membership half of Ringpop. Chapter 30.

Transactions & Isolation

What it takes to make "one driver, one trip" hold under concurrency. Chapter 19.

Kafka & Logs

The event log under the surge pipeline. Chapter 23.