Geospatial Indexing: Geohash, Quadtrees, R-trees, S2 and H3


System Design Phase 6: Scaling Data
Advanced Lesson 31 of 86 16 min read Updated Nov 30, 2026

A food delivery startup stores restaurant locations as two float columns, lat and lng, with a B-tree index on each. The “restaurants near me” query filters lat BETWEEN 40.70 AND 40.74 AND lng BETWEEN -74.02 AND -73.98. With 2,000 restaurants it runs in 3 ms.

Two years later the table has 900,000 restaurants and 4 million couriers posting their position every 5 seconds into a second table. The planner can use only one of the two indexes efficiently. The latitude range alone matches a stripe that crosses the whole planet: every restaurant between 40.70 and 40.74 degrees north, from New Jersey through Spain, Turkey and Beijing. The query reads 60,000 rows to return 40, and the courier table is taking 800,000 writes per second against indexes that were never built for it.

The fix is not a better B-tree. It is a different way of turning two-dimensional space into something an index can work with.

What it is

Geospatial indexing is a family of techniques for answering spatial queries quickly:

  • Radius: everything within 2 km of a point.
  • k nearest neighbours: the 10 closest drivers.
  • Containment: which delivery zone polygon contains this point.
  • Bounding box: everything visible on the map viewport.

A normal index orders keys along one dimension. Space has two (three if you count altitude), and points that are close in space must end up close in the index. Every technique here does one of two things: it maps 2D cells onto a 1D key that preserves locality (geohash, S2, H3), or it builds a tree of nested regions (quadtrees, R-trees).

How it works

The distance math you need

Latitude runs from -90 to 90 degrees, longitude from -180 to 180. One degree of latitude is about 111 km everywhere. One degree of longitude is 111 km times cos(latitude): 111 km at the equator, about 85 km at New York (40.7 degrees), about 56 km at Oslo (60 degrees) and 0 at the poles. That shrinking is why naive lat/lng grids distort near the poles.

For true distance on a sphere, use the haversine formula:

a = sin^2(dlat / 2) + cos(lat1) * cos(lat2) * sin^2(dlng / 2)
d = 2 * R * asin(sqrt(a))        R = 6,371 km

Haversine is accurate to about 0.5% because Earth is not a perfect sphere, which is plenty for “nearby” features. Use an ellipsoidal formula (Vincenty or the geodesic functions in PostGIS) for surveying or billing distances.

The universal pattern: use the index to get a small candidate set, then filter candidates with exact distance. An index never answers “within 2 km” exactly. It answers “in these cells”, and a distance check removes the corners.

Geohash

Geohash interleaves the bits of longitude and latitude (one bit of each, alternately, each bit halving the remaining range) and encodes every 5 bits as one base-32 character. Points that share a prefix are in the same cell, and each extra character divides a cell into 32.

Length Cell size (at equator) Typical use
4 39 km x 19.5 km Region
5 4.9 km x 4.9 km Town, coarse search
6 1.2 km x 0.61 km Neighbourhood
7 153 m x 153 m Street block
8 38 m x 19 m Building
9 4.8 m x 4.8 m Doorway

Cell widths shrink with cos(latitude) just like longitude degrees, so at New York a length-6 cell is about 0.93 km wide. Because a geohash is a string, a prefix query on any ordered index (a B-tree, a sorted set, a key range in a KV store) finds every point in a cell. The ordering follows a Z-order curve.

The edge problem. Two points 5 metres apart on either side of a cell boundary can have completely different geohashes. In the worst case (either side of the equator or the prime meridian) they share no prefix at all. So you never search one cell. You search the cell containing the query point plus its 8 neighbours, chosen at a precision where one cell is at least as large as the search radius, then filter by exact distance.

flowchart TB
subgraph G["Geohash length 6 around the query point"]
  direction TB
  R1["dr5ru4"] --- R2["dr5ru6"] --- R3["dr5ruk"]
  R4["dr5ru1"] --- R5["dr5ru3<br/>query point"] --- R6["dr5ru9"]
  R7["dr5rgc"] --- R8["dr5rgf"] --- R9["dr5rgg"]
