Skip to content

Geospatial Indexing and Proximity Search

Advanced 45 min read Part 9 of 18

Why lat/long B-tree indexes fail, and how geohash, quadtrees, S2, H3, R-trees, PostGIS, Redis GEO and Elasticsearch find nearby things, even moving ones.

Summary#

Proximity search means finding things near a location: the drivers within 2 km of a rider, the restaurants near a user, or the people near a venue. It looks easy, but an ordinary database index cannot do it well. A B-tree sorts on one value at a time, so an index on latitude, or on (latitude, longitude), returns a long thin strip of the planet, and the database must compute the distance to every row in it. The root problem is that a one-dimensional sort order cannot preserve two-dimensional closeness. Production systems recover closeness in one of two ways. Spatial trees build an index that understands space: quadtrees split the map into four quadrants recursively, k-d and BKD trees split at the median one dimension at a time, and R-trees group objects into nested bounding rectangles and handle shapes such as delivery zones. PostGIS (an R-tree through GiST) and Elasticsearch (BKD trees) use these. Encoded keys turn each location into one sortable number or string that an ordinary index can handle: geohash interleaves latitude and longitude bits, S2 maps the sphere onto a cube and a Hilbert curve, and H3 uses hexagons. Redis GEO stores geohashes as sorted-set scores. Whichever you choose, the index only produces candidates: you query a small patch, usually the cell plus its neighbours to avoid missing points just across a boundary, then post-filter by exact distance. Use a spatial tree for polygons and containment, and encoded cells for points that move constantly, such as drivers sending updates every few seconds.

Why It Exists#

Databases are very good at one-dimensional range queries. "Users aged 20 to 25" is fast because a B-tree keeps keys sorted, so 20 sits next to 21 on the same page, and the query is one seek followed by a short sequential read. See Database Indexing.

Location is different. A position has two numbers, latitude and longitude, and the question you care about is a distance that depends on both. Any way of sorting points into a single line puts some neighbours far apart: two shops across the street from each other may sit millions of rows apart in an index sorted by latitude, if one is a little further north than thousands of shops on the other side of the world.

Location queries are everywhere:

  • Ride-hailing and delivery: find available drivers or couriers near a pickup point, with positions changing every few seconds.
  • Local search and reviews: restaurants within 5 km, sorted by rating, filtered by cuisine and opening hours.
  • Social and dating apps: people within a chosen distance.
  • Geofencing: is this phone inside the airport, this delivery address inside a store's zone, this vehicle outside its permitted region?
  • Maps: which roads, buildings and labels fall inside the visible map tile?
  • Analytics: demand per neighbourhood, heat maps, surge pricing by area.

The volumes are large. A local-search service may hold 200 million businesses and serve 5,000 searches per second. A ride-hailing service may have a million active drivers, each sending a location every 4 seconds, which is 250,000 index updates per second. A plain table scan with a distance calculation per row is hopeless at both scales, so the job of a geospatial index is to turn "check every row" into "check a small candidate set", which exact geometry then finishes.

How It Works#

Why a lat/long B-tree index fails#

Suppose a table of 10 million drivers worldwide, with lat and lng columns, and the query "drivers within 2 km of (40.7580, −73.9855)", a point in Times Square.

An index on latitude. 2 km is about 0.018 degrees of latitude, so the query becomes lat BETWEEN 40.740 AND 40.776. The index finds that band quickly, but the band runs around the whole planet: it contains every driver at that latitude in New York, Madrid, Beijing and everywhere else. The database reads all of them and checks longitude and distance one row at a time.

An index on longitude gives a vertical strip from pole to pole instead: the same problem.

A composite index on (lat, lng). A B-tree sorts by the first column and uses the second only to break ties. Latitude values are almost all distinct, so within the latitude range the rows are effectively in latitude order, and the longitude condition cannot narrow the seek: the database scans the whole latitude band in the index, filtering longitude as it goes. That is better than reading table rows, because the filtering happens in the index, but it still touches every entry in the band.

Two separate indexes, intersected. Some databases can combine two indexes with a bitmap AND: rows in the latitude band and rows in the longitude band. Each band may still hold hundreds of thousands of entries, and both must be read in full before intersecting.

And none of them rank by distance. Even the rows inside the bounding box come back in latitude order, not nearest first, so "the 10 nearest drivers" requires computing every candidate's distance and sorting.

How bad is it? If drivers were spread evenly over land, a band 4 km tall would hold about 0.02% of them. They are not: drivers cluster in cities, and a band through a large city's latitude passes through other cities too. In a single-city table, a 4 km band runs straight across the city and can hold 10% to 20% of its drivers, a thousand times more than the 4 km by 4 km box you actually need.

The root problem is dimensional: sorting points onto a line cannot keep all neighbours adjacent. The rest of this page is about the two ways of recovering enough closeness to make an index useful again:

  1. Build an index that is two-dimensional: a spatial tree, such as a quadtree, k-d tree or R-tree.
  2. Map two dimensions onto one in a way that mostly preserves closeness: a space-filling curve or a grid of cells, whose keys go into an ordinary B-tree, hash index or sorted set.

And both approaches end the same way: generate candidates cheaply, then compute exact distances on those few candidates.

Distance on a round Earth#

Before choosing an index, it helps to know how distances are measured, since every spatial index ends with exact distance math on its candidates.

Degrees are not equal distances. One degree of latitude is about 111 km everywhere. One degree of longitude is 111 km at the equator but shrinks with the cosine of the latitude: about 85 km at 40 degrees (New York, Madrid, Beijing), 56 km at 60 degrees (Oslo, Helsinki), and zero at the poles. So a "square" of 0.01 by 0.01 degrees is 1.1 km by 0.85 km in New York, and a bounding box for a 2 km radius must be wider in degrees of longitude than in latitude: 0.018 degrees of latitude, but 0.018 divided by cos(latitude), about 0.024 degrees of longitude, in New York.

The haversine formula gives the great-circle distance, the shortest path over the surface of a sphere, between two points:

d = 2R × asin( sqrt( sin²(Δφ/2) + cos φ1 × cos φ2 × sin²(Δλ/2) ) )

where φ is latitude, λ is longitude, both in radians, and R is the Earth's mean radius, about 6,371 km. It is numerically stable for small distances, which is why it is preferred over the spherical law of cosines.

Approximations for short distances. For distances of a few kilometres, the equirectangular approximation is accurate to well under 1%: treat the area as flat, scale longitude differences by the cosine of the mean latitude, and use Pythagoras: x = Δλ × cos(φm), y = Δφ, d = R × sqrt(x² + y²). It needs one cosine and one square root, and for ranking candidates, you can even skip the square root and compare squared distances.

The Earth is not a sphere. It is slightly flattened at the poles, so haversine distances can be off by up to about 0.5%. For navigation, surveying or legal boundaries, use ellipsoidal formulas on the WGS 84 ellipsoid, such as Vincenty's formulae or Karney's geodesic algorithms, which PostGIS's geography type and GeographicLib implement. For "restaurants within 5 km", sphere math is more than accurate enough.

Straight-line distance is not travel distance. A restaurant 1 km away across a river with no bridge may be a 20-minute drive. Proximity search typically uses straight-line distance to find candidates, and a routing or ETA service to rank the final few. See Design Maps and Navigation.

Space-filling curves#

A space-filling curve is a single line that visits every cell of a grid, so that ordering cells by their position along the line gives each cell a one-dimensional key. Good curves keep most nearby cells close together along the line, which is exactly what an ordinary index needs.

The Z-order curve, or Morton order. Take a cell's x and y coordinates in binary and interleave their bits: x = 5 (101) and y = 3 (011) interleave, taking an x bit then a y bit, to 10 01 11, which is 39. Following cells in this order traces a repeating Z shape: the four cells of each 2 by 2 block, then the next block, and so on at every scale. It is named after G. M. Morton, who described the interleaving in an IBM report in 1966. Interleaving is very cheap to compute, and cells that share a key prefix lie in the same square block, which is the property geohash relies on.

The Hilbert curve, described by David Hilbert in 1891, visits the cells in a U-shaped path that recursively turns, so that consecutive cells along the curve are always adjacent on the grid. Z-order sometimes jumps: after finishing one block, it leaps diagonally to the next, so two cells adjacent in key order can be far apart, and, more importantly for search, two adjacent cells can be far apart in key order. The Hilbert curve has fewer and smaller jumps, so a region of the map maps onto fewer, longer key ranges, which means fewer index seeks per query. It costs slightly more to compute. S2 uses a Hilbert curve; geohash uses Z-order.

