Build a Geo-Filtered Vector Search System for Location-Aware AI
databases scalability performance
AI System Design Deep Dive
Geo-Filtered Vector Search
A radius makes ANN either slow or wrong; the planner picks the path per query.
A map app answers “quiet ramen counter” 22,000 times a second at peak. Each request carries a sentence, a latitude, a longitude and a radius, and the answer has to come from 180 million places in 90 countries, every result inside the radius, in under 120ms at p99. The index is 384-dimensional, 97 GB in RAM per replica, and the radius changes the problem more than the sentence does.
Think of a hotel concierge asked for the best ramen within a ten-minute walk. She has two things: a city-wide ranked list of every ramen shop, and a map. If she reads the ranked list top-down and checks each shop against the map, she is fast in a ramen-dense neighbourhood and hopeless in a quiet one, because the first walkable shop might be 400th on the list. If she instead walks every street within ten minutes and ranks what she finds, she is exact, but in midtown that is 30,000 places. A good concierge decides which of the two to do from the size of the neighbourhood, before she starts.
Vector indexes are the ranked list. Geography is the map. Approximate nearest neighbour search is built to find the closest vectors to a query, not the closest vectors that also satisfy an arbitrary predicate. We replayed 300,000 clustered places (a 64-dimension stand-in for the real 384, 80 city clusters on a 6,000 km plane) against an HNSW index and a radius filter. Fetching 10x the results and filtering afterwards returned 2.4% of the true top-10 at a 3 km radius, 65% at 100 km, and 98% at 1,500 km. Overall recall@10 was 0.65. Fetching 100x helped at 30 km (0.94) and still left only 0.25 at 3 km. Letting the graph walk apply the filter fixed recall to 1.00 and cost 143 ms at 3 km in the same run, against 0.18 ms for a plain scan of the 91 places that were actually inside the circle.
| Radius | Median selectivity | Post-filter 10x recall | Post-filter 100x recall | Filtered HNSW | Exact scan | Planner |
|---|---|---|---|---|---|---|
| 3 km | 0.023% | 0.02 | 0.25 | 143.2 ms | 0.18 ms | 0.18 ms |
| 30 km | 1.6% | 0.51 | 0.94 | 26.0 ms | 2.93 ms | 1.33 ms |
| 100 km | 2.0% | 0.65 | 0.93 | 23.4 ms | 3.23 ms | 1.36 ms |
| 500 km | 3.3% | 0.64 | 0.99 | 7.89 ms | 7.84 ms | 4.57 ms |
| 1,500 km | 16.4% | 0.98 | 1.00 | 0.76 ms | 40.2 ms | 2.99 ms |
| 3,000 km | 49.3% | 1.00 | 1.00 | 0.51 ms | 130 ms | 0.51 ms |
Method note: 300k points, 64-d unit vectors, hnswlib with M=16, efConstruction=200, ef=200, 40 to 50 queries per radius, recall@10 against exact search inside the circle. Filtered HNSW used a Python predicate callback, which inflates its latency, so read the columns as shapes and ratios and not as production numbers. Neither fixed strategy wins at any radius that matters. A per-query choice between them did: recall 1.00 across all six radii, mean 1.88 ms, p99 17.3 ms, against 30.2 ms mean and 193 ms p99 for filtered HNSW alone.
We need to solve for filter selectivity, partition layout, and result quality at the edge of the radius simultaneously, on a fleet small enough that a map query costs a fraction of a cent per thousand.
A radius filter is not a property of the vector index, it is a property of the query. The same index needs a different execution plan at 3 km than at 3,000 km, so the system's central component is a planner that estimates selectivity, not a cleverer graph.
Requirements and Constraints
Functional Requirements
- Accept a text query, a point, and one of: a radius (up to 500 km), a bounding box (a map viewport), or an “implicit radius” for near-me queries.
- Apply optional category filters (a 32-bit category mask) in the same pass as the geo filter.
- Return the top 10 places with distance in km, ordered by a blend of semantic similarity and distance.
- Make upserts visible in under 5 seconds (through a delta index) and folded into the graph within 15 minutes, and deletes visible in under 2 seconds, since a closed restaurant that still shows up is a support ticket.
- Treat the radius as a hard filter. A result outside the circle is a bug, not a low-ranked result.
Non-Functional Requirements
- Latency: p50 under 25ms and p99 under 120ms for retrieval. There is no generation on this path, so TTFT is not ours, but the downstream LLM that summarises the 10 places has a 400ms TTFT budget, and a slow retrieval spends it.
- Throughput: 9,000 queries per second average and 22,000 at peak, 23.65 billion queries a month. Query embeddings come from an embedding cache, so the GPU tier sees only the roughly 36% that miss.
- Quality: recall@10 of at least 0.95 against exact filtered search in every selectivity bucket, zero radius violations, and nDCG@10 monitored against click labels.
- Cost: under $0.20 per million queries, which is the number we hold the design to.
- Capacity: 540 bytes of RAM per place, 97.2 GB per full replica, 3 replicas across 3 availability zones.
Constraints
- Embeddings come from
bge-small-en-v1.5(384 dimensions), stored as int8 codes with an fp16 copy for rescoring. - Hardware is
r7g.4xlarge(16 Graviton3 vCPUs, 128 GB RAM). No GPUs sit in the search tier. - Geometry uses H3 cells. Polygon (administrative boundary) filters, open-now filters, and personalised ranking are out of scope.
The requirement that shapes everything is the hard radius. A result outside the circle is a defect, so the filter must be exact and approximation is spent only on which in-radius places rank first.
High-Level Architecture
Six components carry a query. The Query Parser validates and clamps the geo input. The Query Embedder turns text into a 384-d vector, behind the embedding cache. The Covering and Planner turns the circle into contiguous key ranges, finds the partitions that own them, and picks an execution strategy per partition. The Partition Tier holds the vectors, one HNSW graph plus one cell-sorted payload per partition. The Merge and Rescore stage combines per-partition top-40 lists and re-reads 40 vectors at fp16. The Geo Scorer blends similarity with distance and returns 10 places.
A request flows left to right and then down. The router parses "ramen", (40.74, -73.99), r=2km, embeds the text, and builds the covering: up to 61 contiguous ranges of H3 resolution-9 ids that together contain the circle. It intersects those ranges with the partition map, which gives it the partitions to call (one for 73% of queries). For each partition it estimates how many places fall in the ranges, and tags the call scan, filtered or plain. Each partition node runs that strategy and returns 40 candidates with distances.
The router merges the lists with a heap, rereads the 40 survivors as fp16 vectors to remove int8 quantisation error, applies the distance prior, and returns 10. Nothing on the path looks at a place outside the covering, and nothing returns one outside the circle, because the last step on every path is an exact haversine check.
The architectural decision that matters is sorting every partition's rows by H3 resolution-9 id. It turns any circle into a handful of contiguous array ranges, which makes both the selectivity estimate and the exact scan cheap, and it is the reason a geo filter does not need a separate spatial index at query time.
The Cell Index and Partitions
This component’s job is to turn a point and a radius into key ranges, and key ranges into partitions.
The non-obvious part: an H3 cell id is not an opaque handle. The 64-bit integer encodes the resolution and a path of base-7 digits, and all descendants of a cell share its prefix. So every cell, at any resolution, owns one contiguous numeric interval of resolution-9 ids. If the payload array is sorted by the resolution-9 id of each place, “all places in this cell” is a binary search for two offsets, not an index lookup. A geohash prefix gives the same property with a worse cell shape (cells are rectangles, and their aspect ratio changes with latitude). H3 hexagons have a uniform distance to all six neighbours, which is why a k-ring covers a circle with little waste. S2 has the same range property on a quad-tree of cube faces and is what Google’s systems use; we picked H3 for its hexagonal rings and its tooling.
Think of a street map atlas with the pages sorted in the order a delivery driver would drive them. A neighbourhood is a run of consecutive pages, not a scatter. Sorting by a space-filling curve is the same idea, and it is also why the scan path reads sequential memory.
Space-filling-curve order turns a 2D range query into a few 1D range scans. That one property replaces the spatial index, the filter bitmap and the shard lookup with binary search over a sorted array.
# Cover a circle with contiguous res-9 key ranges and map them to partitions
import bisect
import math
import h3
R_EARTH_KM = 6371.0088
def res9_range(cell: int, res: int) -> tuple[int, int]:
"""Numeric [lo, hi] of every res-9 descendant of `cell` (a superset near pentagons)."""
base = (cell & ~(0xF << 52)) | (9 << 52)
lo, hi = base, base
for k in range(res + 1, 10):
shift = (15 - k) * 3
lo &= ~(7 << shift)
hi = (hi & ~(7 << shift)) | (6 << shift)
return lo, hi
def cover_circle(lat: float, lng: float, radius_km: float) -> list[tuple[int, int]]:
"""Merged, sorted res-9 key ranges whose union contains the circle."""
res, k = 0, 1
for res in range(9, -1, -1):
edge = h3.average_hexagon_edge_length(res, unit="km")
k = math.ceil(radius_km / (1.5 * edge)) + 1
if k <= 4:
break
center = h3.latlng_to_cell(lat, lng, res)
ranges = sorted(res9_range(h3.str_to_int(c), res) for c in h3.grid_disk(center, k))
merged = [ranges[0]]
for lo, hi in ranges[1:]:
if lo <= merged[-1][1] + 1:
merged[-1] = (merged[-1][0], max(merged[-1][1], hi))
else:
merged.append((lo, hi))
return merged
class PartitionMap:
"""rows: (lo_key, hi_key, partition_id), disjoint and sorted by lo_key."""
def __init__(self, rows: list[tuple[int, int, int]]):
self.rows = rows
self.los = [r[0] for r in rows]
def overlapping(self, ranges: list[tuple[int, int]]) -> dict[int, list[tuple[int, int]]]:
hit: dict[int, list[tuple[int, int]]] = {}
for lo, hi in ranges:
i = max(bisect.bisect_right(self.los, lo) - 1, 0)
while i < len(self.rows) and self.rows[i][0] <= hi:
plo, phi, pid = self.rows[i]
if phi >= lo:
hit.setdefault(pid, []).append((max(lo, plo), min(hi, phi)))
i += 1
return hit
We tested the covering against 21,000 random points drawn uniformly inside circles at seven locations, including a point at longitude 179.99 with a 5 km radius that spans the antimeridian and a point at latitude 89.9. Zero points fell outside the returned ranges. The partition map applies the same range logic one level up. Partitions are not fixed cells, they are key intervals chosen so each holds 1 to 3 million vectors: a res-3 cell by default, split into its res-4 children when it holds more than 3 million (Manhattan, Tokyo), and neighbouring sparse cells merged when they hold less. Splitting by population and not by area keeps rebuild and compaction jobs small and keeps any partition from becoming a hot shard.
Premium Content
Unlock the full article along with everything else in the archive — all in one place.