end
R5 --> F["Gather candidates from 9 cells<br/>then haversine filter"]
style R5 fill:#EEEDFE,stroke:#534AB7,color:#3C3489
style R7 fill:#FAEEDA,stroke:#854F0B,color:#633806
style R8 fill:#FAEEDA,stroke:#854F0B,color:#633806
style R9 fill:#FAEEDA,stroke:#854F0B,color:#633806
style F fill:#E1F5EE,stroke:#0F6E56,color:#085041

The bottom row in amber shows the edge problem in action: those cells are geographically adjacent to the query cell but share only the dr5r prefix, so a prefix scan on dr5ru alone would miss them. The cell names here are illustrative; libraries compute neighbours for you.

Quadtrees

A quadtree starts with one square covering the map and splits any square that holds more than a threshold (say 100 points) into four children, recursively. Dense Manhattan ends up 15 levels deep with tiny leaves; the Atlantic stays one huge leaf. A radius query descends only into squares that intersect the search circle.

The strength is adaptivity: leaves hold a roughly constant number of points, so query cost is stable whether you are in a city centre or a village. The cost is that it is usually an in-memory structure you build and rebalance yourself, and points that move constantly cause splits and merges. Geohash is actually a fixed-depth quadtree in disguise (2 bits per level), without the adaptivity.

R-trees

An R-tree groups nearby objects into minimum bounding rectangles, groups those rectangles into bigger rectangles, and so on up to a root, a B-tree for boxes. A query walks down only the branches whose rectangles intersect the search area. Unlike geohash and quadtrees it indexes shapes natively: roads, delivery zones, building footprints. Rectangles can overlap, so a query may have to explore several branches.

This is what PostGIS uses: a GiST index on a geometry or geography column is an R-tree. Typical queries:

CREATE INDEX ON restaurants USING GIST (location);

-- radius: within 2 km (geography uses metres)
SELECT id FROM restaurants
WHERE ST_DWithin(location, ST_MakePoint(-73.99, 40.73)::geography, 2000);

-- k nearest: the index-assisted distance operator in ORDER BY
SELECT id FROM restaurants
ORDER BY location <-> ST_MakePoint(-73.99, 40.73)::geography
LIMIT 10;

R-trees are excellent for data that changes slowly (restaurants, stores, zones). They are a poor fit for millions of points moving every few seconds, because each move is a delete and reinsert that can reshape rectangles, and every write goes through the database’s WAL.

Google S2

S2 projects the sphere onto the six faces of a cube, builds a quadtree on each face, and numbers the cells along a Hilbert curve, so every cell at every level has a 64-bit ID. There are 31 levels, from a whole cube face (level 0) down to roughly a square centimetre (level 30). The Hilbert curve has better locality than the Z-order curve: consecutive IDs are always adjacent cells, so a region maps to fewer contiguous ID ranges.

Its most useful tool is the region coverer: give it a circle or polygon and a maximum cell count, and it returns a small set of cells, at mixed levels, that cover the shape. Each cell is a range of 64-bit IDs, so a circle query becomes a handful of range scans on any ordered key-value store. S2 works on the sphere, so it has no special cases at the poles or the antimeridian. MongoDB’s 2dsphere index is built on S2 cells.

Uber H3

H3 tiles the globe with hexagons (plus 12 pentagons per resolution, an unavoidable consequence of tiling a sphere) at 16 resolutions, 0 to 15. Uber open-sourced it in 2018. Each resolution has cells about 7 times smaller in area than the one above; a resolution 8 cell averages about 0.74 km², a resolution 9 cell about 0.11 km².

Why hexagons: every hexagon has 6 neighbours, all at the same centre-to-centre distance. Squares have 4 edge neighbours and 4 corner neighbours at 1.41x the distance, which makes “ring” queries and movement analysis lumpy. H3 queries use grid disks: gridDisk(cell, k) returns the cell plus k rings around it, which is 1 + 3k(k+1) cells (7 for k = 1, 19 for k = 2, 37 for k = 3). The trade-off is that the hierarchy is approximate: seven children do not exactly tile their parent hexagon, so H3 is weaker than S2 for exact containment by parent ID.

