System Design

Core Concepts

Geospatial Indexing

A spatial index never tells you what is near you. It tells you which few cells could hold something near you, and you check the exact distances yourself. Geohash, S2, H3, PostGIS and Redis all make that same move with a different cell.

Why you are doing this at all

"Find the drivers within 1 km of me" looks like an ordinary query. Every driver has a latitude and a longitude, so you index both columns and ask for a small box around the rider:

CREATE INDEX drivers_lat_lng ON drivers (lat, lng);

SELECT id, lat, lng
FROM drivers
WHERE lat BETWEEN 40.749 AND 40.767
  AND lng BETWEEN -73.997 AND -73.974;

The box is about 2 km on each side, centred on Times Square. The query returns the right rows. The problem is how many index entries it reads to find them.

A B-tree on (lat, lng) is sorted by latitude first. Longitude only sorts entries that have exactly the same latitude, and with coordinates stored to six decimal places, almost no two entries do. So the index seeks to latitude 40.749 and reads every entry up to 40.767. That's every driver in a band 2 km tall, running east and west across all of your data. It checks the longitude of each one and throws most of them away. This is the rule from indexing and query performance: the first range in a composite index ends the useful part of it, and here both columns are ranges.

What a B-tree on (lat, lng) reads
The rider wants the green box, 2 km on each side. The index is sorted by latitude, so it reads every driver in the red band, the full width of the city, and checks each one's longitude. Only the drivers inside the box are kept.The rider wants the green box, 2 km on each side. The index is sorted by latitude, so it reads every driver in the red band, the full width of the city, and checks each one's longitude. Only the drivers inside the box are kept.
The index reads a band as wide as the data to fill a small box. The rider wants the green box, 2 km on each side. The index is sorted by latitude, so it reads every driver in the red band, the full width of the city, and checks each one's longitude. Only the drivers inside the box are kept.
Back of envelopeWhat the band costs
The question is how many index entries the query reads
for each row it returns. Assume the drivers are spread
evenly over the area the table covers.

One city, 40 km across, 50,000 drivers
  density        50,000 / 1,600 km²              ≈ 31 per km²
  box            2 x 2 km                        = 4 km²
  rows returned  31 x 4                          ≈ 125
  band           2 km tall x 40 km wide          = 80 km²
  entries read   31 x 80                         ≈ 2,500

The band and the box are both 2 km tall, so the ratio is
the width of the data over the width of the box:

  one city, 40 km wide         40 / 2            = 20x
  a country, 4,000 km wide     4,000 / 2         = 2,000x

  ─────────────────────────────────────────────────────
The index gets worse as the business grows, with no
change to the query. Two single-column indexes are worse
still: the database reads the latitude band and the
longitude band, then intersects them.

No B-tree setting fixes this, because a sorted index narrows one dimension at a time, and "near" is a statement about two at once. So every spatial index changes the question.

A spatial index never answers "what is near me". It answers "which few cells could hold something near me", and you check the exact distances yourself.

A cell is a small area of the map with an ID. Finding the cells around a point is cheap, often plain arithmetic on the coordinates. Reading the points stored under those cells gives you a short list of candidates. Computing the distance to each candidate gives you the answer. The index's whole job is to keep the candidate list short.

Find the cells, then check the distances
The rider, in blue, stands in the centre cell. The index reads the nine purple cells around them, which hold 23 drivers. Measuring each one keeps the 7 inside the 1 km circle, in green, and drops the 16 in the corners and edges of the cells, in grey.The rider, in blue, stands in the centre cell. The index reads the nine purple cells around them, which hold 23 drivers. Measuring each one keeps the 7 inside the 1 km circle, in green, and drops the 16 in the corners and edges of the cells, in grey.
The cells narrow the search, and the distance check decides. The rider, in blue, stands in the centre cell. The index reads the nine purple cells around them, which hold 23 drivers. Measuring each one keeps the 7 inside the 1 km circle, in green, and drops the 16 in the corners and edges of the cells, in grey.

Every scheme on this page makes that move with a different cell. Geohash, S2 and H3 cut the map into fixed cells with numbered IDs. Quadtrees and R-trees draw their cells around the data. Redis and PostGIS are products built on two of these ideas.

Two decisions matter more than the scheme: how big the cells are, and where the index lives.

Points that stay put, and points that move

A restaurant almost never changes position. A table of restaurants takes a few writes a day. Its index can be any structure in any database, and it can be rebuilt overnight.

A driver is the opposite. Uber described its dispatch system in a 2015 talk. As HighScalability summarised it, drivers sent their position every 4 seconds, and the location index aimed for 1 million writes a second. Each new position replaces the one before it. At 500,000 drivers online, one position every 4 seconds is 125,000 writes a second.

So the first question about any location feature is whether the points move. Points that stay put go in the database you already run, usually Postgres with the PostGIS extension. Points that move go in memory, in a fixed grid.

When to skip this

If you have fewer than about 10,000 points and they don't move, you may not need a spatial index at all. A distance check is a few dozen arithmetic operations, well under a microsecond. Checking all 10,000 takes a few milliseconds, so load them into memory and scan.

The toolkit

Cells, and the curve that numbers them

A grid index computes a point's cell from its coordinates, then reads the points stored under that cell and the cells around it. The useful part is the numbering. Cells that are close on the map should get IDs that are close in order. Then "the cells around this point" becomes a few short ranges of IDs, and any sorted index can read a range: a B-tree, a Redis sorted set, a Bigtable row key. A path that visits every cell of a grid once, numbering the cells in the order it visits them, is called a space-filling curve. The curve decides how often close on the map also means close in the numbering.