No curve is perfect. Any mapping from two dimensions to one has places where neighbours on the map are far apart on the line, at the boundaries between big blocks. So a proximity query on curve keys always looks at several key ranges, typically the query cell and its neighbours, rather than one.

Geohash#

Geohash, published by Gustavo Niemeyer in 2008, encodes a latitude and longitude as a short string, using Z-order interleaving and a base-32 alphabet. It is the simplest encoded key to explain and compute, and it works in any database that can index a string or an integer.

Encoding, step by step.

  1. Start with longitude in the range −180 to 180 and latitude in −90 to 90.
  2. Repeatedly halve the range: for longitude, if the value is in the upper half, emit a 1 and keep the upper half; otherwise emit 0 and keep the lower half. Do the same for latitude.
  3. Interleave the bits, starting with longitude: lng, lat, lng, lat, and so on.
  4. Group the bits in fives and map each group to a character of the alphabet 0123456789bcdefghjkmnpqrstuvwxyz, which omits a, i, l and o to avoid confusion with digits.

A worked example. The point at latitude 57.64911, longitude 10.40744, in northern Denmark, is the example used in geohash's original description. Longitude 10.40744 is above 0, so bit 1; below 90, so 0; below 45, 0; below 22.5, 0; below 11.25, 0. Latitude 57.64911 is above 0, so 1; above 45, 1; below 67.5, 0; above 56.25, 1; below 61.875, 0. Interleaving, longitude first, gives 1 1 0 1 0 for the first five bits, which is 26, the character "u". Continuing gives the full code u4pruydqqvj, which pins the point to within about 15 cm.

Each character zooms in by a factor of 32. Each character adds 5 bits, alternately 3 longitude and 2 latitude bits, then 2 and 3, so cells alternate between being square and twice as wide as tall. At the equator:

CharactersCell width × heightTypical use
15,000 km × 5,000 kmContinent
21,250 km × 625 kmLarge country region
3156 km × 156 kmLarge metropolitan area
439 km × 19.5 kmCity
54.9 km × 4.9 kmDistrict; "within 5 km" searches
61.2 km × 0.61 kmNeighbourhood; "within 1 km" searches
7153 m × 153 mA few city blocks
838 m × 19 mA building
94.8 m × 4.8 mA parking space
123.7 cm × 1.9 cmSurveying precision

Cells get narrower towards the poles, since longitude degrees shrink: a 5-character cell in Oslo is about 2.4 km wide and 4.9 km tall.

The prefix property. Two points that share the first n characters fell into the same cell at every one of the first n levels, so they lie in the same n-character cell. That turns a proximity query into a prefix scan: all points in cell dr5ru are found by WHERE geohash LIKE 'dr5ru%' on an ordinary B-tree index on a text column, or by a range scan geohash >= 'dr5ru' AND geohash < 'dr5rv'. Stored as an integer instead of a string, the same scan is a numeric range of the bits, which is how Redis stores geohashes, as 52-bit integers in a sorted set.

The catch: boundaries. The prefix property only works one way. Points that share a prefix are close, but close points do not necessarily share a prefix. Two points a metre apart on either side of a cell boundary have different codes at that level, and near the boundaries of big blocks, they share almost nothing. The four points within a few metres of latitude 0, longitude 0 have geohashes beginning s0000, kpbpb, ebpbp and 7zzzz, with no common prefix at all. A query that scanned only the rider's cell would miss the driver standing 10 metres away across the line.

The fix: query the cell and its eight neighbours. Compute the query point's cell at a precision whose cells are at least as large as the search radius, then compute the eight cells around it, which is simple arithmetic on the decoded bits, and scan all nine. Any point within the radius of the query point must be in one of these nine cells, wherever in its cell the query point sits. Then compute the exact distance to every candidate, drop those outside the radius, and sort. Almost every encoded-key system does some version of this query the ring, then post-filter step.

Geohash, in depth#

Choosing a precision. The cell size sets a trade-off between the number of scans and the number of wasted candidates:

  • Cells much larger than the radius: the nine cells cover a huge area compared with the search circle. A 1 km search using 5-character cells scans nine cells of about 24 km² each, 216 km², to answer a question about a circle of 3.1 km²: around 70 times more candidates than needed.
  • Cells smaller than the radius: the circle spans many cells, so the query must scan more of them, such as a 5 by 5 block of 6-character cells for a 1 km radius, or, for a precise covering, a list of cells at mixed precisions.

A practical rule is to choose the precision whose cell size is closest to, but not smaller than, the radius, and scan the 3 by 3 block. For a 1 km radius, 6-character cells are 1.2 km by 0.61 km, so the height is too small: either use 5 characters and accept the waste, or use 6 characters with a block of 3 cells across and 5 cells tall.

Searching for the k nearest. "The 10 nearest restaurants" has no fixed radius. Start with a small radius, scan the block, and if fewer than 10 candidates lie within the radius, drop one character of precision, which makes cells 4 to 8 times larger, and repeat. Each step widens the search until enough results are found. A candidate found in an inner step is not necessarily among the true nearest until you have checked every point within its distance, so the search continues until the k-th best distance is smaller than the guaranteed covered radius.

Density varies enormously. A 6-character cell in Manhattan may hold thousands of restaurants, while one in rural Montana holds none. A fixed precision is either too coarse for cities or too fine for the countryside. Systems handle this with an expanding search, as above, or by choosing precision per region from density statistics, or by switching to an adaptive structure such as a quadtree.

Z-order jumps cost seeks. Because the Z-order curve jumps between blocks, a box on the map often maps to several separate key ranges, each needing its own index seek. Nine cells may need up to nine range scans, though adjacent cells are sometimes consecutive and can be merged. On a B-tree, each scan costs a seek of a few page reads, so nine scans are cheap. The cost becomes significant only for large or irregular regions covered by many cells.

Geohash as a partition key. A short geohash prefix is a natural partition key for sharding location data: all points in a 4-character cell go to the same shard, so a local query usually touches one shard, or a few when the 3 by 3 block crosses partition boundaries. Dense cities produce hot partitions, so systems split hot cells into longer prefixes, or partition by city instead. DynamoDB, Cassandra and similar key-value stores have no native spatial index, so a geohash prefix as the partition key and the full geohash as the sort key is a common pattern for them. See Partitioning and Sharding.

Storage forms. A 12-character geohash string takes 12 bytes; the same 60 bits fit in an 8-byte integer. Integers are smaller, compare faster and allow arbitrary bit-level precision, not just multiples of 5 bits. Strings are human-readable, easy to debug and work with LIKE prefix queries. Redis uses 52-bit integers, which fit exactly in the 53-bit mantissa of the double-precision score of a sorted set, giving a precision of well under a metre.

Where geohash falls short. Cells distort with latitude, the Z-order curve has jumps, neighbours across the poles and the 180-degree meridian need special handling, and cells are rectangles, so the distance from a cell's centre to its neighbours' centres differs between edge neighbours and corner neighbours. For a city-scale service, none of this matters much. For a global analytics system, S2 or H3 handle it better.

Quadtree#

A quadtree, introduced by Raphael Finkel and Jon Bentley ("Quad Trees: A Data Structure for Retrieval on Composite Keys", Acta Informatica, 1974), builds the index from the map itself. The whole world is the root node. Split it into four quadrants, north-west, north-east, south-west and south-east, which become the root's four children. Any quadrant holding more than a set number of points, such as 100, splits again into four, and so on recursively. Points live in the leaves.

Searching. To find points near a location, walk down from the root, at each node choosing the quadrant that contains the query point, until reaching a leaf. Its points, plus those of neighbouring leaves that overlap the search circle, are the candidates. More generally, a range search visits every node whose square overlaps the search circle and skips every other subtree, and exact distances finish the job.

Adapting to density. Unlike a fixed grid, a quadtree splits only where data is dense. Manhattan becomes a deep stack of small squares, while the Pacific Ocean and the Sahara remain single large leaves. Every leaf holds at most the set number of points, so every query examines roughly the same number of candidates, whether in a city or a desert. That makes quadtrees especially good for k-nearest searches with no fixed radius: in a sparse area, the leaf is large, and in a dense area it is small, so "the 20 nearest" always means reading a few leaves.

