Geospatial Indexing
Why B-trees fail on two dimensions, and how geohash, quadtrees, S2 and H3 turn "find things near me" into a one-dimensional range query.
#The problem
"Find all restaurants within 5 km of me." The naive query:
SELECT * FROM places
WHERE lat BETWEEN 18.47 AND 18.56 AND lng BETWEEN 73.80 AND 73.90;Why this performs badly: a B-tree index is one-dimensional — it sorts rows by one thing, then breaks ties with the next. An index on (lat, lng) can jump straight to rows with lat between 18.47 and 18.56. But that's a thin strip running right round the planet — through India, Thailand, the Caribbean and Mexico — and within it, rows are ordered by latitude, not longitude. So the database must read every row in the strip and check its longitude: millions of rows to scan and discard.
Two separate indexes aren't better: the database intersects two large result sets, both huge.
The core insight behind every solution below: convert two dimensions into one, in a way that keeps nearby points nearby in the resulting order. Then a B-tree works again.
#Geohash
A geohash turns a latitude and longitude into a short string like tdr1v2q, where the string is a box on the map: the longer the string, the smaller the box.
It works by playing twenty questions with the planet. Cut the world in half, note which side you're on, cut that half in half, note again — encoding each answer as a bit, then writing the result as text.
Split longitude [-180,180] in half: east → 1, west → 0
Split latitude [-90,90] in half: north → 1, south → 0
Interleave the bits, alternating lng/lat, and recurse.
Result: "tdr1v2q" ← more characters = smaller box
1 char ≈ 5000 km 5 chars ≈ 5 km
2 chars ≈ 1250 km 6 chars ≈ 1.2 km
3 chars ≈ 156 km 7 chars ≈ 150 m
4 chars ≈ 39 km 8 chars ≈ 38 mThe property that makes it work: shared prefixes mean spatial proximity. tdr1v2q and tdr1v2r are adjacent cells. So a proximity search becomes a prefix query, which any B-tree, key-value store, or LIKE 'tdr1v%' can serve:
SELECT * FROM places WHERE geohash LIKE 'tdr1v%';Two flaws you must mention:
- Boundary problem. Two points 10 metres apart can sit in different cells with completely different prefixes — right at a major grid line, they share almost no prefix. The fix: always query the target cell plus its 8 neighbours, then filter by true distance.
- Non-uniform cell size. Cells shrink toward the poles because longitude lines converge. A "5 km" cell is 5 km at the equator and much narrower in Norway.
#Quadtree
A tree that subdivides space adaptively: a node splits into four quadrants only when it exceeds a capacity threshold.
┌─────────┬─────────┐ Dense areas (cities) subdivide deeply.
│ ┌──┬──┐ │ │ Empty areas (ocean) stay one big node.
│ ├──┼──┤ │ │
│ └──┴──┘ │ │ → each leaf holds a bounded number
├─────────┼─────────┤ of points, so query cost is
│ │ │ predictable regardless of density
│ │ │
└─────────┴─────────┘Advantage over geohash: it adapts to density. Geohash uses fixed cell sizes, so a Manhattan cell contains 50,000 restaurants while a rural cell contains two — very different query costs. A quadtree gives every leaf roughly the same population.
Costs: it's an in-memory structure (not a simple index you add to a table), it must be rebuilt or rebalanced as data changes, and distributing it across machines is harder than sharding on a geohash prefix.
Good fit for a proximity service holding a large but bounded set of static points in memory. Less good for high-churn data across many nodes.
#S2 (Google) and H3 (Uber)
The two modern production systems, and knowing the difference is a strong signal.
S2 projects the sphere onto the six faces of a cube, then applies a Hilbert curve to order cells within each face. A Hilbert curve is a single continuous line that snakes through every cell of a grid, visiting each once and only ever stepping to an adjacent cell. Number the cells in the order the line visits them, and you have your one-dimensional ordering.
The Hilbert curve is the important part. Geohash's ordering takes big jumps — consecutive cells can be on opposite sides of the map. The Hilbert curve never jumps, so cells with nearby numbers are reliably near each other on the map, and the boundary problem described above happens much less often. S2 cells are also far more uniform in area than geohash cells, and every cell has a 64-bit ID, so it's just an integer range query.
H3 uses hexagons instead of squares. The advantage is subtle and real: a hexagon's six neighbours are all equidistant from its centre, while a square's eight neighbours are not (diagonal neighbours are 1.41× further). For anything modelling movement, coverage, or spatial averaging — surge pricing zones, delivery areas, demand heatmaps — hexagons behave much better.
The catch: hexagons can't tile perfectly hierarchically (a hexagon can't be subdivided into smaller hexagons exactly), so H3's parent/child relationships are approximate. S2's squares nest perfectly.
Choosing: S2 when you need exact hierarchical containment and region coverage — "which of these delivery zones contains this point?", or describing a city's outline as a set of cells, where small cells must sit exactly inside big ones. H3 when you're doing analytics over movement or spatial aggregation — "how many ride requests per zone in the last 10 minutes?".
#PostGIS and R-trees
If you're already on Postgres, the pragmatic answer is often "use PostGIS," and saying so shows you don't reach for a new system unnecessarily:
CREATE INDEX places_geo ON places USING GIST (location);
SELECT * FROM places
WHERE ST_DWithin(location, ST_MakePoint(73.85, 18.52)::geography, 5000)
ORDER BY location <-> ST_MakePoint(73.85, 18.52)::geography
LIMIT 20;GiST implements an R-tree. Each node holds a rectangle that encloses everything beneath it — a box around Pune contains smaller boxes around each neighbourhood, which contain the individual points. A search descends only into boxes that overlap the query area and skips the rest. It handles polygons, distance ordering, and true geodesic math (distance along the Earth's curved surface) correctly — and the <-> operator finds the k nearest points directly from the index, without computing the distance to every row.
For millions of static points and modest QPS, this is genuinely the right answer, and it's one system instead of two.
#Moving objects — the hard case
Static points (restaurants) are easy. Moving points (drivers, delivery riders) are the interesting problem, and it's the core of the ride sharing design.
The challenge is write volume: 1M drivers reporting position every 4 seconds is 250K writes/s, each of which may change the driver's cell.
Design responses:
- Keep it in memory. Live positions belong in Redis or an in-process index, not a disk-backed database. This is ephemeral, high-churn data — durability is nearly worthless, since a 4-second-old position is already stale.
- Redis geospatial commands (
GEOADD/GEOSEARCH) implement geohash on top of sorted sets and handle this workload well. - Update only on cell change. The index only records which cell each driver is in. In 4 seconds a driver usually moves a few dozen metres and stays in the same cell, so the index entry is unchanged — you only overwrite their stored exact position. Only the rare cell crossing needs an index write, which removes most index writes.
- Shard by region. Positions in Pune don't need to be in the same index as positions in Berlin. Geographic sharding is natural here: a "drivers near me" query is always answered by the one shard covering that area, so it never has to ask every shard.
- Reduce frequency adaptively. A stationary driver doesn't need 4-second updates; a fast-moving one does.
#Choosing
| Situation | Approach |
|---|---|
| Postgres already, millions of static points | PostGIS + GiST |
| Simple proximity, key-value store | Geohash prefix + 8 neighbours |
| In-memory, highly variable density | Quadtree |
| Region coverage, hierarchical containment | S2 |
| Movement analytics, zones, heatmaps | H3 |
| Live positions of moving objects | Redis GEO, sharded by region |
Whichever you pick, the final step is always the same and always worth stating: the index gives you candidates, not answers. Cells are rectangles (or hexagons) and your query is a circle, so you must compute true distance on the candidate set and filter. The index's job is to reduce millions of rows to dozens; exact math finishes the job.
#Check yourself
Why do B-trees struggle with "find things near me"?Show answer
How does a geohash turn proximity into a prefix query?Show answer
What is geohash's boundary problem, and the fix?Show answer
What does a quadtree do better than a fixed grid?Show answer
S2 versus H3: when do you choose each?Show answer
You're already on Postgres with millions of static points. What's the pragmatic answer?Show answer
A million drivers report every 4 seconds. How do you handle 250,000 writes a second?Show answer
What final step does every geospatial index still need?Show answer
#What to carry forward
- Geospatial indexing maps two dimensions to one while keeping neighbours close, so a normal index works again.
- Geohash makes proximity a prefix query — always add the eight neighbours.
- Quadtrees adapt to density; S2 gives uniform nested cells; H3's hexagons suit movement and zones.
- PostGIS is often the right answer if you already run Postgres.
- Moving objects need in-memory indexes updated on cell change; the index gives candidates, exact distance finishes.