Geohash

Geohash builds a cell ID by halving the world again and again. The first bit says whether the point is in the east or west half of the longitude range. The second bit says whether it's in the north or south half of the latitude range. The third bit halves the remaining longitude range, the fourth halves the remaining latitude range, and so on, alternating. Every 5 bits become one character, from an alphabet of 32.

How geohash builds a cell ID
For New York, bit 1 picks the west half of the world, bit 2 the north half of what is left, and so on, so each bit halves the purple area. Five bits make the first character, d. Inside every cell, the four smaller cells are numbered in the same zigzag.For New York, bit 1 picks the west half of the world, bit 2 the north half of what is left, and so on, so each bit halves the purple area. Five bits make the first character, d. Inside every cell, the four smaller cells are numbered in the same zigzag.
Each bit halves the cell, alternating between longitude and latitude. For New York, bit 1 picks the west half of the world, bit 2 the north half of what is left, and so on, so each bit halves the purple area. Five bits make the first character, d. Inside every cell, the four smaller cells are numbered in the same zigzag.

Each character narrows the cell. Times Square is dr5ru7v2. Every point whose geohash starts with dr5ru sits in one cell about 4.9 km tall, and every point that starts with dr5ru7 sits in a smaller cell inside it. A shared prefix means a shared cell. So "every point in this cell" is a prefix query, WHERE geohash LIKE 'dr5ru7%', and a B-tree serves it as one range scan.

Inside every cell, the numbering visits the four smaller cells in the same zigzag: south-west, north-west, south-east, north-east. This zigzag path is called the Z-order curve.

geohash lengthcell at the equator
439.1 km x 19.5 km
54.9 km x 4.9 km
61.2 km x 609 m
7153 m x 152 m
838.2 m x 19 m

These sizes hold only at the equator. A cell keeps the same size in degrees everywhere, but a degree of longitude shrinks as you go north. In New York, dr5ru7 is 0.61 km tall and only 0.93 km wide.

The edge problem, and the neighbour rule

A shared prefix proves that two points share a cell. A different prefix proves nothing about distance. Take two points 31 m apart, one just north-east and one just south-west of where the equator crosses the prime meridian. Their geohashes are s0000000 and 7zzzzzzz. They share no prefix at all, because the very first bit, east or west, already split them. The same thing happens at every cell edge on a smaller scale. A driver 20 m away across the edge of your cell has a different prefix, and a prefix query on your cell never sees them.

Close on the map, far apart in the numbering
Four cells meet where the equator crosses the prime meridian. The two points are 31 m apart, but the first bit already sent them to different halves of the world, so their geohashes, s0000000 and 7zzzzzzz, share nothing. A search of the rider's own cell, in purple, misses the driver next door, in red.Four cells meet where the equator crosses the prime meridian. The two points are 31 m apart, but the first bit already sent them to different halves of the world, so their geohashes, s0000000 and 7zzzzzzz, share nothing. A search of the rider's own cell, in purple, misses the driver next door, in red.
Two points 31 m apart can share no prefix at all. Four cells meet where the equator crosses the prime meridian. The two points are 31 m apart, but the first bit already sent them to different halves of the world, so their geohashes, s0000000 and 7zzzzzzz, share nothing. A search of the rider's own cell, in purple, misses the driver next door, in red.

The fix is the neighbour rule: read the point's own cell and the 8 cells around it. If each cell is at least as wide and as tall as the search radius, those nine cells always contain the whole circle. That holds wherever the point sits inside its own cell.

The nine cells hold more than the circle, so what they return is a list of candidates. The last step computes the exact distance to each candidate and drops the ones outside the radius.

Picking the cell size

The cell size sets a trade between two costs. Bigger cells mean fewer cells to read, and more candidates that turn out to be too far away. Smaller cells mean fewer wasted candidates and more cells to read. Once a cell is narrower than the radius, nine cells no longer cover the circle, and you need a 5 by 5 or larger block.

The same circle under three cell sizes
The blue circle has a 1 km radius in every panel. With 2 km cells, nine cells cover four times the area that 1 km cells do. With 250 m cells, the area read shrinks only from 9 to 5.1 km², and the block grows to 81 cells.The blue circle has a 1 km radius in every panel. With 2 km cells, nine cells cover four times the area that 1 km cells do. With 250 m cells, the area read shrinks only from 9 to 5.1 km², and the block grows to 81 cells.
Cells as wide as the radius read the fewest cells for the least waste. The blue circle has a 1 km radius in every panel. With 2 km cells, nine cells cover four times the area that 1 km cells do. With 250 m cells, the area read shrinks only from 9 to 5.1 km², and the block grows to 81 cells.
Back of envelopeCells read against candidates checked
The search radius is 1 km, and the density is an assumed
100 drivers per km². The circle itself is π x 1² = 3.14 km²,
so about 314 drivers are inside it. Each row reads the
smallest square block of cells that always covers it.

  cell edge  block  cells  area read            candidates  inside
  2 km       3 x 3     9   9 x 4       =  36 km²     3,600      9%
  1 km       3 x 3     9   9 x 1       =   9 km²       900     35%
  500 m      5 x 5    25   25 x 0.25   = 6.3 km²       625     50%
  250 m      9 x 9    81   81 x 0.0625 = 5.1 km²       506     62%

  ───────────────────────────────────────────────────────────
Going from 2 km cells to 1 km cuts the candidates 4
times, with no extra cells read. Past 1 km, each halving
of the edge cuts the candidates by a third or less and
roughly triples the cells read.