k-nearest neighbours with a priority queue. The standard algorithm keeps a priority queue ordered by the minimum possible distance from the query point to each node's square. Repeatedly pop the closest node: if it is a leaf, compute the distance to each of its points and keep the best k; if it is internal, push its children. Stop when the closest remaining node is further away than the k-th best point found. This visits only the nodes that could contain a closer point.

Where quadtrees struggle.

  • Depth varies with density. Splits happen at the geometric midpoint, not where the points are, so a dense cluster is halved again and again until its points separate: ten or more levels downtown, two in the countryside. Query cost depends on location, and the busiest regions are the deepest.
  • Pointers do not suit disk. Each node is a separate object holding pointers to four children. In memory that is cheap, but a database reads fixed-size pages, and every pointer hop risks a random disk read. Quadtrees are therefore mostly used as in-memory indexes, rebuilt or updated in RAM, with the data persisted elsewhere.

Quadtree, in depth#

Sizing an in-memory quadtree. A local-search service has 200 million businesses, and the quadtree stores, for each business, its ID and coordinates, 8 bytes each, so 24 bytes. That is 4.8 GB of leaf data. With at most 100 businesses per leaf and leaves typically half to three quarters full, there are about 3 to 4 million leaves, and about a third as many internal nodes, each with four child pointers, perhaps 50 bytes. The internal structure adds well under 100 MB. So the whole index fits comfortably in the memory of one server, and several replicas serve reads.

Building and updating. Building the tree from 200 million points takes minutes: sort or bucket the points recursively. Businesses change slowly, a few thousand per hour, so updates can be applied in place, splitting a leaf when it exceeds the limit, or the tree can be rebuilt nightly while recent changes are held in a small side index. A new server loads a snapshot at startup. This read-mostly pattern is the classic proximity-service design: a quadtree in memory, the business data in a database, and results cached by area. See Design a Proximity Service.

Quadtrees and geohash are close relatives. Each pair of interleaved bits in a geohash, one longitude and one latitude, chooses one of four quadrants, so a geohash of 2n bits is the path to a node at depth n in a complete quadtree. A quadtree's advantage is that it stops splitting where data is sparse; geohash's advantage is that the path is a key that any database can index. The Bing Maps tile system uses quadtree paths directly as quadkeys: each digit from 0 to 3 picks a quadrant, so a tile's key is its path from the root, and prefixes identify parent tiles.

Map tiles. Web maps divide the world, projected with Web Mercator, into 256 by 256 pixel tiles at zoom levels 0 to about 22, where each level splits every tile into four. That is a quadtree of tiles, and each tile at zoom z has coordinates x and y from 0 to 2 to the power z minus 1. Map servers and CDNs cache tiles by (z, x, y). See Design Maps and Navigation.

Point-region versus point quadtrees. The quadtree above, which splits squares at their midpoint, is a point-region quadtree. Finkel and Bentley's original point quadtree split at the data points themselves, which adapts better to the data but makes the shape depend on insertion order. Variants also exist for lines and polygons, and octrees extend the idea to three dimensions, used in graphics, games and 3D mapping.

k-d trees: split at the median, one dimension at a time. Jon Bentley's k-d tree ("Multidimensional Binary Search Trees Used for Associative Searching", Communications of the ACM, 1975) is the binary cousin of the quadtree. Each level splits on one coordinate, alternating: the root splits by longitude, its children by latitude, the next level by longitude again. The key difference is where it splits: at the median point, not the geometric midpoint. Picture ten drivers on one street, nine clustered at the east end and one far to the west. A quadtree's first cut at the midpoint puts one driver on one side and nine on the other, and needs several more cuts through mostly empty space to separate the cluster. A k-d tree cuts at the fifth driver, so each side gets five, however lopsided the distribution. Each split halves the number of points rather than the area, so the tree has depth about log2(n), around 28 for 200 million points, whatever the density. k-d trees were the standard structure for nearest-neighbour search for decades, but like quadtrees, they are pointer structures that suit memory, not disk, and they become unbalanced under many inserts and deletes.

BKD trees: k-d trees for disk. The Bkd-tree (Octavian Procopiuc, Pankaj Agarwal, Lars Arge and Jeffrey Vitter, "Bkd-Tree: A Dynamic Scalable kd-Tree", SSTD 2003) packs points into blocks sized for disk pages, with each internal node splitting at the median as in a k-d tree. Instead of updating the tree in place, it builds a set of static trees of geometrically increasing size and merges them as data arrives, much like an LSM tree. Apache Lucene adopted block k-d trees for its numeric and geographic "points" in Lucene 6, in 2016, and this is what Elasticsearch uses for geo_point fields. It fits Lucene perfectly: each segment is immutable, so its BKD tree is built once when the segment is written and rebuilt only when segments merge.

R-tree#

The R-tree (Antonin Guttman, "R-Trees: A Dynamic Index Structure for Spatial Searching", SIGMOD 1984) was the first spatial index designed from the start for on-disk databases, and it solved two problems the earlier trees could not: shapes and disk pages.

Shapes, not just points. A driver is a point, but much geographic data is not: a road is a line, a county is a polygon, a store's delivery zone is a polygon, and a lake is a polygon with islands. A polygon cannot be placed in a single quadtree cell, because it spans many.

Minimum bounding rectangles. The R-tree wraps every object in its minimum bounding rectangle, or MBR: the smallest rectangle aligned with the latitude and longitude axes that contains it. A point is a rectangle of zero size, a road is a long thin rectangle, and a county is a large box. Nearby rectangles are grouped under a parent entry whose rectangle encloses them all, those parents are grouped under bigger rectangles, and so on up to the root.

Balanced like a B-tree. Each node is sized to one disk page and holds between a minimum and maximum number of entries, such as 50 to 100. All leaves are at the same depth, inserts that overflow a node split it, and the split can propagate upwards, exactly as in a B-tree. So any query reads a predictable number of pages, and the tree stays balanced as data changes.

Searching. To find all objects intersecting a query rectangle or circle, start at the root and descend into every child whose rectangle overlaps the query region. At the leaves, the MBRs that overlap are candidates, and an exact geometry test, such as point-in-polygon or polygon intersection, makes the final decision. This two-step approach is called filter and refine: the index filters by rectangles, which is cheap, and exact geometry refines the few survivors, which is expensive.

Overlap is the cost. Unlike quadtree cells, R-tree rectangles can overlap. If a query point lies inside two sibling rectangles, both subtrees must be searched. A poor insertion strategy produces lots of overlap and lots of wasted branches, while a good one keeps sibling rectangles compact and separate. Guttman's paper proposed linear and quadratic split algorithms. The R*-tree (Norbert Beckmann, Hans-Peter Kriegel, Ralf Schneider and Bernhard Seeger, SIGMOD 1990) improved insertion with heuristics that minimise overlap, area and perimeter, plus forced reinsertion, which removes and reinserts some entries when a node overflows, instead of splitting immediately. Most modern R-tree implementations are based on R*-tree ideas.

Where R-trees are used. PostGIS indexes geometries through PostgreSQL's GiST framework, which provides R-tree-style bounding-box indexing. SQLite has an R*Tree module, MySQL's InnoDB uses R-trees for spatial indexes, and Oracle Spatial offers R-tree indexes. If the problem involves real geometry, such as "which delivery zones contain this address?" or "which roads cross this county?", an R-tree is the standard tool.

R-tree, in depth#

Bulk loading. Inserting millions of objects one at a time produces a tree with more overlap than necessary, and takes longer. Bulk loading builds the tree from a sorted batch instead. Sort-Tile-Recursive (Scott Leutenegger, Mario Lopez and Jeffrey Edgington, ICDE 1997) sorts objects by x, cuts them into vertical slices, sorts each slice by y, and packs consecutive runs into full leaf pages, then repeats for upper levels. The Hilbert R-tree (Ibrahim Kamel and Christos Faloutsos, VLDB 1994) orders objects by the Hilbert value of their centre. Both produce nearly full, well-separated nodes. PostgreSQL's GiST indexes can be built using a sorted method for points, which is much faster than repeated inserts.

