Geospatial Indexing
A geospatial index is a data structure that makes location queries fast: "find restaurants within 2 km of me," "which drivers are closest to this pickup point?", "which delivery zone contains this address?" Without one, every such query means scanning every row and computing distances. With one, the database only looks at points that are actually nearby.
The core idea behind almost every approach:
- Map 2D space onto something indexable: Either turn a (latitude, longitude) pair into a single sortable key (geohash, S2 cell ID, H3 cell ID) that a normal B-tree, sorted set or hash map can index, or build a tree that partitions space directly (quadtree, R-tree).
- Prune, then refine: The index returns a small set of candidates from the cells or boxes overlapping the search area. Exact distances are computed only for those candidates, and anything outside the radius is filtered out.
- Trade-offs between approaches: Fixed grids are simple and shard easily; adaptive trees handle uneven density; hexagons make neighbors and aggregation cleaner; databases like PostGIS give you everything (polygons, joins, exact geometry) at the cost of write throughput.
Location comes up constantly in interviews: Yelp and proximity search, Uber and DoorDash dispatch, Tinder-style matching, heatmaps, geofencing and Find My Device. Interviewers expect you to know at least one indexing technique in depth (geohash or quadtree is the classic pair), and strong candidates can compare them and pick the right one for the workload: mostly static places, or millions of moving drivers. See /system-design/proximity-service and /system-design/ride-sharing for full designs.
Why a Normal Index Doesn't Work
The naive approach stores latitude and longitude in two columns, indexes both, and runs:
SELECT id, name FROM places
WHERE lat BETWEEN 37.75 AND 37.80
AND lng BETWEEN -122.45 AND -122.40;
A B-tree on lat can quickly find every row in the latitude band. But that band is a strip that wraps around the entire planet, about 5.5 km tall and 40,000 km long, so it contains every place at that latitude in California, Nevada, Utah and beyond, across the Atlantic and through Asia. The database then filters those rows by longitude. A composite index on (lat, lng) doesn't help either: within each distinct latitude value, rows are sorted by longitude, but a range on the first column still forces a scan through every latitude value in the band. Databases can intersect the two separate indexes, but they still have to read both large strips first.
The fundamental issue is that a B-tree sorts on one dimension, and "nearby" is a two-dimensional idea. Every technique below either finds a one-dimensional ordering that keeps nearby points close together, or uses a tree that splits space in two dimensions at once.
Distance itself is also worth getting right: one degree of latitude is about 111 km everywhere, but one degree of longitude is about 111 km × cos(latitude), so roughly 88 km in San Francisco and 56 km in Oslo. Exact distances use the haversine formula on a sphere (or a geodesic on the ellipsoid when meter-level precision matters).
Geohash
A geohash encodes a location as a short string, like 9q8yy for downtown San Francisco, by recursively halving the world.
But what is actually happening under the hood?
- Split the longitude range [-180, 180] in half. If the point is in the east half, write a 1; otherwise a 0. Narrow the range to that half.
- Do the same for latitude [-90, 90].
- Alternate longitude and latitude bits, halving each range every time.
- Group the bits into 5-bit chunks and write each chunk as one base-32 character.
Each extra character adds 5 bits and shrinks the cell by a factor of 32. Longer geohashes are smaller cells, and every cell is contained in the cell named by its prefix: 9q8yy is inside 9q8y, which is inside 9q8.
| Length | Cell size (approx., at the equator) | Typical use |
|---|---|---|
| 4 | 39 km × 20 km | City-level buckets |
| 5 | 4.9 km × 4.9 km | "Within a few km" searches |
| 6 | 1.2 km × 0.6 km | Neighborhood search, ride dispatch |
| 7 | 153 m × 153 m | Block-level precision |
| 8 | 38 m × 19 m | Building-level |
Cells shrink in width away from the equator, since lines of longitude converge.
The key property: points with a common geohash prefix are close together. So a proximity search becomes a prefix query on a normal index: WHERE geohash LIKE '9q8yy%' on a B-tree, or a range scan in any sorted key-value store (DynamoDB, Cassandra, Bigtable, Redis sorted sets). The interleaved bit order is a Z-order curve (Morton code), a path that zig-zags through the grid and mostly keeps nearby cells near each other in the 1D ordering.
The Edge Problem
"Mostly" is the catch. Two points a few meters apart can sit on opposite sides of a cell boundary and have very different geohashes. In San Francisco, the cell 9q8yy has neighbors 9q8yz to the east, but 9q8zn to the north: the shared prefix drops from four characters to three just by crossing a line. At bigger boundaries it's worse; points on either side of the equator or the prime meridian share no prefix at all.
The fix is standard: search the user's cell plus its eight neighbors, then filter by exact distance. Neighbor cells can be computed directly from the geohash. Choose the precision so a cell is at least as large as the search radius; then any point within the radius is guaranteed to be in one of those nine cells. For a 2 km search, length-5 cells (about 4.9 km) work; for a 500 m search, length 6.
In an interview, say "nine cells, then filter by distance" before your interviewer asks about boundaries. It's the most common follow-up on geohash designs, and answering it up front shows you've actually reasoned through the geometry.
Strengths and Weaknesses
Geohashes are simple, work with any database that can sort strings, and make sharding easy (shard by a geohash prefix). Their weakness is that the grid is fixed: a length-6 cell in Manhattan might hold 5,000 restaurants while a length-6 cell in rural Montana holds none. You can choose different precisions per query, but the cells themselves don't adapt to density. The rectangular cells also vary in shape with latitude, and the Z-order curve has jumps where nearby cells are far apart in the ordering.
Quadtrees
A quadtree partitions space adaptively. Start with one node covering the whole map. When a node holds more than some capacity (say, 100 points), split it into four equal quadrants (NW, NE, SW, SE) and push its points down into them. Repeat recursively. Dense areas end up with deep trees of tiny cells; empty areas stay as a single large leaf.
To find points near a location, walk down from the root to the leaf containing it, then expand to neighboring leaves until you've collected enough candidates or covered the search radius. For k-nearest-neighbor queries ("the 20 closest restaurants"), this adapts naturally: in Manhattan you'll find 20 within a block; in Montana the search keeps widening until it finds them.
A rough size check: 200 million places at 100 per leaf is about 2 million leaves, and around 2.7 million nodes in total. At, say, 100 bytes per node plus 32 bytes per place for an ID and coordinates, that's a few hundred MB for the tree plus about 6.4 GB for the points. That fits in memory on one server, which is why quadtree designs usually build the tree in memory on each read replica, often rebuilding it from the database at startup.
Quadtrees are a great fit for mostly static data with uneven density, like businesses on Yelp. They're a weaker fit for moving objects: a driver who moves may need to be removed from one leaf and inserted into another, splits and merges cascade, and keeping many replicas of a mutable tree consistent is hard. They're also awkward to shard across machines, since the tree's shape depends on the data.
Space-Filling Curves and S2
Geohash's Z-order curve has an improvement: the Hilbert curve, a different 1D path through a 2D grid that never jumps. Consecutive positions on a Hilbert curve are always adjacent cells, so ranges of the 1D key map to more compact regions, and range scans read fewer irrelevant cells.
Google's S2 library uses this idea on a sphere. It projects the Earth onto the six faces of a cube, divides each face with a quadtree, and orders cells along a Hilbert curve, giving every cell a 64-bit ID across 31 levels (from a face down to about a square centimeter). A search area, even an irregular polygon, is approximated by a covering: a small set of cells, possibly at different levels, whose ID ranges you then scan. S2 avoids the distortion of latitude/longitude grids near the poles, and it's used in Google's own products and in databases like MongoDB and CockroachDB for spherical geometry indexing.
In an interview, you don't need S2's details. It's enough to know it exists, that it uses a Hilbert curve for better locality than geohash, and that cell IDs are integers you can store in any sorted index.
H3: Hexagonal Grids
H3 is a hierarchical grid of hexagons created at Uber and now widely used for ride-sharing, delivery and mobility analytics. It covers the globe at 16 resolutions (0 to 15); each cell at one resolution has seven children at the next finer resolution, and cells get a 64-bit ID.
| Resolution | Avg. hexagon area | Typical use |
|---|---|---|
| 7 | about 5 km² | City-district demand |
| 8 | about 0.7 km² | Neighborhood surge pricing, heatmaps |
| 9 | about 0.1 km² (edges around 200 m) | Pickup zones, driver matching |
| 10 | about 0.015 km² | Street-level detail |
Why hexagons? In a square grid, a cell has two kinds of neighbors: four that share an edge and four that touch only at a corner, at different distances from the center. In a hexagonal grid, every neighbor shares an edge and sits at the same distance. That makes a few things clean:
- Rings: "all cells within k steps" (a k-ring) is a good approximation of a circle, so radius searches cover fewer wasted cells.
- Aggregation and smoothing: counting supply and demand per cell and then smoothing across neighbors (for surge pricing or a driver heatmap) treats every direction equally.
- Movement analysis: paths between cells and flows between neighbors don't have the diagonal artifacts of squares.
The trade-off is that hexagons can't be perfectly subdivided into smaller hexagons, so H3's children only approximately cover their parent. That's fine for aggregation, but it means H3 isn't a strict containment hierarchy like a quadtree or S2, and exact polygon containment still needs a geometry check.
For ride-sharing and delivery questions, H3 is often the strongest choice to name: index drivers by H3 cell at resolution 8 or 9, search the rider's cell plus a k-ring, and reuse the same cells to aggregate demand for surge pricing. One indexing scheme covers dispatch and analytics.
R-Trees and PostGIS
The other big family doesn't map points to cells at all. An R-tree groups nearby objects into bounding rectangles, groups those rectangles into bigger rectangles, and so on up to a root, like a B-tree for boxes. A query descends only into rectangles that overlap the search area. R-trees handle not just points but lines and polygons (roads, delivery zones, building footprints, country borders), which grid indexes don't handle naturally.
PostGIS, the geospatial extension for PostgreSQL, is the most common way to get this in an interview design. It adds geometry and geography types, hundreds of spatial functions and R-tree-like indexes through Postgres's GiST framework:
CREATE TABLE places (
id bigserial PRIMARY KEY,
name text,
kind text,
geom geography(Point, 4326)
);
CREATE INDEX places_geom_idx ON places USING GIST (geom);
-- Coffee shops within 1 km, nearest first
SELECT id, name, ST_Distance(geom, ST_MakePoint(-122.4194, 37.7749)::geography) AS meters
FROM places
WHERE kind = 'coffee'
AND ST_DWithin(geom, ST_MakePoint(-122.4194, 37.7749)::geography, 1000)
ORDER BY geom <-> ST_MakePoint(-122.4194, 37.7749)::geography
LIMIT 20;
-- Which delivery zone contains this address? (geofencing)
SELECT zone_id FROM delivery_zones
WHERE ST_Contains(boundary, ST_SetSRID(ST_MakePoint(-122.41, 37.78), 4326));
ST_DWithin uses the index to find candidates within the bounding box of the radius and then checks the exact distance; the <-> operator does index-assisted nearest-neighbor ordering. Postgres can combine all of this with ordinary filters, joins and transactions.
PostGIS is the right answer when data is mostly static, queries involve polygons or complex filters, and the write rate is moderate. It's the wrong answer for a million drivers updating their location every few seconds: every update rewrites a row and its index entries, and a single Postgres primary won't absorb hundreds of thousands of index updates per second.
Other databases have their own geospatial indexes: Elasticsearch and OpenSearch index geo_point and geo_shape fields with BKD trees and are a good choice when location is one filter among full-text and faceted search ("Thai restaurants open now within 3 km, rated above 4"). MongoDB has 2dsphere indexes built on S2 cells.
Redis GEO
Redis has a built-in geospatial API on top of sorted sets:
GEOADD drivers:sf -122.4194 37.7749 driver:48213
GEOADD drivers:sf -122.4102 37.7835 driver:91022
GEOSEARCH drivers:sf FROMLONLAT -122.4150 37.7800 BYRADIUS 2 km ASC COUNT 20 WITHDIST
But what is actually happening under the hood? GEOADD computes a 52-bit interleaved geohash of the coordinates and stores the member in a sorted set with that number as its score. Because the score is a geohash, nearby points have nearby scores. GEOSEARCH works out which geohash cells cover the search radius (the center cell and its neighbors at a suitable precision), does a range lookup on the sorted set for each, and filters the results by exact distance. It's the geohash technique, implemented for you in memory.
That makes Redis a natural fit for moving objects:
- Updates are O(log N) in memory, so a single Redis node can absorb on the order of 100,000 location updates per second.
- Searches over the nearby candidates take well under a millisecond.
- Stale entries can be handled by storing each driver's last update time in a separate key or hash, and filtering or periodically removing drivers who haven't reported in, say, 30 seconds (individual sorted-set members can't have their own TTL).
Since all members of one key live on one Redis node, you shard by geography: one key per city, or per coarse geohash or H3 cell, so each node holds a manageable set of drivers and searches stay local. A search near a shard boundary queries the neighboring shard's key too. See /system-design/redis.
Choosing an Approach
| Geohash | Quadtree | S2 / Hilbert | H3 | PostGIS (R-tree) | Redis GEO | |
|---|---|---|---|---|---|---|
| What it is | Fixed grid, string or integer key | Adaptive in-memory tree | Hierarchical cells on a sphere | Hierarchical hexagons | Database with spatial index | Geohash on sorted sets |
| Storage | Any sorted index | Custom, in memory | Any sorted index | Any key-value or sorted index | Postgres | Redis |
| Uneven density | Pick precision per query | Adapts automatically | Coverings mix levels | Pick resolution | Adapts | Fixed precision |
| Polygons | Approximate with cells | Possible, unusual | Good coverings | Polyfill into cells | Native, exact | No |
| High write rate | Good | Poor (tree updates) | Good | Good | Moderate | Excellent |
| Typical use | Proximity search in any DB | Static places (Yelp) | Global mapping, Google-scale geo | Ride-sharing, delivery, heatmaps | Geofencing, rich queries | Live driver locations |
A useful way to decide in an interview:
- Mostly static points, rich filters, moderate scale (restaurants, hotels): PostGIS or Elasticsearch, with read replicas and a cache for popular areas. A geohash column on any database works too.
- Static points, huge read volume, uneven density: an in-memory quadtree on read replicas, or geohash cells precomputed into a cache.
- Moving objects at high update rates (drivers, couriers, devices): Redis GEO or an in-memory grid (geohash or H3) sharded by region.
- Aggregation and analytics over areas (surge pricing, heatmaps, demand forecasting): H3 cells as the grouping key.
- Polygons (delivery zones, geofences, service areas): PostGIS, or precompute which H3 or S2 cells each polygon covers and look up by cell, with an exact check for points near the edge.
Moving Objects at Scale
The hardest version of geospatial indexing is the one ride-sharing interviews ask about, so let's size it. Suppose 1 million active drivers each send a location every 4 seconds. That's 250,000 writes per second, each one moving a driver within the index. Riders request matches at a much lower rate, perhaps a few thousand per second.
The workload is write-heavy, so the design looks like this:
- Keep the live index in memory, sharded by geography: Redis GEO keys per city or region, or a custom service holding an H3-cell → drivers map per shard. Writes go to the shard owning the driver's current cell.
- Don't write every update to a database. The live index only needs the latest position. Persist location history asynchronously through a stream like Kafka for trip records and analytics.
- Handle cell changes. When a driver crosses into a cell owned by another shard, remove them from the old shard and add them to the new one. With cells sized at a few hundred meters, a driver changes cells only every minute or so, so cross-shard moves are a small fraction of updates.
- Handle hot spots. A stadium letting out or an airport queue concentrates thousands of drivers in a few cells. Use finer cells there (H3 resolution 9 or 10 instead of 8), or split hot regions across more shards.
- Expire stale drivers. A driver whose app crashed shouldn't receive dispatches; filter by last-update time.
For a rider search, the dispatcher takes the rider's cell plus a k-ring of neighbors, fetches drivers from those cells, filters by exact distance and availability, and then ranks candidates by estimated time of arrival from a routing service, not straight-line distance. The index's job is only to shrink a million drivers to a few dozen candidates in a millisecond.
Geospatial Indexing in an Interview
When to Use It
- Proximity search: Yelp, nearby friends, store locators, "restaurants near me." See /system-design/proximity-service.
- Matching supply and demand by location: ride-sharing, food delivery, couriers, Tinder-style discovery. See /system-design/ride-sharing and /system-design/food-delivery.
- Aggregating by area: heatmaps, surge pricing, demand forecasting, live maps of activity.
- Geofencing: delivery zones, service areas, entering or leaving a region, location-based compliance.
Knowing Its Limitations
- Cells are approximations. Every grid method returns candidates that must be filtered by exact distance, and every method must handle cell boundaries (neighbors, k-rings or coverings).
- Straight-line distance isn't travel time. For dispatch, the index narrows candidates; a routing engine computes real ETAs.
- Density varies by orders of magnitude. A fixed precision that works in a suburb returns thousands of candidates downtown; use adaptive structures or per-area precision.
- Write-heavy workloads need in-memory indexes. Disk-based spatial indexes in a relational database don't keep up with millions of frequently moving objects.
- Projections and the poles. Latitude/longitude grids distort away from the equator, and the antimeridian (±180° longitude) breaks naive range math. S2 and H3 handle the sphere properly.
Questions You Might Get
- "How does a geohash work, and what's wrong with a prefix search alone?" Interleave halving bits of longitude and latitude and encode them in base 32; shared prefixes mean shared cells. But nearby points across a cell boundary can have different prefixes, so search the cell and its eight neighbors and filter by distance.
- "Geohash or quadtree?" Geohash for simplicity, any database and moving objects; quadtree for static points with very uneven density and k-nearest queries, held in memory.
- "How would you track a million moving drivers?" In-memory geospatial index (Redis GEO or an H3 cell map) sharded by region, about 250,000 updates per second, latest position only, history to Kafka, stale drivers filtered by timestamp.
- "How do you know which delivery zone an address is in?" PostGIS
ST_Containswith a GiST index on zone polygons, or precompute the H3 cells each zone covers and look up the address's cell, with an exact check near boundaries.
Summary
Geospatial indexes turn "what's near here?" from a full scan into a lookup of a few cells or tree nodes followed by an exact distance filter. Geohash and S2 map locations to sortable keys along space-filling curves, quadtrees and R-trees split space adaptively, H3 uses hexagons whose equidistant neighbors make radius searches and aggregation clean, and PostGIS and Redis GEO package these ideas into databases you can drop into a design.
In an interview, pick based on the workload: PostGIS or Elasticsearch for static places with rich queries, a quadtree for static points with uneven density at high read volume, Redis GEO or an in-memory H3 grid sharded by region for moving objects, and H3 cells for anything involving aggregation by area. Then handle the details that interviewers probe: cell boundaries, density hot spots and the difference between distance and travel time.