Set the cell edge to about the search radius.

Uber and Lyft both describe this trade in terms of shards. HighScalability's summary of Uber's 2015 talk says smaller cells mean more fan-out: more cells, and so more shards, for each query to read. Lyft's 2017 slides describe choosing the geohash length as balancing scattered gets, reads spread over many shards, against hot shards.

Each geohash character divides the cell area by 32, which makes this choice coarse. For a 1 km radius in New York, a 6-character cell is 0.93 km by 0.61 km, smaller than the radius both ways, so you need a 5 by 5 block of 25 cells. A 5-character cell is 3.7 km by 4.9 km, so nine of them cover the circle but read 163 km² to search a circle of 3 km². There's no size in between.

Redis gets finer steps by working on the bits rather than the characters. It computes the range of IDs to read by dropping low bits from the 52-bit geohash it stores. S2 divides the cell area by 4 per level and H3 by 7 per resolution, so both get closer to the radius you want.

Quadtrees

A fixed grid uses one cell size everywhere, and the points in a city are never spread evenly. A quadtree lets the data choose. It starts with one cell covering the whole map. When a cell holds more than a set number of points, say 100, it splits into four equal quarters, and its points move into them. That repeats. Downtown, where points are dense, cells split many times and end up small. In the suburbs they barely split, and one cell covers many square kilometres. Every leaf holds at most 100 points, so a search reads about the same number of candidates wherever it lands.

A quadtree over one city
Every cell that holds more than 4 points splits into four. Downtown, at the top right, the cells split three or four times and end up small. The bottom-left quarter holds 3 points, so it never splits. The two purple cells, one small and one large, hold about the same number of points.Every cell that holds more than 4 points splits into four. Downtown, at the top right, the cells split three or four times and end up small. The bottom-left quarter holds 3 points, so it never splits. The two purple cells, one small and one large, hold about the same number of points.
Cells split where the points are dense, so every cell holds about the same number. Every cell that holds more than 4 points splits into four. Downtown, at the top right, the cells split three or four times and end up small. The bottom-left quarter holds 3 points, so it never splits. The two purple cells, one small and one large, hold about the same number of points.

A search walks down the tree to the leaf that holds the point, then reads that leaf and the leaves around it. Finding the neighbours is harder than on a grid. A neighbouring leaf can sit at a different depth, so you walk the tree instead of doing arithmetic on an ID.

Quadtrees suit points that stay put. When a point moves, it leaves one leaf and joins another. A leaf that fills up splits, and one that empties can merge with its siblings, so with moving points the tree changes shape all the time.

A quadtree also lives in one process's memory. To spread it across machines you cut it into subtrees by area, and that's a fixed grid again, at the top level. Geohash is a quadtree that never adapts: each pair of bits is one level of a tree that splits every cell into four, everywhere.

S2 cells

S2 is a library for geometry on a sphere. It projects the Earth onto the six faces of a cube. It splits each face into four cells, each of those into four, and so on down to level 30, where a cell is about 1 cm across. Every cell has a 64-bit ID.

S2 differs from geohash in two ways that matter for search.

The first is the curve. S2 numbers cells along a Hilbert curve instead of a Z-order curve. A Hilbert curve never jumps: each step moves to a cell that shares an edge with the one before. So two cells with close IDs are always close on the map. The reverse doesn't hold: two cells side by side can still sit far apart on the curve, so the neighbour rule still applies.

Two ways to number the same 16 cells
The Z-order curve that geohash follows, on the left, often jumps between cells that do not touch, the red dashed steps. The Hilbert curve that S2 follows, on the right, never does. Both still give some touching cells distant numbers, so neither curve removes the neighbour rule.The Z-order curve that geohash follows, on the left, often jumps between cells that do not touch, the red dashed steps. The Hilbert curve that S2 follows, on the right, never does. Both still give some touching cells distant numbers, so neither curve removes the neighbour rule.
The Hilbert curve never jumps, and the Z-order curve does. The Z-order curve that geohash follows, on the left, often jumps between cells that do not touch, the red dashed steps. The Hilbert curve that S2 follows, on the right, never does. Both still give some touching cells distant numbers, so neither curve removes the neighbour rule.

The second is shapes. S2's region coverer takes any shape, such as a circle around the rider, and returns a small set of cells at mixed levels that covers it, at most 8 by default. All the cells inside one cell form a single unbroken range of IDs, so a covering of 8 cells becomes at most 8 range scans.

The cost is that cell areas vary across the cube. At level 12 a cell covers anywhere from 3.04 to 6.38 km², about a factor of 2, depending on where it sits on its face. Uber's 2015 dispatch system used level 12 cells and sharded its index of drivers by cell ID.

H3 hexagons

H3 is Uber's grid, published in 2018, and its cells are hexagons. It projects the Earth onto an icosahedron, a solid with 20 triangular faces. Each resolution divides every hexagon into seven smaller cells, each about a seventh of the area, across 16 resolutions numbered 0 to 15.

Hexagons alone cannot cover a sphere, so every resolution also has exactly 12 pentagons, one at each corner of the icosahedron. A pentagon has 5 neighbours instead of 6.

The reason for hexagons is the distance to the neighbours. A square has 8 neighbours at two distances. The 4 that share an edge are one cell width away, and the 4 that share only a corner are about 1.4 widths away. A hexagon has 6 neighbours, all at the same distance. So a ring of hexagons around a cell is close to a circle, and "everything within two rings" means about the same distance in every direction.