Nearest-neighbour search. Nick Roussopoulos, Stephen Kelley and Frédéric Vincent ("Nearest Neighbor Queries", SIGMOD 1995) gave a branch-and-bound algorithm for R-trees, and Gísli Hjaltason and Hanan Samet ("Distance Browsing in Spatial Databases", ACM TODS 1999) gave the incremental version that most systems use: a priority queue of nodes and objects ordered by their minimum distance to the query point, popping the closest each time. It returns neighbours in order, nearest first, so "the 10 nearest" can stop after 10 results without knowing a radius in advance. PostGIS exposes this as the <-> distance operator in ORDER BY ... LIMIT, which the GiST index answers directly.

GiST, the generalised search tree. Joseph Hellerstein, Jeffrey Naughton and Avi Pfeffer ("Generalized Search Trees for Database Systems", VLDB 1995) defined a framework in which a balanced tree is customised by a few methods: how to combine keys into a parent key, how to test whether a subtree might match a query, how to choose where to insert, and how to split a node. With bounding boxes as keys, GiST behaves like an R-tree. PostgreSQL also offers SP-GiST, for space-partitioning trees such as quadtrees and k-d trees, and BRIN, block range indexes that store a bounding box per range of table pages, which are tiny and useful when rows are physically ordered by location.

Writes and churn. Every insert may enlarge rectangles up the tree, every split rewrites pages, and every delete may require condensing nodes. Updating a moving object's position means a delete plus an insert, touching several pages. That is fine for thousands of updates per second, but expensive at hundreds of thousands, and the index's quality degrades as objects drift, increasing overlap. This is one reason R-trees in a database are not the usual choice for live driver positions.

S2 cells#

Geohash treats the world as a flat rectangle of latitude and longitude, but the Earth is a sphere. Cells shrink towards the poles, the curve has seams at the poles and the 180-degree meridian, and polygons crossing those seams are awkward. Google's S2 Geometry library, largely designed by Eric Veach, divides the sphere itself into a hierarchy of cells of roughly equal area.

How S2 builds cells.

  1. Project onto a cube. Surround the Earth with a cube and project every point on the sphere outwards onto one of the cube's six faces.
  2. Make the projection fair. A straight projection would make cells near face corners smaller than those in the middle, so S2 applies a quadratic correction that makes cell areas far more uniform, within a factor of about 2 between the smallest and largest cells at a level.
  3. Subdivide each face as a quadtree, to 30 levels. Level 0 is a whole face. Each level splits every cell into four.
  4. Order the cells along a Hilbert curve on each face, so consecutive cell IDs are adjacent on the map, and the six faces' curves connect into one continuous path around the globe.

Cell IDs. Each cell has a 64-bit ID: 3 bits for the face, 2 bits per level of quadtree path, and a trailing marker bit that encodes the level. Truncating the path gives the parent cell, and all descendants of a cell have IDs in one contiguous numeric range. So "all points inside cell X" is one range scan on an ordinary integer index.

Cell sizes. Each level has about a quarter of the area of the previous one. The average cell area is roughly 85 million km² divided by 4 to the power of the level:

LevelAverage areaApproximate edgeTypical use
81,300 km²36 kmMetropolitan region
1081 km²9 kmCity district
125 km²2.2 kmNeighbourhood
140.32 km²560 mA few blocks; driver matching
160.02 km²140 mStreet segment
2077 m²9 mA building's footprint
30About 1 cm²1 cmMaximum precision

Region coverings. S2's most useful tool is the region coverer: given a circle, rectangle or polygon, it returns a small set of cells, at mixed levels, whose union covers the region, such as at most 8 or 20 cells. Big cells cover the interior and small ones follow the edge. Each cell corresponds to one contiguous ID range, so a query for "points within this polygon" becomes a handful of range scans followed by an exact test. More cells give a tighter covering and fewer wasted candidates, at the cost of more scans.

Where S2 is used. MongoDB's 2dsphere index uses S2 cells, Google BigQuery's geography functions are built on S2, and many location services use S2 cell IDs at a fixed level as shard keys: for example, Tinder has described grouping S2 cells into geoshards of roughly balanced user counts, each served by its own search index, so a recommendation query touches only the shards near the user.

H3 cells#

H3, which Uber open-sourced in 2018, divides the world into hexagons. Uber built it for dispatch, pricing and analytics, where questions such as "how much demand is there in each area, and in the areas around it?" are asked constantly.

Why hexagons. A square has two kinds of neighbours: four that share an edge, whose centres are one cell-width away, and four that share only a corner, about 1.41 cell-widths away. That lopsidedness distorts anything computed from neighbours, such as smoothing a demand map, or "everything within 2 cells". A hexagon has six neighbours, all sharing an edge, all at the same distance. Rings of hexagons around a cell approximate circles well, and movement between cells looks the same in every direction.

How H3 builds cells. H3 projects the Earth onto an icosahedron, a 20-faced solid, and tiles it with hexagons. A sphere cannot be tiled with hexagons alone, so each resolution has exactly 12 pentagons, placed at the icosahedron's vertices, which are over the oceans. Resolution 0 has 122 cells, 110 hexagons and 12 pentagons. Each finer resolution has about 7 times as many cells: each hexagon's children are one central hexagon and six around it, rotated slightly. There are 16 resolutions, 0 to 15.

ResolutionAverage hexagon areaApproximate edge lengthTypical use
5253 km²9.9 kmRegional analytics
75.2 km²1.4 kmCity zones, surge areas
80.74 km²530 mNeighbourhood demand
90.11 km²200 mDriver positions, pickup matching
100.015 km²76 mPickup points
15About 0.9 m²0.6 mMaximum precision

Neighbours by arithmetic, not by curve. H3 cells are not laid out along a space-filling curve, so numerically close IDs are not reliably close on the map, and "a region" is not one ID range. Instead, H3 provides fast grid functions: latLngToCell finds a point's cell at a resolution, gridDisk(cell, k) returns all cells within k steps, which is 1 + 3k(k + 1) cells, so 7 for k = 1 and 19 for k = 2, cellToParent gives the coarser cell, and polygonToCells fills a polygon with cells. A proximity query looks up the exact list of cell IDs: WHERE h3_cell IN (...), or one key lookup per cell in a key-value store.

The dispatch pattern. Snap each driver to a resolution-9 cell, about 200 m across, and keep a set of available drivers per cell. When a rider requests a trip, take the rider's cell and gridDisk with k = 1 or 2, look up the drivers in those 7 or 19 cells, and if there are too few, widen to k = 3 or move to a coarser resolution. Then post-filter by exact distance and rank by estimated time of arrival. Every write is a simple set update, and every query is a few key lookups, with no spatial extension anywhere.

S2 and H3 cells, in depth#

Hierarchy: exact versus approximate containment. In S2 and geohash, every cell is exactly the union of its four or 32 children, so aggregating counts from fine cells to coarse cells is exact. H3's hexagons cannot be split exactly into seven smaller hexagons, so a parent's children cover approximately the same area, with small slivers along the edges belonging to neighbouring parents. For analytics that roll up counts by parent, that is usually acceptable; for billing or legal boundaries, it is not, and exact polygons are needed.

Choosing between S2, H3 and geohash.

NeedBest fitWhy
Range scans on an ordinary sorted indexGeohash or S2Space-filling curve: a cell is one key range
Equal-area cells worldwide, polygons crossing the poles or the 180th meridianS2Built on the sphere, with region coverings
Neighbour-based analytics, smoothing, rings, movementH3Six equidistant neighbours; rings approximate circles
Simplest implementation, human-readable keysGeohashA few lines of code; prefixes are strings
Precise covering of arbitrary polygons with few cellsS2Mixed-level coverings map to few ranges

In an interview, naming the exact system matters less than explaining why a plain index fails, choosing a cell-based approach for moving points, and describing the query-the-neighbours-then-post-filter step. Name S2 or H3 if you know them; the reasoning is what counts.

Cells as join keys. Encoding locations as cell IDs turns spatial joins into ordinary joins. "Count ride requests and available drivers per neighbourhood every minute" becomes a GROUP BY h3_cell on two streams, joined by cell ID, which any stream processor or warehouse handles. This is how surge pricing, demand forecasting and heat maps are computed: aggregate by cell, smooth across neighbouring cells, and compare. See Batch and Stream Processing.