flowchart LR
P["Lat, lng"] --> GH["Geohash<br/>Z-order, squares"]
P --> S2["S2<br/>cube faces, Hilbert curve"]
P --> H3["H3<br/>hexagons, 16 resolutions"]
GH --> K1["String prefix<br/>B-tree or sorted set"]
S2 --> K2["64-bit cell ID ranges<br/>any ordered KV store"]
H3 --> K3["64-bit cell ID<br/>hash map of cell to members"]
K1 --> F["Candidate set"]
K2 --> F
K3 --> F
F --> D["Exact distance filter"]
style GH fill:#F1EFE8,stroke:#888780,color:#444441
style S2 fill:#EEEDFE,stroke:#534AB7,color:#3C3489
style H3 fill:#E1F5EE,stroke:#0F6E56,color:#085041
style D fill:#FAEEDA,stroke:#854F0B,color:#633806

Worked example: drivers within 2 km

This is the core of the ride-hailing design in design ride hailing, which adds matching, dispatch and ETA on top.

Where it breaks

Searching one cell. The classic bug: a point near a cell edge misses neighbours a few metres away. Always search neighbours or a covering, then filter by true distance.

Wrong precision. Cells much smaller than the radius mean hundreds of cell lookups per query; cells much larger mean thousands of candidates to filter. Aim for a cell size somewhere between half the radius and the full radius.

Hot spots. Density varies by four orders of magnitude between a stadium after a concert and farmland. Fixed-size cells and city-based shards both concentrate load. Quadtree-style adaptive splitting, or simply more shards for hot regions, fixes it.

Lat/lng order mix-ups. GeoJSON, PostGIS ST_MakePoint and Redis take longitude first; most humans and many map APIs say latitude first. Swapped coordinates put your driver in Antarctica or the Indian Ocean. Validate ranges at the edge.

Poles and the antimeridian. Bounding-box math on raw degrees breaks near the 180 degree meridian (Fiji, eastern Russia) and the poles. S2 and H3 work on the sphere and avoid this; hand-rolled lat/lng boxes do not.

Planar math on geographic data. Euclidean distance on degrees treats a degree of longitude as 111 km everywhere. In Oslo that roughly doubles every east-west distance. Use haversine or a geography type.

Stale positions in Redis GEO. Members of a sorted set cannot expire individually, so a driver who goes offline stays “nearby” forever unless you clean up. Keep a second sorted set of last-seen times and prune it, or rotate time-bucketed keys.

Real-world systems (Nov 2026)

PostGIS adds geometry and geography types to Postgres with GiST (R-tree) indexes, ST_DWithin, ST_Contains and index-assisted k-nearest via the <-> operator. It is the default choice for relational data with locations that do not move every second.

Redis GEO stores members in a sorted set whose score is a 52-bit interleaved geohash. GEOADD adds or moves a member, GEOSEARCH (Redis 6.2 and later) finds members by radius or box, with GEORADIUS deprecated in its favour. Valkey supports the same commands.

GEOADD drivers:nyc -73.9857 40.7484 driver:8812
GEOSEARCH drivers:nyc FROMLONLAT -73.99 40.73 BYRADIUS 2 km ASC COUNT 20 WITHDIST

Each GEOADD is O(log N) and a single Redis primary handles on the order of 100,000 simple writes per second per core, so shard by city or region for the 250,000 per second case.

Elasticsearch and OpenSearch index geo_point fields in Lucene’s BKD trees and support geo_distance, geo_bounding_box and geo_shape queries, so you can combine “within 5 km” with full-text relevance in one query (see search engines). Elasticsearch also has geohash_grid, geotile_grid and H3-based geohex_grid aggregations for map heat maps.

MongoDB 2dsphere indexes are built on S2 cells. H3 has bindings for most languages and is used widely for pricing zones, supply and demand heat maps and analytics, where equal-area hexagons make cell-to-cell comparisons fair.

How to apply it