The cost is containment. Seven hexagons don't exactly fill a larger hexagon, so a child cell is only approximately inside its parent. If you truncate a point's H3 index to a coarser resolution, the parent you get may not contain the point. In S2, truncating to the parent is exact. So H3 suits adding things up per area, such as the supply and demand per hexagon that Uber measures to set surge prices. S2 suits exact containment and range scans over cell IDs.

R-trees and PostGIS

Grids cut up space without looking at the data. An R-tree works the other way: it groups the data and draws a box around each group. Each leaf holds a handful of shapes and their bounding box, the smallest rectangle that encloses them. Each level up holds the bounding boxes of the level below. Boxes may overlap, and dense areas get many small boxes, so like a quadtree it adapts to density.

An R-tree's boxes
Each purple box is the bounding box of a few shapes, and each grey dashed box holds a few purple ones. A search for the blue point opens only the boxes that contain it (1, 2). Then it runs the exact test on the shapes in box 2 (3). The red shape's box holds the point but the shape does not, and the green shape does.Each purple box is the bounding box of a few shapes, and each grey dashed box holds a few purple ones. A search for the blue point opens only the boxes that contain it (1, 2). Then it runs the exact test on the shapes in box 2 (3). The red shape's box holds the point but the shape does not, and the green shape does.
The boxes come from the data, so they are small where the data is dense. Each purple box is the bounding box of a few shapes, and each grey dashed box holds a few purple ones. A search for the blue point opens only the boxes that contain it (1, 2). Then it runs the exact test on the shapes in box 2 (3). The red shape's box holds the point but the shape does not, and the green shape does.

PostGIS, the geospatial extension for Postgres, builds its spatial index as an R-tree on GiST, Postgres's general framework for search trees: CREATE INDEX ... USING GIST (location). The index stores bounding boxes, not the shapes themselves, so every query runs in two steps. First the index finds the shapes whose boxes match. Then an exact test runs on those shapes only.

Two queries do most of the work.

-- every restaurant within 1 km
SELECT id FROM restaurants
WHERE ST_DWithin(location, 'POINT(-73.9855 40.7580)'::geography, 1000);

-- the 10 nearest, with no radius at all
SELECT id FROM restaurants
ORDER BY location <-> 'POINT(-73.9855 40.7580)'::geography
LIMIT 10;

location is a geography column, so distances are in metres along the Earth's surface rather than in degrees. ST_DWithin includes a bounding-box test that uses the index, then checks the exact distance. The <-> operator uses the index only inside ORDER BY, and that's how PostGIS answers "the 10 nearest" without you picking a radius.

The cost is writes. Postgres doesn't change a row in place. An UPDATE writes a new row version and a new index entry, and vacuum removes the old versions later. Each insert into the R-tree can also enlarge boxes or split nodes on the way up. That's nothing at restaurant rates. At 125,000 position updates a second it means index bloat and constant vacuum work.

R-trees also index shapes, which a grid of points can't do directly. A delivery zone is a polygon. An R-tree stores its bounding box and answers "which zones contain this address" with the same two steps.

Redis GEO

Redis has a set of geospatial commands, which its documentation calls GEO, built on a sorted set. GEOADD interleaves the latitude and longitude bits into a 52-bit geohash integer and stores it as the member's score. GEOSEARCH with BYRADIUS or BYBOX reads the score ranges for the centre area and its 8 neighbours, computes each member's distance, and drops what falls outside.

GEOADD drivers:nyc -73.9855 40.7580 driver:8812
GEOSEARCH drivers:nyc FROMLONLAT -73.9850 40.7590 BYRADIUS 1 km ASC COUNT 10 WITHDIST

Distances use the Haversine formula, which treats the Earth as a sphere. There's no command to delete a location. You remove a member with ZREM, because the index is just a sorted set.

That last fact matters for moving points. A member of a sorted set has no expiry of its own, so a driver who closes the app stays at their last position until something removes them. And a key lives on one shard, so a whole city in one key is one shard's capacity. Lyft's 2017 slides on their location index give both as the reason they didn't use the GEO commands: great for prototyping, no expiration or sharding.

Choosing among them

indexcellsadapts to densityindexes shapesmoving a point costswhere you meet it
geohashrectangles, area divided by 32 per characternono, points onlychanging one keya string column in any database, Lyft's 2017 index
quadtreesquares that split when fullyespointsa remove, an insert, and sometimes a splitin-memory indexes over points that stay put
S2squares on a cube, area divided by 4 per levelno, but covers a shape with mixed levelsyes, through coveringschanging one keyUber's 2015 dispatch system
H3hexagons, area divided by 7 per resolutionnoyes, through coveringschanging one keyUber's surge pricing
R-treebounding boxes drawn from the datayesyesa new row version and index entry, cleaned up later by vacuumPostGIS on Postgres
Redis GEOa 52-bit geohash in a sorted setnono, circles and boxes as queries onlyone GEOADDprototypes and small fleets

The method

Six steps, the same for any nearby query.

1. Ask whether the points move. If they stay put, use the database you have, with PostGIS. If they move, plan an in-memory grid.

2. Get the radius and the result count. "Everything within 1 km" and "the 10 nearest" are different queries. The second has no radius, so it needs either a search that widens until it has 10, or a nearest-neighbour index.

3. Estimate the density at both ends. Write down the points per km² in the densest area you serve and in the emptiest. The cell size has to work for both.

4. Set the cell edge to about the radius, and price one query. Candidates per query are density x 9 x edge². Check that number at the dense end.