Coverings approximate, exact tests decide. A covering of a circle with cells always includes some area outside the circle. A covering of a polygon such as a delivery zone, with cells small enough to follow its edge, may take thousands of cells. Systems often combine both: an interior covering of cells that lie entirely inside the polygon, where any point is definitely inside with no further test, and a boundary covering of cells that cross the edge, where an exact point-in-polygon test is needed. Most points land in interior cells, so most lookups need no geometry at all.

PostGIS and Redis GEO#

Two of the most common tools in proximity designs take opposite approaches: PostGIS is a spatial tree inside a relational database, and Redis GEO is an encoded key in an in-memory sorted set.

PostGIS is the spatial extension for PostgreSQL, and the most complete open-source spatial database.

  • Types. geometry stores shapes on a flat plane in a chosen coordinate system, identified by an SRID, such as 4326 for WGS 84 latitude and longitude, or a local projection in metres. geography stores shapes on the sphere or ellipsoid and computes distances in metres along the Earth's surface, which is simpler and correct for global data, at a modest CPU cost.
  • Index. CREATE INDEX ON places USING GIST (location) builds an R-tree-style GiST index of bounding boxes.
  • Radius queries. ST_DWithin(location, point, 2000) on a geography column finds rows within 2,000 metres, and it uses the index: it expands the point into a bounding box, scans the index for overlapping boxes, then checks exact distance. Writing ST_Distance(location, point) < 2000 instead computes the distance for every row, a full scan. This is the most common PostGIS performance mistake.
  • Nearest neighbours. ORDER BY location <-> point LIMIT 10 uses the GiST index's distance ordering to return the 10 nearest rows without a radius.
  • Shapes. ST_Contains(zone, point) for "which delivery zone contains this address", ST_Intersects for overlaps, and hundreds of other functions for buffers, unions, areas and projections.
  • Everything else in SQL. Spatial predicates combine with ordinary columns, joins and indexes: open restaurants, of a given cuisine, rated above 4, within 2 km, sorted by distance, in one query.

Redis GEO stores locations in a sorted set, using a 52-bit geohash integer as each member's score.

  • GEOADD drivers:nyc -73.9855 40.7580 driver:42 adds or updates a member. Note that longitude comes first.
  • GEOSEARCH drivers:nyc FROMLONLAT -73.9855 40.7580 BYRADIUS 2 km ASC COUNT 20 WITHDIST returns the 20 nearest members within 2 km, nearest first, with their distances. BYBOX searches a rectangle, and FROMMEMBER searches around an existing member. The older GEORADIUS commands are deprecated in favour of GEOSEARCH.
  • GEOPOS, GEODIST and GEOHASH return positions, distances and standard 11-character geohash strings, and since a GEO key is a sorted set, ZREM removes a member and ZCARD counts them.
  • How a search works. Redis picks a geohash precision based on the radius, computes the cell containing the centre and its eight neighbours, performs a sorted-set range scan for each, and then filters the candidates by exact distance. The documented complexity is O(N + log M), where N is the number of members inside the grid-aligned boxes around the search area, all of which must be checked against the exact shape, and M is the number of members that fall inside the shape. In practice the cost is dominated by N, the candidates, which is why oversized boxes in dense areas are slow. Precision is about 0.6 m, and valid latitudes are limited to about ±85.05 degrees, the range of Web Mercator.

Redis's limits for location data.

  • One key lives on one shard. In Redis Cluster, a sorted set cannot span nodes, so a global drivers key would put all writes on one node. Split keys by city or region, such as drivers:nyc, or by a coarse geohash cell, so load spreads across shards, remembering that searches near a key's boundary must query several keys.
  • No per-member expiry. Members of a sorted set cannot expire individually, so a driver who closes the app stays in the set until removed. Keep a second sorted set of last_seen timestamps and periodically remove members older than, say, 30 seconds from both, or keep one GEO key per time bucket and query the current and previous buckets.
  • Memory. Each member costs roughly 60 to 100 bytes, depending on the member name, so a million drivers take about 100 MB: trivial. A billion points would not fit on one node.
  • Durability. Live positions are ephemeral and refresh within seconds, so losing them on failover is usually tolerable: the set refills from the next round of updates. Static data, such as business locations, should live in a durable database, with Redis as a fast index rebuilt from it.

PostGIS and Redis GEO, in depth#

When PostGIS is enough. For tens of millions of static points or polygons and thousands of queries per second, PostGIS on a well-sized server, with read replicas, is usually the simplest correct design. A GiST-indexed radius query over 50 million rows typically completes in a few milliseconds when the index is in memory. Its strengths are correctness, rich geometry and transactions with the rest of your data. Its weak points are very high write rates on the indexed column, since every update rewrites index pages and creates a new row version under PostgreSQL's MVCC, and horizontal scaling beyond one primary, which needs sharding by region or an extension such as Citus. See PostgreSQL in Practice.

When Redis GEO fits. Redis suits ephemeral, frequently updated points with simple radius queries: drivers, couriers, users currently online, or active scooters. An update is a sorted-set insert, about O(log n), and Redis handles tens of thousands to over a hundred thousand such operations per second per node. Filtering is limited, so attributes, such as vehicle type or rating, need either separate keys per category, such as drivers:nyc:xl, or a second step that fetches attributes and filters candidates in the application. See Redis.

Other databases.

  • MongoDB offers 2dsphere indexes built on S2 cells, with $near, $geoWithin and $geoIntersects queries over GeoJSON.
  • MySQL InnoDB supports spatial indexes, R-trees on geometry columns, with ST_Distance_Sphere and ST_Contains.
  • DynamoDB and Cassandra have no native spatial index, so applications store a geohash or S2 cell as a key, such as a coarse cell as the partition key and a fine cell as the sort key, and run the neighbour queries themselves.
  • Tile38 is an open-source in-memory geospatial database with a Redis-compatible protocol, built for moving objects and geofences, which can push notifications when objects enter or leave areas.
  • BigQuery, Snowflake and other warehouses offer geography types and functions for analytics, with BigQuery built on S2.

Elasticsearch geo queries#

Elasticsearch is the usual choice when proximity is one part of a richer search: "Italian restaurants within 2 miles, open now, matching the text 'wood-fired pizza', sorted by a mix of relevance, rating and distance". A relational database struggles to combine full-text relevance with geography and facets at high query rates, while Elasticsearch does all three in one query. See Elasticsearch and Search Systems.

Field types.

  • geo_point stores a single latitude and longitude, such as a restaurant's location, and is indexed in a BKD tree, which narrows the search in two dimensions efficiently.
  • geo_shape stores arbitrary geometries: polygons, lines, multi-polygons, envelopes and circles, such as delivery zones and city boundaries. Since Elasticsearch 7, shapes are decomposed into triangles and indexed in a BKD tree as well; earlier versions used geohash or quadtree prefix trees.

Queries.

  • geo_distance: documents within a distance of a point, such as 5 km.
  • geo_bounding_box: documents inside a rectangle, which suits "search this area of the map" as the user pans.
  • geo_shape: documents whose shape, or point, intersects, lies within, contains or is disjoint from a given shape, such as "restaurants whose delivery zone contains this address".
  • All of these are filters that combine with full-text queries, term filters and ranges in a bool query, so the expensive scoring runs only on documents that pass the cheap filters.

Sorting and ranking. Sort by _geo_distance for "nearest first", or blend distance into relevance with a function_score decay function, such as Gaussian decay with a scale of 2 km, so a highly rated restaurant 3 km away can outrank a mediocre one next door.

Aggregations. geohash_grid and geotile_grid bucket matching documents into cells, which draws clusters and heat maps on a map; geo_distance aggregations count documents in rings, such as within 1, 5 and 10 km; and geo_bounds and geo_centroid summarise where results lie.

Elasticsearch geo queries, in depth#

Elasticsearch is near-real-time, and indexing is costly. A document becomes searchable only after the next refresh, by default every second. An update is a delete plus a reinsert into a new segment, and segments are merged in the background, rebuilding their BKD trees. That is fine for business listings that change a few times a day, and workable for thousands of updates per second, but a poor fit for a million drivers updating every few seconds, which would cause constant segment churn and merge load. Use Redis, an in-memory cell index or a purpose-built service for live positions, and Elasticsearch for searchable, slowly changing entities.

