1. What It Is
Every near me feature, from nearby drivers to restaurants to friends to bikes, needs the same primitive, which is finding the few points around a location without scanning every row. Geospatial indexing turns a two dimensional position into a cell identifier so that an ordinary key lookup returns the candidates, and an exact distance check finishes the job.
What:
A way to map a latitude and longitude to a cell ID (geohash string, quadtree leaf, S2 cell ID, H3 index) or to a bounding box in a tree (R-tree), so that points close in space share a cell or sit in neighbouring cells.
Primary purpose:
Answer "what is within r of here" and "which k are nearest" in milliseconds, with work proportional to the cells touched rather than the table size.
Usually used for:
Driver and courier matching, nearby search for businesses and friends, geofencing, surge zones and heatmaps, ETA caching, and sharding location traffic by region.
2. Core Mental Model
Think of a map cut into labelled tiles. The label is a key, so finding points near you is a lookup of your tile and the tiles around it, followed by an exact distance check. The tile size is the knob that trades candidates fetched against lookups performed.
π§© Cell ID
Quantize the plane into cells, give each a sortable ID, and store points under the ID of the cell they fall in. A key or range lookup on the ID is a spatial lookup.
π² Cell plus neighbours
A point near an edge has its closest neighbours in the next cell, so a query always reads the home cell and the ring around it, never the home cell alone.
π Exact distance last
Cells are rectangles or hexagons rather than circles, so they only shortlist candidates. The haversine formula, which gives the great-circle distance between two latitude and longitude pairs, decides the final answer and the order.
In the room
Say the recipe in four beats: find the cell and its neighbours, fetch candidates, compute exact great-circle distance, sort and cut off. Then volunteer how you pick the cell size from the radius and what happens in a dense downtown cell. Name one structure and give a reason, for example geohash for static data and prefix scans, H3 for moving drivers and surge.
3. Why It Matters in HLD
Why a latitude and longitude index cannot answer near me
A B-tree sorts keys along one dimension. A composite index on (lat, lng) can narrow latitude to a range, but every row in that band is contiguous in the index no matter its longitude, so the longitude test becomes a filter applied while scanning the whole band. A 5 km radius needs a band 10 km tall, which is 10 / 111 = 0.09 degrees out of 180, or 0.05 percent of the latitude range. Even if 200M rows were spread evenly across latitude, that band holds 200M x 0.0005 = 100,000 rows that are scanned to find a few hundred, and real data is clumpier so it is worse. Two separate single column indexes fare no better, because each returns a huge strip (a band around the world and a band from pole to pole) and the engine must intersect them.
The root cause is that nearness in two dimensions has no one dimensional order. Cell IDs fix this by giving points in the same area the same key or a contiguous key range, so a B-tree, a Redis sorted set or a hash map becomes useful again. This is the same move as in Indexing and Query Optimization: pick an index whose ordering matches the access pattern.
Needed When:
The product says nearby, closest, within a zone, or in this area, and the data set or the update rate is too large for a scan.
Avoids:
Full table scans, latitude band scans, rectangle corners returning wrong answers, and one overloaded shard holding a whole city.
Optimizes For:
Query latency that depends on cells touched, cheap location updates for moving objects, and shard keys that keep nearby data together.
4. Architecture & Data Flow
Step 1 (index): encode every point at one fixed level and store its ID under that cell. Step 2 (query): encode the query point at a level chosen from the radius. Step 3 (neighbours): add the ring of surrounding cells. Step 4 (candidates): fetch every point stored in those cells. Step 5 (exact): compute the haversine distance, drop anything beyond the radius, sort, and cut off.
How a geohash is built
A geohash halves the longitude range and the latitude range in turn and records one bit per halving, 1 for the upper half and 0 for the lower half. The bits are interleaved with longitude first, then every 5 bits become one base 32 character from the alphabet 0123456789bcdefghjkmnpqrstuvwxyz (digits and lowercase letters without a, i, l and o). Each extra character adds 5 bits and divides the cell area by 2^5 = 32.
Encode latitude 42.6, longitude -5.6 at length 5 (25 bits) longitude -5.6 in [-180, 180]: 0 1 1 1 1 1 0 0 0 0 0 0 0 (13 bits) step 1: -5.6 >= 0 ? no, bit 0, keep [-180, 0] step 2: -5.6 >= -90 ? yes, bit 1, keep [-90, 0] and so on latitude 42.6 in [-90, 90]: 1 0 1 1 1 1 0 0 1 0 0 1 (12 bits) interleave, longitude first: 0110111111110000010000010 5-bit groups: 01101 11111 11000 00100 00010 values: 13 31 24 4 2 base 32 digits: e z s 4 2 gives "ezs42"
Two properties drive every geohash design. Prefix means containment, since every point hashed to 9q8yy lies inside the cell 9q8yy, which lies inside 9q8y, so a prefix match is a range scan that an ordinary B-tree serves. The converse is false, which is the boundary problem. Two points a few metres apart on opposite sides of a cell edge can share no prefix at all. For example, at latitude 37.7749 the points at longitude -0.0001 and +0.0001 are about 18 m apart (0.0002 x 111.32 km x cos 37.77 degrees = 0.0176 km) yet hash to eyxyzu and sn8nbh at length 6, because crossing the prime meridian flips the very first bit. That is why a query reads the home cell and its 8 neighbours, never one prefix alone.
The nearest neighbour recipe
type LatLng = { lat: number; lng: number };
type Place = LatLng & { id: string };
const EARTH_RADIUS_KM = 6371;
const rad = (deg: number) => (deg * Math.PI) / 180;
function haversineKm(a: LatLng, b: LatLng): number {
const dLat = rad(b.lat - a.lat);
const dLng = rad(b.lng - a.lng);
const h = Math.sin(dLat / 2) ** 2
+ Math.cos(rad(a.lat)) * Math.cos(rad(b.lat)) * Math.sin(dLng / 2) ** 2;
return 2 * EARTH_RADIUS_KM * Math.asin(Math.sqrt(h));
}
function findNearby(center: LatLng, radiusKm: number, limit: number): Place[] {
const level = levelForRadius(radiusKm, center.lat); // 1. pick the cell size
const cells = cellWithNeighbours(center, level); // 2. home cell plus the ring
const candidates = cells.flatMap((cell) => index.get(cell) ?? []); // 3. fetch
return candidates
.map((place) => ({ place, km: haversineKm(center, place) })) // 4. exact distance
.filter((hit) => hit.km <= radiusKm) // drops the rectangle corners
.sort((x, y) => x.km - y.km) // 5. sort, then cut off
.slice(0, limit)
.map((hit) => hit.place);
}In the room
Draw the 3 by 3 block, mark the query circle crossing a cell edge, and say why the neighbours are mandatory. Then say the cell index only shortlists. The haversine pass gives the real distance and the order, and any category or rating filter runs on the shortlist before the final cut.
5. Key Characteristics
Five structures cover almost every interview. They differ in cell shape, whether cells adapt to density, and what they shard well:
| Structure | Shape | Adapts | Best |
|---|---|---|---|
| Geohash | Lat/lng rectangles, base 32 string, Z-order curve | No, one size per length | Prefix range scans on any B-tree, Redis keys, cheap sharding by prefix |
| Quadtree | Recursive quarters, split when a leaf exceeds a threshold | Yes, deep in cities and shallow in deserts | In-memory index over very uneven point density |
| S2 | Cube faces projected on a sphere, 64-bit IDs along a Hilbert curve, levels 0 to 30 | Per query, via mixed-level coverings | Region coverings, global data, ID range scans in a sorted store |
| H3 | Hexagons (plus 12 pentagons), 64-bit index, resolutions 0 to 15 | No, one size per resolution | Uniform neighbours, ring search, surge and heatmap aggregation |
| R-tree | Nested bounding rectangles, balanced tree | Yes, follows the data | Polygons and rectangles inside a database (PostGIS GiST) |
Geohash cell size by length
Sizes below are at the equator. A degree of longitude shrinks by cos(latitude), so at San Francisco a length 5 cell is 4.89 x 0.79 = 3.9 km wide and still 4.9 km tall. Longitude spans 360 degrees against 180 for latitude, so even lengths (equal bits on each axis) are twice as wide as tall, while odd lengths get one extra longitude bit and come out close to square.
| Length | Bits | Cell (width by height) | Typical use |
|---|---|---|---|
| 1 | 5 | 5,000 km by 5,000 km | Continent scale, almost never queried directly |
| 2 | 10 | 1,250 km by 625 km | Country or large region |
| 3 | 15 | 156 km by 156 km | Region or state |
| 4 | 20 | 39 km by 19.5 km | Metro area, a good shard prefix |
| 5 | 25 | 4.9 km by 4.9 km | District search, radii up to a few km |
| 6 | 30 | 1.2 km by 0.6 km | Walking distance, ETA cache cells |
| 7 | 35 | 153 m by 153 m | Street level |
| 8 | 40 | 38 m by 19 m | Building level |
| 9 | 45 | 4.8 m by 4.8 m | Doorway or parking space |
Quadtree
A quadtree starts with one node for the whole area and splits a node into four quadrants when it holds more than a threshold of points, for example 100 as in Proximity Server and Ride-Hailing Service (Uber). Dense downtowns end up deep and empty oceans stay shallow, which a fixed grid cannot do. Each level halves the cell width, so from a world 40,075 km wide it takes 13 levels to reach about 4.9 km (40,075 / 2^13 = 4.9), and a dense district simply keeps splitting. Search walks from the root, prunes boxes that miss the circle, and collects points from the leaves that intersect it. With 200M points and a threshold of 100 there are at least 200M / 100 = 2M leaves. It lives in memory, so it suits read-heavy catalogs that are rebuilt nightly with incremental updates in between.
S2
S2 projects the Earth onto the six faces of a cube and recursively quarters each face, so there is no polar blow-up. Levels run from 0 (a whole face, about 85 million km2) to 30 (about 0.7 cm2), and a level k cell has an average area of 510 million km2 / (6 x 4^k), which is about 5 km2 at level 12 and about 0.02 km2 at level 16. Cells are numbered along a Hilbert curve, which preserves locality better than geohash's Z-order, which has long ID jumps between adjacent cells at the big quadrant boundaries. A parent's ID range contains its children, so a circle or polygon becomes a bounded covering of mixed-level cells and each covering cell is one contiguous ID range to scan in a sorted store. MongoDB's 2dsphere index is built on S2 cells. Elsewhere S2 is usually a library that your application calls rather than a database feature, and in interviews it is the answer for polygons and global data.
H3
H3 tiles the globe with hexagons, plus 12 pentagons per resolution to close the shape, across resolutions 0 to 15. Every neighbour of a hexagon is the same centre distance away, whereas a square has diagonal neighbours sqrt(2) = 1.41 times farther than edge neighbours. A k-ring, which is the cell plus every cell within k steps of it, is therefore a fair stand-in for a circle and contains 3k^2 + 3k + 1 cells, which is 7 for k = 1, 19 for k = 2 and 37 for k = 3. Uniform neighbours and similar areas per resolution are why surge pricing, supply and demand ratios and heatmaps use hexagons, since a per-cell value has no corner bias. The hierarchy is approximate, because a child hexagon is not exactly inside its parent, so use H3 for neighbourhoods and aggregation rather than strict containment.
| Resolution | Average area | Average edge | Typical use |
|---|---|---|---|
| 7 | about 5.16 km2 | about 1.41 km | Surge pricing zones, dispatch zones, traffic partitions |
| 8 | about 0.74 km2 | about 531 m | Highway tracking, coarser dispatch zones |
| 9 | about 0.105 km2 | about 201 m | Dense urban driver matching, cell to cell ETA matrix |
| 10 | about 0.015 km2 | about 76 m | Fine sharding of very dense areas |
R-trees in databases
An R-tree is a balanced tree where each node stores the bounding rectangle of its children and leaves store the bounding boxes of real objects. Boxes may overlap, so a search can descend a few branches, but it still touches a tiny part of the tree. PostGIS builds it through GiST indexes and MySQL spatial indexes are R-trees. Because it indexes extents rather than points, it handles polygons and lines, and it adapts to density. The costs are rebalancing on writes and the fact that you cannot shard it by a simple key. The Geofencing Service uses it to cut 100M fences to 10 to 50 candidates before ray casting confirms the hit.
6. Strategic Tradeoffs
Cells trade exactness and uniformity for speed and shardability, so we state both sides:
| Benefit | Cost |
|---|---|
| Key lookups instead of scans (a spatial query becomes 9 or so ordinary lookups on a hash map, sorted set or B-tree) | Over-fetch and an exact pass (cells are not circles, so corners return extra candidates that haversine must discard) |
| Fixed grids are easy to shard, cache and precompute (a cell ID is a plain key for routing, caching and ETA matrices) | One cell size cannot fit downtown and the desert (a quadtree adapts, but it is a stateful in-memory structure you must rebuild and shard yourself) |
| Hexagons give uniform neighbours (every neighbour is the same distance away, so ring expansion and heatmaps are fair) | Library and hierarchy cost (H3 needs a library, and a child hexagon is only approximately inside its parent, unlike a geohash prefix) |
Sharding has its own tradeoff. Sharding by cell prefix keeps neighbours on the same shard so a query touches one or two shards, but it concentrates a busy city on one machine. Hashing the cell balances load, but a ring query now fans out to as many as 9 shards. The usual answer is range or prefix sharding with a split plan for hot prefixes, as covered in Database Sharding and Partitioning. In most interviews the pragmatic default is geohash or H3 in Redis for moving points, a geohash column or quadtree for static catalogs, and PostGIS or S2 only when shapes appear.
7. Failure / Bottleneck Awareness
Boundary misses, mis-sized cells, hot downtown cells and stale positions are the usual traps, so we name the mitigation for each:
Problem: Querying only the home cell misses a point 40 m away across a cell edge. Cells also wrap at longitude 180, and they shrink toward the poles, so the edge cases are not only local.
Mitigation: Always read the home cell plus its ring, verify with haversine, and test at cell borders and the antimeridian. Redis GEO rejects latitudes beyond about 85.05 degrees, which is fine for cities.
Problem: Cells far larger than the radius return huge candidate sets, and cells far smaller force dozens or hundreds of lookups (99 instead of 9 in the diagram above). Cutting the list by cell order before measuring distance also lets far points displace near ones.
Mitigation: Derive the level from the radius, cap the covering cell count, alert on p99 candidate count per query, and always sort by exact distance before the cut off.
Problem: A stadium event or rush hour puts a disproportionate share of writes and reads on one cell, so its shard saturates while others idle.
Mitigation: Split the hot cell into its 32 children, salt keys inside it, add read replicas, and stretch client update intervals at peak. The deep dive walks through each option.
Problem: A driver whose app crashed stays in a cell forever, and a delayed ping can move a driver backwards in time.
Mitigation: Expire members after a short silence (for example 60 seconds without telemetry removes a driver from availability sets), and ignore pings with an older sequence number than the stored one.
8. Common HLD Usage
Matching, nearby search, geofencing, ETA caching and fleet maps all reuse the same cell ideas, so these are the designs to link to when the question arises:
| Design | Spatial pattern | Rationale |
|---|---|---|
| Ride-Hailing Service (Uber) | H3 resolution 9 cells in Redis sets, k-ring expansion from the pickup cell, surge on resolution 7 clusters | Uniform neighbours make ring growth predictable, and ranking by routing ETA happens after the cell lookup. |
| Proximity Server | Geohash length 5 index with the home cell plus 8 neighbours (more cells as the radius nears the cell size), then haversine. Redis GEO keys per city and geohash prefix for Nearby Friends | Static catalog reads and moving friend writes are different workloads, so they get different indexes. |
| Food Delivery | Redis GEO of available dashers per city, dispatch workers keyed by H3 resolution 7 zone | One writer per zone serializes assignment, and the zone doubles as the Kafka partition key. |
| Geofencing Service | R-tree over fence bounding boxes, then point-in-polygon, partitioned by geohash region | Fences are polygons rather than points, so a bounding box tree shortlists them and ray casting confirms. |
| Map Rendering and Navigation | z/x/y tile pyramid (each tile splits into four) and traffic telemetry partitioned by H3 resolution 7 | The tile scheme is quadtree shaped, and spatial partitioning spreads dense metro traffic across Kafka partitions. |
| Foursquare Check-ins | PostGIS for admin queries, Elasticsearch geo_distance for search, haversine 200 m check at check-in, trending keys sharded by geohash prefix | Search wants filters and 10K QPS, while the exact distance check guards against spoofed check-ins. |
| ETA Calculation Service | Geohash length 6 origin and destination as the cache key, H3 resolution 9 cell to cell ETA matrix | Snapping points to cells turns near-identical requests into cache hits and makes matching an O(1) lookup. |
| Real-Time Vehicle Tracking | Dashboards subscribe to geohash scoped Redis Pub/Sub channels for their viewport | A map only needs vehicles in view, so cells bound the fan out instead of broadcasting every ping. |
| Bike Sharing System | PostGIS GiST index (or a Redis GEO set) over about 5,000 stations | A small static set needs no clever cell scheme, which is a good thing to say out loud. |
9. Decision Signals
Pick the structure from the workload, which means moving or static points, points or shapes, and how uneven the density is:
| Use case | Reach for | Why |
|---|---|---|
| Nearby drivers or couriers (millions of moving points) | H3 or geohash cells in Redis, ring or neighbour lookup | In-memory, and a ping is one cheap move between two cell sets |
| Static catalog such as restaurants, radius search | Geohash column with a prefix range scan, or an in-memory quadtree | Reads dominate, and a quadtree adapts to dense cities |
| Nearby friends (moving, small candidate set) | Redis GEO sharded by city and prefix | GEOSEARCH is built in, and a sweeper expires stale members |
| Surge, supply and demand heatmaps | H3 resolution 7 and a GROUP BY cell | Uniform neighbours and near-equal cell areas make comparisons fair |
| Polygons: geofences, delivery zones, neighbourhoods | R-tree (PostGIS GiST) or an S2 covering | Point cell indexes cannot hold shapes, so use bounding boxes or covered cell sets |
| Global data in a sorted key store | S2 cell ID ranges | Hilbert ordering turns a region into a few contiguous ID ranges |
| Cache key for near-identical location queries | Geohash length 5 or 6, or H3 resolution 8 or 9 | Quantizing the point converts many distinct requests into one key |
| A few thousand fixed points | Any spatial index or even a scan | At this size the simplest option wins |
- Geohash when you want cell IDs in any database column, prefix range scans, or a simple shard prefix.
- Quadtree when density varies wildly and the catalog is read-heavy enough to hold in memory.
- H3 when you need uniform neighbours, ring expansion, or per-cell aggregates such as surge.
- S2 when regions are polygons, the data is global, or you scan ID ranges in a sorted store.
- R-tree when objects have extent (fences, zones) and a database index is acceptable.
- Proposing a B-tree on (lat, lng) and calling the search done, or querying only the home cell.
- Writing every location ping to a disk index when only the latest position matters.
- Using one cell size for downtown and the countryside, or forgetting that a cell is narrower than it is tall away from the equator.
- Cutting the candidate list before computing exact distance, and skipping the haversine pass.
11. Deep Dive (Optional)
Choosing a cell size from the query radius
The rule is to take the coarsest level whose shorter cell edge, measured at your latitude, is at least the radius. A circle of radius r around any point in the home cell then reaches at most r past the home cell boundary, which is inside the ring of 8 neighbours, so 9 cells always cover it. The tradeoff is candidates against lookups, shown with a 3 km radius at San Francisco.
Length 5: cell 3.87 km wide by 4.88 km tall, shorter edge 3.87 km >= 3 km, so 9 cells cover it block = (3 x 3.87) by (3 x 4.88) = 11.6 km by 14.6 km = about 170 km2 circle = pi x 3^2 = 28.3 km2, so 28.3 / 170 = 17% of the fetched points survive Length 6: cell 0.97 km wide by 0.61 km tall rings needed: ceil(3 / 0.97) = 4 east and west, ceil(3 / 0.61) = 5 north and south cells = (2 x 4 + 1) x (2 x 5 + 1) = 9 x 11 = 99, area = 99 x 0.59 = 58.4 km2 28.3 / 58.4 = 48% survive, but that is 99 lookups instead of 9 H3 resolution 9: cell width (flat to flat) about sqrt(2 x 0.105 / 1.732) = 0.35 km 1 km radius: ceil(1 / 0.35) = 3 rings, plus 1 for the point's offset in its cell = k 4 cells = 3 x 4^2 + 3 x 4 + 1 = 61
A 5 km radius is the borderline case at length 5, because the cell is only 4.9 km tall at best and 3.9 km wide at San Francisco, so read the larger 5 by 5 block or the full covering set rather than 9 cells. At length 6 the same 5 km search is a 10 km by 10 km box over 1.2 km by 0.6 km cells, which is about 140 cells as in Proximity Server, so the finer length trades 9 or 25 lookups for about 140 and far less over-fetch. For k nearest instead of within r, expand ring by ring and stop once the k-th best distance is no larger than j x (shorter cell edge) after ring j, because every point outside that block is at least that far from the query. Redis GEOSEARCH BYRADIUS chooses the cell size and does the neighbour reads for you by checking the home area plus its 8 neighbours and discarding anything outside the circle. With COUNT but without ANY it still collects and sorts every member inside the radius, so a tiny COUNT over a huge radius is slow.
Haversine, with arithmetic
a = sin^2(dLat / 2) + cos(lat1) x cos(lat2) x sin^2(dLng / 2) d = 2 x R x asin(sqrt(a)) R = 6,371 km, the mean Earth radius San Francisco (37.7749, -122.4194) to Oakland (37.8044, -122.2712) dLat = 0.0295 degrees = 0.000515 rad, dLng = 0.1482 degrees = 0.002587 rad sin^2(dLat / 2) = 0.0000000663 cos(lat1) x cos(lat2) = 0.7904 x 0.7901 = 0.6245 sin^2(dLng / 2) = 0.000001673, times 0.6245 = 0.000001045 a = 0.0000000663 + 0.000001045 = 0.000001111, sqrt(a) = 0.001054 d = 2 x 6371 x 0.001054 = 13.4 km
Haversine treats Earth as a sphere, so it can be off by a fraction of a percent against the true ellipsoid, which is irrelevant for ranking nearby places. At city scale a flat approximation (scale longitude by cos of latitude, then Pythagoras) is also fine, but haversine stays correct near the antimeridian and for long distances, and it is cheap enough to run on a few hundred candidates.
Indexing fast moving objects
A driver pings every 4 seconds, so 2M active drivers produce 2M / 4 = 500K updates per second, or 500K x 86,400 = 43.2 billion pings a day, about 4.3 TB at 100 bytes each. Every ping overwrites a position that is stale within seconds, so pushing each one through a disk B-tree or PostGIS index buys random page writes, WAL traffic and index maintenance for data nobody reads again. Keep only the latest position in memory, as an in-process grid (cell ID to a set of driver IDs), Redis sets per cell as in Ride-Hailing Service (Uber), or a Redis GEO key per city. The live index is small, since 2M drivers x 64 bytes = 128 MB, and a ping that stays inside its cell only refreshes a timestamp. History goes to a Kafka topic and a batched append to Cassandra or a time-series store, off the matching path.
Redis GEO members are sorted set entries and cannot carry their own TTL, so pair the GEO key with a second sorted set scored by last-seen time and sweep it, or rotate keys per time bucket and let EXPIRE drop whole keys. The Proximity Server Nearby Friends design uses the sweeper with a 15 second expiry.
GEOADD drivers:sf -122.4194 37.7749 driver_42
ZADD drivers:sf:seen {now_epoch} driver_42
GEOSEARCH drivers:sf FROMLONLAT -122.4194 37.7749 BYRADIUS 3 km ASC COUNT 20 WITHDIST
# sweeper: find members silent since the cutoff, then remove them from both keys
ZRANGEBYSCORE drivers:sf:seen -inf {cutoff_epoch}
ZREM drivers:sf driver_42
ZREM drivers:sf:seen driver_42Sharding by cell and splitting hot cells
Route by a cell prefix and keep the prefix to shard map in a small config that every gateway caches, using a directory or consistent hashing so a new shard takes few prefixes. When a prefix runs hot, apply these in order of cost. First, split it one level, because a geohash cell has 32 children (9q8yy0 to 9q8yyz, each about 1.0 km by 0.6 km at this latitude) and a quadtree leaf has 4, and route the children by hash so the load spreads. Second, split by load rather than area, which is what an adaptive quadtree does when a leaf passes its threshold. Third, salt write-heavy keys inside the cell (cell plus id mod 4) and merge the sub-keys on read. Fourth, cut the load itself with read replicas and longer client update intervals at peak, as the Proximity Server design does with 10 seconds. Split along the same boundaries your queries use, so a typical query still touches few shards.
Review
How helpful was this walkthrough?
Click a star to rate. We actively use this feedback to refine and update our system design content.
Discussion
Share your thoughts, ask questions, or help others.