5. Shard by cell, never by city, and plan for the busiest area. Decide how the same cells, read by many users at once, get served without reading them again for every request.

6. Filter, then check. Compute the exact distance to every candidate, sort, and keep the first K, where K is the result count from step 2. If fewer than K are inside the radius the block fully covers, add a ring of cells and repeat. Then say how a point that left, such as a driver who went offline, leaves the index, and how long that takes.

Worked examples, start to finish

Four systems follow. In each one, the obvious index fails in a different way.

Nearby restaurants, where one cell size is wrong at both ends of a city

A listings app shows the 20 restaurants nearest the user. Restaurants don't move, so anything works on the write side. The obvious design is a fixed grid of 1 km cells, a 3 by 3 read, and a sort by distance.

Back of envelopeOne cell size, three neighbourhoods
Nine 1 km cells are read per query, which is 9 km². The
densities are assumed, to show the spread inside one city.

  downtown        300 per km²   x 9 km²   = 2,700 candidates
  inner suburb      4 per km²   x 9 km²   =    36 candidates
  edge of town    0.2 per km²   x 9 km²   ≈     2 candidates

How big a circle holds 20 restaurants?
  downtown       20 / 300   = 0.067 km²   radius ≈ 146 m
  edge of town   20 / 0.2   = 100 km²     radius ≈ 5.6 km

  ─────────────────────────────────────────────────────
Downtown reads 135 candidates for every result it shows.
The edge of town can't fill the page at all. The right
radius differs about 39 times between the two, so no
single cell size serves both.

The fix is to let the data decide how far the search goes, and there are two ways to do it.

For points that stay put, ask for the nearest K. PostGIS's ORDER BY location <-> point LIMIT 20 walks the R-tree outward from the point and stops when it has 20. The R-tree's boxes are already small downtown and large at the edge of town, so the work stays about the same in both places. A quadtree with a leaf limit gives you the same property inside your own process.

On a fixed grid, widen in rings. Read the 3 by 3 block. If it doesn't give you 20 results, read the next ring out to make a 5 by 5 block, then 7 by 7, up to a maximum radius you choose. A block only holds every point out to the distance of its nearest edge, which is at least one cell width for a 3 by 3 block and two for a 5 by 5. A candidate in the block's far corner can be farther away than an unread point just past the edge. So you stop only when your 20th result is closer than that guaranteed distance.

Widening the search in rings
In a sparse area, the 3 by 3 block (1) holds 2 restaurants, the 5 by 5 block (2) holds 9, and the 7 by 7 block (3) holds 23. The dashed blue circle is the distance the 7 by 7 block guarantees. The 20 nearest are all inside it, in green, so the search stops, and the 3 in the corners, in grey, are dropped.In a sparse area, the 3 by 3 block (1) holds 2 restaurants, the 5 by 5 block (2) holds 9, and the 7 by 7 block (3) holds 23. The dashed blue circle is the distance the 7 by 7 block guarantees. The 20 nearest are all inside it, in green, so the search stops, and the 3 in the corners, in grey, are dropped.
Stop when the 20th result is inside the distance the rings guarantee. In a sparse area, the 3 by 3 block (1) holds 2 restaurants, the 5 by 5 block (2) holds 9, and the 7 by 7 block (3) holds 23. The dashed blue circle is the distance the 7 by 7 block guarantees. The 20 nearest are all inside it, in green, so the search stops, and the 3 in the corners, in grey, are dropped.

Decision: PostGIS with a nearest-K query for the restaurant listing, because the points stay put and the database already holds them. Ring expansion is for a grid of moving points, where an R-tree is the wrong structure.

Live drivers, where the database can't take the writes

A ride-hailing app shows riders the cars around them, and dispatch needs the drivers near each pickup. Say 500,000 drivers are online at peak, and each driver's app sends its position every 4 seconds. Each of those messages is called a ping.

Back of envelopeWhere 125,000 positions a second can go
The question is which kind of data store can take the
position writes, and whether the writes need to last.

  writes        500,000 drivers / 4 s           = 125,000/s

Per-node write rates, the working figures from
choosing a database:
  relational    5k to 20k/s per node
                125,000 / 20,000 to 125,000 / 5,000
                                                = 7 to 25 nodes
  in-memory     100k to 1M/s per node
                125,000 / 1M to 125,000 / 100,000
                                                = 1 to 2 nodes

  one position is read until the next ping      = 4 s

  ─────────────────────────────────────────────────────
Throughput says memory. The 4 second life says the writes
need no durability: a lost position is replaced by the
next ping within 4 seconds.

Storing the position is the easy part. The index is harder: a rider's query must see each driver within a few seconds of their last ping, and every ping can move a driver. So where do 125,000 position updates a second go, and what exactly does the index hold?

Naive

One drivers table in Postgres, with a PostGIS index

This is tempting. It's the design from the toolkit, the query is two lines, and the driver's profile already lives in Postgres. It breaks on the write rate. 125,000 updates a second is 7 to 25 Postgres nodes' worth of writes, so you'd shard a relational database. Each update also writes a log record, and vacuum has to clean up the old row versions at the same rate.

Postgres stays in the design for the things that do need to last: the driver's account, and every trip.

Senior

Redis GEO, one key per city

Each ping is one GEOADD drivers:nyc <lng> <lat> driver:8812, which replaces the driver's old score. A rider's query is one GEOSEARCH with BYRADIUS. Writes stay in memory, and Redis applies the neighbour rule and the distance check for you. At a few thousand drivers per city this is the right answer, and it's the standard first one.