Sharding by geography. A query must normally visit every shard of an index, so a global index with 50 shards turns each search into 50 shard queries. Routing documents to shards by region, or splitting into per-region indexes, lets a local query touch only the relevant shard. Tinder's geosharding, mentioned above, applies this idea: S2 cells grouped into geoshards, each with its own index, sized so that each holds a similar number of active users, and a query touches only the geoshards that overlap the user's search radius.

Caching repeated searches. Many proximity searches repeat: the same popular area, the same filters, within minutes. Round the query location to a cell, such as a 6-character geohash, and use the cell plus the normalised filters as a cache key, with a short TTL of a minute or so. Many users in the same neighbourhood then share one cached result, which is post-filtered by exact distance for each user. Elasticsearch also caches filter results internally, per segment, which helps repeated filters even without an application cache.

Data modelling for access patterns. Index what you query: if most searches are "within a city, by category, sorted by rating", a compound structure, such as an index per city, or a category filter plus a geo filter with rating as a sort field, serves them better than one huge index with every field. The same principle applies to PostGIS, where a partial index, such as one on open businesses only, or a composite of a category and a GiST index through the btree_gist extension, can cut query time substantially.

Indexing moving objects (drivers)#

Moving objects turn a read-heavy problem into a write-heavy one. A ride-hailing platform with 1 million active drivers, each sending a position every 4 seconds, produces 250,000 location updates per second, and rider queries for nearby drivers add tens of thousands of reads per second. The index must absorb the writes, answer reads in milliseconds, and never return a driver who went offline a minute ago.

Why spatial trees struggle. In an R-tree or BKD tree, moving an object means deleting and reinserting it, which rewrites pages, enlarges rectangles and, in the BKD case, means rebuilding segments. At hundreds of thousands of moves per second, the index spends all its time maintaining itself. In-memory quadtrees fare better, but splitting and merging nodes as clusters form and disperse, such as when a concert ends, is still costly and complicates concurrency.

Why cells work. With an encoded-key index, a moving driver is one cheap update: in Redis GEO, a GEOADD that changes the member's score; in a cell-based index, moving the driver from one cell's set to another. Better still, a driver moving at 30 km/h crosses a 200 m H3 cell only every 24 seconds or so, so most location updates do not change the driver's cell at all. Store the exact position in a fast key-value record, and touch the cell index only when the cell changes, which cuts index writes by a large factor.

The usual architecture.

  1. Ingest: drivers send positions over a persistent connection or HTTP to a location gateway, which validates them and writes the latest position per driver to an in-memory store, plus a stream, such as Kafka, for analytics and trip history.
  2. Index: a location index, sharded by region or cell, keeps the set of available drivers per cell, or a Redis GEO key per city, updated only on cell changes, with each driver's exact position and timestamp in a hash.
  3. Expire stale drivers: each record carries a last-seen time, and readers ignore drivers not seen for, say, 15 to 30 seconds, while a sweeper removes them from the index.
  4. Query: a rider's request computes the rider's cell and its neighbours, reads the candidate drivers, filters by freshness, availability and vehicle type, computes exact distances, then asks the routing service for ETAs for the best few.
  5. Assign: offering the trip to a driver must not double-book them. The matching service locks or atomically claims the driver, for example with a conditional update or a short-lived lock, before sending the offer. See Pattern: Dealing with Contention.

Reducing the write rate. Clients can send updates adaptively: less often when stationary or on a highway far from demand, more often near a pickup. Servers can dead-reckon, predicting a driver's position from the last position, heading and speed, so a slightly stale position is still close. And positions within the same cell need not touch the index at all, as above.

Sharding by location, and hot spots. Sharding the index by region or cell means a rider query usually touches one shard. Events concentrate demand: when a stadium empties, thousands of riders and drivers crowd into a few cells, and a shard owning that area becomes hot. Mitigations include splitting busy cells into finer cells across more shards, replicating hot shards for reads, and sharding by a finer cell level in dense cities than in rural regions. Uber has described in conference talks around 2015 sharding its supply and demand services by S2 cells, with a consistent-hashing ring, Ringpop, assigning cells to service instances.

The write path, where most updates never touch the index:

The read path, from a rider's request to an assigned driver:

Indexing moving objects, in depth#

Worked capacity numbers. With 1 million drivers, 250,000 updates per second, and cells of about 200 m, suppose a typical driver changes cells every 20 to 30 seconds while driving, and spends much of the time waiting stationary. Index updates then fall to perhaps 20,000 to 40,000 per second, spread across, say, 20 regional shards, which is 1,000 to 2,000 per shard: easy for an in-memory structure. The latest-position store still takes all 250,000 writes per second, but those are simple key overwrites, which a sharded Redis or in-memory key-value cluster handles with a handful of nodes, each managing tens of thousands of writes per second. Rider queries, say 20,000 per second at peak, each read 7 to 19 cell sets and a few hundred driver records, which is cheap from memory.

Freshness versus consistency. A rider sees drivers on the map that are 4 to 8 seconds stale, which is fine: the map is a visual estimate. The assignment must be correct, so the final step checks the driver's current state, available and not offered elsewhere, atomically. Location data does not need to be durable or strongly consistent; driver state does.

Indexes for moving objects in research. Database research has long studied this problem. The TPR-tree (Simonas Šaltenis, Christian Jensen, Scott Leutenegger and Mario Lopez, "Indexing the Positions of Continuously Moving Objects", SIGMOD 2000) stores each object's position as a function of time, with bounding rectangles that grow at the speed of their contents, so the tree needs updating only when an object changes course, and can answer "who will be near here in 2 minutes?". The Bx-tree (Christian Jensen, Dan Lin and Beng Chin Ooi, VLDB 2004) maps moving objects onto a space-filling curve and stores them in an ordinary B+-tree partitioned by time, which is closely related to the cell-based designs used in practice. Production systems mostly use the simplest version of these ideas: cells, latest positions, and expiry.

Geofencing for moving objects. Many systems must also know when an object enters or leaves an area: a driver arriving at an airport queue, a scooter leaving its permitted zone, a courier arriving at a restaurant. Index the fences, not the objects: cover each geofence polygon with cells, keep a map from cell to the fences that touch it, and on each position update, look up the cell's fences and test the point against them, often answered immediately by an interior covering. Compare the result with the object's previous fences to emit enter and exit events. Uber described a geofence lookup service of this kind, written in Go, in a 2016 engineering post, in which a city-level index first narrows the candidate fences before point-in-polygon tests.

Choosing#

SituationChooseWhy
Static points, rich filters, moderate scalePostGIS with a GiST indexSQL, transactions, exact geometry, nearest-neighbour ordering
Polygons and containment: zones, boundaries, roadsPostGIS, or Elasticsearch geo_shapeR-tree-style or BKD indexes over shapes
Proximity plus full-text search and facetsElasticsearch geo_pointBKD index combined with text relevance and aggregations
Many static points, read-heavy, in memoryQuadtree or geohash index in service memoryFast, adaptive, rebuilt from the database
Points moving constantly, radius queriesRedis GEO, or a cell index on H3 or S2Cheap writes; candidate generation by cells
Key-value or wide-column store with no spatial supportGeohash or S2 cell as partition and sort keyOrdinary range queries do the spatial work
Global data, polar or antimeridian shapesS2Cells on the sphere, region coverings
Neighbourhood analytics, surge, heat mapsH3Equidistant neighbours, rings, hierarchy

The short version: a spatial tree for shapes, encoded cells for moving points, and always post-filter by exact distance.

When to Use It#

  • Any query by location rather than by ID or value: nearby drivers, restaurants, people, stores, events or devices.
  • Containment and intersection: which zone contains this address, which fences contain this vehicle, which map features fall inside the visible area.
  • Data large enough that a scan is slow: more than a few hundred thousand rows, or a query rate where per-row distance math adds up.
  • Location as a partition key: sharding users, drivers or listings by area so local queries touch one shard.
  • Spatial aggregation: demand per neighbourhood, heat maps, density for pricing, by grouping on cell IDs.

When NOT to Use It#

  • Small data sets: a few thousand stores can be scanned in memory with exact distances in well under a millisecond. Add a spatial index when the numbers require it.
  • When the "location" is really a category: "restaurants in Paris" is a filter on a city column, not a proximity query.
  • When travel time, not distance, is the criterion: a spatial index finds candidates, but a routing engine must rank them. Do not pretend straight-line distance is ETA.
  • Elasticsearch or an R-tree for live positions updated every few seconds: the write churn is the wrong fit. Use cells in memory.
  • Fine-grained cells for analytics that must be exact at boundaries, such as tax or legal jurisdictions: use real polygons, since H3 hierarchies and cell coverings are approximate.
  • Building your own spatial index when PostGIS, Redis GEO, Elasticsearch or a cell library already solves the problem: the edge cases, such as poles, the antimeridian and boundary neighbours, are where home-grown code breaks.

