Geospatial indexing and proximity
Restaurants that deliver here, and the nearest free rider right now: two nearness questions that need cells, neighbours and very different storage.
A geospatial index answers “what is near this point?” without measuring the distance to everything. Every practical version does it the same way: it divides the map into cells, gives each cell a value that an ordinary index can sort, fetches candidates from a few cells around the point, and only then measures exact distances on that short list. This chapter builds the two location queries Dabba depends on, and shows why they need different designs even though both are about nearness.
The first query runs when a customer opens the app: which restaurants deliver to where I am standing? The restaurants barely move, and there are about 50,000 of them. The second runs when an order is ready to be picked up: which available riders are closest to this restaurant right now? The brief from the first chapter says about 50,000 riders online at the dinner peak, each reporting a location every 5 seconds. That is 10,000 location updates a second, and an answer that is 30 seconds old can send a rider who has already left.
Why an index on latitude and longitude does not work
The obvious approach stores latitude and longitude as columns, indexes them, and asks for rows within a box: latitude between a and b, longitude between c and d. A B-tree on latitude can find the rows in the latitude range quickly. It has no help to offer for the longitude condition, which is checked row by row on everything the first range returned.
The trouble is how much the first range returns. A 5 km band around Bengaluru’s latitude, about 12.97° north, is a thin strip running across the whole country. Chennai sits at about 13.08° north, inside that strip. So the index on latitude hands back every rider in Bengaluru and every rider in Chennai, and the database then discards the Chennai ones by checking longitude. A composite index on (latitude, longitude) has the same problem, since it sorts first by latitude. B-trees order one dimension; nearness on a map needs two.
The fix every geospatial index uses is to map two dimensions onto one ordering in which nearby points mostly get nearby values. Then a normal sorted index can find them.
Geohash: cells with names that sort
A geohash is built by repeatedly halving the world. The first bit says whether the point is in the eastern or western half of the longitude range; the next bit halves the latitude range; the next halves longitude again, and so on, alternating. The bits are then written five at a time as base-32 characters. Each character adds five more halvings, so each extra character makes the cell 32 times smaller in area.
The useful sizes, near the equator: five characters give a cell about 4.9 km by 4.9 km; six characters, about 1.2 km by 0.6 km; seven characters, about 150 m by 150 m. Central Bengaluru sits in cells starting tdr1. Because of the way the bits are built, two points whose geohashes share a long prefix are in the same small cell, and so close together. A B-tree index on the geohash string turns “riders in this cell” into a prefix range scan, which any database does well.
The reverse is not true, and the mistake that follows from it is the one to avoid.
A restaurant sits near the eastern edge of geohash cell tdr1x. To find riders nearby, the rider service scans for every rider whose geohash starts with tdr1x. There is an available rider 150 m away, just across the cell boundary. Does the query find that rider?
Show the worked answer
No. The cell to the east is tdr38. It shares only the prefix tdr with tdr1x, because the boundary between them is also a boundary between larger cells. A prefix scan on tdr1x finds riders inside that cell only, which here means one rider 3 km away on the far side.
Points in the same cell are close, but close points are not always in the same cell. Every correct query therefore searches the point’s cell and its eight neighbours, then measures the real distance to each candidate and discards those outside the radius.
Geohash cells have two other weaknesses worth knowing. They are rectangles whose width shrinks away from the equator, which matters little in most of India (Delhi at 28.6° north has cells about 10% narrower than Bengaluru’s) and a great deal in Oslo. And their size is fixed, while density is not: a six-character cell over Koramangala holds hundreds of restaurants, while the same size cell on the city’s edge holds none.
Other ways to cut the map
A quadtree handles uneven density directly. It starts with one square and splits any square holding more than some number of points, say 100, into four. Dense neighbourhoods end up with small squares and sparse ones with large ones, so every leaf holds a manageable list. It is a good structure for in-memory indexes of points that do not move much. For points that move constantly, splitting and merging squares as riders drive around becomes its own source of work.
S2, from Google, projects the sphere onto the six faces of a cube and orders each face’s cells along a Hilbert curve, a path that visits every cell and keeps consecutive cells close together. Every cell, at every level from a face down to about a square centimetre, is a 64-bit integer. Its strength is covering arbitrary shapes: a delivery zone drawn as a polygon becomes a small set of cells of mixed sizes, and “is this point in the zone?” becomes a few integer range checks.
H3, from Uber, uses hexagons. A hexagon’s six neighbours are all the same distance from its centre, where a square has four neighbours sharing edges and four more touching only at corners, further away. That makes H3 well suited to anything that spreads across neighbouring cells, like smoothing demand into nearby areas or computing rings of cells around a point. Useful sizes: resolution 7 cells are about 5 km² with edges of about 1.2 km; resolution 8, about 0.74 km² with edges of about 460 m; resolution 9, about 0.1 km² with edges of about 175 m. The price is that hexagons do not nest exactly: a parent hexagon’s seven children cover approximately, not exactly, the same area.
| Structure | Good at | Weakness | Where Dabba uses it |
|---|---|---|---|
| Geohash | Fits any database with a string index; easy to debug | Edge effects, rectangular cells, fixed size regardless of density | Inside Redis GEO, which holds live rider locations |
| Quadtree | Adapts to density | Restructuring cost when points move often | Not used; riders move too much |
| S2 | Covering polygons with few cells; 64-bit ids | Harder to reason about by eye | Delivery-zone polygons |
| H3 | Equal-distance neighbours, rings, aggregation | Inexact nesting between resolutions | Serviceability, demand heatmaps |
| R-tree (PostGIS GiST) | Shapes and points in a database, exact queries | Heavy updates are expensive | Restaurant locations and zone edits |
Restaurants: precompute the answer, because they barely move
Each restaurant has a location and a delivery area, usually a polygon drawn by the operations team that follows roads and avoids, say, a river with no bridge nearby. The question “which restaurants deliver here?” is a point-in-polygon test against every restaurant’s zone.
PostGIS with a GiST index (an R-tree) can answer that directly, and for an admin tool it is the right choice. For the customer’s home screen, asked thousands of times a second, Dabba precomputes. Bengaluru covers about 740 km², roughly 1,000 H3 cells at resolution 8. For each cell, a batch job lists the restaurants whose delivery zone covers it. When a customer opens the app, we compute her cell, read one list, and filter by “open now”. One key lookup replaces a geometric query.
The job reruns when a restaurant’s zone changes, which happens a few times a day across the whole country, and the change flows through the same CDC pipeline as everything else. The cost is that a cell is coarse: a customer at the very edge of a zone may see a restaurant that cannot quite reach her, or miss one that could. Dabba checks the exact polygon at checkout for the restaurant she has chosen, so the coarse list only decides what she browses.
Riders: the Redis index from the storage chapter, and what it needs next
Riders are the opposite case, and the storage chapter has already told the story of what happened when their locations lived in the orders database: 10,000 updates a second, each one a new row version, a spatial index full of dead entries, and order placement slowing down at dinner. The fix there was to keep each rider’s latest position in Redis with a geospatial index, and to send the history through a stream into an LSM or time-series store for disputes and payouts. This chapter starts from that design and looks at what it does and where it needs help.
Redis’s geospatial commands are this chapter’s geohash idea, packaged. GEOADD stores a rider as a member of a sorted set whose score is a 52-bit interleaved geohash of the position, so updating a location overwrites one score in memory. GEOSEARCH with a radius works out which geohash ranges cover the circle, the centre cell and its neighbours, reads those ranges from the sorted set, and then filters the candidates by exact distance. That is the over-fetch-then-measure pattern from the prediction above, done for us.
Dabba keeps one key per city and per state: riders:avail:blr holds only Bengaluru riders who are free. When a rider accepts an order, the dispatcher removes him from that key; when he delivers, he is added back. A rider in city traffic averages perhaps 20 km/h, about 28 m between 5-second updates, so each update is a single score overwrite. The search for an order then reads only free riders, without paging through busy ones.
When an order is ready at a restaurant, the search goes like this:
GEOSEARCH riders:avail:blr FROMLONLAT lng lat BYRADIUS 1 km ASC COUNT 30: the closest free riders within a kilometre, already sorted by straight-line distance.- If fewer than 10 come back, double the radius and repeat, up to a limit of a few kilometres.
- Drop any candidate whose last update is older than 20 seconds, four missed updates (the next section explains where that time comes from).
- Keep the closest 10 of those that remain.
- Ask the routing service for travel times for those 10 and offer the order to the best one.
The last step matters because straight-line distance lies in a real city. A rider 400 m away on the other side of a flyover with no nearby ramp may be eight minutes away by road. Routing is expensive, so we spend it only on the short list the index produced. The pattern is the same throughout: a cheap coarse filter, then an exact measurement on what survives.
Partitioning the rider index follows naturally. Here city is a good key, unlike for orders in the sharding chapter, because these queries never cross a city boundary. All 10,000 updates a second fit one Redis primary comfortably, and Bengaluru’s 30% share is about 3,000. Per-city keys mean a city can move to its own Redis node when it needs to, and a city that outgrows even that can split by zone, since a restaurant in the north of the city never needs a rider from the south. The cost from the storage chapter still applies: if a Redis node restarts, dispatch is blind for that city for about one update interval, 5 seconds, until riders report again.
Counting supply and demand per cell
The same cells serve a third purpose that is not a nearness query at all. Every minute, Dabba counts, for each resolution-8 cell, how many orders are waiting for a rider and how many riders are available. Where orders outnumber riders, the app shows longer delivery estimates, the delivery fee rises slightly, and the rider app shows a heatmap nudging free riders towards those cells.
Raw per-cell counts are noisy. A cell with 3 waiting orders and no riders looks like a crisis, while the cell next door has 8 idle riders two minutes away. So the ratio for each cell is smoothed with its ring of neighbours, weighting the cell itself most and its six neighbours less. This is where hexagons earn their place: all six neighbours are the same distance away, so one weight fits all of them. With squares, the four edge neighbours and four corner neighbours sit at different distances and need different weights, and getting that wrong leaves visible diagonal artefacts in the heatmap.
This is where Dabba’s geo design moves beyond the Redis index it started with. Redis GEO answers “who is near this point?” well; it has no notion of hexagonal cells or neighbour rings. The demand computation is an aggregate over the rider-location and order-events streams, keyed by H3 cell and recomputed every minute, so it belongs in a stream processor and not in the rider index. It is derived data in the sense of the derived-data chapter: if it is lost, the next minute rebuilds it.
Ghost riders: a walk-through
At 20:40 rider 4411 finishes a delivery in a basement car park and loses signal just as the app marks him free again. His last update put him near the entrance of a busy restaurant. He stays in riders:avail:blr at that position, looking like the ideal candidate for the next three orders from that restaurant.
Each time, the dispatcher offers him the order and waits 30 seconds for an acceptance that never comes, then moves to the next candidate. Three customers each lose 30 seconds of preparation-to-pickup time, and the restaurant’s food sits on the counter. Worse, the dispatcher might mark him as declining orders, which affects his pay.
The step-3 freshness check in the search above catches him after 20 seconds of silence, but it needs something Redis GEO does not have: a sorted-set member carries a position and nothing else, and Redis expires whole keys, not individual members. So Dabba keeps a companion sorted set, riders:seen:blr, scored by the time of each rider’s last update. The search reads it to filter candidates, and a sweep every few seconds uses ZRANGEBYSCORE to find riders silent for more than 20 seconds, removes them from the available set and marks them “unreachable”. Their next update adds them back. Without the sweep, the available set fills with ghosts and every search pays to read and discard them.
The cost is visible to riders with poor networks. A rider whose phone drops a few updates in a row flickers out of the pool and misses offers. Dabba sets the threshold at four missed updates rather than two, and the rider app sends a lightweight heartbeat when location has not changed, so that standing still at a restaurant does not look like silence.
When this machinery is not needed
At launch, with 2,000 riders and 400 updates a second, the storage chapter’s first design, a PostGIS table in the main database, was adequate. Redis became necessary at tens of thousands of riders, and the companion freshness set and sweep are worth adding as soon as dispatch is automated. A small operation that assigns riders by hand from a map needs none of it.
We would revisit the cell choices if the product changed shape. Batching two orders onto one rider makes the question “which rider is near both restaurants and both customers?”, a route problem rather than a nearest-point problem. And scheduled deliveries make it a question about where riders will be, not where they are.
The rider search ends by offering order 8812 to rider 4411, and that order id has been passing through every chapter so far: in shard routing, in event keys, in index documents. The next chapter, on identity and unique IDs, asks where it comes from, and what an order id reveals to anyone who sees two of them.