The costs are the two facts from the toolkit. A driver who goes offline is never removed, so you need a job that finds departed drivers and removes them. And each city is one key on one shard, so the largest city's writes and reads all land on one Redis node, and you can't split a key.

Staff

Index the cell, not the position

Question what the index holds. By the thesis, the index only has to answer which cells could hold a nearby driver, so it needs each driver's cell. The exact position is for the distance check, and that can live somewhere else.

So split the two. Each driver gets one key, driver:8812, holding their position and their current cell, with a 30 second expiry that every ping resets. Each cell gets one set of driver IDs, cell:{cellId}, and the cell sets are spread across shards by a hash of the cell ID.

A ping always rewrites the driver key, through a small script that also returns the old cell. It touches a cell set only when the cell has changed: one SREM from the old cell and one SADD to the new one.

At 30 km/h a car covers 33 m between pings. It crosses a 1 km cell about once every 2 minutes, which is once in 30 pings, and a parked car never does. So there are about 4,200 cell changes a second, against 125,000 pings.

Expiry now comes from the driver key. A driver who goes offline stops resetting it, and it disappears after 30 seconds. The reader fetches every candidate's driver key for the distance check anyway, so it skips the missing ones.

Lyft described a close relative of this in 2017. It kept one key per driver as the source of truth, and one sorted set per geohash. Each set scored a driver by the time they were last seen, and dropped anyone not seen for 30 seconds. Because the score is the last-seen time, every ping rewrites the cell entry. Moving the expiry onto the driver key lets the cell sets change only when a driver crosses a cell edge.

What you give up. A rider's query reads up to nine cell sets, then about 900 driver keys. The driver keys are spread by a hash of the driver ID, so those 900 reads land on nearly every shard: the scattered gets from Lyft's slides.

Departed drivers stay in the cell sets until a sweep removes them, so readers fetch and skip some dead entries, and you own the sweep. Every ping also reads the old cell before it writes.

If an SADD to the new cell fails, the driver is invisible in that cell until their next crossing. So the service re-adds each driver to their current cell once a minute, which costs 500,000 / 60, about 8,300 writes a second. With two writes per cell change, cell-set writes total about 16,700 a second, about a seventh of the 125,000 that one write per ping would cost.

The re-add is also how a lost shard recovers. Its driver keys refill from the next round of pings within 4 seconds, but its cell sets refill only through the re-add, within a minute.

A crowded downtown, where every rider asks the same question

Take the cell-sharded index from the last example. On a Friday night, say 30,000 riders have the app open in 12 one-kilometre cells downtown, and each app refreshes the cars around it every 5 seconds.

Back of envelopeWhat 6,000 queries a second read
Each query reads the 9 cells around its rider, then each
candidate's driver key. At 100 drivers per km² and 1 km
cells, nine cells hold about 900 candidates. The riders
stand in a 3 by 4 patch of 12 cells, and the 3 by 3
blocks around those cover a 5 by 6 patch, 30 cells.

  queries           30,000 riders / 5 s           = 6,000/s

  cell-set reads    6,000 x 9                     = 54,000/s
  busiest cell set  in the blocks of up to 9 of
                    the 12 rider cells,
                    9 x 6,000 / 12                = 4,500/s

  driver-key reads  6,000 x 900                   = 5.4M/s
  distinct keys     30 cells x 100 drivers        = 3,000
  reads per key     5.4M / 3,000                  = 1,800/s

  total             54,000 + 5.4M                 ≈ 5.45M/s
  at 100k to 1M simple reads per node             = 6 to 55 nodes

  ─────────────────────────────────────────────────────
No key is hot. The busiest cell set takes 4,500 reads a
second, which one node handles easily. The cost is
volume, and nearly all of it is the same 3,000 driver
keys, each read 1,800 times a second.

Nothing here needs splitting. The problem is repeated work: riders a few hundred metres apart get almost the same answer, and every request builds it from scratch. So how do you serve 6,000 queries a second without reading the same 3,000 keys over and over?

Naive

Add nodes

It's the usual answer to read load, and here it works. The driver keys are spread across the whole cluster by a hash of the driver ID, so each new node takes its share. But it buys 6 to 55 nodes to read the same 3,000 keys again and again, and the count grows with the riders: if the riders downtown double, so do the reads.

Senior

Cache the reads in each service instance

Each service instance keeps the cell sets and driver keys it has read in its own memory for 1 second. Say there are 20 instances. Each one reads each of the 30 cell sets and 3,000 driver keys at most once a second, so the index serves at most 20 x 3,030, about 61,000 reads a second instead of 5.45 million. This is the local tier from caching strategies and invalidation, and it's the standard answer.

The cost is that every request still runs the whole filter: nine cell lookups and 900 position lookups, now in local memory. Every instance also holds its own copy of the same 3,000 positions, up to 1 second old.

Staff

Answer each cell once, not each rider

Question the premise that each rider's request is its own query. The filter step depends only on the rider's cell. Only the distance check depends on their exact point. So every rider standing in one cell reads the same 9 cell sets and the same 900 driver keys.

So route each request to a service instance by the rider's cell ID, and let that instance own the cell's candidate list. Once a second it reads the 3 by 3 block, fetches the positions and keeps the result for 1 second. Each rider's request then sorts that list by its own distance, in memory. Requests that arrive while a list is being built wait for that build rather than starting their own. This is called request coalescing.

