Geospatial Indexing: Geohash, Quadtree, R-Tree
"Grid systems are critical to analyzing large spatial data sets, partitioning areas of the Earth into identifiable grid cells." — Isaac Brodsky, H3: Uber's Hexagonal Hierarchical Spatial Index, Uber Blog, 27 June 2018
Summary: "Who is within 2 km of me?" and "which 10 drivers are nearest?" cannot be answered by a normal B-tree on latitude and longitude; a geospatial index turns two-dimensional closeness into something a one-dimensional index, a tree or a hash map can search, at the price of cell borders, approximations and an exact-distance filter on top. Focus: the proximity problem and why two B-trees fail, coordinate systems (WGS84, SRID 4326 and 3857, great-circle distance, haversine, projection), geohash (base32, Z-order curve, precision, neighbour cells, boundary problem, prefix search), S2 (Hilbert curve, cell levels, coverings) and H3 (hexagons, resolutions, k-ring), quadtrees (point and region), R-trees and R*-trees (MBR, GiST, SQLite R*Tree), k-d trees, ball trees and grid indexes, the real products (Redis GEO, PostGIS, MySQL, MongoDB 2dsphere, Elasticsearch geo_point and geo_shape), moving objects and hot cells, geofencing and privacy truncation, with Go and Laravel 13 code. Learning goal: Given a query (radius, bounding box, polygon containment, kNN) and a data motion (static, slowly changing, or thousands of updates per second), choose an index, state its error and its failure mode (the boundary problem, hot cells, the antimeridian), and implement the filter-then-refine pattern that every product uses.
This chapter sits in the Distributed Systems Primitives group, after CRDTs and before Top-K & Heavy Hitters. It owns the system-level decision, the numbers and the trade-off tables for location data. The mechanics live with their owners: B-tree and GiST internals in Indexing, plans in Query Planning, the Redis server in Redis, shard placement in Sharding at System Level, keyword and relevance search (not location) in Search Systems, and the full ride-hailing design that uses all of this in Case Study: Uber.
Page map
| If you are looking for | Go to |
|---|---|
| The whole page in three tables | Everything in one minute |
| Why not just index latitude and longitude | Why it exists, The proximity problem |
| Sources and dates for each structure | Where it comes from |
| Degrees, metres, SRID, haversine, projections | Coordinates and distance |
| Geohash, boundaries, precision, prefix search | Geohash |
| S2 and H3 | Space-filling curves and S2, H3 |
| Quadtree, R-tree, k-d tree, ball tree, grid | Quadtree, R-tree, k-d tree and ball tree, Grid index |
| Redis, PostGIS, MySQL, MongoDB, Elasticsearch, SQLite | Redis GEO, PostGIS, Other databases |
| Millions of moving points | Moving objects |
| Is this point inside that zone | Geofencing |
| Location privacy | Privacy and truncation |
| Exact knobs, limits, error messages | Mechanics |
| Code | Go, Laravel |
| Nearby drivers, viewport, polygon, closest store | Solving the classic problems |
| Which index for which query | Choosing |
| Monolith to distributed system | In architecture |
| Measured demo and drills | Lab |
| Wrong beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The structures.
| Structure | In plain words | Tiny example | Good at | Bad at |
|---|---|---|---|---|
| Geohash | Interleave the bits of lon and lat, write base32; a prefix is a cell | ezs42 is a cell of about 4.9 km | Any key-value store or B-tree; prefix scans | Cell borders: neighbours may share no prefix |
| S2 cells | Cube faces, four children per cell, numbered along a Hilbert curve | Level 13, one 64-bit id | Uniform global cells, coverings of arbitrary regions | Library only; ids are not human-readable |
| H3 cells | Hexagons on an icosahedron, 16 resolutions, 7 children | Resolution 9 about 0.105 km2 | One neighbour distance, k-rings, analytics roll-ups | Children are approximate; 12 pentagons per resolution |
| Quadtree | Split a square into four when it holds too many points | Capacity 8, depth 16 | In-memory kNN and window queries on uneven density | Rebuilds, pointer chasing, no disk layout |
| R-tree / R*-tree | Balanced tree of bounding rectangles | PostGIS GiST, SQLite R*Tree | Points and shapes on disk, overlap queries | Overlapping rectangles; write amplification |
| k-d tree / ball tree | Binary space split by axis, or by nested balls | scikit-learn, Go libraries | Static kNN in memory | Hard to update; poor on the sphere without care |
| Grid / bucket index | Hash map from cell to items | floor(x / 500 m) | Simple, fast updates, easy sharding | Cell size is a guess; hot cells |
The tools.
| Product | Spatial type | Index | Radius | kNN | Polygon |
|---|---|---|---|---|---|
| Redis | Sorted set with geohash score | The sorted set itself | GEOSEARCH ... BYRADIUS | GEOSEARCH ... COUNT n ASC | No (box and circle only) |
| PostgreSQL + PostGIS | geometry, geography | GiST, SP-GiST, BRIN | ST_DWithin | ORDER BY a <-> b LIMIT k | ST_Covers, ST_Contains |
| MongoDB | GeoJSON, legacy pairs | 2dsphere | $geoWithin with $centerSphere, $nearSphere | $near sorted by distance | $geoWithin, $geoIntersects |
| Elasticsearch | geo_point, geo_shape | BKD tree in Lucene (inference from Lucene design) | geo_distance | sort by _geo_distance | geo_shape queries |
| MySQL | POINT, POLYGON | SPATIAL index (R-tree) in InnoDB | ST_Distance_Sphere plus box filter | ORDER BY ST_Distance_Sphere | ST_Contains, MBRContains |
| SQLite | Rectangles | R*Tree virtual table | Box overlap, then exact check | Application code | Application code |
The problems and their first fix.
| Problem | Symptom | First fix | Section |
|---|---|---|---|
| Two B-trees on lat and lon | Slow, wrong shape (square in degrees) | One spatial index, then exact distance | Proximity |
| Neighbours with different geohash prefixes | A driver 20 m away is missing | Query the cell plus 8 neighbours | Geohash |
| Longitude and latitude swapped | Points land in the sea | GEOADD and ST_MakePoint take lon first; test with a known city | Coordinates |
| Distance in degrees | Radius is an ellipse | haversine or geography, or project first | Coordinates |
| Millions of location updates | Index writes dominate | Keep live points in memory or Redis; batch durable history | Moving objects |
| One cell has 10,000 drivers | One shard or key is hot | Smaller cells, sub-split hot cells, shard by cell | Moving objects |
| Ghost drivers | Offline drivers still match | TTL on last update; sweep or expire | Moving objects |
| Location leaks | Raw coordinates in logs and APIs | Truncate or snap to a cell | Privacy |
Numbers to keep in your head. Each is from a cited page or a labelled calculation.
| Fact | Value | Source |
|---|---|---|
| Redis geo score | 52-bit interleaved integer in a sorted set double | Redis GEOADD docs |
| Redis geo latitude limit | -85.05112878 to 85.05112878 degrees | Redis GEOADD docs |
GEORADIUS status | Deprecated since 6.2.0, replaced by GEOSEARCH | Redis GEORADIUS docs |
| Geohash length 5 error | about 2.4 km (cell about 4.9 km wide, my calculation) | Wikipedia (secondary), calculation |
| Geohash length 7 error | about 76 m | Wikipedia (secondary) |
| S2 levels | 0 to 30, leaf cells about 1 cm, 6 * 4^30 of them | s2geometry.io |
| H3 resolutions | 0 to 15; 122 cells at res 0, 12 pentagons per resolution | h3geo.org |
| H3 average hexagon area | res 8: 0.737 km2; res 9: 0.105 km2; res 10: 0.015 km2 | h3geo.org |
| Mean Earth radius for haversine | 6,371,008.8 m (error up to about 0.5% vs the ellipsoid) | Standard IUGG value; error from the spherical approximation |
| Measured here: 200,000 points, 1 km radius | full scan 5.9 ms; geohash 5 plus exact filter 0.39 ms; quadtree 0.019 ms | Lab demo on one laptop, see Lab |
The picture shows the central trick of the page. A 4 by 4 grid is numbered along a Z-shaped curve, so "inside this cell" becomes a prefix or a numeric range. The two shaded cells touch on the map but are nine steps apart on the curve: that is the boundary problem, and every cell-based index needs the same fix (look at the neighbours too).
Why it exists
A "nearby" feature (drivers near a rider, shops near a phone, friends within 5 km) is a question about closeness in two dimensions. Relational and key-value indexes are one-dimensional: they keep keys in one sorted order. A geospatial index maps two dimensions to something that order, a tree or a hash can use, and returns a small candidate set that the application then filters by exact distance.
| Without a spatial index | With a spatial index |
|---|---|
| Scan every row and compute distance: O(n) per request | Read a few cells or tree nodes: about O(log n + k) |
| Two B-tree ranges (lat strip and lon strip), intersect afterwards | One structure that prunes both axes at once |
| "Radius" is a square in degrees | Radius is metres on the sphere (after a refine step) |
| Nearest 10 requires a full sort | kNN reads results in distance order and stops |
| Easy to write, dies at about a million points | Scales to hundreds of millions, with caveats |
One analogy, reused through the page: a city street map with a grid. The map has squares labelled A1 to J20 (cells). To find coffee shops near you, you look up your square and the eight around it, then use a ruler on the few shops you find (the exact-distance filter). Squares are cheap but you may stand on a border (look at the neighbours). In a dense downtown a square holds hundreds of shops, in a desert none (quadtree: cut crowded squares into four). A better atlas draws boxes around groups of nearby shops and boxes around those boxes (R-tree).
Three common misunderstandings, up front
- "A geohash prefix tells me what is near." It tells you what is inside the same cell. Near points can have completely different prefixes (the boundary problem), so a correct query reads the cell and its eight neighbours.
- "The index returns the answer." It returns candidates. Every product here, from Redis
GEOSEARCHto PostGISST_DWithin, ends with an exact distance check; if you build your own index you must add it. - "Distance on lat/lon is just Pythagoras." One degree of longitude shrinks with the cosine of latitude (about 0.82 of a degree of latitude at 35 degrees north), and longitude wraps at 180 degrees. Degrees are not metres.
Where it comes from
Every statement below was read on the saved page named in References. Secondary sources are labelled.
| Source | What it states | Why it matters here |
|---|---|---|
| Finkel and Bentley, Quad trees: a data structure for retrieval on composite keys (1974) | Quadtree, invented 1974 by Raphael Finkel and J. L. Bentley (the Wikipedia infobox, secondary; the paper itself is behind a paywall and was not fetched) | The first practical hierarchical subdivision of a plane |
| Guttman, R-trees: a dynamic index structure for spatial searching (SIGMOD 1984) | "a dynamic index structure called an R-tree" for objects of non-zero size in multi-dimensional space, with search and update algorithms | The basis of GiST spatial indexes, SQLite R*Tree, MySQL SPATIAL indexes |
| Morton (1966), as reported by Wikipedia (secondary) | Z-order idea in "A Computer Oriented Geodetic Data Base and a New Technique in File Sequencing" | The bit interleaving behind geohash |
| Gustavo Niemeyer, geohash (2008) | Public-domain geocoding invented in 2008; short strings, shared prefix means same cell, longer means more precise | The most portable cell index; works in any string-keyed store |
Redis 3.2 (2016), GEOADD docs | Data is "stored into the key as a sorted set"; 52-bit geohash score; GEOSEARCH since 6.2.0 | Geospatial queries on a sorted set |
| PostGIS manual | geometry (planar), geography (geodesic); ST_DWithin uses indexes; <-> distance operator | The reference SQL implementation |
| Google S2 (s2geometry.io) | Unit sphere decomposed into cells; six cube faces; levels 0 to 30; 64-bit S2CellId along a Hilbert-curve-based path | Uniform, hierarchical, sortable cells for any region |
| Uber H3 (2018) | Hexagonal hierarchical index; "hexagons have only one distance between a hexagon centerpoint and its neighbors"; used to compute surge pricing from supply and demand per hexagon | Hexagons, k-rings and roll-ups |
MongoDB 2dsphere docs | Index on an earth-like sphere; GeoJSON or legacy pairs; longitude first | Document-database geo queries |
| Elasticsearch docs | geo_point accepts lat-lon pairs for bounding box, distance and polygon queries; geo_shape for arbitrary shapes | Search-engine geo queries |
| SQLite R*Tree docs | "An R-Tree is a special index that is designed for doing range queries" over rectangles | Embedded spatial index |
The concept catalogue
Each block follows the same order: plain words, the usual wrong belief, a definition, a sequence, real scenarios, how products provide it, and how to use it.
The proximity problem and why B-trees on lat/lon fail Must-know
In plain words: "find things near this point" has two coordinates that both matter at once, but an ordinary index sorts by one thing at a time.
Common misunderstanding: "Index lat and lon and the database will combine them." It can use one index to read a strip (all points with latitude in a band) and then filter that strip by longitude, or intersect two bitmap scans; both read far more than the answer. A band one kilometre tall around the globe holds roughly every point at that latitude, not the ones near you.
Definition: the proximity problem comes in four shapes: a radius query (all points within r metres), a bounding box query (all points in a rectangle, such as a map viewport), polygon containment (all points inside a zone), and kNN (the k nearest points). A spatial index must support at least the first two with sub-linear cost.
Request: drivers within 1 km of (35.689, 51.389), two B-trees on lat and lon
1 Plan A: range scan lat in [35.680, 35.698] -> every driver in a strip 2 km tall, any longitude
2 Filter lon in [51.378, 51.400] -> keep a few, after reading the whole strip
3 Square in degrees, not a circle in metres -> corners are 1.4 km away, east-west is shorter than north-south
4 Order by distance -> compute for every candidate, then sort
5 Plan B: bitmap AND of both indexes -> two big bitmaps, then heap fetchesReal scenario: a ride-hailing table of 5 million rows where the "nearby" endpoint scans a 50 km latitude band; a store locator that sorts all stores by distance on each request; a "friends nearby" feature that returns the first 50 rows of a square, not the nearest 50.
What each approach costs:
| Approach | Reads for one radius query | Notes |
|---|---|---|
| Full scan with haversine | All n rows | Fine below about 10,000 points |
| B-tree on lat, filter on lon | A whole latitude band | Skew: dense cities dominate |
| Composite B-tree (lat, lon) | Same band, order matters | Only the first column prunes |
| Geohash prefix in a B-tree | A few prefix ranges | Needs neighbours; approximate cell shape |
| GiST / R-tree | A few tree nodes | Exact for boxes; refine for circles |
| Redis geo | A few score ranges in a sorted set | In memory; points only |
How to use it: write the query as one of the four shapes, pick the index in Choosing, always add the exact-distance refine step, and compare with the baseline in the Lab.
Coordinates, WGS84, SRID, projections and distance Must-know
In plain words: a location is a latitude (north-south, -90 to 90) and a longitude (east-west, -180 to 180) on a model of the Earth; distance on a sphere is not distance on a flat sheet.
Common misunderstanding: "Lat/lon is x/y." Mathematically the pair is (lat, lon) in speech and (lon, lat) in most GIS code (x is longitude), which is the single most common spatial bug. Redis GEOADD key longitude latitude member, PostGIS ST_MakePoint(lon, lat) and GeoJSON [lon, lat] are longitude first; Elasticsearch arrays are [lon, lat] but strings are "lat,lon"; Google Maps URLs are lat first.
Definition: WGS84 is the datum GPS uses; its EPSG code, also called SRID 4326, labels coordinates in degrees. A projection maps the curved Earth to a plane in linear units: Web Mercator (EPSG:3857, SRID 3857) powers web maps and inflates distances by 1/cos(lat), UTM zones are accurate within a band, and a local equirectangular approximation x = lon * cos(lat0) is enough for a city. Great-circle distance is the shortest path on the sphere; the haversine formula computes it from two lat/lon pairs and is accurate to about 0.5% against the ellipsoid; PostGIS geography uses the spheroid (more exact, slower).
Distance from Paris (48.8566, 2.3522) to London (51.5074, -0.1278)
1 Pythagoras on degrees sqrt(2.65^2 + 2.48^2) = 3.63 "units" -> meaningless
2 Haversine, R = 6371 km about 343.5 km -> great-circle on a sphere
3 ST_Distance(geography) close to 343 km -> spheroid; differs slightly from the sphere
4 ST_Distance(geometry 3857) larger by about 1/cos(lat) = 1.5-1.6x here -> Mercator inflation, wrong for distanceReal scenario: a delivery app shows "1.2 km" using planar maths and drivers in Norway see numbers 40% off; a viewport query crosses the antimeridian (Fiji, the Aleutians) and returns nothing because minLon > maxLon; a fleet service stores 3857 and reports distances as metres.
What each product assumes:
| Product | Coordinate order | Distance behaviour |
|---|---|---|
| Redis GEO | longitude, latitude | Spherical haversine; latitude limited to +-85.05112878 |
PostGIS geography | ST_MakePoint(lon, lat) | Geodesic metres on the spheroid by default |
PostGIS geometry | ST_MakePoint(x, y) | Planar in the SRID's units; SRID 4326 geometry gives degrees |
MongoDB 2dsphere | [longitude, latitude] | Spherical metres for $near and $geoNear |
Elasticsearch geo_point | object lat/lon, array [lon, lat], string "lat,lon" | Arc distance by default |
| S2 / H3 | LatLng constructors take degrees, lat first | Cells, not distances |
How to use it: store WGS84 lon/lat, convert to geography or a metric projection only inside a query, validate ranges at the API boundary (the Laravel controller below rejects values outside the Redis limits), and test every integration with a known place (Tehran is about lon 51.39, lat 35.69, so a swap puts the point in the Indian Ocean).
Geohash Must-know
In plain words: cut the world in half by longitude, then each half in two by latitude, and so on; write the left/right and up/down answers as bits, read five bits at a time as a base32 character. Points whose characters match from the start are in the same box.
Common misunderstanding: "Longer common prefix means closer, and no common prefix means far." The first direction is true (a shared prefix means the same cell), the second is false: two points either side of the equator, the prime meridian or any cell border share no prefix at all, yet they may be metres apart. Wikipedia notes the same edge cases near the 180 degree meridian and the poles.
Definition: a geohash is the base32 (alphabet 0123456789bcdefghjkmnpqrstuvwxyz, no a, i, l, o) encoding of the Morton code (Z-order curve interleave) of the longitude and latitude bisection bits, longitude bit first. Each character adds five bits; a prefix names a rectangle that contains all longer hashes beginning with it. Neighbour cells are found by decoding the cell, stepping one cell width or height, and re-encoding.
Encode (lat 42.6, lon -5.6) with 5 characters
1 lon in [-180,180], mid 0 -5.6 < 0 -> bit 0 range [-180, 0]
2 lat in [-90, 90], mid 0 42.6 >= 0 -> bit 1 range [0, 90]
3 lon in [-180,0], mid -90 -5.6 >= -90 -> bit 1 range [-90, 0]
4 lat in [0,90], mid 45 42.6 < 45 -> bit 0 range [0, 45]
5 ... 25 bits in total: 01101 11111 00000 10001 00010 -> e z s 4 2
6 result "ezs42"; prefix "ezs" is a larger cell that contains itReal scenario: a key-value store with no geo support (DynamoDB, Cassandra, Redis hashes) keeps a geohash7 attribute and answers "within 1 km" with nine prefix queries; Elasticsearch accepts a geohash string as a geo_point; geohash.org turns a location into a shareable short link; a push service truncates to 5 characters before logging.
Precision per length (cell size at the equator is my calculation from the bit counts; error is the Wikipedia table, secondary):
| Length | lon bits / lat bits | Cell (width x height) | Typical use |
|---|---|---|---|
| 1 | 3 / 2 | 5,009 km x 5,009 km | Continents |
| 2 | 5 / 5 | 1,252 km x 626 km | Countries |
| 3 | 8 / 7 | 157 km x 157 km | Regions |
| 4 | 10 / 10 | 39.1 km x 19.6 km | Metropolitan area |
| 5 | 13 / 12 | 4.9 km x 4.9 km | City district; radius queries of a few km |
| 6 | 15 / 15 | 1.22 km x 0.61 km | Neighbourhood; radius up to about 600 m |
| 7 | 18 / 17 | 153 m x 153 m | Street block; driver matching |
| 8 | 20 / 20 | 38 m x 19 m | Building |
| 9 | 23 / 22 | 4.8 m x 4.8 m | Entrance |
| 10 | 25 / 25 | 1.2 m x 0.6 m | Parking spot |
| 11 | 28 / 27 | 0.15 m x 0.15 m | Sub-metre; mostly beyond GPS accuracy |
| 12 | 30 / 30 | 3.7 cm x 1.9 cm | Rarely useful |
Prefix search in any key-value store. Store the hash as the (sort) key or a string attribute with a prefix-capable index (text_pattern_ops in PostgreSQL), then scan the range [prefix, prefix + "~"). For a radius r choose the shortest length whose cell is at least r wide and tall, compute the cell and its 8 neighbours, scan the nine prefixes, and refine by haversine. If r is larger than the cell, nine cells do not cover the circle (the Go helper documents this).
How to use it: pick the length from the table, never from the middle of a range (a 1 km radius with a 1.22 km by 0.61 km cell can miss points; use length 5 or add the next ring), keep both the hash and the raw coordinates (the hash is lossy), and test the boundary case on the equator, the prime meridian and the antimeridian (the Go tests do).
Space-filling curves and S2 cells Important
In plain words: a space-filling curve visits every cell of a grid in one long path, so a place on the plane gets a single number; places that are close on the path are usually close on the map. S2 uses such a curve on a cube wrapped around the Earth.
Common misunderstanding: "Any curve keeps neighbours together." Z-order jumps (cells 3 and 12 in the picture above). The Hilbert curve jumps less: it is continuous, with no long diagonal leaps, so its ranges cover more compact regions and a covering needs fewer ranges.
Definition: S2 (Google, s2geometry.io) projects the six faces of a cube onto the unit sphere and subdivides each cell into four children recursively. Cell levels run from 0 to 30; level 30 leaf cells are about 1 cm and there are 6 * 4^30 of them. Each cell has a 64-bit S2CellId; the S2 curve is "six Hilbert curves linked together to form a single continuous loop", so the ids of all descendants of a cell form one contiguous range (RangeMin to RangeMax). A covering approximates a region (a circle, polygon or the viewport) by a small set of cells; the RegionCoverer takes MinLevel, MaxLevel and MaxCells.
Radius query "within 1 km" with S2 in any ordered store
1 cap = circle(center, 1000 m / R) -> a spherical cap
2 RegionCoverer{Min 10, Max 16, MaxCells 8} -> at most 8 cells, mixed levels
3 for each cell: range [id.RangeMin, id.RangeMax] -> 8 range scans on a B-tree of 64-bit ids
4 union of rows -> candidates
5 refine: exact distance <= 1000 m -> final answerReal scenario: Google's own S2 library is the reference; MongoDB's 2dsphere index and CockroachDB's geospatial index are also S2-based (from their public design, not from a page fetched for this chapter); a store with 64-bit integer keys can range-scan a covering with no special type.
What the structure gives you:
| Property | Geohash | S2 | H3 |
|---|---|---|---|
| Cell shape | Rectangle (distorted near the poles) | Quadrilateral on the sphere | Hexagon (12 pentagons) |
| Hierarchy | Prefix | 4 children, levels 0 to 30 | 7 children, resolutions 0 to 15 |
| Key | String | 64-bit integer | 64-bit integer |
| Curve | Z-order | Hilbert | None (index encodes the path) |
| Region cover | Manual: prefix list | RegionCoverer | polygonToCells |
| Neighbours | Compute by decode/encode | Neighbour API | gridDisk (k-ring) |
How to use it: the Go snippet s2cover builds a covering for a radius and converts it to [RangeMin, RangeMax] pairs; use cell levels 12 to 16 for city-scale matching and cap the number of cells (8 to 20) so one query is a handful of range scans.
H3 hexagonal cells Important
In plain words: cover the Earth with hexagons (and a few pentagons) at several sizes; a point belongs to exactly one hexagon at each size, and a hexagon's neighbours are all the same distance away.
Common misunderstanding: "A hexagon cell contains exactly its seven child hexagons." It does not: hexagons do not subdivide cleanly, so the seven children only approximate the parent (H3's docs: "by alternating the orientation of grids a subdivision into seven cells can be approximated"). Aggregate on one resolution rather than assuming exact containment, and note there are always exactly 12 pentagons at every resolution.
Definition: H3 is Uber's hierarchical hexagonal index, laid out on an icosahedron: 122 base cells at resolution 0, aperture 7 (about seven children per cell), resolutions 0 to 15. A k-ring (called gridDisk in H3 v4; kRing in Uber's original post) returns the cell and all cells within k grid steps: 1 + 3k(k+1) cells (7 for k=1, 19 for k=2, 37 for k=3). Uber chose hexagons because "hexagons have only one distance between a hexagon centerpoint and its neighbors", compared to two for squares and three for triangles, which "greatly simplifies performing analysis and smoothing over gradients."
Surge pricing sketch (the use Uber describes: supply and demand per hexagon)
1 rider opens app at (lat, lon) -> cell = LatLngToCell(lat, lon, res 8) about 0.74 km2
2 demand[cell] += 1 -> count requests per hexagon per minute
3 driver positions -> supply[LatLngToCell(...)] += 1
4 smooth: ring = GridDisk(cell, 1) -> average over the 7 cells, no square-corner bias
5 multiplier = f(demand_ring / supply_ring) -> a business function, not part of H3Real scenario: Uber's H3 post reports bucketing events into hexagons for city-level analysis and surge pricing; a delivery company rolls up orders per resolution-8 cell; a map heat layer at resolution 9 (about 0.105 km2 per cell on average); a data warehouse uses h3_cell as a join and group key.
H3 resolution quick reference (average hexagon area from h3geo.org):
| Resolution | Average area | Typical use |
|---|---|---|
| 5 | 252.9 km2 | Region roll-ups |
| 7 | 5.16 km2 | City zones |
| 8 | 0.737 km2 | Surge and demand cells |
| 9 | 0.105 km2 | Block-level heat maps |
| 10 | 0.015 km2 | Sub-block analysis |
| 12 | 0.0003 km2 | Building scale |
How to use it: the Go snippet h3cell uses github.com/uber/h3-go/v4, a cgo binding that needs a C toolchain; choose one resolution per metric, aggregate with GROUP BY cell, smooth with GridDisk, and use S2 or geohash instead when you need arbitrary region coverings in a plain key-value store.
Quadtree (point quadtree and region quadtree) Must-know
In plain words: put all points in one square; when a square has more than a few points, cut it into four equal squares; repeat only where it is crowded. Dense downtowns get deep trees, deserts stay shallow.
Common misunderstanding: "A quadtree is a database index." It is an in-memory structure with pointers and no standard disk layout; databases use R-trees (GiST) or cell keys instead. Its sweet spot is a service holding live points in RAM.
Definition: a region quadtree splits space into four equal quadrants regardless of data (used for images and rasters); a point quadtree (or point-region PR quadtree) splits at a fixed centre or at a data point and stores up to a bucket capacity of points per leaf. Dynamic splitting happens on insert when a leaf exceeds capacity, down to a maximum depth (otherwise many points at one location recurse forever). Range queries visit only quadrants that intersect the window; nearest-neighbour is a best-first search using a priority queue ordered by minimum possible distance. Finkel and Bentley introduced the structure in 1974.
Nearest 3 points to Q with a quadtree (priority queue of nodes and points)
1 push root (distance to its box = 0)
2 pop root -> push its 4 quadrants, each keyed by box-to-Q distance
3 pop NE (nearest box) -> leaf: push its 6 points keyed by exact distance
4 pop point p1 (nearest of all queued) -> result 1
5 pop point p2 -> result 2; pop point p3 -> result 3 (nothing queued is closer)
6 quadrants still in the queue are never opened: their boxes are farther than result 3Real scenario: an in-memory dispatcher keeping 100,000 driver positions per city; a game server finding entities near a player; collision detection; map clustering on a server. The measured kNN in the Lab below is about 7.8 microseconds for k=10 over 100,000 points on one laptop.
Per-structure behaviour:
| Property | Point quadtree (this chapter's Go code) | Region quadtree |
|---|---|---|
| Split rule | Four equal quadrants when a leaf exceeds capacity | Always four equal quadrants until uniform |
| Stores | Points with ids | Cells of a raster or region |
| Update | Insert and remove; moves are remove plus insert | Rebuild |
| Skew | Handles dense clusters with depth | Cost grows with resolution |
| Sphere | Planar only; project lat/lon first | Planar |
How to use it: the Go quadtree package gives Insert, Remove, Range, Radius and Nearest; project coordinates to local metres (Project), set capacity 8 to 32 and a depth cap, wrap it in a sync.RWMutex or shard per city, and keep Redis or a database as the durable store.
R-tree and R*-tree Must-know
In plain words: like a B-tree, but each entry is a rectangle (the smallest box that contains everything below it). To search, open every box that overlaps your window.
Common misunderstanding: "R-trees are only for polygons." They index any shape through its bounding box (MBR); points are degenerate boxes. And "R-tree search is exact": it finds boxes that overlap, then the database checks the real shape (ST_Intersects, ST_DWithin).
Definition: an R-tree (Guttman, 1984) is a height-balanced tree whose leaf entries are minimum bounding rectangles (MBRs) of objects and whose inner entries are MBRs of child nodes; nodes hold between a minimum and a maximum number of entries and split when full. Because sibling MBRs may overlap, a search may descend several branches. The R*-tree (Beckmann et al., 1990; not fetched for this chapter) refines the insertion and split heuristics (minimise overlap, forced re-insertion) to reduce that overlap; SQLite's module is named R*Tree.
Window query on an R-tree (two overlapping MBRs)
1 root node: entries R1, R2 -> test the window against each MBR
2 window overlaps R1 and R2 -> descend both (an overlap is paid twice)
3 R1 leaf: boxes a, b, c -> b overlaps the window, a and c do not
4 R2 leaf: boxes d, e, f -> e overlaps the window
5 candidates {b, e} -> refine with the exact geometry testReal scenario: PostGIS GiST indexes on geography or geometry columns (PostgreSQL's GiST docs: "B-trees, R-trees and many other indexing schemes can be implemented in GiST"); a SQLite mobile app with an R*Tree virtual table for map tiles; MySQL SPATIAL INDEX on InnoDB (per MySQL docs; the page was not fetched, see HANDOFF); store-locator tables with millions of polygons.
Per-engine behaviour:
| Engine | Structure | Notes |
|---|---|---|
| PostgreSQL + PostGIS | GiST (R-tree-like), also SP-GiST (quad-tree, k-d tree) and BRIN | CREATE INDEX ... USING gist (col); SP-GiST "facilitate[s] development of a wide range of different non-balanced data structures, such as quad-trees, k-d trees, and radix trees" |
| SQLite | R*Tree virtual table | "designed for doing range queries"; rectangles with min/max per axis; 32-bit float bounds by default |
| MySQL (InnoDB) | SPATIAL index | R-tree on geometry columns; needs a NOT NULL column; SRID-aware in 8.0 (per MySQL docs, see HANDOFF) |
| MongoDB | 2dsphere | S2 cells, not an R-tree |
| Elasticsearch / Lucene | BKD tree for points | k-d-based; inference from Lucene design, not quoted from the fetched pages |
How to use it: create the index, always let ST_DWithin or && use it (see PostGIS), bulk-load before indexing for better packing, and expect heavy write churn to bloat GiST; schedule REINDEX as for any index.
k-d tree and ball tree Good to know
In plain words: a k-d tree cuts the points in half by x, then by y, then x again, alternating axes. A ball tree groups points inside nested circles.
Common misunderstanding: "They are databases for geo data." They are in-memory structures for nearest-neighbour search over a mostly static set; neither is designed for frequent updates, and the standard k-d tree compares planar coordinates (a naive one on lat/lon breaks at the antimeridian and distorts with latitude).
Definition: a k-d tree is a binary space-partitioning tree: each node picks an axis, splits at the median, and nearest-neighbour search prunes the far side when the splitting plane is farther than the best so far. A ball tree stores a centre and radius per node and prunes with the triangle inequality, so it works with any metric including haversine. The point quadtree in this chapter is a close relative; PostgreSQL's SP-GiST can store a k-d tree or quad-tree on disk.
Real scenario: scikit-learn's BallTree(metric='haversine') for batch matching of 1 million points; a static dataset of 50,000 stations loaded at startup; an offline job joining two point sets.
| Structure | Update cost | Metric | Best for |
|---|---|---|---|
| k-d tree | Rebuild or lazy delete | Euclidean (project first) | Static kNN |
| Ball tree | Rebuild | Any, including haversine | Static kNN on the sphere |
| Quadtree | O(depth) insert/remove | Euclidean | Moving points in RAM |
| Grid | O(1) | Any (filter step) | Simplest moving-points case |
How to use it: use them for offline or static kNN; for live traffic prefer a grid, quadtree or Redis.
Grid (bucket) index Must-know
In plain words: divide the map into equal squares, keep a list of items per square, and look only at the squares around the query.
Common misunderstanding: "A grid is naive and nobody uses it." It is the base of geohash, S2 level cells and H3 at one level; production dispatchers use it because updates are O(1) and shards map onto cells.
Definition: a grid index maps (floor(x / s), floor(y / s)) to a bucket of ids. A radius query reads the buckets overlapped by the circle's bounding square (3 by 3 when radius is at most the cell size), then filters by exact distance. The weakness is the cell size s: too large and each bucket is crowded; too small and a query reads many empty buckets.
Driver update and query in a grid with 500 m cells
1 d17 reports (x=1203, y=-410) -> cell (2, -1)
2 d17 reports (x=1510, y=-390) -> cell (3, -1): delete from (2,-1), insert in (3,-1)
3 rider asks radius 400 m at (1480,-400) -> cells x 2..3, y -1..-1 (bounding square)
4 read 2 buckets, 41 drivers -> candidates
5 exact distance filter -> 9 drivers inside 400 m, sorted by distanceReal scenario: Uber-style supply maps (the H3 grid), a game with 1,000 players per region, the Go grid package here which also exposes Hottest() to find crowded cells and Expire() for TTL.
How to use it: pick the cell as large as the typical query radius, move items by delete-then-insert (a missed delete creates ghost entries), watch the hottest cell, and treat a cell as the unit of sharding.
Redis GEO Must-know
In plain words: Redis stores places in a sorted set whose score is a number made from the place's geohash, so a radius search is a few range lookups.
Common misunderstanding: "Redis GEO is a separate data type." There is no geo type: GEOADD writes a sorted set, TYPE returns zset, ZREM deletes a member (there is no GEODEL), ZRANGE works, and ZCARD counts. Also, GEORADIUS still appears in older tutorials but is deprecated.
Definition: GEOADD key [NX|XX] [CH] longitude latitude member ... adds items; the 52-bit interleaved geohash is the sorted-set score, exactly representable in a double. GEOSEARCH key (FROMMEMBER member | FROMLONLAT lon lat) (BYRADIUS r unit | BYBOX w h unit) [ASC|DESC] [COUNT n [ANY]] [WITHCOORD] [WITHDIST] [WITHHASH] (since Redis 6.2.0) replaces GEORADIUS, GEORADIUSBYMEMBER (deprecated as of 6.2.0); GEOSEARCHSTORE saves results; GEODIST returns the distance between two members; GEOPOS and GEOHASH read back. The search checks "the 1+8 areas needed to cover the whole shape" and discards elements outside it. Coordinates are limited to longitude -180 to 180 and latitude -85.05112878 to 85.05112878 (the Web Mercator limits).
Nearby drivers with Redis (key drivers:geo:tehran)
1 GEOADD drivers:geo:tehran 51.3890 35.6892 d17 -> (integer) 1
2 GEOADD drivers:geo:tehran 51.4000 35.7000 d18 -> (integer) 1
3 GEOSEARCH drivers:geo:tehran FROMLONLAT 51.39 35.69 BYRADIUS 2 km ASC COUNT 5 WITHDIST
4 1) 1) "d17" 2) "0.1100" -> nearest first, distance in km
5 ZREM drivers:geo:tehran d17 -> remove an offline driver (no GEODEL)
6 GEOADD with latitude 89 -> an error that starts with "ERR invalid longitude,latitude pair" (the coordinates are outside the limits above)Real scenario: a ride-hailing dispatcher keeping the last position per driver; a "stores near me" cache keyed per country; a food-delivery radius filter. With 52-bit hashes the stored position is rounded (sub-metre), so read back values differ slightly from what you wrote.
Per-product comparison with Redis variants:
| Feature | Redis (6.2+) | Redis Cluster | Notes |
|---|---|---|---|
| Add / search | GEOADD, GEOSEARCH | Same, one key lives on one slot | One huge geo key is one node: shard by city or cell key |
| Delete | ZREM | Same | No GEODEL |
| Shapes | circle, box | Same | No polygons |
| Expiry | None per member | None | Companion sorted set by last-seen time plus sweep |
| Old API | GEORADIUS, GEORADIUSBYMEMBER deprecated | Same | Migrate to GEOSEARCH |
How to use it: one geo key per city or per H3/geohash cell (hash tag the cell if you use Cluster), a companion ZADD seen for TTL, GEOSEARCH ... COUNT n ASC for dispatch. See the PHP DriverLocationStore below.
PostGIS: geography versus geometry, indexes and KNN Must-know
In plain words: PostGIS adds map types to PostgreSQL. geography knows the Earth is round and measures in metres; geometry is a flat plane and is faster and richer.
Common misunderstanding: "ST_Distance(a, b) < 1000 uses the index." It does not: ST_Distance is a function that must be computed for each row. ST_DWithin(a, b, 1000) "includes a bounding box comparison that makes use of any indexes that are available" and is the form to write; the PostGIS docs call ST_Distance the non-indexable step you apply only to the few rows ST_DWithin returns.
Definition: geometry(Point, 4326) stores coordinates in a spatial reference system (SRID); for SRID 4326 distances are in degrees. geography(Point, 4326) always measures on the spheroid in metres (use_spheroid = false uses a sphere for speed). A GiST index (CREATE INDEX ... USING gist (col)) is an R-tree-like structure over bounding boxes; SP-GiST offers quad-tree and k-d tree layouts; BRIN suits huge, physically ordered data. The <-> operator returns the distance between two values and, in an ORDER BY ... LIMIT k, lets the GiST index return rows nearest first (the KNN operator). SRID 3857 is Web Mercator, convenient for tiles and planar maths but not for reporting distance.
kNN with PostGIS (table places, 5 million rows, GiST index)
1 ORDER BY location <-> ST_MakePoint(51.389, 35.689)::geography LIMIT 10
2 planner: Index Scan using places_location_gix -> ordered by the index, not a sort
3 read tree nodes by distance to the query; stop after 10 rows
4 ST_DWithin(location, p, 1000) + ST_Distance for the display value
5 expected (not run): single-digit milliseconds with a warm cacheReal scenario: a marketplace "closest 20 sellers" with <->; a geofence table of delivery zones using ST_Covers; a viewport query with && and ST_MakeEnvelope; a data team storing SRID 3857 geometries for tiles. The full SQL is imported in the Solving section.
What to pick:
| Need | Type | Why |
|---|---|---|
| Metres on the planet, simple model | geography | Correct distance; fewer functions; slower |
| City-scale planar maths, lots of functions | geometry in a local projected SRID | Fast, rich; units match the projection |
| Web map tiles | geometry 3857 | Matches the tile grid |
| Global distance | geography or geometry with ST_DistanceSphere | Avoid Mercator distances |
How to use it: store geography(Point, 4326) with a GiST index, query radius with ST_DWithin, kNN with <->, polygon containment with ST_Covers, and run EXPLAIN to confirm an index scan (see Query Planning).
MySQL, MongoDB, Elasticsearch and SQLite Important
In plain words: most databases now index places; the query names differ but the pattern is the same: index, candidates, exact check.
Common misunderstanding: "All of them index the same way." They do not: MongoDB uses S2-based cell indexes, PostGIS an R-tree-like GiST, Elasticsearch a Lucene point structure, SQLite an R*Tree you query by rectangles. Behaviours differ on polygons, antimeridian handling and what the index guarantees.
Definition and usage:
| Product | Create | Radius | kNN | Polygon containment |
|---|---|---|---|---|
| MongoDB | db.places.createIndex({ loc: "2dsphere" }) | $geoWithin: { $centerSphere: [[lon, lat], r / 6378.1] } | $near: { $geometry: ..., $maxDistance: m } | $geoWithin: { $geometry: polygon } |
| Elasticsearch | mapping "location": { "type": "geo_point" } | geo_distance filter, distance: "2km" | sort by _geo_distance | geo_shape or geo_shape query; geo_shape stores lines, rectangles and polygons |
| MySQL | SPATIAL INDEX (loc) on a NOT NULL POINT SRID 4326 column | ST_Distance_Sphere plus an MBRContains box prefilter | ORDER BY ST_Distance_Sphere(...) LIMIT k (a sort of the box candidates) | ST_Contains, MBRContains |
| SQLite | CREATE VIRTUAL TABLE t USING rtree(id, minX, maxX, minY, maxY) | Box query then exact check in SQL or code | Application | Application |
MongoDB's 2dsphere docs say the index supports "queries on an earth-like sphere" and values may be "GeoJSON objects" or "legacy coordinate pairs"; Elasticsearch's geo_point docs list the object, array [lon, lat], string "lat,lon" and geohash input forms and note that a geo_point serves bounding box, distance and polygon queries.
Real scenario: a MongoDB product catalogue with 2dsphere for "available within 5 km"; Elasticsearch location-and-text search ("pizza near me") where relevance and distance combine; SQLite on a phone showing offline points in the viewport; a MySQL monolith using a POINT column with a spatial index. For text relevance plus distance see Search Systems and Full-Text Search.
How to use it: whichever product you choose, check three things: coordinate order, whether the radius query uses the index (explain it), and how polygons crossing the antimeridian behave.
Moving objects, location updates and hot cells Must-know
In plain words: drivers move every few seconds. A million of them means hundreds of thousands of position writes per second, and most of those writes are about data that will be stale in 10 seconds.
Common misunderstanding: "Store every GPS ping in the spatial database." A disk-based spatial index (GiST, R-tree) pays heavy write amplification per update. Hold live positions in memory (Redis GEO, an in-process grid or quadtree) and write history to an append-only log or time-series store in batches.
Definition: moving objects are entities whose position changes continuously; a location update is one position report. Each report must (1) update the live index, (2) refresh a last-seen time (TTL) so offline objects disappear, and (3) optionally append to history. A hot cell is a cell with far more objects or queries than its peers (an airport, a stadium, a city centre at 18:00); with cell-based sharding it becomes a hot shard.
Back-of-envelope (an estimate, not a measurement): 500,000 online drivers, one ping every 4 s
1 updates = 500000 / 4 = 125,000 writes/s -> a single Redis node handles this order of load only with pipelining; shard by city
2 per ping 40 bytes of history -> 5 MB/s, 430 GB/day -> compress or sample for storage
3 queries: 20,000 rider requests/s, each reads about 9 cells -> 180,000 cell reads/s
4 one cell downtown holds 8,000 drivers -> the exact-distance filter sees 8,000 candidates per query
5 fix: cell level one finer for that region, or per-cell sub-index, plus a COUNT limitReal scenario: the dispatch tier of a ride-hailing service (see Case Study: Uber); a fleet tracker with 30-second pings; a live-delivery map; a multiplayer game with regions. For batching and coalescing the writes see Write Buffering.
Where each design puts the write load:
| Design | Write cost per update | Query cost | Failure mode |
|---|---|---|---|
| PostGIS GiST row update | Heap tuple + index entry + WAL; MVCC bloat | Excellent for static data | Update storms bloat the index |
Redis GEOADD per ping | O(log N) sorted-set insert | GEOSEARCH is O(N+log(M)), N = elements in the grid-aligned box around the shape, M = items inside the shape | One key on one node; shard by city |
| In-process grid | O(1) map update | 9 buckets | Process restart loses state; rebuild from the stream |
| Kafka log + stream processor | Append; index consumer rebuilds | Indirect | Lag between truth and index |
How to use it: set a TTL by last-seen time (the Go Expire and the PHP expire), shard by city and then by cell, alert on the hottest cell population (Hottest()), drop updates that do not move more than a few metres, and rate-limit clients (the route group uses throttle:60,1; see Rate Limiting).
Geofencing and polygon containment Important
In plain words: a geofence is a virtual fence: a polygon or circle that triggers an action when a device enters or leaves it.
Common misunderstanding: "Check each device against every zone." With 10,000 zones and 1 million devices that is 10 billion polygon tests per sweep. Index the zones (GiST, or a cell covering) and test only the zones whose MBR or cells contain the point.
Definition: polygon containment tests whether a point is inside a polygon; the standard algorithm is ray casting (count edge crossings of a horizontal ray; odd means inside). Geofencing runs it on each location update and compares with the previous state to emit enter or exit events. Two stages: an index narrows the zones to a few candidates (R-tree MBR test, or a precomputed cell to zones map with S2 or H3), then the exact polygon test decides.
Geofence event pipeline
1 ping(d17, 35.689, 51.389) -> location update
2 candidates = zones whose MBR contains the point -> 2 of 10,000 via GiST / cell lookup
3 InPolygon(point, zone) for each candidate -> zone 7: inside, zone 9: outside
4 state[d17] was {} -> now {7}: emit ENTER zone 7
5 next ping leaves zone 7 -> emit EXIT zone 7 (hysteresis avoids flapping at the border)Real scenario: delivery zones and surge areas; airport pick-up lanes; "arrived at destination" detection; compliance regions that restrict content or features; asset tracking with alerts.
| Product | Polygon containment |
|---|---|
| PostGIS | ST_Covers(zone, point) or ST_Contains, GiST on the zone column |
| MongoDB | $geoWithin with $geometry polygon; $geoIntersects |
| Elasticsearch | geo_shape query with relation contains or intersects |
| Redis | No polygon support; do box or circle, then check in the application |
| Go (this chapter) | grid.InPolygon ray casting after a cell prefilter |
How to use it: keep zones in PostGIS, load a cell-to-zone cache for the hot path, test with a buffer or hysteresis near borders, and treat GPS error (5 to 20 m) as a reason for hysteresis rather than a bug.
Privacy and precision truncation Important
In plain words: exact coordinates identify homes and habits; if you only need "roughly where", store or show less precision.
Common misunderstanding: "Rounding to 3 decimals anonymises it." Three decimals is about 110 m; a repeated pattern of such points (home at night, office by day) still re-identifies a person. Truncation reduces precision, it does not make data anonymous.
Definition: privacy truncation is the deliberate reduction of location precision: dropping geohash characters (length 5 is about 4.9 km, length 6 about 1.2 km by 0.6 km), rounding coordinates to n decimal places (2 places is about 1.1 km of latitude), snapping to an H3 or S2 cell, or adding noise. Because geohash is a prefix structure, truncating is just cutting the string. Combine with access control, retention limits and not logging raw coordinates.
| Precision | Geohash length | Decimal places | Approximate resolution |
|---|---|---|---|
| Country or region | 2 to 3 | 0 | 100 km or more |
| City district | 5 | 2 | 1 to 5 km |
| Neighbourhood | 6 | 3 | 100 m to 1 km |
| Street block | 7 | 3 to 4 | 50 to 150 m |
| Exact | 9 or more | 5 or more | Metres or better |
Real scenario: a rider app that shows nearby drivers at 50 m granularity and never returns coordinates (the Laravel controller rounds distance to 50 m); analytics tables that store only an H3 resolution-8 cell; logs scrubbed to geohash 5.
How to use it: geo.Truncate in Go, rounding in the controller, and a retention policy for raw pings; remember that a "nearby" API that returns exact distances to many points can be used to triangulate a position (trilateration), so quantise distances and rate-limit.
Mechanics
Knobs and limits, per product
| Product | Knob or limit | Value or default | Effect |
|---|---|---|---|
| Redis | Latitude / longitude range | -85.05112878 to 85.05112878 / -180 to 180 | Points near the poles are not indexable |
| Redis | GEOSEARCH ... COUNT n ANY | optional | Return the first n found, not the nearest n: faster, unordered |
| Redis | GEOSEARCH vs GEORADIUS | GEOSEARCH since 6.2.0 | GEORADIUS is deprecated; GEORADIUS_RO exists for replicas |
| Redis | Coordinate precision | 52-bit geohash | Stored position is rounded; do not compare floats for equality |
| PostGIS | ST_DWithin(a, b, d) | index-assisted | Uses a bounding-box prefilter and then exact distance |
| PostGIS | ST_Distance(geography, geography, use_spheroid) | true | false measures on a sphere: faster, slightly less exact |
| PostGIS | <-> in ORDER BY with LIMIT | GiST or SP-GiST | Index returns rows nearest-first |
| PostGIS | SRID 4326 vs 3857 | degrees vs Mercator metres | Mercator metres inflate by 1/cos(latitude) |
| MongoDB | 2dsphere longitude range | -180 to 180; latitude -90 to 90 | Out-of-range values are rejected at index time |
| Elasticsearch | Input forms | object, array [lon, lat], string "lat,lon", geohash | Mixed orders are the common bug |
| SQLite | R*Tree bounds | 32-bit float (rtree) or 32-bit int (rtree_i32) | Values are stored at that width, so very fine bounds are rounded |
| Geohash | Length | 1 to 12 | Each character adds 5 bits |
| S2 | MaxCells of a covering | your choice, e.g. 8 to 20 | More cells: tighter fit, more range scans |
| H3 | Resolution | 0 to 15 | One step is about 7 times smaller area |
What goes wrong, verbatim
| Symptom or message | Meaning | Fix |
|---|---|---|
ERR invalid longitude,latitude pair (Redis GEOADD) | Coordinates outside the allowed range, often because lat and lon are swapped | Validate ranges; longitude first |
Operation on mixed SRID geometries (PostGIS) | Two geometries with different SRIDs in one function | ST_Transform one of them; set SRID with ST_SetSRID on creation |
Geometry SRID (0) does not match column SRID (4326) (PostGIS insert) | Point built without an SRID | ST_SetSRID(ST_MakePoint(lon, lat), 4326) |
Can't extract geo keys ... longitude/latitude is out of bounds (MongoDB) | Invalid coordinate in an indexed field | Reject at the API; longitude first |
geo_point mapping error "illegal latitude value" (Elasticsearch) | Lat outside -90..90, often a swap | Same |
| Results empty near longitude 180 | Box with minLon > maxLon mishandled | Split into two boxes or use a library that wraps (the Go Box does) |
| Nearest result missing although 20 m away | Boundary problem: neighbour cell not queried | Query the 9 cells, or use ST_DWithin/GEOSEARCH |
| Radius result looks like an ellipse | Degrees used as distance | Haversine, geography, or a metric projection |
| Index not used | ST_Distance(...) < d or a cast on the column | Use ST_DWithin; keep the column type unchanged in the predicate |
(The exact wording of the PostGIS, MongoDB and Elasticsearch messages is from common usage and was not on the pages fetched for this chapter; the Redis range limits and the PostGIS functions are from the saved docs.)
The filter-then-refine pattern
Every spatial index here returns a superset and every correct implementation adds an exact check. The first step is cheap and coarse (cells, MBRs), the second is exact and applied to few rows.
Filter then refine, whatever the index
1 query: radius 1000 m at P
2 filter: bounding box / 9 cells / tree nodes -> 120 candidates (cheap, may include false positives)
3 refine: haversine or ST_Distance <= 1000 -> 87 results (exact, applied to 120 rows only)
4 sort by distance, LIMIT k -> final answer
5 a false NEGATIVE in step 2 is a bug; a false positive is just workGo
Before
Two coordinates compared in degrees over a full scan: the shape and the cost are both wrong.
// Before: "nearby drivers" as two range predicates plus a full scan.
// This is what WHERE lat BETWEEN ... AND lon BETWEEN ... does when the only
// indexes are two separate B-trees: it works, but it reads a whole strip of
// the planet for every request and treats degrees as if they were metres.
package main
import (
"fmt"
"math"
)
type Driver struct {
ID int
Lat, Lon float64
}
// naiveNearby uses a square in DEGREES and Euclidean distance on raw
// coordinates. At latitude 60 a degree of longitude is half as long as a
// degree of latitude, so the "radius" is an ellipse on the ground.
func naiveNearby(all []Driver, lat, lon, radiusDeg float64) []Driver {
var out []Driver
for _, d := range all { // O(n): every driver is touched
if math.Hypot(d.Lat-lat, d.Lon-lon) <= radiusDeg {
out = append(out, d)
}
}
return out
}
func main() {
drivers := []Driver{{1, 35.6892, 51.3890}, {2, 35.7000, 51.4000}, {3, 59.9343, 30.3351}}
fmt.Println(len(naiveNearby(drivers, 35.69, 51.39, 0.05)), "driver(s) within 0.05 degrees")
}After
geo has haversine, a bounding box that wraps the antimeridian and truncation:
// Package geo holds the coordinate maths every index in this chapter needs.
package geo
import "math"
// EarthRadiusM is the IUGG mean Earth radius in metres (6371008.8).
// Haversine on this sphere is within about 0.5% of the WGS84 ellipsoid.
const EarthRadiusM = 6371008.8
// Point is a WGS84 position in degrees (SRID 4326), latitude first.
type Point struct{ Lat, Lon float64 }
// Valid reports whether the point is inside the WGS84 coordinate range.
func (p Point) Valid() bool {
return p.Lat >= -90 && p.Lat <= 90 && p.Lon >= -180 && p.Lon <= 180
}
func rad(d float64) float64 { return d * math.Pi / 180 }
// Haversine returns the great-circle distance in metres between a and b.
func Haversine(a, b Point) float64 {
dLat := rad(b.Lat - a.Lat)
dLon := rad(b.Lon - a.Lon)
s := math.Sin(dLat/2)*math.Sin(dLat/2) +
math.Cos(rad(a.Lat))*math.Cos(rad(b.Lat))*math.Sin(dLon/2)*math.Sin(dLon/2)
return 2 * EarthRadiusM * math.Asin(math.Min(1, math.Sqrt(s)))
}
// Box is a latitude/longitude rectangle. MinLon > MaxLon means the box
// crosses the antimeridian (180 degrees).
type Box struct{ MinLat, MinLon, MaxLat, MaxLon float64 }
// Contains reports whether p is inside the box, handling antimeridian wrap.
func (b Box) Contains(p Point) bool {
if p.Lat < b.MinLat || p.Lat > b.MaxLat {
return false
}
if b.MinLon <= b.MaxLon {
return p.Lon >= b.MinLon && p.Lon <= b.MaxLon
}
return p.Lon >= b.MinLon || p.Lon <= b.MaxLon
}
// BoundingBox returns a box that fully contains the circle of radiusM metres
// around c. It is a filter, not an answer: corners are outside the circle.
// Near a pole it widens to all longitudes.
func BoundingBox(c Point, radiusM float64) Box {
dLat := radiusM / EarthRadiusM * 180 / math.Pi
box := Box{MinLat: c.Lat - dLat, MaxLat: c.Lat + dLat, MinLon: -180, MaxLon: 180}
if box.MinLat < -90 {
box.MinLat = -90
}
if box.MaxLat > 90 {
box.MaxLat = 90
}
if box.MaxLat >= 90 || box.MinLat <= -90 {
return box // a pole is inside the circle: every longitude matches
}
dLon := math.Asin(math.Sin(radiusM/EarthRadiusM)/math.Cos(rad(c.Lat))) * 180 / math.Pi
box.MinLon, box.MaxLon = wrapLon(c.Lon-dLon), wrapLon(c.Lon+dLon)
return box
}
func wrapLon(l float64) float64 {
for l < -180 {
l += 360
}
for l > 180 {
l -= 360
}
return l
}
// Truncate rounds a coordinate to the given number of decimal places.
// 2 places is about 1.1 km of latitude: a privacy step, not a security one.
func Truncate(v float64, places int) float64 {
p := math.Pow(10, float64(places))
return math.Trunc(v*p) / p
}package geo
import (
"math"
"testing"
)
func TestHaversineKnownDistance(t *testing.T) {
paris := Point{48.8566, 2.3522}
london := Point{51.5074, -0.1278}
d := Haversine(paris, london) / 1000
if math.Abs(d-343.5) > 3 { // about 343-344 km
t.Fatalf("Paris-London = %.1f km", d)
}
}
func TestHaversineAcrossAntimeridian(t *testing.T) {
a, b := Point{0, 179.9}, Point{0, -179.9}
if d := Haversine(a, b); d > 25000 { // 0.2 degrees, about 22 km
t.Fatalf("expected a short hop, got %.0f m", d)
}
}
func TestBoundingBoxContainsCircle(t *testing.T) {
c := Point{35.6892, 51.3890}
box := BoundingBox(c, 2000)
for _, brg := range []float64{0, 45, 90, 135, 180, 225, 270, 315} {
p := destination(c, brg, 1999)
if !box.Contains(p) {
t.Fatalf("bearing %v outside box", brg)
}
}
}
func TestBoundingBoxWrapsAntimeridian(t *testing.T) {
box := BoundingBox(Point{0, 179.99}, 5000)
if box.MinLon <= box.MaxLon {
t.Fatalf("expected wrapped box, got %+v", box)
}
if !box.Contains(Point{0, -179.99}) {
t.Fatal("point across the antimeridian must be inside")
}
}
func TestBoundingBoxNearPole(t *testing.T) {
box := BoundingBox(Point{89.99, 10}, 5000)
if box.MinLon != -180 || box.MaxLon != 180 {
t.Fatalf("pole box must span all longitudes: %+v", box)
}
}
func TestTruncate(t *testing.T) {
if got := Truncate(35.689234, 2); got != 35.68 {
t.Fatalf("got %v", got)
}
}
// destination moves from p by dist metres along a bearing in degrees.
func destination(p Point, bearingDeg, dist float64) Point {
d := dist / EarthRadiusM
br := rad(bearingDeg)
lat1, lon1 := rad(p.Lat), rad(p.Lon)
lat2 := math.Asin(math.Sin(lat1)*math.Cos(d) + math.Cos(lat1)*math.Sin(d)*math.Cos(br))
lon2 := lon1 + math.Atan2(math.Sin(br)*math.Sin(d)*math.Cos(lat1), math.Cos(d)-math.Sin(lat1)*math.Sin(lat2))
return Point{lat2 * 180 / math.Pi, wrapLon(lon2 * 180 / math.Pi)}
}geohash encodes, decodes, finds neighbours and prefix ranges; the tests include the two known vectors and the equator boundary problem:
// Package geohash implements Gustavo Niemeyer's geohash: interleave the
// longitude and latitude bisection bits (a Z-order / Morton code) and write
// them in base32.
package geohash
import (
"errors"
"strings"
)
const alphabet = "0123456789bcdefghjkmnpqrstuvwxyz"
var decodeMap = func() map[byte]int {
m := make(map[byte]int, 32)
for i := 0; i < len(alphabet); i++ {
m[alphabet[i]] = i
}
return m
}()
// Cell is the decoded rectangle of a geohash.
type Cell struct{ MinLat, MaxLat, MinLon, MaxLon float64 }
// Center returns the middle of the cell.
func (c Cell) Center() (lat, lon float64) {
return (c.MinLat + c.MaxLat) / 2, (c.MinLon + c.MaxLon) / 2
}
// Encode returns the geohash of (lat, lon) with the given number of characters.
// Bit order: longitude first, then latitude, alternating (5 bits per char).
func Encode(lat, lon float64, length int) string {
minLat, maxLat, minLon, maxLon := -90.0, 90.0, -180.0, 180.0
var sb strings.Builder
bit, ch, evenBit := 0, 0, true
for sb.Len() < length {
if evenBit {
mid := (minLon + maxLon) / 2
if lon >= mid {
ch = ch<<1 | 1
minLon = mid
} else {
ch <<= 1
maxLon = mid
}
} else {
mid := (minLat + maxLat) / 2
if lat >= mid {
ch = ch<<1 | 1
minLat = mid
} else {
ch <<= 1
maxLat = mid
}
}
evenBit = !evenBit
if bit++; bit == 5 {
sb.WriteByte(alphabet[ch])
bit, ch = 0, 0
}
}
return sb.String()
}
// ErrInvalid is returned for characters outside the geohash alphabet.
var ErrInvalid = errors.New("geohash: invalid character")
// Decode returns the cell of a geohash.
func Decode(hash string) (Cell, error) {
c := Cell{-90, 90, -180, 180}
evenBit := true
for i := 0; i < len(hash); i++ {
v, ok := decodeMap[hash[i]]
if !ok {
return Cell{}, ErrInvalid
}
for mask := 16; mask > 0; mask >>= 1 {
if evenBit {
mid := (c.MinLon + c.MaxLon) / 2
if v&mask != 0 {
c.MinLon = mid
} else {
c.MaxLon = mid
}
} else {
mid := (c.MinLat + c.MaxLat) / 2
if v&mask != 0 {
c.MinLat = mid
} else {
c.MaxLat = mid
}
}
evenBit = !evenBit
}
}
return c, nil
}
// Neighbours returns the 8 cells around hash (N, NE, E, SE, S, SW, W, NW),
// computed by decoding, stepping one cell width/height and re-encoding.
// Longitude wraps at the antimeridian; latitude does not wrap at the poles,
// so cells above the north row or below the south row are omitted.
func Neighbours(hash string) ([]string, error) {
c, err := Decode(hash)
if err != nil {
return nil, err
}
lat, lon := c.Center()
h, w := c.MaxLat-c.MinLat, c.MaxLon-c.MinLon
var out []string
for _, d := range [][2]int{{1, 0}, {1, 1}, {0, 1}, {-1, 1}, {-1, 0}, {-1, -1}, {0, -1}, {1, -1}} {
nl := lat + float64(d[0])*h
if nl > 90 || nl < -90 {
continue
}
no := lon + float64(d[1])*w
if no > 180 {
no -= 360
} else if no < -180 {
no += 360
}
out = append(out, Encode(nl, no, len(hash)))
}
return out, nil
}
// SearchCells returns the cell itself plus its neighbours: the nine prefixes
// a radius query must scan. Choose the length so that one cell is at least as
// large as the radius, otherwise nine cells do not cover the circle.
func SearchCells(lat, lon float64, length int) []string {
h := Encode(lat, lon, length)
n, _ := Neighbours(h)
return append([]string{h}, n...)
}
// PrefixRange returns the half-open key range [lo, hi) that holds every
// geohash starting with prefix. It is how a plain key-value store or a B-tree
// answers "everything in this cell" with one range scan.
func PrefixRange(prefix string) (lo, hi string) {
return prefix, prefix + "~" // '~' sorts after every base32 character
}package geohash
import (
"math"
"slices"
"testing"
)
func TestEncodeKnownVectors(t *testing.T) {
cases := []struct {
lat, lon float64
n int
want string
}{
{57.64911, 10.40744, 11, "u4pruydqqvj"}, // Wikipedia example
{42.6, -5.6, 5, "ezs42"}, // original geohash.org example
}
for _, c := range cases {
if got := Encode(c.lat, c.lon, c.n); got != c.want {
t.Errorf("Encode(%v,%v,%d)=%s want %s", c.lat, c.lon, c.n, got, c.want)
}
}
}
func TestDecodeContainsPoint(t *testing.T) {
h := Encode(35.6892, 51.3890, 8)
c, err := Decode(h)
if err != nil {
t.Fatal(err)
}
if 35.6892 < c.MinLat || 35.6892 > c.MaxLat || 51.3890 < c.MinLon || 51.3890 > c.MaxLon {
t.Fatalf("cell %+v does not contain the point", c)
}
}
func TestPrefixIsContainment(t *testing.T) {
long := Encode(35.6892, 51.3890, 9)
short := Encode(35.6892, 51.3890, 6)
if long[:6] != short {
t.Fatal("a longer hash must start with the shorter one")
}
}
func TestDecodeRejectsBadCharacter(t *testing.T) {
if _, err := Decode("ezs4a"); err == nil { // 'a' is not in the alphabet
t.Fatal("expected error")
}
}
func TestNeighboursCount(t *testing.T) {
n, _ := Neighbours("ezs42")
if len(n) != 8 {
t.Fatalf("want 8 got %d", len(n))
}
}
// The boundary problem: two points 20 m apart, on either side of the equator,
// share no prefix at all, yet the neighbour set of one contains the other.
func TestBoundaryProblem(t *testing.T) {
a := Encode(0.0001, 10, 7)
b := Encode(-0.0001, 10, 7)
if a[0] == b[0] {
t.Fatalf("expected different first characters: %s %s", a, b)
}
n, _ := Neighbours(a)
if !slices.Contains(n, b) {
t.Fatalf("%s should be a neighbour of %s: %v", b, a, n)
}
}
func TestNeighboursWrapAntimeridian(t *testing.T) {
h := Encode(0, 179.999, 5)
n, _ := Neighbours(h)
found := false
for _, x := range n {
c, _ := Decode(x)
if c.MaxLon < 0 { // a western-hemisphere cell
found = true
}
}
if !found {
t.Fatalf("no neighbour wrapped past 180: %v", n)
}
}
func TestCellSizeHalvesPerBitPair(t *testing.T) {
c5, _ := Decode(Encode(10, 10, 5))
c6, _ := Decode(Encode(10, 10, 6))
w5, w6 := c5.MaxLon-c5.MinLon, c6.MaxLon-c6.MinLon
if math.Abs(w5/w6-8) > 0.001 && math.Abs(w5/w6-4) > 0.001 {
t.Fatalf("width ratio %v", w5/w6)
}
}
func TestPrefixRange(t *testing.T) {
lo, hi := PrefixRange("ezs")
if !(lo <= "ezs42" && "ezs42" < hi) || ("ezt00" < hi && "ezt00" >= lo) {
t.Fatal("range wrong")
}
}quadtree has dynamic splitting, range, radius and best-first kNN, checked against brute force:
// Package quadtree is an in-memory point quadtree with a bucket capacity:
// a leaf holds up to Capacity points, then splits into four quadrants.
// Coordinates are PLANAR (metres or any Euclidean unit). Project latitude and
// longitude first (see Project); the tree never calls haversine.
package quadtree
import (
"container/heap"
"math"
)
// Point is an item with an id at planar position (X, Y).
type Point struct {
ID int
X, Y float64
}
// Rect is an axis-aligned rectangle (a minimum bounding rectangle).
type Rect struct{ MinX, MinY, MaxX, MaxY float64 }
func (r Rect) contains(x, y float64) bool {
return x >= r.MinX && x <= r.MaxX && y >= r.MinY && y <= r.MaxY
}
func (r Rect) intersects(o Rect) bool {
return r.MinX <= o.MaxX && r.MaxX >= o.MinX && r.MinY <= o.MaxY && r.MaxY >= o.MinY
}
// distSq is the squared distance from (x, y) to the nearest point of r.
func (r Rect) distSq(x, y float64) float64 {
dx := math.Max(0, math.Max(r.MinX-x, x-r.MaxX))
dy := math.Max(0, math.Max(r.MinY-y, y-r.MaxY))
return dx*dx + dy*dy
}
// Tree is the root. It is not safe for concurrent use; guard it with a
// sync.RWMutex or shard it by cell.
type Tree struct {
root *node
capacity int
maxDepth int
size int
}
type node struct {
bounds Rect
points []Point
kids *[4]*node // nil while the node is a leaf
}
// New returns a tree covering bounds. capacity is the leaf bucket size and
// maxDepth stops splitting when many points share one location.
func New(bounds Rect, capacity, maxDepth int) *Tree {
return &Tree{root: &node{bounds: bounds}, capacity: capacity, maxDepth: maxDepth}
}
// Len returns the number of stored points.
func (t *Tree) Len() int { return t.size }
// Insert adds p and reports false when p is outside the tree bounds.
func (t *Tree) Insert(p Point) bool {
if !t.root.bounds.contains(p.X, p.Y) {
return false
}
t.insert(t.root, p, 0)
t.size++
return true
}
func (t *Tree) insert(n *node, p Point, depth int) {
for n.kids != nil {
n = n.kids[quadrant(n.bounds, p.X, p.Y)]
depth++
}
n.points = append(n.points, p)
if len(n.points) > t.capacity && depth < t.maxDepth {
t.split(n, depth)
}
}
func (t *Tree) split(n *node, depth int) {
b := n.bounds
mx, my := (b.MinX+b.MaxX)/2, (b.MinY+b.MaxY)/2
n.kids = &[4]*node{
{bounds: Rect{b.MinX, b.MinY, mx, my}}, // 0: south-west
{bounds: Rect{mx, b.MinY, b.MaxX, my}}, // 1: south-east
{bounds: Rect{b.MinX, my, mx, b.MaxY}}, // 2: north-west
{bounds: Rect{mx, my, b.MaxX, b.MaxY}}, // 3: north-east
}
old := n.points
n.points = nil
for _, p := range old {
t.insert(n, p, depth) // re-route; may split again if all land together
}
}
func quadrant(b Rect, x, y float64) int {
q := 0
if x >= (b.MinX+b.MaxX)/2 {
q |= 1
}
if y >= (b.MinY+b.MaxY)/2 {
q |= 2
}
return q
}
// Remove deletes the point with the given id at (x, y) and reports success.
// Leaves are not merged back; rebuild the tree if deletes dominate.
func (t *Tree) Remove(id int, x, y float64) bool {
n := t.root
if !n.bounds.contains(x, y) {
return false
}
for n.kids != nil {
n = n.kids[quadrant(n.bounds, x, y)]
}
for i, p := range n.points {
if p.ID == id {
n.points = append(n.points[:i], n.points[i+1:]...)
t.size--
return true
}
}
return false
}
// Range returns every point inside r (the range, or window, query).
func (t *Tree) Range(r Rect) []Point {
var out []Point
var walk func(n *node)
walk = func(n *node) {
if !n.bounds.intersects(r) {
return
}
if n.kids == nil {
for _, p := range n.points {
if r.contains(p.X, p.Y) {
out = append(out, p)
}
}
return
}
for _, k := range n.kids {
walk(k)
}
}
walk(t.root)
return out
}
// Radius returns points within distance r of (x, y): a Range over the
// bounding square followed by an exact distance filter.
func (t *Tree) Radius(x, y, r float64) []Point {
var out []Point
for _, p := range t.Range(Rect{x - r, y - r, x + r, y + r}) {
if (p.X-x)*(p.X-x)+(p.Y-y)*(p.Y-y) <= r*r {
out = append(out, p)
}
}
return out
}
// Nearest returns the k points closest to (x, y), nearest first. It is a
// best-first search: a priority queue holds nodes and points ordered by their
// minimum possible distance, so whole quadrants farther than the k-th result
// are never opened.
func (t *Tree) Nearest(x, y float64, k int) []Point {
pq := &minHeap{{node: t.root, d: t.root.bounds.distSq(x, y)}}
var out []Point
for pq.Len() > 0 && len(out) < k {
it := heap.Pop(pq).(item)
switch {
case it.node == nil: // a concrete point: nothing closer remains
out = append(out, it.p)
case it.node.kids == nil:
for _, p := range it.node.points {
heap.Push(pq, item{p: p, d: (p.X-x)*(p.X-x) + (p.Y-y)*(p.Y-y)})
}
default:
for _, kid := range it.node.kids {
heap.Push(pq, item{node: kid, d: kid.bounds.distSq(x, y)})
}
}
}
return out
}
type item struct {
node *node
p Point
d float64
}
type minHeap []item
func (h minHeap) Len() int { return len(h) }
func (h minHeap) Less(i, j int) bool { return h[i].d < h[j].d }
func (h minHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *minHeap) Push(x any) { *h = append(*h, x.(item)) }
func (h *minHeap) Pop() any {
old := *h
it := old[len(old)-1]
*h = old[:len(old)-1]
return it
}
// Project maps latitude/longitude to local planar metres around origin using
// the equirectangular approximation. It is accurate to well under 1% for a
// city-sized area and useless across the antimeridian or near a pole.
func Project(originLat, lat, lon, originLon float64) (x, y float64) {
const r = 6371008.8
const d2r = math.Pi / 180
return (lon - originLon) * d2r * r * math.Cos(originLat*d2r), (lat - originLat) * d2r * r
}package quadtree
import (
"math/rand"
"sort"
"testing"
)
func fill(n int, seed int64) (*Tree, []Point) {
rng := rand.New(rand.NewSource(seed))
t := New(Rect{0, 0, 10000, 10000}, 8, 16)
pts := make([]Point, n)
for i := range pts {
pts[i] = Point{i, rng.Float64() * 10000, rng.Float64() * 10000}
t.Insert(pts[i])
}
return t, pts
}
func TestRangeMatchesBruteForce(t *testing.T) {
tr, pts := fill(5000, 1)
r := Rect{2000, 3000, 4500, 6000}
want := 0
for _, p := range pts {
if r.contains(p.X, p.Y) {
want++
}
}
if got := len(tr.Range(r)); got != want {
t.Fatalf("range got %d want %d", got, want)
}
}
func TestNearestMatchesBruteForce(t *testing.T) {
tr, pts := fill(5000, 2)
x, y := 5123.0, 4876.0
sort.Slice(pts, func(i, j int) bool {
return (pts[i].X-x)*(pts[i].X-x)+(pts[i].Y-y)*(pts[i].Y-y) <
(pts[j].X-x)*(pts[j].X-x)+(pts[j].Y-y)*(pts[j].Y-y)
})
got := tr.Nearest(x, y, 10)
if len(got) != 10 {
t.Fatalf("got %d", len(got))
}
for i := range got {
if got[i].ID != pts[i].ID {
t.Fatalf("rank %d: got %d want %d", i, got[i].ID, pts[i].ID)
}
}
}
func TestRadiusExactCircle(t *testing.T) {
tr := New(Rect{0, 0, 100, 100}, 2, 8)
tr.Insert(Point{1, 50, 50})
tr.Insert(Point{2, 59, 59}) // inside the bounding square, outside the circle
tr.Insert(Point{3, 53, 54})
if got := len(tr.Radius(50, 50, 10)); got != 2 {
t.Fatalf("got %d want 2", got)
}
}
func TestDuplicatePointsDoNotRecurseForever(t *testing.T) {
tr := New(Rect{0, 0, 10, 10}, 2, 6)
for i := 0; i < 100; i++ {
tr.Insert(Point{i, 5, 5}) // 100 points at the same spot
}
if tr.Len() != 100 || len(tr.Range(Rect{4, 4, 6, 6})) != 100 {
t.Fatal("lost points")
}
}
func TestRemoveAndOutOfBounds(t *testing.T) {
tr := New(Rect{0, 0, 10, 10}, 2, 6)
if tr.Insert(Point{1, 11, 5}) {
t.Fatal("out of bounds insert must fail")
}
tr.Insert(Point{2, 3, 3})
if !tr.Remove(2, 3, 3) || tr.Len() != 0 || tr.Remove(2, 3, 3) {
t.Fatal("remove misbehaved")
}
}
func TestProjectNorthIsPositive(t *testing.T) {
_, y := Project(35.0, 35.01, 51.0, 51.0)
x, _ := Project(35.0, 35.0, 51.01, 51.0)
if y < 1000 || y > 1200 || x < 850 || x > 950 { // 0.01 deg is ~1.11 km N, ~0.91 km E at 35 N
t.Fatalf("x=%.0f y=%.0f", x, y)
}
}
func BenchmarkNearest10(b *testing.B) {
tr, _ := fill(100000, 3)
for i := 0; i < b.N; i++ {
tr.Nearest(5000, 5000, 10)
}
}grid is the bucket index with per-cell hot-cell metric, TTL expiry and the polygon test:
// Package grid is the simplest spatial index: a fixed-size bucket (cell) per
// square of the plane, in a hash map. It is also the model for sharding live
// driver locations by cell.
package grid
import (
"math"
"sync"
"time"
)
// Key identifies a cell.
type Key struct{ X, Y int }
// Entry is one object in a cell, stamped for TTL expiry.
type Entry struct {
ID int
X, Y float64
LastSeen time.Time
}
// Index buckets points into square cells of side CellSize (planar units).
type Index struct {
mu sync.RWMutex
CellSize float64
cells map[Key]map[int]Entry
where map[int]Key
}
// New returns an empty grid.
func New(cellSize float64) *Index {
return &Index{CellSize: cellSize, cells: map[Key]map[int]Entry{}, where: map[int]Key{}}
}
func (g *Index) key(x, y float64) Key {
return Key{int(math.Floor(x / g.CellSize)), int(math.Floor(y / g.CellSize))}
}
// Upsert records a location update. A move across a cell border removes the
// old entry: forgetting that is the classic "ghost driver" bug.
func (g *Index) Upsert(id int, x, y float64, now time.Time) {
g.mu.Lock()
defer g.mu.Unlock()
k := g.key(x, y)
if old, ok := g.where[id]; ok && old != k {
delete(g.cells[old], id)
if len(g.cells[old]) == 0 {
delete(g.cells, old)
}
}
if g.cells[k] == nil {
g.cells[k] = map[int]Entry{}
}
g.cells[k][id] = Entry{id, x, y, now}
g.where[id] = k
}
// Nearby returns entries within radius of (x, y), reading only the cells the
// circle's bounding square touches (3x3 when radius <= CellSize).
func (g *Index) Nearby(x, y, radius float64) []Entry {
g.mu.RLock()
defer g.mu.RUnlock()
lo, hi := g.key(x-radius, y-radius), g.key(x+radius, y+radius)
var out []Entry
for cx := lo.X; cx <= hi.X; cx++ {
for cy := lo.Y; cy <= hi.Y; cy++ {
for _, e := range g.cells[Key{cx, cy}] {
if (e.X-x)*(e.X-x)+(e.Y-y)*(e.Y-y) <= radius*radius {
out = append(out, e)
}
}
}
}
return out
}
// Expire drops entries not updated since cutoff (the TTL sweep) and returns
// how many were removed.
func (g *Index) Expire(cutoff time.Time) int {
g.mu.Lock()
defer g.mu.Unlock()
n := 0
for k, cell := range g.cells {
for id, e := range cell {
if e.LastSeen.Before(cutoff) {
delete(cell, id)
delete(g.where, id)
n++
}
}
if len(cell) == 0 {
delete(g.cells, k)
}
}
return n
}
// Hottest returns the largest cell population: the hot-cell metric to alert on.
func (g *Index) Hottest() (Key, int) {
g.mu.RLock()
defer g.mu.RUnlock()
var bk Key
best := 0
for k, c := range g.cells {
if len(c) > best {
bk, best = k, len(c)
}
}
return bk, best
}
// InPolygon reports whether (x, y) is inside the polygon (ray casting). It is
// the geofence test: cheap index filter first, then this exact check.
func InPolygon(x, y float64, poly [][2]float64) bool {
in := false
for i, j := 0, len(poly)-1; i < len(poly); j, i = i, i+1 {
xi, yi, xj, yj := poly[i][0], poly[i][1], poly[j][0], poly[j][1]
if (yi > y) != (yj > y) && x < (xj-xi)*(y-yi)/(yj-yi)+xi {
in = !in
}
}
return in
}package grid
import (
"testing"
"time"
)
func TestUpsertMovesAcrossCells(t *testing.T) {
g := New(100)
now := time.Unix(0, 0)
g.Upsert(1, 10, 10, now)
g.Upsert(1, 510, 10, now) // moved five cells east
if n := len(g.Nearby(10, 10, 50)); n != 0 {
t.Fatalf("ghost entry left behind: %d", n)
}
if n := len(g.Nearby(510, 10, 50)); n != 1 {
t.Fatalf("want 1 got %d", n)
}
}
func TestNearbyExactCircle(t *testing.T) {
g := New(100)
now := time.Unix(0, 0)
g.Upsert(1, 0, 0, now)
g.Upsert(2, 70, 70, now) // same 3x3 block, but 99 away from origin
if n := len(g.Nearby(0, 0, 90)); n != 1 {
t.Fatalf("want 1 got %d", n)
}
}
func TestNegativeCoordinatesFloorCorrectly(t *testing.T) {
g := New(100)
g.Upsert(1, -1, -1, time.Unix(0, 0))
if n := len(g.Nearby(1, 1, 5)); n != 1 { // across the origin cell border
t.Fatalf("want 1 got %d", n)
}
}
func TestExpireAndHottest(t *testing.T) {
g := New(100)
old, fresh := time.Unix(0, 0), time.Unix(100, 0)
g.Upsert(1, 5, 5, old)
g.Upsert(2, 6, 6, fresh)
g.Upsert(3, 7, 7, fresh)
if _, n := g.Hottest(); n != 3 {
t.Fatalf("hottest %d", n)
}
if g.Expire(time.Unix(50, 0)) != 1 {
t.Fatal("expected one expiry")
}
if _, n := g.Hottest(); n != 2 {
t.Fatalf("hottest after expiry %d", n)
}
}
func TestInPolygon(t *testing.T) {
sq := [][2]float64{{0, 0}, {10, 0}, {10, 10}, {0, 10}}
if !InPolygon(5, 5, sq) || InPolygon(11, 5, sq) {
t.Fatal("square test failed")
}
l := [][2]float64{{0, 0}, {10, 0}, {10, 10}, {5, 10}, {5, 5}, {0, 5}} // concave L
if InPolygon(2, 8, l) || !InPolygon(8, 8, l) {
t.Fatal("concave test failed")
}
}S2 and H3 use verified libraries (github.com/golang/geo is pure Go; github.com/uber/h3-go/v4 is a cgo binding):
// Package s2cover shows the S2 workflow with github.com/golang/geo: a leaf
// cell id per point, and a region covering for a radius query.
package s2cover
import (
"github.com/golang/geo/s1"
"github.com/golang/geo/s2"
)
// CellID returns the S2 cell id of a point at the given level (0..30).
// Level 13 cells are roughly 1 km across; level 16 roughly 120 m.
func CellID(lat, lon float64, level int) s2.CellID {
return s2.CellIDFromLatLng(s2.LatLngFromDegrees(lat, lon)).Parent(level)
}
// Covering returns at most maxCells cells that together cover a spherical cap
// of radiusM metres around the centre. Each cell id is a 64-bit integer, and
// the ids of one cell's descendants form ONE contiguous range on the Hilbert
// curve, so a B-tree answers "inside this cell" with a range scan.
func Covering(lat, lon, radiusM float64, minLevel, maxLevel, maxCells int) s2.CellUnion {
const earthRadiusM = 6371008.8
centre := s2.PointFromLatLng(s2.LatLngFromDegrees(lat, lon))
cap := s2.CapFromCenterAngle(centre, s1.Angle(radiusM/earthRadiusM))
rc := s2.RegionCoverer{MinLevel: minLevel, MaxLevel: maxLevel, MaxCells: maxCells}
return rc.Covering(cap)
}
// Ranges converts a covering into [min, max] leaf-id ranges, the form a
// key-value store or SQL BETWEEN needs.
func Ranges(u s2.CellUnion) [][2]uint64 {
out := make([][2]uint64, 0, len(u))
for _, c := range u {
out = append(out, [2]uint64{uint64(c.RangeMin()), uint64(c.RangeMax())})
}
return out
}package s2cover
import "testing"
func TestCoveringContainsCentreAndRangesAreOrdered(t *testing.T) {
u := Covering(35.6892, 51.3890, 1000, 10, 16, 8)
if len(u) == 0 || len(u) > 8 {
t.Fatalf("unexpected covering size %d", len(u))
}
leaf := CellID(35.6892, 51.3890, 30)
if !u.ContainsCellID(leaf) {
t.Fatal("covering must contain the centre point")
}
for _, r := range Ranges(u) {
if r[0] > r[1] {
t.Fatal("range inverted")
}
}
}
func TestParentContainsChild(t *testing.T) {
if !CellID(35.6892, 51.3890, 12).Contains(CellID(35.6892, 51.3890, 16)) {
t.Fatal("hierarchy broken")
}
}// Package h3cell shows Uber's H3 through github.com/uber/h3-go/v4 (a cgo
// binding: it needs a C compiler to build). The calls below are the whole
// workflow: index a point, take a k-ring, move up a resolution.
package h3cell
import "github.com/uber/h3-go/v4"
// Cell returns the H3 cell of a point at a resolution (0..15).
// Resolution 8 cells are about 0.74 km2; resolution 9 about 0.105 km2.
func Cell(lat, lon float64, res int) (h3.Cell, error) {
return h3.LatLngToCell(h3.NewLatLng(lat, lon), res)
}
// Around returns the cell and every cell within k grid steps (a "k-ring",
// called GridDisk in H3 v4): 1 + 3k(k+1) cells, all hexagons unless a
// pentagon is near.
func Around(c h3.Cell, k int) ([]h3.Cell, error) { return h3.GridDisk(c, k) }
// Coarser returns the parent at a lower resolution, which is how a
// per-resolution aggregate (supply and demand per area) rolls up.
func Coarser(c h3.Cell, res int) (h3.Cell, error) { return c.Parent(res) }package h3cell
import "testing"
func TestKRingSize(t *testing.T) {
c, err := Cell(35.6892, 51.3890, 9)
if err != nil {
t.Fatal(err)
}
ring, err := Around(c, 2)
if err != nil || len(ring) != 19 { // 1 + 3*2*3
t.Fatalf("k=2 ring: %d cells, err %v", len(ring), err)
}
p, err := Coarser(c, 8)
if err != nil || p.Resolution() != 8 {
t.Fatalf("parent %v %v", p, err)
}
}A runnable comparison used by the Lab:
// Command demo compares a full scan, a geohash-bucketed index and a quadtree
// on 200,000 synthetic drivers around one city, and prints counts and timings.
package main
import (
"fmt"
"math/rand"
"time"
"academy/geospatial-indexing/geo"
"academy/geospatial-indexing/geohash"
"academy/geospatial-indexing/quadtree"
)
func main() {
rng := rand.New(rand.NewSource(42))
centre := geo.Point{Lat: 35.6892, Lon: 51.3890}
const n = 200000
pts := make([]geo.Point, n)
buckets := map[string][]int{}
tree := quadtree.New(quadtree.Rect{MinX: -30000, MinY: -30000, MaxX: 30000, MaxY: 30000}, 16, 20)
for i := range pts {
pts[i] = geo.Point{Lat: centre.Lat + (rng.Float64()-0.5)*0.5, Lon: centre.Lon + (rng.Float64()-0.5)*0.6}
h := geohash.Encode(pts[i].Lat, pts[i].Lon, 5)
buckets[h] = append(buckets[h], i)
x, y := quadtree.Project(centre.Lat, pts[i].Lat, pts[i].Lon, centre.Lon)
tree.Insert(quadtree.Point{ID: i, X: x, Y: y})
}
const radius = 1000.0 // metres; a length-5 geohash cell is about 4.9 km x 4.9 km
t0 := time.Now()
scan := 0
for _, p := range pts {
if geo.Haversine(centre, p) <= radius {
scan++
}
}
dScan := time.Since(t0)
t0 = time.Now()
gh, seen := 0, 0
for _, cell := range geohash.SearchCells(centre.Lat, centre.Lon, 5) { // a 5-char cell (4.9 km) is larger than the radius
for _, i := range buckets[cell] {
seen++
if geo.Haversine(centre, pts[i]) <= radius {
gh++
}
}
}
dHash := time.Since(t0)
t0 = time.Now()
qt := len(tree.Radius(0, 0, radius))
dTree := time.Since(t0)
fmt.Printf("full scan : %d hits, %v\n", scan, dScan)
fmt.Printf("geohash 5 : %d hits, %d candidates, %v (9 cells, then exact haversine)\n", gh, seen, dHash)
fmt.Printf("quadtree : %d hits (planar approximation), %v\n", qt, dTree)
}The Go angle
Go has no geospatial package in the standard library, so the choice is a library or a small piece of your own code. The structures here are small enough to own (a few hundred lines with tests); the libraries to know are github.com/golang/geo (S2: cell ids, covering, caps), github.com/uber/h3-go/v4 (H3, needs cgo and a C compiler) and, for SQL, github.com/twpayne/go-geom or PostGIS through pgx with plain SQL text (the geography type travels as WKB or text). Practical rules: keep the index behind an interface so you can swap a grid for Redis, guard shared trees with sync.RWMutex or one goroutine per shard (the grid package uses an RWMutex), take context.Context on any call that reaches Redis or a database, and never store floats as map keys. Note that go get for these two libraries raised the module's go directive to 1.25.0.
Laravel
Before
-- Two B-trees. This is what the query below can use.
CREATE INDEX drivers_lat_idx ON drivers (lat);
CREATE INDEX drivers_lon_idx ON drivers (lon);<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
// Before: two B-tree indexes on lat and lon, a square in degrees, no distance ordering.
class DriverController
{
public function nearby(Request $request)
{
$lat = (float) $request->query('lat');
$lon = (float) $request->query('lon');
$d = 0.01; // about 1.1 km north-south, but only about 0.9 km east-west at 35 N
return DB::table('drivers')
->whereBetween('lat', [$lat - $d, $lat + $d]) // one index range, millions of rows in the strip
->whereBetween('lon', [$lon - $d, $lon + $d]) // filtered after the first range
->limit(50) // arbitrary 50, not the nearest 50
->get();
}
}After
PostGIS migration (raw statements, since Laravel has no geography column helper for PostgreSQL in the documented schema builder):
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
return new class extends Migration
{
public function up(): void
{
DB::statement('CREATE EXTENSION IF NOT EXISTS postgis');
DB::statement('CREATE TABLE places (
id bigserial PRIMARY KEY,
name text NOT NULL,
location geography(Point, 4326) NOT NULL,
created_at timestamp NULL,
updated_at timestamp NULL
)');
DB::statement('CREATE INDEX places_location_gix ON places USING gist (location)');
}
public function down(): void
{
DB::statement('DROP TABLE IF EXISTS places');
}
};An Eloquent model with scopes that use raw expressions with bindings (Laravel 13 documents selectRaw, whereRaw and orderByRaw and warns that raw expressions are not protected from injection unless values are bound):
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
class Place extends Model
{
protected $fillable = ['name'];
/** Insert with a raw expression and bindings: longitude first, then latitude. */
public static function createAt(string $name, float $lat, float $lon): int
{
return (int) DB::scalar(
'INSERT INTO places (name, location, created_at, updated_at)
VALUES (?, ST_SetSRID(ST_MakePoint(?, ?), 4326)::geography, now(), now())
RETURNING id',
[$name, $lon, $lat]
);
}
/** Index-assisted radius filter plus distance column, nearest first. */
public function scopeWithin(Builder $q, float $lat, float $lon, float $metres): Builder
{
$point = 'ST_SetSRID(ST_MakePoint(?, ?), 4326)::geography';
return $q->selectRaw("places.*, ST_Distance(location, $point) AS metres", [$lon, $lat])
->whereRaw("ST_DWithin(location, $point, ?)", [$lon, $lat, $metres])
->orderBy('metres');
}
/** k nearest neighbours through the GiST-backed distance operator. */
public function scopeNearest(Builder $q, float $lat, float $lon, int $k): Builder
{
return $q->orderByRaw('location <-> ST_SetSRID(ST_MakePoint(?, ?), 4326)::geography', [$lon, $lat])
->limit($k);
}
}Redis GEO through the connection's phpredis client (rawCommand):
<?php
namespace App\Geo;
use Illuminate\Support\Facades\Redis;
/**
* Live driver positions in Redis GEO. A geo set is a sorted set whose score is a 52-bit
* geohash, so ZREM removes a member and ZRANGEBYSCORE-style expiry works on a companion set.
* Uses phpredis rawCommand so the same call works for GEOSEARCH without client-specific
* signatures; the key is built explicitly because rawCommand bypasses the Laravel key prefix.
*/
class DriverLocationStore
{
public function __construct(private readonly string $city = 'tehran')
{
}
private function key(): string
{
return "drivers:geo:{$this->city}";
}
private function seenKey(): string
{
return "drivers:seen:{$this->city}";
}
public function update(string $driverId, float $lat, float $lon): void
{
$client = Redis::connection()->client();
// GEOADD key lon lat member: longitude first.
$client->rawCommand('GEOADD', $this->key(), $lon, $lat, $driverId);
$client->rawCommand('ZADD', $this->seenKey(), time(), $driverId);
}
/** @return list<array{id: string, metres: float}> nearest first */
public function nearby(float $lat, float $lon, float $metres, int $limit = 20): array
{
$rows = Redis::connection()->client()->rawCommand(
'GEOSEARCH', $this->key(),
'FROMLONLAT', $lon, $lat,
'BYRADIUS', $metres, 'm',
'ASC', 'COUNT', $limit, 'WITHDIST'
);
return array_map(fn (array $r) => ['id' => $r[0], 'metres' => (float) $r[1]], $rows ?: []);
}
/** TTL sweep: drop drivers not heard from for $olderThan seconds. Returns how many. */
public function expire(int $olderThan = 30): int
{
$client = Redis::connection()->client();
$stale = $client->rawCommand('ZRANGEBYSCORE', $this->seenKey(), '-inf', time() - $olderThan) ?: [];
foreach ($stale as $id) {
$client->rawCommand('ZREM', $this->key(), $id); // there is no GEODEL
$client->rawCommand('ZREM', $this->seenKey(), $id);
}
return count($stale);
}
}The endpoint and its routes:
<?php
namespace App\Http\Controllers;
use App\Geo\DriverLocationStore;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class NearbyDriversController
{
public function __construct(private readonly DriverLocationStore $drivers)
{
}
public function index(Request $request): JsonResponse
{
$data = $request->validate([
'lat' => ['required', 'numeric', 'between:-85.05112878,85.05112878'], // Redis GEO limits
'lon' => ['required', 'numeric', 'between:-180,180'],
'radius' => ['sometimes', 'numeric', 'between:50,5000'],
]);
$found = $this->drivers->nearby($data['lat'], $data['lon'], $data['radius'] ?? 1500, 20);
// Privacy: report distance rounded to 50 m and never the raw coordinates.
return response()->json(array_map(fn ($d) => [
'id' => $d['id'],
'distance_m' => (int) (round($d['metres'] / 50) * 50),
], $found));
}
public function update(Request $request, string $driver): JsonResponse
{
$data = $request->validate([
'lat' => ['required', 'numeric', 'between:-85.05112878,85.05112878'],
'lon' => ['required', 'numeric', 'between:-180,180'],
]);
$this->drivers->update($driver, $data['lat'], $data['lon']);
return response()->json(['ok' => true], 202);
}
}<?php
use App\Http\Controllers\NearbyDriversController;
use Illuminate\Support\Facades\Route;
Route::middleware('throttle:60,1')->group(function () {
Route::get('/drivers/nearby', [NearbyDriversController::class, 'index']);
Route::put('/drivers/{driver}/location', [NearbyDriversController::class, 'update']);
});The Laravel angle
Laravel 13's Redis facade passes any method name to Redis as a command, and Redis::command('lrange', [...]) is documented for explicit calls. For GEOADD and especially the newer GEOSEARCH, whose argument shape differs between phpredis and Predis, the example calls rawCommand on the underlying phpredis client so the Redis command text is exactly what the Redis docs show; rawCommand does not apply the Laravel key prefix, so the keys are written in full. phpredis is Laravel's default client ('client' => env('REDIS_CLIENT', 'phpredis')). For PostgreSQL there is no first-party spatial column type, so migrations use DB::statement and queries use selectRaw, whereRaw with bound parameters and orderByRaw; the bindings keep longitude and latitude from becoming SQL text. For MySQL, use raw statements the same way; the schema builder's spatial helpers were not checked for this chapter. Throttle the location-update route (throttle:60,1) and validate ranges in the controller. None of the PHP was executed; all files pass php -l.
Solving the classic problems
Nearby drivers within a radius
| Solution | How | Advantage | Cost or limit |
|---|---|---|---|
Redis GEOSEARCH | One geo key per city; BYRADIUS ... ASC COUNT | One command, sorted by distance | In memory; points only; one key per node |
| Geohash buckets in a store | 9 prefixes of length 5 to 7, then haversine | Works in DynamoDB, Cassandra, SQL | Boundary handling is yours |
| In-process grid or quadtree | 3 by 3 buckets or a best-first search | Microseconds | State lives in RAM; rebuild on restart |
PostGIS ST_DWithin | GiST index and exact distance | Correct metres, joins with other data | Write cost for moving data |
Closest k stores (kNN)
-- PostGIS: index-ordered nearest 10 stores, then the exact distance for display
SELECT id, name, ST_Distance(location, p.pt) AS metres
FROM places, (SELECT ST_SetSRID(ST_MakePoint(51.3890, 35.6892), 4326)::geography AS pt) p
ORDER BY location <-> p.pt
LIMIT 10;The full file with schema, radius, viewport, polygon and projection examples:
-- PostGIS: places and drivers, geography (metres on the spheroid) vs geometry.
CREATE EXTENSION IF NOT EXISTS postgis;
CREATE TABLE places (
id bigserial PRIMARY KEY,
name text NOT NULL,
location geography(Point, 4326) NOT NULL -- SRID 4326 = WGS84 lon/lat
);
-- A GiST index stores bounding boxes in an R-tree-like structure.
CREATE INDEX places_location_gix ON places USING gist (location);
-- Insert: ST_MakePoint takes (x, y) = (LONGITUDE, latitude). Swapping them is the classic bug.
INSERT INTO places (name, location)
VALUES ('Azadi Tower', ST_SetSRID(ST_MakePoint(51.3380, 35.6997), 4326)::geography);
-- 1. Radius query: index-assisted, distance in metres. ST_DWithin uses the GiST index;
-- ST_Distance(...) < 1000 on its own would not.
SELECT id, name, ST_Distance(location, q.p) AS metres
FROM places, (SELECT ST_SetSRID(ST_MakePoint(51.3890, 35.6892), 4326)::geography AS p) q
WHERE ST_DWithin(location, q.p, 1000)
ORDER BY metres;
-- 2. k nearest neighbours: the <-> operator lets the GiST index return rows in distance
-- order, so LIMIT stops the scan early. No WHERE radius is needed.
SELECT id, name
FROM places
ORDER BY location <-> ST_SetSRID(ST_MakePoint(51.3890, 35.6892), 4326)::geography
LIMIT 10;
-- 3. Bounding box (map viewport): && is the index-only overlap test.
SELECT id, name FROM places
WHERE location::geometry && ST_MakeEnvelope(51.30, 35.65, 51.45, 35.75, 4326);
-- 4. Polygon containment (geofence): the zone table and a point-in-polygon lookup.
CREATE TABLE zones (
id serial PRIMARY KEY,
name text NOT NULL,
area geography(Polygon, 4326) NOT NULL
);
CREATE INDEX zones_area_gix ON zones USING gist (area);
SELECT z.id, z.name FROM zones z
WHERE ST_Covers(z.area, ST_SetSRID(ST_MakePoint(51.3890, 35.6892), 4326)::geography);
-- 5. geometry in a projected SRID for fast planar maths inside one city (3857 = Web Mercator;
-- distances in 3857 are inflated by 1/cos(latitude), so do not report them as metres).
ALTER TABLE places ADD COLUMN location_m geometry(Point, 3857)
GENERATED ALWAYS AS (ST_Transform(location::geometry, 3857)) STORED;
-- Expected plan for query 1 (expected, not run):
-- Index Scan using places_location_gix on places
-- Index Cond: (location && _st_expand(...))
-- Filter: st_dwithin(location, ..., 1000)Geohash in a plain B-tree
-- Geohash in any B-tree: store the hash as text and answer "inside this cell" as a prefix range.
CREATE TABLE drivers (
id bigint PRIMARY KEY,
lat double precision NOT NULL,
lon double precision NOT NULL,
geohash7 text NOT NULL, -- written by the application (7 chars, about 150 m)
seen_at timestamptz NOT NULL DEFAULT now()
);
-- text_pattern_ops makes LIKE 'abc%' use the index regardless of collation.
CREATE INDEX drivers_geohash_idx ON drivers (geohash7 text_pattern_ops);
-- A radius search = the cell holding the centre plus its 8 neighbours (computed in the
-- application), each as a prefix of length 6, then an exact distance filter.
SELECT id, lat, lon
FROM drivers
WHERE (geohash7 LIKE 'ths4hw%' OR geohash7 LIKE 'ths4hy%' OR geohash7 LIKE 'ths4hx%') -- ... 9 prefixes
AND 6371008.8 * 2 * asin(sqrt(
power(sin(radians(lat - 35.6892) / 2), 2) +
cos(radians(35.6892)) * cos(radians(lat)) * power(sin(radians(lon - 51.3890) / 2), 2)
)) <= 1000;
-- Equivalent without LIKE, on any key-value store: scan the key range [prefix, prefix || '~').Map viewport
A bounding box query on geometry with && and ST_MakeEnvelope (query 3 above); in Elasticsearch a geo_bounding_box query; in MongoDB $geoWithin with a $box or polygon. Cap the number of returned markers and cluster server-side (H3 or geohash group-by) when zoomed out.
Is this point inside the zone
Polygon containment with an index: store zones in PostGIS with GiST and ST_Covers; in Go use grid.InPolygon after a cell prefilter; in Elasticsearch a geo_shape query.
Choosing
Index for the query and the motion
| Query | Data motion | Recommended | Extra technique | Reason |
|---|---|---|---|---|
| Radius, points | Fast-moving (seconds) | Redis GEO or in-process grid | TTL sweep, shard by city | Cheap updates, in-memory reads |
| Radius, points | Mostly static | PostGIS GiST (ST_DWithin) | CLUSTER or bulk load | Joins and correctness |
| kNN, points | Static | PostGIS <->, k-d tree or ball tree offline | Limit radius | Index-ordered reads |
| kNN, points | Moving | Quadtree or grid with expanding rings | Cap ring growth | Best-first search |
| Bounding box (viewport) | Static | PostGIS &&, SQLite R*Tree, Elasticsearch | Marker clustering | MBR overlap is native |
| Polygon containment | Static zones, moving points | PostGIS ST_Covers plus cell cache | Hysteresis | Two-stage test |
| Region cover for arbitrary shape | Any | S2 RegionCoverer or H3 polygonToCells | 8 to 20 cells | Range scans on integer keys |
| Analytics roll-ups, surge | Streaming | H3 resolution 7 to 9 as a group key | GridDisk smoothing | One neighbour distance |
| Key-value store without geo | Any | Geohash prefix or S2 id | 9 cells, exact filter | Portable |
| Mobile offline | Static | SQLite R*Tree | Box then exact check | Embedded |
Build, adopt or avoid
| Situation | Choose | Why |
|---|---|---|
| Under about 10,000 points | A full scan with haversine | The index costs more than the scan |
| Already running PostgreSQL | PostGIS | One system, SQL joins, correct maths |
| Already running Redis, points only | Redis GEO | No new component |
| Text search plus location | Elasticsearch geo_point | Relevance and distance in one query |
| Document store | MongoDB 2dsphere | Native; S2-based |
| Global uniform cells or analytics | S2 or H3 | Fixed hierarchy, integer keys |
| Hand-rolled spatial index in application code | Avoid unless in-memory and tested | Boundary and wrap bugs |
In architecture: from a single process to a distributed system
Monolith: one process, one database
One PostgreSQL with PostGIS: places has a geography column and a GiST index; "nearby" is ST_DWithin plus <->; no cache, no sharding. This serves millions of static points. Live driver positions at low volume (a few hundred updates per second) can also be rows, with the seen_at column and a partial index on recent rows.
Modular monolith: boundaries without the network
A Location module owns the spatial index behind an interface (Nearby(point, radius, k)); other modules never see cells or SQL. The live store can be Redis while the durable catalogue stays in PostGIS; the module keeps them in step. In Laravel this is a service class (like DriverLocationStore) bound in the container.
Microservices: every arrow is a decision
A location service ingests pings (gRPC or UDP-like streaming, see Real-Time Communication), updates the live index and publishes a compacted stream; a dispatch service queries "nearby"; a geofence service consumes the stream and emits enter/exit events; a trip service stores history. The contracts are the Nearby query and the ping event; the index never crosses a service boundary. See Case Study: Uber for the full design.
Distributed data: replicas, caches, regions
Live positions are eventually consistent by nature: a replica a second behind shows a driver one street away from reality, so choose per-city primaries and never fail over positions across regions. Partition by city first, then by cell when one city outgrows a node (the H3 or geohash prefix is the shard key; see Sharding at System Level and Consistent Hashing). A hot cell defeats hashing: split that cell into finer cells or give it its own shard. A read cache for "nearby" results has a short TTL (seconds) and a cell-based key (see Caching).
Scaling path: 1x, 10x, 100x
| Scale | Points / updates | Design | Next bottleneck |
|---|---|---|---|
| 1x | 100,000 points, 100 updates/s | PostGIS, GiST, ST_DWithin | Index bloat on frequent updates |
| 10x | 1 million points, 5,000 updates/s | Redis GEO per city for live data; PostGIS for the catalogue | One Redis key per city on one node |
| 100x | 50 million points, 100,000+ updates/s | Cells (H3 or geohash) as the shard key; in-memory quadtree or grid per shard; stream for history | Hot cells; fan-out of a query to 9 cells over several shards; see Load Shedding |
Lab: measure, compare, break the boundary
Run the Go demo (run on the author's laptop)
cd docs/snippets/system-design/geospatial-indexing/go
go test ./...
go run ./cmd/demo
go test -bench=. -run xxx ./quadtree Output observed on one laptop (Go 1.2x, Apple silicon); numbers vary by machine
1 full scan : 200 hits, 5.9 ms (200,000 points, haversine on every point)
2 geohash 5 : 200 hits, 11445 candidates, 0.39 ms (9 cells, then exact filter)
3 quadtree : 200 hits (planar approximation), 0.019 ms
4 BenchmarkNearest10-12 129331 7810 ns/op (k=10 over 100,000 points)The three methods agree on the hit count; the index narrows 200,000 points to 11,445 candidates (geohash) or to a handful of leaves (quadtree). Absolute times depend on the machine; the ratios are the point.
Drills (expected, not run)
Experiments 1 to 3 need PostgreSQL with PostGIS; 4 and 5 need Redis 6.2 or later. Output is expected, not run (خروجی موردانتظار؛ اجرا نشده in the Persian page).
1 Create the table and index from sql/postgis.sql, load 1,000,000 random points around Tehran
2 EXPLAIN (ANALYZE) SELECT ... WHERE ST_DWithin(location, p, 1000)
expected: Index Scan using places_location_gix, rows removed by filter small
3 Rewrite as WHERE ST_Distance(location, p) < 1000
expected: Seq Scan on places (the index is not used); time grows by orders of magnitude
4 redis-cli GEOADD drivers 51.3890 35.6892 d1 51.4000 35.7000 d2
expected: (integer) 2
5 redis-cli GEOSEARCH drivers FROMLONLAT 51.39 35.69 BYRADIUS 2 km ASC WITHDIST
expected: d1 first with a small distance, d2 about 1.5 km
6 Boundary: encode (0.0001, 10) and (-0.0001, 10) with geohash length 7
expected: different first characters, yet each is in the other's Neighbours() (a Go test asserts this)Common misconceptions
| Belief | Reality |
|---|---|
| Two B-tree indexes on lat and lon are enough | They read a strip of the planet; use a spatial index and an exact filter |
| A shared geohash prefix means near, a different prefix means far | A shared prefix means the same cell; neighbours across a border share none |
ST_Distance(a, b) < d is the right radius filter | It does not use the index; ST_DWithin does |
| Lat/lon is x/y | Longitude is x; Redis, PostGIS and GeoJSON take longitude first |
GEORADIUS is the Redis geo command | Deprecated since 6.2.0; use GEOSEARCH |
| Redis has a geo data type | It is a sorted set with a geohash score; delete with ZREM |
| SRID 3857 distances are metres | Mercator metres are inflated by 1/cos(latitude) |
| Hexagons subdivide exactly into seven hexagons | They only approximate; 12 pentagons exist at every resolution |
| Quadtrees are database indexes | They are in-memory structures; databases use R-trees or cell keys |
| Rounding coordinates anonymises location | It lowers precision; patterns still identify people |
| Every GPS ping belongs in the spatial database | Keep live positions in memory and append history elsewhere |
Cheat sheet
| Topic | What to remember |
|---|---|
| Four query shapes | Radius, bounding box, polygon containment, kNN |
| Pattern | Index filter, then exact distance |
| Coordinates | WGS84, SRID 4326, longitude first in Redis, PostGIS, GeoJSON |
| Distance | Haversine on the sphere; geography in PostGIS; never degrees |
| Geohash | Base32 of interleaved bits (Morton code); prefix equals same cell |
| Geohash boundary | Query cell plus 8 neighbours; pick the length from the radius |
| S2 | Cube faces, Hilbert curve, levels 0 to 30, 64-bit ids, coverings |
| H3 | Hexagons, resolutions 0 to 15, k-ring, aggregate per resolution |
| Quadtree | Split at capacity; best-first kNN; in-memory only |
| R-tree | MBRs, balanced, GiST in PostGIS, R*Tree in SQLite |
| Redis | GEOADD, GEOSEARCH, GEODIST; sorted set; ZREM; GEORADIUS deprecated |
| PostGIS | geography, GiST, ST_DWithin, <->, ST_Covers |
| Moving objects | Live positions in memory, TTL, shard by city and cell, watch the hottest cell |
| Privacy | Truncate geohash or round decimals; quantise returned distances |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Why can two B-trees on latitude and longitude not answer a radius query efficiently? Must-know
Answer
Answer: Each index prunes one axis, so a query reads a whole strip (all longitudes at that latitude) and filters afterwards; the shape is a square in degrees and results still need sorting by real distance.
2 — What is the boundary problem in geohash and how is it handled? Important
Answer
Answer: Two nearby points on opposite sides of a cell border can share no prefix. Query the cell containing the point plus its eight neighbours, choosing a length whose cell is at least as large as the radius, then filter by exact distance.
3 — Which Redis command replaces GEORADIUS and since which version? Good to know
Answer
Answer: GEOSEARCH (with GEOSEARCHSTORE), since Redis 6.2.0; GEORADIUS is deprecated as of 6.2.0.
4 — How does Redis store geo data, and how do you delete a member? Important
Answer
Answer: As a sorted set whose score is a 52-bit geohash integer; use ZREM because there is no GEODEL.
5 — Why does PostGIS recommend ST_DWithin over ST_Distance in a WHERE clause? Important
Answer
Answer: ST_DWithin includes a bounding box comparison that uses the spatial index; ST_Distance is evaluated per row and is not indexable.
6 — What does the KNN operator do and how is it written? Good to know
Answer
Answer: The distance operator in an ORDER BY with LIMIT lets a GiST (or SP-GiST) index return rows nearest-first: ORDER BY location <-> point LIMIT k.
7 — Compare geohash, S2 and H3 in one sentence each. Good to know
Answer
Answer: Geohash: rectangular string cells, prefix hierarchy, Z-order, works anywhere. S2: cube-face cells numbered along a Hilbert curve, 64-bit ids, levels 0 to 30, region coverings. H3: hexagons with a single neighbour distance, resolutions 0 to 15, k-rings, aggregation.
8 — Why is a quadtree not used as a disk index in databases? Good to know
Answer
Answer: It is pointer-based, unbalanced and has no standard page layout; databases use R-tree-like GiST or cell keys in a B-tree. It fits a service holding live points in memory.
9 — What is an MBR and why does it make R-tree search a filter step? Important
Answer
Answer: A minimum bounding rectangle is the smallest box around an object. The tree finds boxes that overlap the query, which may not contain the real shape, so the exact geometry test must follow.
10 — How would you keep a million moving drivers searchable? Must-know
Answer
Answer: Keep live positions in memory (Redis GEO or an in-process grid), shard by city and cell, expire by last-seen time, append history to a log, and monitor the hottest cell.
11 — Why is rounding coordinates not anonymisation? Must-know
Answer
Answer: Repeated rounded positions still reveal home and work patterns; combine truncation with retention limits, access control and quantised distances.
Glossary
| Term | Meaning |
|---|---|
| Geospatial index | A structure that finds items by location in sub-linear time |
| Latitude | Angle north or south of the equator, -90 to 90 |
| Longitude | Angle east or west of the prime meridian, -180 to 180 |
| WGS84 | The world geodetic datum used by GPS |
| SRID 4326 | The EPSG code for WGS84 lon/lat in degrees |
| SRID 3857 | Web Mercator, used for web map tiles; not distance-true |
| Projection | A map from the curved Earth to a plane |
| Great-circle distance | The shortest path between two points on a sphere |
| Haversine | The formula for great-circle distance from two lat/lon pairs |
| Geohash | A base32 string naming a lat/lon rectangle; a prefix is a larger cell |
| Base32 | Five bits per character; geohash alphabet skips a, i, l, o |
| Z-order curve | A curve that visits grid cells by interleaving coordinate bits |
| Morton code | The bit-interleaved number behind the Z-order curve |
| Precision | Geohash length or resolution: more characters, smaller cell |
| Neighbour cells | The eight cells around a cell, queried together |
| Boundary problem | Near points on opposite sides of a cell border with no shared prefix |
| Prefix search | A range scan on a string key for everything in a cell |
| S2 | Google's spherical cell library with 64-bit cell ids |
| Hilbert curve | A continuous space-filling curve with better locality than Z-order |
| Cell level | S2's depth, 0 to 30 |
| Covering | A small set of cells that together cover a region |
| H3 | Uber's hexagonal hierarchical index |
| Hexagon | H3's cell shape, with one neighbour distance |
| Resolution | H3's size level, 0 to 15 |
| k-ring | All cells within k steps of a cell (gridDisk in v4) |
| Quadtree | A tree that splits a square into four |
| Point quadtree | A quadtree holding points, split at a bucket capacity |
| Region quadtree | A quadtree that splits space into equal quadrants for regions or rasters |
| R-tree | A balanced tree of bounding rectangles |
| R*-tree | An R-tree variant with better split and re-insertion rules |
| MBR | Minimum bounding rectangle |
| Bounding box | An axis-aligned rectangle around a shape or a viewport |
| GiST | PostgreSQL's generalized search tree used for spatial indexes |
| SP-GiST | PostgreSQL's space-partitioned GiST for quad-trees and k-d trees |
| k-d tree | A binary tree that splits on alternating axes |
| Ball tree | A tree of nested balls usable with any metric |
| Grid index | A map from cell to the items inside it |
| GEOADD | Redis command that adds longitude, latitude, member |
| GEOSEARCH | Redis command for radius or box queries (6.2+) |
| GEORADIUS | Deprecated Redis radius command |
| GEODIST | Redis command for distance between two members |
| PostGIS | The spatial extension for PostgreSQL |
| geography | PostGIS type measuring on the spheroid in metres |
| geometry | PostGIS planar type in the units of its SRID |
| ST_DWithin | Index-assisted "within distance" predicate |
| ST_Distance | Exact distance function; not indexable in a WHERE |
| KNN operator | The <-> distance operator ordering index results nearest-first |
| 2dsphere | MongoDB's spherical geospatial index |
| geo_point | Elasticsearch point field type |
| geo_shape | Elasticsearch shape field type |
| Spatial index | Any index built for location queries |
| Moving objects | Entities whose position changes over time |
| Location update | One position report from a moving object |
| Hot cell | A cell with far more objects or queries than others |
| Geofencing | Detecting entry to or exit from a region |
| kNN | The k nearest neighbours of a point |
| Radius query | All points within a distance |
| Polygon containment | Whether a point is inside a polygon |
| Privacy truncation | Reducing location precision on purpose |
References
- Redis, GEOADD: https://redis.io/docs/latest/commands/geoadd/
- Redis, GEOSEARCH: https://redis.io/docs/latest/commands/geosearch/
- Redis, GEORADIUS (deprecated): https://redis.io/docs/latest/commands/georadius/
- Redis, GEODIST: https://redis.io/docs/latest/commands/geodist/
- PostGIS, data management (geometry and geography types): https://postgis.net/docs/using_postgis_dbmanagement.html
- PostGIS, ST_DWithin: https://postgis.net/docs/ST_DWithin.html
- PostGIS, ST_Distance: https://postgis.net/docs/ST_Distance.html
- PostGIS, distance operators (
<->): https://postgis.net/docs/geometry_distance_knn.html - PostgreSQL, GiST: https://www.postgresql.org/docs/current/gist.html
- PostgreSQL, SP-GiST: https://www.postgresql.org/docs/current/spgist.html
- Guttman, R-trees: a dynamic index structure for spatial searching (1984), copy: http://www-db.deis.unibo.it/courses/SI-LS/papers/Gut84.pdf
- Quadtree (secondary): https://en.wikipedia.org/wiki/Quadtree
- R-tree (secondary): https://en.wikipedia.org/wiki/R-tree
- Geohash (original service): http://geohash.org/
- Geohash (secondary): https://en.wikipedia.org/wiki/Geohash
- S2 cell hierarchy: https://s2geometry.io/devguide/s2cell_hierarchy
- H3 resolution table: https://h3geo.org/docs/core-library/restable
- H3 indexing: https://h3geo.org/docs/highlights/indexing
- Uber, H3: Uber's Hexagonal Hierarchical Spatial Index: https://www.uber.com/blog/h3/
- MongoDB, 2dsphere indexes: https://www.mongodb.com/docs/manual/core/indexes/index-types/geospatial/2dsphere/
- MongoDB, geospatial queries: https://www.mongodb.com/docs/manual/geospatial-queries/
- Elasticsearch, geo_point: https://www.elastic.co/guide/en/elasticsearch/reference/current/geo-point.html
- Elasticsearch, geo_shape: https://www.elastic.co/guide/en/elasticsearch/reference/current/geo-shape.html
- SQLite R*Tree module: https://www.sqlite.org/rtree.html
- phpredis README: https://github.com/phpredis/phpredis/blob/develop/README.md
- Laravel 13, Redis: https://laravel.com/docs/13.x/redis
- Laravel 13, query builder: https://laravel.com/docs/13.x/queries