Geospatial indexing (geohash, S2, H3)
Map coordinates to cell ids so "what's near me?" becomes a lookup of a few cells plus an exact distance filter; size cells to the search radius and split cells that get hot.
Analogy: Postal codes: to find pizzerias near you, check your postcode and the ones bordering it, then measure the real walk to each shop.
How it works
- B-trees sort one dimension; cells turn 2D proximity into ordinary key lookups.
- Geohash interleaves lat/lng bits: a shared prefix means close, but close points across an edge may share none.
- So query the cell plus its neighbors, then filter candidates by exact distance.
- Quadtrees split dense cells; H3 hexagons have equidistant neighbors; S2 orders cells on a Hilbert curve.
- Size cells to the search radius; split or shard hot cells like stadiums and airports.
Check yourself
Answer to mark it learned; your answers aren't scored.
Your "drivers near me" feature computes the rider's geohash-6 cell (~1.2 km × 609 m) and returns the drivers stored under that exact cell. Riders complain that a car parked across the street never shows up. Best fix?
Go deeper
Full explanation
A B-tree sorts one dimension; "nearby" needs two. A geospatial index maps (lat, lng) to cells, so proximity becomes ordinary key lookups.
- Geohash interleaves latitude and longitude bits into a base-32 string; each extra character shrinks the cell. A shared prefix means close, but two close points across a cell edge may share no prefix, so you query the cell plus its 8 neighbors. Redis GEO stores a 52-bit geohash as a sorted-set score.
- Quadtree splits a square into 4 children when it holds too many points: small cells downtown, big ones in the desert.
- S2 (Google) projects the sphere onto a cube and orders cells on a Hilbert curve. H3 (Uber) uses hexagons, whose 6 neighbors are all the same distance away.
- R-tree (PostGIS) indexes bounding boxes, so it handles shapes, not just points.
Nearby search: find the query's cell, take the ring of cells covering the radius, fetch candidates, filter by exact distance, sort. Hot cells (a stadium, an airport) get split finer or their own shard.
Code Nearby drivers with H3 cells
import math
from collections import defaultdict
import h3 # h3-py v4
RES, EDGE_KM = 8, 0.53 # res 8: ~0.74 km2 hexagons, ~0.53 km edge
cells: dict[str, set[str]] = defaultdict(set) # cell -> driver ids
where: dict[str, tuple[float, float, str]] = {} # driver -> (lat, lng, cell)
def update(driver: str, lat: float, lng: float) -> None:
cell = h3.latlng_to_cell(lat, lng, RES)
old = where.get(driver)
if old and old[2] != cell:
cells[old[2]].discard(driver) # moved: leave the old cell
cells[cell].add(driver)
where[driver] = (lat, lng, cell)
def nearby(lat: float, lng: float, radius_km: float, k: int = 10) -> list:
origin = h3.latlng_to_cell(lat, lng, RES)
rings = math.ceil(radius_km / EDGE_KM) # conservative: the disk covers the radius
found = []
for c in h3.grid_disk(origin, rings): # 1 + 3r(r+1) cells
for d in cells.get(c, ()):
dist = h3.great_circle_distance((lat, lng), where[d][:2], unit="km")
if dist <= radius_km: # cells are coarse; distance is exact
found.append((dist, d))
return sorted(found)[:k]Real example
Ride-hailing, with labelled assumptions: 500k online drivers ping every 4 s, so ~125k location writes/s. Drivers are indexed by H3 res 8 cells (~0.53 km edge) in sharded Redis. "Nearest 10 drivers within 1 km" reads a 2-ring: 19 cells, a few hundred candidates, one exact distance pass. When a concert ends, 3,000 drivers crowd one cell: that key takes ~750 writes/s plus every nearby rider's read. The hot cell is split into its res 9 children, spreading the load over ~7 keys.
Trade-offs +3 · −3
+ You gain
- Turns 2D "near me" into key lookups that any KV store, cache or shard map can serve.
- Cell ids are cheap to shard on and aggregate by (supply and demand per area).
- Hierarchical: coarse cells for analytics, fine cells for matching, one scheme.
− You pay
- Edge effects: points just across a boundary need extra neighbor lookups.
- Fixed grids skew: one downtown cell can hold thousands of points while rural cells sit empty.
- Moving objects mean constant re-indexing writes: leave the old cell, join the new one.
Use it when
Nearby search, geofencing, ride or delivery matching, per-area aggregation (surge pricing, heatmaps) and sharding location data by region.
Avoid it when
Small datasets (a scan or PostGIS on one box is fine), complex shape queries (use an R-tree), or non-geographic similarity (use ANN indexes).
Numbers to know 5
- Geohash at the equator: 5 chars ≈ 4.9 × 4.9 km, 6 ≈ 1.2 km × 609 m, 7 ≈ 153 × 152 m.
- H3: 16 resolutions, each with ~7× more cells; res 8 ≈ 0.74 km² (edge ~0.53 km), res 9 ≈ 0.1 km².
- An H3 k-ring holds 1 + 3k(k+1) hexagons: 7 for k=1, 19 for k=2.
- S2: 31 levels (0–30) of 64-bit cell ids; leaf cells are ~1 cm across.
- Redis GEO: a 52-bit geohash as the sorted-set score; a radius query checks the 1 + 8 surrounding areas.
Common pitfalls 4
- Querying only the user's own cell: a driver 50 m away across the edge is invisible.
- Assuming geohash cells are uniform squares: they narrow toward the poles, and even lengths are 2:1 rectangles.
- One fixed resolution city-wide: downtown cells overflow while suburbs need many rings.
- Sharding by cell with no plan for hot cells: the stadium shard melts while the rest idle.
Interview questions 3
Answer out loud first, then reveal.
How would you find the 10 nearest drivers to a rider?Show answer
I'd index drivers by cell, H3 or geohash, in an in-memory store like Redis, updated on every ping. For a query I compute the rider's cell, take the ring of cells covering the radius, fetch candidates, filter by exact distance and sort. If there are too few, I widen the ring. Locations are ephemeral, so memory with a TTL is fine. The real bottleneck is the write rate and hot cells, so I shard by region.
Geohash, quadtree or H3: which would you pick?Show answer
It depends on the store and the query. Geohash is a string prefix, so it works on any sorted KV store and Redis has it built in: my default for radius search. A quadtree adapts to density, good for very skewed data that fits in memory. H3's equidistant hexagon neighbors make per-area aggregation clean; Uber built it for surge pricing and dispatch. For polygons and spatial joins I'd use PostGIS and its R-tree.
A concert ends and thousands of drivers and riders pile into one cell. What breaks?Show answer
That cell's key becomes a hot spot: every ping writes it and every nearby rider reads it, so one shard saturates while others idle. I'd split hot cells into finer children so load spreads over several keys, or give hot regions their own shard, and cap candidates per query. Reads tolerate a second of staleness, so replicas or a short cache can absorb them.