One candidate list per cell
On the left, every rider's request reads the nine cells and their drivers itself, in red. On the right, the instance that owns the cell builds its candidate list from the cells once a second (1) and keeps it for 1 second (2). Each rider's request only ranks that list by its own distance (3).On the left, every rider's request reads the nine cells and their drivers itself, in red. On the right, the instance that owns the cell builds its candidate list from the cells once a second (1) and keeps it for 1 second (2). Each rider's request only ranks that list by its own distance (3).
Riders in the same cell share the filter, and each runs their own check. On the left, every rider's request reads the nine cells and their drivers itself, in red. On the right, the instance that owns the cell builds its candidate list from the cells once a second (1) and keeps it for 1 second (2). Each rider's request only ranks that list by its own distance (3).

Twelve cells, one build a second each, at about 909 reads per build, come to about 11,000 reads a second. That's 500 times fewer than one query per rider, and about 5.5 times fewer than the instance caches. The filter also runs 12 times a second instead of 6,000.

This only works with the routing. Without it, each of the 20 instances builds its own list for every cell, which is 20 times the reads, about 218,000 a second. That's more than the instance caches.

The answer is still exact. The neighbour rule guarantees the 3 by 3 list holds every driver within one cell width of any point in the centre cell. So each rider gets the same drivers they would have found on their own, only up to 1 second older.

What you give up. Positions that were already up to 4 seconds old can now be 5 seconds old. You own the routing, and an instance that owns a busy cell takes all of that cell's requests. And in quiet areas, where a cell holds one rider at a time, the shared list saves nothing, so build it only for cells with many riders.

Delivery zones, where the things you index are shapes

A food delivery app needs the restaurants that deliver to an address. Each restaurant has a delivery zone, drawn as a polygon around the area its couriers can reach in time. The zones follow roads and rivers, and they aren't circles.

The obvious design reuses the point index: find restaurants within 3 km of the address. It fails in both directions. It returns a restaurant 1 km away across a river whose zone stops at the bank, so the user picks a restaurant that won't deliver to them. And it misses a restaurant 5 km away whose zone runs along a highway to the user's door.

A radius against the delivery zones
The dashed blue circle is 3 km around the address. Restaurant A is inside it, but A's zone, in red, stops at the river, so A cannot deliver here. Restaurant B is outside the circle, but B's zone, in green, follows the highway to the address. Only a test against each zone's polygon gets both right.The dashed blue circle is 3 km around the address. Restaurant A is inside it, but A's zone, in red, stops at the river, so A cannot deliver here. Restaurant B is outside the circle, but B's zone, in green, follows the highway to the address. Only a test against each zone's polygon gets both right.
A circle around the address answers the wrong question. The dashed blue circle is 3 km around the address. Restaurant A is inside it, but A's zone, in red, stops at the river, so A cannot deliver here. Restaurant B is outside the circle, but B's zone, in green, follows the highway to the address. Only a test against each zone's polygon gets both right.

The question has changed from "which points are near this point" to "which shapes contain this point". The method is still filter, then check, with the shapes indexed instead of the addresses.

In PostGIS, store each zone as a polygon with a GiST index, and ask WHERE ST_Intersects(zone, 'POINT(-73.9855 40.7580)'::geography). The index finds the zones whose bounding box holds the point, and the exact test checks the polygon.

On a grid, cover each zone with cells when it's saved, using S2's region coverer or the equivalent H3 function. Store a list of zone IDs under each cell ID in a key-value store such as DynamoDB. At query time, compute the address's cell, read the zone IDs under it, and run the exact point-in-polygon test on each. The cells along a zone's edge are partly outside it, so the exact test is still required.

Zones change rarely, and they're read on every search, so computing the covering when a zone is saved costs almost nothing. Decision: PostGIS while one database can take the search rate, then precomputed coverings in the key-value store.

Where it goes wrong

These are ordered by how often they come up.

1. Putting a B-tree on latitude and longitude

It reads a band the full width of your data to fill a small box, 20 entries per row returned in one 40 km city.

2. Reading one cell and forgetting the neighbours

A driver 20 m away across the cell edge has a different prefix, so always read the 3 by 3 block.

3. Returning the candidates as the answer

Nine cells hold much more than the circle. With the cell edge equal to the radius, the far corner of the block can be 2.8 radii away, so a "within 1 km" answer can include a driver 2.8 km off. Check the distances, then sort.

Sort by the right distance, too. The index measures a straight line. A driver 300 m away across a river can be 15 minutes away by road. Use the index to get the candidates, and rank them by estimated travel time wherever travel time is what the user cares about.

4. Choosing a cell size without the radius and the density

"We use geohash 6" is half an answer. The cell edge should match the search radius, and the candidates per query should be priced at peak density: density x 9 x edge². At 300 restaurants per km² and 1 km cells, that's 2,700 candidates for one query.

5. Sharding by city

A city looks like a natural shard key, because every query stays inside one. But the largest city is then one shard, and you can't split it. Lyft's 2017 slides name region as a poor hash key that created hot shards. Shard by cell instead. One query's cell sets then sit on up to nine shards, and the 900 driver keys behind them on nearly all of them. Partitioning and sharding works through that scatter cost.

6. Treating degrees as distance

A degree of latitude is about 111 km everywhere. A degree of longitude is 111 km at the equator, about 84 km in New York and about 56 km at 60 degrees north, because it shrinks with the cosine of the latitude. A box of 0.01 degrees each way is close to a square at the equator and about half as wide as it is tall in Oslo. Use a distance function that works in metres: ST_DWithin on a geography column, GEOSEARCH with a radius in km, or the Haversine formula.

If you memorise nothing else

