PATTERN · ORIGINAL
Geospatial indexing: turning "near me" into a lookup
Geohash, quadtrees and S2 or H3 style cells, how to answer radius queries that cross cell boundaries, and why live locations belong in a different index from static places.
"Find coffee shops within 1 km" and "find the closest available driver" look like the same question. Both ask for points near a point. They are different systems because one dataset sits still and is read millions of times, while the other moves every few seconds. The shared foundation is a trick for making two-dimensional nearness fit into the one-dimensional indexes databases are good at.
Why a normal index is not enough
Put latitude and longitude in two indexed columns and ask for a box around a point. The database can use one index, say latitude, and that matches a thin strip around the whole planet at that latitude. It then filters by longitude row by row. For a city-sized box in a dataset of 200 million places, that strip can hold millions of rows. You need an index where points that are close in space are usually close in the index.
Geohash
Geohash interleaves the bits of longitude and latitude: split the world in half by longitude, then by latitude, then longitude again, writing one bit per split. Group the bits into base-32 characters and you get a string like tdr1v. Every prefix is a rectangle containing all longer strings that start with it.
- 5 characters: a cell about 4.9 km by 4.9 km.
- 6 characters: about 1.2 km by 0.6 km.
- 7 characters: about 150 m by 150 m.
The appeal is that a geohash is just a string. Store it in any sorted store, and "everything in this cell" becomes a prefix range scan. You can shard by prefix too.
The flaw is at the edges. Two points 10 m apart on either side of a cell boundary can share no prefix at all. The worst case is the line between two top-level halves, where neighbors have entirely different hashes. So a geohash search never queries one cell. It queries the cell plus its eight neighbors. Cells also shrink in width toward the poles, so a "6-character cell" covers less ground in Oslo than in Singapore.
Quadtrees
A quadtree starts with one square and splits any square holding more than K points (say 100) into four. Dense downtowns become deep, tiny cells; empty deserts stay as one big cell. A "find nearby" query descends to the leaf containing the point and widens to neighboring leaves until it has enough results.
The density adaptivity is the main reason to use one. A fixed grid tuned for Manhattan wastes millions of empty cells over the ocean, and a grid tuned for rural areas puts 50,000 restaurants in one Manhattan cell. Quadtrees usually live in memory, built from the database and rebuilt periodically. They are a good fit for mostly static data. For points that move constantly, rebalancing splits and merges on every update gets expensive.
S2 and H3 style cells
S2 projects the sphere onto the six faces of a cube and subdivides each face into a hierarchy of cells, 31 levels deep, ordered along a Hilbert curve. Each cell has a 64-bit ID, and children of a cell occupy a contiguous range of IDs. Two things follow. Cells are far more uniform in area than geohash rectangles, especially away from the equator. And a region (a circle, a polygon) can be covered by a handful of cells at mixed levels, which become a handful of ID ranges to scan in any sorted index.
H3 tiles the globe with hexagons at 16 resolutions. A hexagon's six neighbors are all the same distance from its center, unlike a square's, whose corner neighbors are farther away than its edge neighbors. That makes "rings" of neighbors and smooth aggregations clean, which is why hexagons suit per-area statistics such as supply and demand for surge pricing. Uber has publicly described building H3 for pricing and dispatch analysis (see further reading). The cost: children do not exactly fill their parent, and each resolution has 12 pentagons, so hierarchy tricks are approximate.
Radius queries across cell boundaries
Whatever the cell scheme, a radius query follows the same recipe:
- Pick a level where a cell is about the size of the radius. For 1 km with geohash, 6 characters is a reasonable fit.
- Cover the circle. With geohash, take the cell plus eight neighbors. With S2, ask a region coverer for up to, say, 8 cells that cover the circle.
- Fetch candidates from each cell or ID range.
- Filter exactly. Compute true distance (the haversine formula is fine at these scales) and drop anything outside the radius. The covering always over-fetches; this step makes it correct.
- Rank and widen. Sort by distance or by a blend of distance and rating. If you have fewer than the requested 20 results, widen to the next ring of cells or a coarser level and repeat.
Static places vs moving objects
Static places: read-heavy, index offline
Nearby search over restaurants or shops is overwhelmingly reads. Places change a few times a day at most. Store each place with its cell ID as an indexed column (or use a database with a native spatial index), replicate widely, and cache popular cells. Results for "coffee near this cell" are the same for everyone in the cell, so they cache well. Updates can flow through a nightly or hourly rebuild, which also lets you rebuild a quadtree or re-tune cell levels. Marketplace listings sit in between: listings appear and disappear daily, but still change far less often than they are read. Caching and hot keys covers the cache side.
Moving objects: in memory, by region
Drivers are the opposite. Do the arithmetic: 5 million active drivers reporting every 4 seconds is 1.25 million location updates per second. Writing each one into a disk-based spatial index, with its index maintenance, is wasteful, and almost every write is overwritten seconds later.
Keep the live index in memory instead:
- A map from cell ID to the set of driver IDs in it, at a level where a cell holds tens of drivers.
- A map from driver ID to its last cell, position, status and timestamp.
- On each update, overwrite the position. Only if the cell changed, move the ID between sets. Most updates do not change cells.
- Drop drivers who have not reported for 30 seconds, so a phone that lost signal stops being matched.
Partition the index by region (city or metro area). Trips rarely cross region boundaries, so a query almost always hits one partition, and one large city fits comfortably in memory on one machine plus a replica. If the process restarts, it rebuilds from the next few seconds of updates; there is nothing durable to recover. Separately, append the raw location stream to a log for trip history, ETA models and disputes. That durable path does not need to be fast.
For dispatch matching, this index produces candidates; claiming one driver without double-booking is a separate step covered in reservations and contention. For ride tracking and ETA, the same location stream is also fanned out to the one rider watching that trip, which is a delivery problem (see fan-out and real-time delivery).
Hot cells
A stadium emptying out puts 40,000 people and hundreds of drivers in a few cells. Because cell schemes are hierarchical, you can index busy areas at a finer level, or split a hot region into its own partition. Plan for it by keeping cell level a configuration choice per region, not a constant baked into the code. Partitioning and ordering covers hot partitions more generally.
| Option | Wins when | Costs |
|---|---|---|
| Geohash | You want a plain string in an ordinary sorted store, with prefix scans and simple sharding. | Edge effects need neighbor queries; cell size varies with latitude. |
| Quadtree in memory | Density varies wildly and data changes slowly, such as places or listings. | Rebuilds or rebalancing on updates; custom code to persist and shard. |
| S2-style cells | You need uniform cells and tight region coverings mapped to ID ranges. | More concepts to explain; you depend on a library for coverings. |
| H3-style hexagons | Aggregating by area (supply, demand, pricing) with even neighbor distances. | Approximate parent-child containment; pentagons complicate edge cases. |
| Database spatial index (R-tree) | Moderate scale, static data, and you already run a database that supports it. | Write-heavy moving data strains it; sharding is on you. |
TAKE THIS TO YOUR NEXT SKETCH
- Map two-dimensional nearness onto a one-dimensional key (geohash, S2 cell ID, H3 index) so ordinary indexes can answer it.
- Never query a single cell: cover the radius with several cells, then filter by exact distance and widen if results are thin.
- Static places belong in a durable, replicated, cache-friendly index rebuilt offline; live locations belong in memory.
- Partition live-location indexes by region, expire silent objects quickly, and log raw positions separately for history.
- Pick hexagons for per-area aggregation, quadtrees for uneven density, and keep the cell level configurable per region.
PRACTICE WITH THIS
Now sketch one.
OFF-SITE READING · NOT WRITTEN BY US
Further reading
- S2 Cells (developer guide)
Primary documentation for S2’s cube-face projection, cell levels and Hilbert-curve cell IDs; the diagrams of cell levels are worth a look before you draw your own.
- H3 documentation
Official docs for the hexagonal grid: resolutions, neighbor traversal and the honest caveats about pentagons and imperfect parent-child containment.
- H3: Uber’s Hexagonal Hierarchical Spatial Index
The team that built H3 explains why they chose hexagons for pricing and dispatch analysis; useful context for the surge-pricing question.
- Geospatial indexing (GEO commands)
A compact example of an in-memory index for points with radius search, close to what a live-location tier needs.