How to Implement It#

  1. Characterise the data: points or shapes, static or moving, how many, how dense in the busiest city, and the update rate.
  2. Characterise the queries: radius or k-nearest, typical radius, containment, extra filters such as category or availability, sort order, and the query rate.
  3. Choose the approach: a spatial tree (PostGIS, Elasticsearch) for shapes and rich filtering, or encoded cells (Redis GEO, geohash, S2, H3) for moving points and very high write rates.
  4. Pick a cell size or precision that matches the typical search radius, and plan for expanding the search when too few results are found.
  5. Always query neighbours and post-filter: the cell plus its neighbours, or the index's radius operator, then exact distance, then sort.
  6. Shard by geography when one node cannot hold the data or the writes, and handle queries that cross shard boundaries by querying each overlapping shard.
  7. Handle staleness for moving objects: timestamps, expiry, and an atomic check of current state before acting on a result.
  8. Cache popular areas: round locations to a cell and cache results per cell and filter set for a short time.
  9. Test the edge cases: the poles, the 180-degree meridian, points on cell boundaries, longitude and latitude order, and empty or extremely dense areas.

A PostGIS schema and the two most common queries:

CREATE EXTENSION IF NOT EXISTS postgis;
 
CREATE TABLE places (
  id        bigint PRIMARY KEY,
  name      text NOT NULL,
  category  text NOT NULL,
  rating    numeric(2,1),
  location  geography(Point, 4326) NOT NULL   -- longitude, latitude
);
CREATE INDEX places_location_gist ON places USING GIST (location);
 
-- Italian places within 2 km, nearest first: ST_DWithin uses the index
SELECT id, name, ST_Distance(location, q.pt) AS metres
FROM places,
     (SELECT ST_MakePoint(-73.9855, 40.7580)::geography AS pt) AS q
WHERE category = 'italian'
  AND ST_DWithin(location, q.pt, 2000)
ORDER BY metres
LIMIT 20;
 
-- The 10 nearest places of any kind, with no radius: GiST distance ordering
SELECT id, name
FROM places
ORDER BY location <-> ST_MakePoint(-73.9855, 40.7580)::geography
LIMIT 10;

And the Redis equivalent for live driver positions, with expiry handled by a timestamp set:

GEOADD   drivers:nyc  -73.9855 40.7580 driver:42        # position update
ZADD     drivers:nyc:seen  1767225600 driver:42         # last-seen time, Unix seconds
GEOSEARCH drivers:nyc FROMLONLAT -73.9840 40.7570 BYRADIUS 2 km ASC COUNT 20 WITHDIST
# Sweeper, every few seconds: find drivers not seen for 30 s and remove them from both sets
ZRANGEBYSCORE drivers:nyc:seen -inf 1767225570
ZREM drivers:nyc driver:17 driver:93
ZREM drivers:nyc:seen driver:17 driver:93
TechnologyFits when
PostGIS (PostgreSQL)Points and shapes with SQL filters, joins and transactions; tens of millions of rows
MySQL spatial, SQLite R*Tree, Oracle SpatialSpatial queries inside an existing database of that kind
Elasticsearch or OpenSearch (geo_point, geo_shape)Proximity combined with full-text search, facets, ranking and map aggregations
MongoDB 2dsphereDocument data with GeoJSON locations and spherical queries
Redis GEOMoving points, simple radius queries, sharded by city or region
Tile38Moving objects with live geofence notifications
H3 librariesCell-based dispatch, pricing and analytics with hexagons
S2 librariesSphere-aware cells, coverings, shard keys and global polygons
Geohash librariesSimple keys for key-value stores and prefix queries
BigQuery GIS, Snowflake geographyLarge-scale spatial analytics and joins

Trade-offs#

OptionProsConsPick when
Latitude and longitude B-treeNo extra toolingScans a whole band; no distance orderTiny data sets only
Geohash keysAny database; prefix scans; simpleBoundary misses need neighbours; distorted cells; Z-order jumpsKey-value stores, simple services
Quadtree in memoryAdapts to density; fast k-nearestPointer structure; rebuilds; memory-boundRead-heavy static points
k-d or BKD treeBalanced by median; BKD suits immutable segmentsPoor for frequent updatesSearch engines such as Elasticsearch
R-tree (PostGIS GiST)Points, lines and polygons; balanced on diskOverlap; costly churnShapes, containment, SQL workloads
S2 cellsEqual-area cells on the sphere; coverings; rangesMore complex; square cellsGlobal data, polygons, shard keys
H3 cellsEquidistant neighbours; rings; analyticsNo range scans; approximate hierarchyDispatch, pricing, heat maps
Redis GEOVery fast writes and radius queriesOne key per shard; no expiry per member; simple filtersLive driver or user positions

Common Pitfalls#

  • Swapping latitude and longitude. GeoJSON, PostGIS ST_MakePoint, Redis GEOADD and Elasticsearch arrays take longitude first, while many APIs and humans write latitude first. A swapped point lands in the wrong hemisphere or fails validation.
  • Querying only the cell that contains the point, missing results just across the boundary. Always include neighbours.
  • Forgetting the post-filter, returning candidates in the corners of the 3 by 3 block that are outside the radius.
  • Using ST_Distance(...) < r instead of ST_DWithin in PostGIS, which defeats the index.
  • Treating degrees as distances, so search boxes are too narrow in longitude away from the equator, or using flat-plane distance across hundreds of kilometres.
  • One fixed precision everywhere, which is far too coarse in Manhattan and returns nothing in rural areas. Expand the search when results are few.
  • Putting all moving points under one Redis key, creating a single hot shard.
  • Never removing stale drivers, so riders are matched to drivers who went offline.
  • Using Elasticsearch or an on-disk R-tree for positions updated every few seconds, overwhelming refreshes and merges.
  • Ignoring the antimeridian and the poles, where naive bounding boxes wrap the wrong way around the planet, such as for Fiji or the Bering Strait.
  • Assuming cell hierarchies are exact with H3, when parents only approximately contain their children.
  • Sorting the final results by straight-line distance when users care about travel time.

Real-World Examples#

  • Uber open-sourced H3 in 2018, and uses hexagonal cells for dispatch, surge pricing and marketplace analytics. Its engineering blog also described a geofence lookup service written in Go, in 2016.
  • Google built the S2 library for its geographic products. S2 underlies BigQuery's geography functions, and MongoDB's 2dsphere index uses S2 cells.
  • Tinder has described geosharding its recommendation search with S2 cells, grouping cells into shards with balanced user counts, each with its own Elasticsearch index.
  • Yelp has described moving its core business search to Elasticsearch, where geographic filters combine with text relevance and ranking.
  • Bing Maps names its map tiles with quadkeys, quadtree paths of digits 0 to 3, and web maps generally serve tiles in a quadtree of zoom levels.
  • Redis added GEO commands in version 3.2, in 2016, storing 52-bit geohashes as sorted-set scores, and later added GEOSEARCH in 6.2.
  • Elasticsearch and Lucene moved geo_point indexing to BKD trees with Lucene 6 in 2016, and geo_shape to BKD-indexed triangles in Elasticsearch 7.
  • PostGIS has been the standard open-source spatial database extension since the early 2000s, used by mapping projects such as OpenStreetMap tooling and many government GIS systems.

In the Interview#

Deep Dive: Designing a proximity service for 200 million placesShow

Requirements. A Yelp-style service stores 200 million businesses worldwide. Users search for businesses within a radius of 0.5 to 20 km, optionally filtered by category and opening hours, sorted by distance or rating. Peak load is 5,000 searches per second, and latency should be under 200 ms at the 99th percentile. Businesses are added or edited a few hundred thousand times a day, and a new business may take a few minutes to appear.

The key observation: it is read-heavy and nearly static. 5,000 reads per second against a few writes per second means the index can be built for reads, replicated freely, and updated in batches.