factwhy it matters
A spatial index returns cells, not answersyou check the exact distances yourself, every time
A B-tree on (lat, lng) reads a band as wide as your data20 times the rows in one city, 2,000 times across a country
Read the point's cell and its 8 neighbourstwo points 31 m apart can share no geohash prefix
Set the cell edge to about the search radiusbigger wastes candidates, smaller multiplies the cells read
Candidates per query = density x 9 x edge²price it at the densest place you serve
A geohash character divides cell area by 32, an S2 level by 4, an H3 resolution by 7geohash can't get close to an arbitrary radius
Geohash cell sizes are quoted at the equatora degree of longitude is 84 km in New York, 56 km at 60 degrees north
First ask whether the points movepoints that stay put go in PostGIS, moving points in an in-memory grid
Index the driver's cell, not their positionthe cell changes about once in 30 pings
Shard by cell, never by citythe largest city becomes one shard, and you cannot split it
Riders in one cell share one candidate listroute by cell, build it once a second, rank it per rider
A Redis GEO member never expiresa driver who went home stays on the map until something removes them
An H3 child only approximately fills its parentS2 truncation to a parent is exact, H3's is not
Delivery zones are shapes, not pointsindex the polygons, then test the address against each

What is expected at each level

Mid-level

Know why a B-tree on latitude and longitude doesn't serve "nearby", and be able to explain one grid scheme, usually geohash: cells, prefixes, and reading the neighbours. Know that the cells return candidates and that you compute the distances afterwards.

You aren't expected to size the cells or raise density without being asked. You are expected to answer sensibly when asked "what about a driver just across the edge of the cell?" A good answer is "I read the 8 cells around it too, and then check each distance."

Senior

You lead this part of the discussion, and three things must come up without prompting.

Whether the points move, and what that does to storage. Moving drivers mean a six-figure write rate. Say where those writes go and what the index holds.

The cell size as a number. Tie it to the search radius, and price the candidates per query at the densest place you serve.

How departed points leave the index. A design with no expiry shows a rider a driver who went home an hour ago.

Two things are disqualifying: a B-tree on latitude and longitude for a nearby search, and driver positions written to the primary relational database, Postgres or MySQL, on every ping.

Staff+

A correct design is still the bar. A staff+ answer also decides which parts don't need building.

Split the filter from the check. The index answers which cells, and the positions live beside it. That lets the cell index change only when a driver crosses a cell edge, and it lets every rider in a cell share one candidate list.

Treat the index as rebuildable. It's a copy of the last round of pings and the last minute of re-adds, so it needs no disk and no replication across regions. A lost shard's driver keys refill within 4 seconds, and its cell sets within a minute.

Design for the density spread. A cell size that is right downtown is wrong at the edge of town. Say which of nearest-K, ring expansion or adaptive cells handles that here, and why.

Pick the scheme last. Geohash, S2 and H3 differ in cell shape and step size. Choose by what the system needs: exact containment and range scans for S2, equal-distance neighbours for adding up demand with H3, or a string any database can index for geohash.

And say what you would not build. Each of these can cost a team a quarter.

A custom quadtree service for drivers whose positions change every 4 seconds. Road distances computed inside the index, when the index only has to supply candidates for a ranking by travel time. A migration from geohash to H3 when the problem was a cell size chosen without the radius. And a location index replicated across regions, when a driver's position only matters to riders in the same city, so each region can index only its own drivers.

Sources

Densities, fleet sizes and rider counts in the worked examples are assumptions, stated where they're used.

  • Geohash, Wikipedia. The 32-character alphabet, how bits alternate between longitude and latitude, and the Z-order curve. Nearby points with no common prefix at the equator, the prime meridian, the poles and the 180° meridian.
  • Geohash grid aggregation, Elasticsearch documentation. The cell size at the equator for each geohash length.
  • Redis documentation for GEOADD and GEOSEARCH. The 52-bit geohash stored as a sorted-set score, and the centre area plus 8 neighbours checked on every search. Haversine distances, and ZREM in place of a delete command.
  • S2 Geometry, the cell hierarchy and cell statistics. The cube projection, levels 0 to 30, 64-bit cell IDs, and the Hilbert curve with its one-way guarantee. Cell ID ranges, the region coverer's default of 8 cells, and level 12 cells of 3.04 to 6.38 km².
  • Isaac Brodsky, H3: Uber's Hexagonal Hierarchical Spatial Index, Uber Engineering, 2018, with the H3 documentation on resolutions, terminology, hexagons and the comparison with S2. The icosahedron, 12 pentagons per resolution, 16 resolutions, children only approximately inside their parents, equal-distance neighbours, pentagons with 5 neighbours, and surge pricing measured per hexagon.
  • PostGIS documentation on spatial indexing, ST_DWithin and the <-> operator. The R-tree on GiST over bounding boxes, the two-step search, and nearest-neighbour ordering that uses the index only inside ORDER BY.
  • How Uber Scales Their Real-Time Market Platform, HighScalability, 2015, a summary of Matt Ranney's QCon talk. Drivers reporting every 4 seconds, the goal of 1 million writes a second, S2 level 12 cells, the cell ID as the shard key, and smaller cells meaning more fan-out.
  • Daniel Hochman, Geospatial Indexing at Scale: The 15 Million QPS Redis Architecture Powering Lyft, 2017 slides. A key per driver beside a sorted set per geohash trimmed after 30 seconds. Region as a poor hash key, the geohash length as a trade between scattered gets and hot shards, and why GEO was set aside.

Spot a mistake, or something unclear? . Or get in touch.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.