Situation Good default
Static places, polygons, SQL joins PostGIS with a GiST index
Moving objects, high write rate In-memory cell index (H3 or geohash) sharded by region, or Redis GEO per city
Radius search combined with text relevance Elasticsearch or OpenSearch geo_point
Analytics, heat maps, pricing zones H3 cells as a grouping key
Arbitrary regions on a KV store, exact containment S2 cell coverings

Checklist:

  • Write down the write rate first. Static data goes in a database index; moving data goes in memory.
  • Pick cell size from the search radius, and always query neighbours or a covering.
  • Filter candidates by haversine distance, then rank (distance, ETA, rating).
  • Shard by coarse cell or city, and plan extra shards for dense regions.
  • Treat live positions as soft state with a staleness cutoff.
  • Store and validate coordinates as (longitude, latitude) at the API boundary.

Interview questions

Q1: Why can’t you just index latitude and longitude with two B-trees?

A B-tree orders one dimension. A range on latitude alone matches a thin band around the whole planet, and a range on longitude alone matches a band from pole to pole. The database can use one index and must filter the other condition row by row, or intersect two large bitmaps, so cost grows with the size of the band, not the size of the answer. Spatial indexes fix this by mapping 2D cells onto a single locality-preserving key (geohash, S2 cell ID) that a B-tree can range-scan, or by indexing 2D bounding rectangles directly (an R-tree, as PostGIS GiST does). A composite B-tree on (lat, lng) does not solve it either, because it is still sorted by latitude first.

Q2: A user is 10 metres from a geohash cell boundary. Their search for restaurants within 500 m misses one right across the street. Why, and how do you fix it?

Geohash cells are rigid squares, and points close in space but on opposite sides of a boundary can have different prefixes, in the worst case no shared prefix at all. Querying only the user’s cell misses anything across the edge. The fix is to choose a precision whose cell is at least as large as the radius (length 6, about 1.2 x 0.6 km at the equator, for 500 m), query the user’s cell plus its 8 neighbours, and then filter the candidates by exact haversine distance so the corners of the 3 x 3 block are removed.

Q3: Compare S2 and H3 for a ride-hailing company.

Both map the sphere to 64-bit cell IDs at many resolutions and work without pole or antimeridian special cases. S2 uses squares from a cube projection ordered on a Hilbert curve, with an exact hierarchy: a parent cell contains exactly its four children, and the region coverer turns any circle or polygon into a few ID ranges, which is ideal for range scans on a key-value store and for exact containment. H3 uses hexagons, whose six neighbours are all equidistant, which makes rings, smoothing and movement analysis uniform; it is the better fit for supply and demand heat maps, surge pricing zones and nearby-driver searches with grid disks. Its hierarchy is approximate, since children do not exactly tile the parent, and each resolution has 12 pentagons to handle. Many systems use H3 for analytics and matching and S2 or polygons for exact geofencing.

✅ Key takeaways

  • Spatial queries need locality in two dimensions. Either map cells to a 1D key (geohash, S2, H3) or index nested regions (quadtree, R-tree).
  • The index returns candidates, never the answer. Always search neighbouring cells, then filter by exact haversine distance.
  • Geohash is simple and prefix-friendly but has rigid square cells and the edge problem. S2 adds a sphere-aware Hilbert ordering and coverings. H3 gives equidistant hexagon neighbours with grid disks.
  • PostGIS GiST (an R-tree) is the default for static places and polygons. Fast-moving objects belong in an in-memory cell index sharded by region.
  • For live locations the constraint is write rate and hot spots, not memory: 1 million drivers every 4 s is 250,000 writes per second but only about 200 MB of state.

🧠 Check your understanding

0 / 4
  1. 1You search for drivers within 1 km using geohash. Which approach is correct?

  2. 21 million drivers send their position every 4 seconds. What is the main design constraint for the nearby-driver index?

  3. 3Which index type does PostGIS use for geometry columns, and what is it best at?

  4. 4Why do many analytics and pricing systems prefer H3 hexagons over square cells?

Where to go next

Finished this lesson?

Mark it complete to track your progress across the roadmap.