Design nearby search
Read first: Indexes: B-trees and LSM trees, Partitioning and sharding
Nearby search is a cell lookup plus the neighboring cells, then a sort by true distance. A geohash or a quadtree is how you build the cell. The index is derived and can be stale, so every point carries a timestamp and the query drops the ones that are too old.
“What is near this point” is an index question, not a product question and not a database question. You need a key that puts nearby things on the same key, a query that also reads the keys next door, and a sort, because the cell is a bag of candidates. Naming an engine that happens to have a spatial type does not answer any of those.
Requirements
The user is a person who drops a pin, or whose device has a location, and wants the nearest places. The same index has to be able to hold moving points, because ride matching sits on it. Places and drivers do not share a freshness rule. They share the cell.
It must:
- Given a latitude, a longitude, and a radius, return the closest places inside that radius.
- Rank by distance, not by “this cell’s id sorts first.”
- Keep working at the edge of a cell, where the nearest place is across the boundary.
- Ignore a point that has not been updated inside its freshness window.
Non-goals:
- Turn-by-turn routing and travel time. Distance here is geometric. A one-way street can make the nearest place a bad suggestion. Say that if they ask, and do not design the road graph unless they insist.
- Historical tracks. You keep the latest point per entity. A trail of every GPS tick is a time series with a terrifying cardinality, and it is a different bill.
- Full-text search over place names. A name query can run beside this. It is not the spatial index.
Latency assumption: the list is back within about 150 ms at p99. The result is 20 places. Assumption: default radius is 2 km, and you would rather return an honest empty list than a place 40 km away labeled as nearby.
Estimation
Two workloads. Do not add them together.
Places, the read-mostly product. Assumptions:
- 20 million places in the catalog.
- A place record is 100 bytes of id, name, lat, lon, and a timestamp.
- 30 million searches a day, five per searcher if you would rather start from people: that is 6 million searchers. Use the 30 million searches as the given.
- Peak is 4 times the average. Still inside 2x to 5x. Chosen because this product spikes at meal times more than a flat service does.
- A response is 20 places at about 200 bytes, so 4 KB.
Moving points, a separate assumption, so you can see the write path before the ride-matching lesson spends it:
- 1 million moving entities.
- Each reports every 5 seconds.
- An update is 40 bytes.
place storage = 20e6 * 100 bytes = 2e9 bytes = 2 GB
searches per day = 30e6
average QPS = 30e6 / 86,400 = about 350
shortcut / 1e5 = 300 per second
peak at 4x = about 1,400 QPS
response bandwidth, peak = 1,400 * 4 KB = about 6 MB/s
moving updates = 1e6 / 5 = 200,000 writes per second
update bandwidth = 200,000 * 40 bytes = 8 MB/s
Three hundred and fifty searches a second is a quiet read path. Two gigabytes is one process, with room for the index beside the records. If your design opens with fifty database shards, you have not done the arithmetic. The moving-point path is the opposite shape: the current locations are 1e6 * 40 bytes = 40 MB, and the write rate is 200,000 per second. The bytes are trivial. The update rate and the hot cell are not.
A million searches a day would be about 12 per second. You are above that on reads and far above it on moving writes. Bandwidth on both paths is a few megabytes a second. Stop talking about bandwidth.
Place updates, for completeness: assumption, 0.1 percent of places change in a day, 20,000 writes a day, well under one write a second average. The place index is rebuilt or edited rarely. The driver index is edited constantly. Same key design, different durability. A lost driver update is healed by the next report a few seconds later. You do not need a durable log of every tick unless the product grew a history requirement you already listed as a non-goal.
High-level design
flowchart LR
seeker[Person searching]
query[Query service]
grid[Cell index]
points[Latest point records]
ranker[Distance filter]
seeker --> query --> grid
grid --> points --> ranker
The latest-point table is the source: entity id, lat, lon, timestamp. The cell index maps a cell id to the entity ids currently in it. It is derived. You can drop it and rebuild it from the latest-point table. Queries do not scan the table.
A B-tree or a hash index on the cell id, the ordinary structures from the indexing page, makes the cell read a point read. The spatial idea is how you chose the key. The engine is how you look the key up.
Deep dive
The cell
Latitude runs about 180 degrees, longitude about 360. Interleave their bits and a shared prefix is a rectangle. That interleaved prefix is a geohash, whether you print it as bits or in a base-32 alphabet. Equal prefixes are inside one cell. Points on opposite sides of a boundary are in different cells even when they are meters apart. A prefix scan does not see across the boundary. You look up the cell and the neighbors.
How big is the cell? Assumption, stated as a conversion and not as a surveyed constant: 111 km per degree of latitude, from a 40,000 km circumference divided by 360. At 40 degrees of latitude, longitude shrinks by about cos 40 degrees, roughly 0.77, so about 85 km per degree. You want cells on the order of a kilometer or two, because the search radius is 2 km. Fourteen bits of latitude:
180 / 2^14 degrees = 180 / 16,384 = 0.01099 degrees
0.01099 * 111 km = 1.22 km of latitude
360 / 16,384 = 0.02197 degrees of longitude
0.02197 * 85 km = 1.87 km of longitude at the assumed latitude
A coarser grid, 12 bits, is about four times larger on a side, around 5 km by 7 km. A finer grid, 16 bits, is about 300 m by 470 m. The 14-bit cell is the one this design stores.
Neighbors are not “the eight cells I memorized.” The circle has to cover the radius. A box of side 2R on a grid of cell size S touches about (2R / S + 1) squared cells. With R = 2 km and S around 1.5 km, 2R / S is about 2.7, plus one is about 4, squared is about 16. Plan on a few dozen cell reads, not nine. A 3 by 3 block is what you get when the cell is larger than the radius. Here it is not, and a point near the corner would miss a place 2 km away. Compute the lat index and the lon index, add and subtract the ring size, wrap longitude at the dateline, and clamp latitude at the poles. Interleave again and you have the cell ids. The dateline bug is two indexes that are numerically far apart and geographically the same place. Handle the wrap in the index math, not as a special case you hope the query avoids.
A quadtree is the same idea with a variable depth. Start from one rectangle. When a cell holds more than a limit, split it into four. Assumption: split above 200 points. A query walks the nodes whose rectangles intersect the circle, collects candidates, and stops descending elsewhere. Downtown gets small cells. A desert stays one big cell. That is the appeal. The cost shows up when points move: splits and merges churn the tree under the write stream. A fixed geohash grid does not churn. When a fixed cell exceeds the cap, store that cell at one extra bit of lat and one extra bit of lon, which is four children, and mark the parent split. You just grew a quadtree under the cells that needed it, and nowhere else.
Rank by distance, then drop the stale
The cell read returns candidates in a square-ish blob that is larger than the circle. For each candidate, compute distance and drop anyone outside the radius. At a few kilometers the cheap approximation is enough, and you should say it is an approximation:
dx = delta longitude * 85 km per degree
dy = delta latitude * 111 km per degree
distance = square root of dx squared plus dy squared
Sort, return 20. The cell id is not a rank. Two points in one cell can be 2 km apart, and a point in a neighbor cell can be 50 meters away.
Empty neighborhoods are normal. If the circle is empty, expand the ring once, then again, and cap the expansion. Assumption: stop at 50 km or at 20 results, whichever comes first. An uncapped walk scans the world from a pin dropped in the ocean. Expansion uses the same index. You do not switch structures to answer “give me the nearest anyway.”
Timestamps. A place record older than a day is a candidate for “closed, not updated,” and you can still show it with that lag stated as an assumption. A moving point older than 30 seconds is not where the cell says it is. The query drops it. The ride-matching lesson will tighten that number because a dispatch depends on it. The index does not get to hide the timestamp inside the storage engine.
Writes, ghosts, and hot cells
A place edit updates the latest-point row, then the cell. Rare, boring, durable.
A moving edit is a new lat and lon. If the cell changed, write the entity into the new cell first, then delete it from the old cell. The other order leaves a window where the entity is in neither, which is a missed match. The insert-first order leaves a window where it is in both. Readers keep the newest timestamp per entity and drop anything older than the freshness window, so the ghost expires even if the delete is lost. Prefer a ghost you can expire over a hole.
Do not trust the cell index as the only copy. It is derived. A bug that leaves ghosts everywhere is fixed by rebuilding from the latest-point table, not by heroic edits to the cells. That rebuild is offline. Queries can keep serving the old cells with the timestamp filter while it runs.
Hot cell: a stadium, or a downtown grid at dinner. Partitioning by cell id puts that cell on one shard, and more shards do not split one id. The place data for a whole city is small. One metro of 1,000 km squared at about 2.3 km squared per cell is about 400 cells. At 50,000 places in that metro, the average cell holds a bit over 100 places. Twenty-five cells is a couple of thousand candidates. Sorting that is noise next to a network hop. The stadium cell might hold 10 times the average. Still a memory problem only if you refuse to split it. When a cell crosses the cap, split into four and let the query read the children. Cache the candidate list of a hot cell for a second or two if the read rate requires it. For places, a few seconds of cache is invisible. For drivers, those few seconds are a slice of the freshness budget, so the cache TTL has to be shorter than the 30-second drop rule or you will serve points you are about to call stale.
Scatter of a few dozen cell gets: if the cells live on different nodes, the user waits on the slowest. That is fanout. For the place catalog, keep a city’s index, or the whole 2 GB, in the query process and skip the scatter. Partition because the write rate of the moving-point case demands it, or because you want a second copy, not because 2 GB looked like big data.
Tradeoffs
| Choice | What you gain | What you spend |
|---|---|---|
| Fixed geohash grid, neighbors computed from the index | A stable key, easy to shard, no rebalance when a point moves inside the cell | A downtown cell is fat until you split it, and a short prefix does not cross a boundary |
| Quadtree that splits past a count | Small cells where the points actually are | Moving points reshuffle the tree, and the query has to walk a structure |
| Geohash plus a four-way split only on overflow | A calm write path, and depth only where a cell is crowded | Two read shapes: a leaf, or a parent you must expand |
| Rank by cell id | A shorter query | Wrong order, and misses next door |
| Filter by timestamp at read time | A lost delete heals itself when the point goes stale | You may return a ghost until the window expires |
| Radius query with a capped ring expansion | Sparse areas still return something | A wide ring reads many empty cells, so the cap has to be real |
| Cache a hot cell’s candidate list | The stadium does not recompute for every searcher | The cache adds lag on top of the timestamp, and it must be shorter than the freshness window |
Failure modes
- You query one cell and skip the ring. Symptom: a person standing on a boundary sees an empty street that has a cafe on the other side. The fix is the neighbor math, including the dateline wrap, and then the distance filter so the extra cells do not leak into the result.
- The stadium cell is one partition and you add partitions without changing the key. Symptom: one shard is hot, the rest are idle. Split the cell into children, or cache that one list. More identical shards do nothing.
- Deletes of the old cell fail and you have no timestamp. Symptom: a driver who left an hour ago is still a candidate, forever. The timestamp filter is the backstop. The delete is an optimization.
- You delete the old cell before the new write lands, and the process dies in between. Symptom: the entity vanishes until the next update. Insert first.
- The latest-point store is up and the cell index is corrupt. Symptom: nonsense neighbors. Rebuild the cells from the points. If the query path cannot survive that, you treated a derived index as the only copy.
- Searchers retry a slow query in a tight loop. Symptom: a retry storm on the hot cell, which was already the expensive one. The read is idempotent and still multiplies load. A short client timeout and a cap on in-flight searches beat a second copy of the fleet.
- A moving-point pipeline stalls. Symptom: everything goes stale together and the radius returns empty, which is the correct failure if your window is 30 seconds. Do not loosen the window to “whatever we have” during an incident, or you will dispatch ghosts. The ride-matching lesson depends on that refusal.
There is no strong consistency requirement between a place edit and a search. Lag of a minute on a restaurant listing is a product choice. Lag of ten minutes on a driver is a correctness bug in the product that consumes this index. Say which freshness you are selling.
In the interview
First five minutes: radius search, the cell as a candidate generator, neighbors because boundaries exist, rank by distance, drop stale timestamps. Give the storage number, 2 GB for the place catalog, and the moving-write number, 200,000 updates a second under that separate assumption. The contrast is the point. You are not sharding 2 GB because it sounds serious.
Skip the name of a geographic database. If they want a quadtree instead of a geohash, draw the four-way split and the walk. The rest of the design is the same.
The follow-up is the boundary, the stadium, or “the driver moved.” Walk insert-then-delete, the newest-timestamp rule, and the cap on how far you expand an empty search.
Check yourself
A 2 km search uses cells about 1.2 km by 1.9 km. Why is a 3 by 3 neighborhood not enough?
The circle’s diameter is 4 km. The rule of thumb is a block about (2R / S + 1) cells on a side, which lands near 4, so a few dozen cells, not nine. A 3 by 3 block is about right when the cell is larger than the radius. After the lookups you still filter by true distance, because the block is a square and the request was a circle.
The place catalog is about 2 GB and searches average a few hundred per second. What is actually expensive if entities also move?
The current locations are tens of megabytes. At one report per entity per 5 seconds, one million entities is 200,000 writes a second. The hard part is the cell update and the hot cell, not the disk. A lost tick is acceptable because the next report replaces it. A lost tick you still serve an hour later is not.
A point moves from cell A to cell B and the process crashes after deleting A and before writing B. What does the user see, and which order avoids it?
The point is in neither cell until the next update, so a search misses it. Write B first, then delete A. A crash then leaves a ghost in A. The timestamp filter drops the older copy, and a later delete or a rebuild cleans the cell.
Why does adding shards fail to cool a stadium cell, and what do you change instead?
The cell id is one key, so it has one home. New shards with the same partition function leave it there. Split that cell into four finer cells, or cache its candidate list. Both change the work of that key. A bigger cluster does not.
Based on: Designing Data-Intensive Applications, Kleppmann and Riccomini; Alex Xu, ByteByteGo volumes.