Geospatial Indexing
Finding things near a point fast, using geohash, quadtrees and S2/H3 cells instead of scanning every location.
What is it?
"Show drivers within 2 km of me" sounds simple. But a database index on latitude, or on longitude, only narrows one dimension. Filtering lat BETWEEN a AND b AND lng BETWEEN c AND d with two separate indexes still touches a huge strip of the map.
Geospatial indexing turns 2D positions into something a normal index can search quickly. The common approaches:
- Geohash: encodes a point as a short string. Nearby points usually share a prefix, so a prefix search finds neighbours. - Quadtree: splits the map into four squares, and splits busy squares again, so dense cities get small cells and oceans get big ones. - S2 (Google) and H3 (Uber): hierarchical cell systems over the whole globe. Each cell has a 64-bit ID at a chosen resolution.
All of them share one idea: bucket the world into cells, index by cell, then filter precisely by real distance.
Explain like I'm 10
It's like postal codes. To find pizza places near you, you don't measure the distance to every pizza place on Earth; you look in your postal code and the ones next to it, then check exact distances on that short list.
Examples
Nearby search with a geohash prefix
// Drivers table indexed on geohash6 (cells about 1.2 km x 0.6 km)
async function findNearbyDrivers(lat: number, lng: number, radiusMeters: number) {
const center = geohash.encode(lat, lng, 6);
// The query point may sit near an edge, so always include all 8 neighbours.
const cells = [center, ...geohash.neighbors(center)];
const candidates = await db.query(
"SELECT id, lat, lng FROM drivers WHERE geohash6 = ANY($1)",
[cells],
);
return candidates
.map((driver) => ({ ...driver, distance: haversineMeters(lat, lng, driver.lat, driver.lng) }))
.filter((driver) => driver.distance <= radiusMeters)
.sort((a, b) => a.distance - b.distance);
}Two phases: a coarse cell lookup using an ordinary index, then an exact distance filter. The 3x3 block covers any radius smaller than one cell.
Redis GEO for live positions
GEOADD drivers:sf -122.4194 37.7749 driver:17
GEOADD drivers:sf -122.4090 37.7835 driver:42
GEOSEARCH drivers:sf FROMLONLAT -122.4150 37.7800 BYRADIUS 2 km ASC COUNT 10 WITHDISTRedis stores a 52-bit geohash-style score in a sorted set and does the neighbour-cell search for you. Good for fast-changing positions held in memory.
PostGIS for durable, complex queries
CREATE INDEX places_geo_idx ON places USING GIST (location);
SELECT id, name, ST_Distance(location, ST_MakePoint(-122.415, 37.78)::geography) AS meters
FROM places
WHERE ST_DWithin(location, ST_MakePoint(-122.415, 37.78)::geography, 2000)
ORDER BY location <-> ST_MakePoint(-122.415, 37.78)::geography
LIMIT 20;A GiST index (an R-tree style structure) supports radius, polygon and nearest-neighbour queries on stored places.
How it works
Geohash. Alternately bisect longitude and latitude, writing a 1 if the point is in the upper half and 0 otherwise. Interleave the bits and encode 5 bits per base-32 character. Longer strings mean smaller cells: 5 chars ≈ 4.9 km × 4.9 km, 6 chars ≈ 1.2 km × 0.6 km, 7 chars ≈ 153 m × 153 m. The bits follow a Z-order curve, so a prefix is a rectangle and points in one rectangle are contiguous in a sorted index.
The boundary problem. Two points a metre apart can sit on either side of a cell edge and share no prefix at all (worst case: across the equator or the prime meridian). That's why you always query the cell plus its neighbours, then filter by real distance. Cell size must be chosen so the search radius fits inside that 3×3 block.
Quadtree. Start with one square for the whole map. When a node holds more than a set number of points, split it into four children. Density adapts automatically: Manhattan may be 18 levels deep while the Pacific is one node. Good for in-memory indexes of fairly static points (businesses). Updating moving objects means removing and reinserting, and rebalancing splits and merges.
S2. Projects the sphere onto the six faces of a cube, then divides each face with a quadtree ordered along a Hilbert curve (better locality than Z-order). 31 levels (0 to 30); a cell ID is a 64-bit integer, and a region can be covered by a small set of cells of mixed levels, each one a contiguous range of IDs. Used by Google, MongoDB's 2dsphere index and others.
H3. Uber's hexagonal grid with 16 resolutions (0–15). Hexagons have six neighbours all at the same distance, which makes k-ring searches ("everything within k hops") and smoothing (surge pricing, demand heatmaps) uniform. Children don't nest perfectly inside parents, and each resolution has 12 pentagons, which code must tolerate.
At scale. Shard by a coarse cell (city or S2 level ~6–10) so a query touches one or a few shards. For moving drivers, keep latest positions in memory (Redis or an in-house service), update every few seconds, and expire stale entries. Hot cells (an airport, a stadium) need finer cells or splitting.
Geohash 3x3 neighbour search Quadtree adapts to density
+------+------+------+ +-----------+-----+-----+
| 9q8y | 9q8z | 9q9p | | | . . | . |
+------+------+------+ | empty +--+--+-----+
| 9q8v | 9q8y*| 9q9n | | (1 node) |..|..| . |
+------+------+------+ | +--+--+-----+
| 9q8t | 9q8w | 9q9j | | | . | |
+------+------+------+ +-----------+-----+-----+
* = user's cell (labels illustrative). Points near an edge can live
in a neighbour with a totally different prefix.Why does it exist?
B-tree indexes sort one dimension. Location is two dimensions on a sphere, and the questions people ask ("near me", "inside this zone", "k nearest") need both at once. Mapping 2D cells to 1D IDs lets ordinary sorted indexes, key-value stores and sharding schemes handle spatial queries, which is what ride-hailing, delivery, maps, dating and local search all need.
When to use it
- Proximity search: nearby drivers, restaurants, stores, friends. - Matching and dispatch: find the k nearest available couriers. - Geofencing: is this point inside a delivery zone or airport polygon? (Cover the polygon with cells, then do an exact point-in-polygon test.) - Aggregation: demand heatmaps and surge zones keyed by H3 cell. - Sharding location data so each query hits few partitions.
When not to use it
- A few thousand points: just compute distances in memory, or use PostGIS and let it handle the index. - Region-level filters (country, city) where a normal column is enough. - Routing or travel-time questions. "Nearest by straight line" is not "nearest by road"; you need a road graph and an ETA service for that.
Common mistakes
Searching only the user's own cell and missing results just across the boundary.
Picking a cell size smaller than the search radius, so even the 3x3 neighbour block doesn't cover it.
Treating latitude and longitude as flat x/y and using Euclidean distance. A degree of longitude shrinks toward the poles; use haversine or a geography type.
Writing every GPS ping to the primary database. Keep live positions in memory and persist trips or samples asynchronously.
Ignoring hot cells: one airport cell can hold thousands of drivers and become a hot shard.
Practice exercises
- Easy:
Explain why two points 10 metres apart can have completely different geohashes.
- Medium:
Design the 'restaurants within 5 km' query for 50 million restaurants that rarely move. Choose an index, a cell size and a sharding key.
- Hard:
Design the driver-location service for a ride-hailing app: 1 million active drivers sending a position every 4 seconds, and riders requesting the 10 nearest drivers. Cover write path, index, sharding, hot cells and staleness.
Interview questions
Why can't a regular B-tree on latitude and longitude answer 'nearby' queries efficiently?
It sorts by one column, so a range on latitude returns a whole horizontal band of the world that then has to be filtered by longitude. Spatial indexes cover both dimensions at once.
What is a geohash?
A base-32 string made by interleaving bits from repeated halving of longitude and latitude. Each extra character shrinks the cell; shared prefixes usually mean nearby points.
What is the geohash boundary problem and how do you handle it?
Nearby points on opposite sides of a cell edge can have unrelated prefixes. Query the target cell plus its 8 neighbours, then filter candidates by exact distance.
When would you use a quadtree over a fixed grid?
When density varies a lot. A quadtree subdivides only busy areas, keeping the number of points per cell roughly bounded, whereas a fixed grid has huge cells in cities or millions of empty cells elsewhere.
What advantages do H3 hexagons have?
Every neighbour of a hexagon is equidistant from its centre and shares an edge, so k-ring searches and spatial smoothing are uniform. Squares have edge and corner neighbours at different distances.
What does S2 do differently from geohash?
It works on the sphere by projecting onto a cube and orders cells with a Hilbert curve, giving better locality and less distortion. Regions are covered by a set of mixed-level cells, each mapping to a contiguous range of 64-bit IDs.
How would you store rapidly changing driver locations?
In memory, keyed by cell (for example Redis GEO or a sharded in-house service), overwriting the latest position and expiring stale drivers with a TTL. Stream raw pings to a log for analytics instead of writing each to the primary database.
How do you shard geospatial data?
By a coarse cell ID or by city/region, so most queries hit one shard. Watch for skew: dense cities need more shards, and queries near a shard boundary must fan out to neighbours.
How do you answer 'k nearest' when you don't know the radius?
Start with a small ring of cells and expand ring by ring (or level by level) until you have at least k candidates and the next ring can't contain anything closer than the current k-th result. Then sort by exact distance.
Straight-line nearest isn't always best for dispatch. How would you improve matching?
Use the spatial index only to get a candidate set, then rank by ETA from a routing service, factoring in road network, direction of travel and traffic. Batch matching across many riders can beat greedy nearest-driver assignment.