Option A: geohash columns in a relational database. Store each business with precomputed geohashes at several precisions, such as 4, 5 and 6 characters, each indexed. For a search, pick the precision by radius, compute the 9 cells, and run WHERE geohash6 IN (...) with the other filters, then post-filter by distance. Read replicas absorb the load: each query is 9 index lookups and a few hundred rows, perhaps 5 to 10 ms, so a handful of replicas handle 5,000 per second. Simple, and any database works.

Option B: an in-memory quadtree service. Load all 200 million businesses' IDs and coordinates, about 5 GB, into a quadtree on each of several index servers. A search returns business IDs in a millisecond or two; business details then come from a database or cache by ID. The quadtree adapts to density, so a k-nearest search in Manhattan and in rural Nevada both read only a few leaves. New businesses are applied every few minutes from a change stream, and a fresh server loads a nightly snapshot plus the stream.

Option C: Elasticsearch. Index businesses with geo_point, text fields and attributes, and run geo_distance filters with category filters and a decay-based ranking. It handles text queries such as "vegan brunch" as well, at the cost of running a search cluster.

A sensible combination. PostgreSQL with PostGIS, or with geohash columns, as the source of truth; Elasticsearch, or an in-memory index, for search; and a result cache keyed by the 6-character geohash of the user's location, the radius bucket and the filters, with a TTL of a few minutes. Popular areas, such as city centres at lunchtime, serve most queries from the cache. Shard the search index by region if it outgrows a node: a query near a region boundary queries both regions and merges.

Capacity check. 5,000 searches per second with a 60% cache hit rate leaves 2,000 per second for the index. Each Elasticsearch geo query over a regional shard takes perhaps 10 to 30 ms, so a cluster of a few nodes per region with replicas has ample headroom. Business details, 200 million records of about 1 KB, are 200 GB, served from a sharded database and cached by ID. See Design a Proximity Service.

Deep Dive: Candidate counts, precision and the cost of a queryShow

The cost of a cell query is the number of candidates. Every approach reads some area A of index and checks every point in it, while the useful answer comes from a circle of area πr². With point density ρ per km², the work is about ρ × A candidates, and the waste is the ratio A / πr².

A worked example in a dense city. Suppose a dense downtown area has about 330 food businesses per km², the kind of density found in the centres of the largest cities. A 1 km radius search:

  • 9 cells of 5-character geohash, about 4.9 km by 4.9 km each, so 216 km²: if the whole block were that dense, about 70,000 candidates. Far too many.
  • A block of 6-character cells, 1.2 km by 0.6 km each, arranged 3 across and 5 tall to cover a 2 km by 2 km square: about 11 km², roughly 3,600 candidates, about 3.5 times the circle's 1,040. Acceptable.
  • An S2 covering of the circle with up to 16 cells at mixed levels: perhaps 4.5 km², about 1,500 candidates, 1.4 times the circle, at the cost of up to 16 range scans.
  • A quadtree with leaf capacity 100: in such a dense area, leaves are small, so a 1 km circle overlaps perhaps 15 to 25 leaves, about 1,500 to 2,500 candidates.

So the choice of precision matters more than the choice of structure: a poorly chosen cell size turns a few thousand candidates into tens of thousands.

Distance checks are cheap; reading rows is not. An exact equirectangular distance takes nanoseconds, so checking 3,000 candidates is a few microseconds of CPU. The real cost is reading them: 3,000 index entries from memory is fast, but 3,000 random row reads from disk is slow. That is why spatial indexes often store the coordinates in the index itself, so the post-filter happens without touching table rows, and the database fetches full rows only for the 20 results returned. PostGIS's GiST index on the location achieves this for the bounding-box step, and covering indexes or index-only data in Elasticsearch help similarly.

k-nearest without a radius. For "the 20 nearest", an expanding search is efficient when density is unknown: start small and grow the radius by a factor of 2 to 4 until at least 20 candidates lie within the guaranteed radius. In a dense city, the first step often suffices; in a rural area, several steps run, each cheap because the cells are nearly empty. Tree indexes with incremental nearest-neighbour search, such as PostGIS's <->, do this automatically, visiting nodes in distance order.

Filters change the arithmetic. If only 5% of businesses match the user's filter, such as "open now and vegan", the index must produce 20 times more candidates to find 20 results. Either apply the filter inside the index scan, as Elasticsearch and PostgreSQL can when the filter is indexed, or keep separate indexes for common categories, or widen the radius when results are filtered out.

Deep Dive: Edge cases, precision and location privacyShow

The antimeridian and the poles. A bounding box around Fiji, which straddles longitude 180, has a western edge at 179 degrees and an eastern edge at −179 degrees. Naive code that requires lng BETWEEN west AND east either finds nothing or wraps the box the long way around the planet. Correct code splits such boxes into two, one on each side of the meridian. Near the poles, a circle of a few hundred kilometres can cover every longitude, so the bounding box must expand to the full longitude range. Geohash cells and naive grids handle both cases poorly; S2 and PostGIS's geography type handle them correctly.

Projections. Web maps use Web Mercator, EPSG:3857, which keeps angles and shapes locally correct but stretches areas enormously towards the poles: Greenland looks as large as Africa, which is about 14 times bigger. Distances and areas computed in Mercator coordinates are wrong except near the equator. Store and compute in WGS 84 latitude and longitude, EPSG:4326, with spherical or ellipsoidal math, or in a local equal-distance projection for city-scale work, and use Mercator only for drawing tiles.

Numeric precision. A 32-bit float has 24 bits of precision, so a longitude near 180 is stored to about 0.00002 degrees, about 2 metres: often enough for display, not for surveying. A 64-bit double is precise to well under a millimetre. Storing coordinates as integers of microdegrees, the degrees times one million, gives about 11 cm precision in 4 bytes each, a compact choice for large point sets. Five decimal places in text are about 1 metre, six about 10 cm; GPS on a phone is typically accurate to about 5 metres in open sky, and much worse among tall buildings.

Location privacy. Location is among the most sensitive data a service holds: a few points reveal home, work and habits. Practical protections include storing only what is needed, rounding or snapping displayed locations to a grid, deleting history after a retention period, and access controls on raw positions. Apps that show exact distances to other users are vulnerable to trilateration: an attacker who measures the distance to a victim from three spoofed positions can compute the victim's location. Dating apps have had to defend against this by rounding distances, snapping users to grid cells before computing distances, and rate-limiting location changes. More formal techniques exist, such as geo-indistinguishability (Miguel Andrés, Nicolás Bordenabe, Konstantinos Chatzikokolakis and Catuscia Palamidessi, "Geo-Indistinguishability: Differential Privacy for Location-Based Systems", CCS 2013), which adds calibrated noise to reported locations. See Security Fundamentals and Design a Dating App.

Testing. Build a test set of tricky locations: points exactly on cell boundaries, the equator and prime meridian at (0, 0), where four top-level geohash cells meet, Fiji and the Bering Strait for the antimeridian, Svalbard and Antarctica for high latitudes, and very dense and very empty areas. Compare every query against a brute-force exact scan over a sample, which catches missing neighbours and swapped coordinates immediately.

Key Takeaways#

  • A B-tree on latitude and longitude returns a band, not a neighbourhood, because a one-dimensional order cannot preserve two-dimensional closeness.
  • Spatial indexes generate candidates; exact distance or geometry always finishes the query.
  • Geohash interleaves bits along a Z-order curve: shared prefixes mean nearness, but near points may not share prefixes, so query the cell and its 8 neighbours and post-filter.
  • Quadtrees adapt to density and suit in-memory, read-heavy indexes; k-d and BKD trees split at the median, and BKD trees power Elasticsearch's geo_point.
  • R-trees index shapes with bounding rectangles, stay balanced on disk, and underlie PostGIS's GiST indexes; use ST_DWithin and <-> so the index is used.
  • S2 builds equal-area cells on the sphere along a Hilbert curve, with region coverings; H3 uses hexagons with six equidistant neighbours, ideal for rings and analytics.
  • Redis GEO stores geohashes in sorted sets: fast for moving points, but shard keys by area and expire stale members yourself.
  • For moving objects, keep latest positions in memory, update the cell index only when the cell changes, expire stale entries, and claim results atomically.
  • Choose precision to match the radius, expand when results are few, and remember that the number of candidates, not the structure, sets the cost.
  • Spatial trees for shapes, encoded cells for moving points, and always post-filter.