Case study: design a proximity service
A senior-level walkthrough of a nearby-places service: why two indexes fail, geohash cells and the boundary problem, the search cover, quadtrees for uneven density, S2 and H3, serving from memory and caching by cell, with tested C#.
Case studyApplied50 min readUpdated
- 1 architecture diagram
- 1 sequence flow
- 1 data model
- 1 API design
- 10 code samples
- 10 interviewer follow-ups
- 5 self-checks
On this page18 sectionsHLDLLDSenior depth
Read first: A framework for system design interviews, Caching, Replication and sharding
- Map two dimensions to one sortable key (geohash, S2, H3) so that a region becomes a few key ranges, instead of a scan over two thin bands of a B-tree.
- Never search only the user's own cell. Search every cell the circle touches, filter by exact distance, and choose a cell about the size of the radius.
- Use an adaptive quadtree for static data with uneven density, fixed cells for data that moves, and know S2, H3 and R-trees by their trade-offs.
- The index is small enough for memory, so replicate for traffic, shard by area and not by id only when you must, and cache candidates by cell instead of by exact coordinates.
- Keep the index fresh with a change stream, immutable snapshots and a small delta, and answer the senior follow-ups.
9 code samples (450 lines), collapsed so the explanation stays in focus.
Every app that says "near you" runs the same query: given a point, find the places, people or vehicles close to it. A restaurant search, a store locator, "friends nearby" and the driver search inside a ride-hailing app are all variants of it. The query looks trivial, and it is not, because a database index orders its entries along one dimension and the surface of the Earth has two. The whole design answers one question: how do you turn two dimensions into something a hash map or a B-tree can find quickly?
This lesson builds the answer in steps, and each step is tested in C#: geohash cells, the boundary problem and the search that fixes it, a quadtree for places packed unevenly, and the serving design around them. It is the base for designing a ride-hailing service, where the points move every few seconds and a different structure wins. It leans on caching and replication and sharding, and on storage engines and indexes for what a B-tree can and cannot do.
Spend the first minutes on questions. Each answer changes the design.
| Ask | Why it matters |
|---|---|
| Are the points fixed (restaurants, stores) or moving (drivers, friends)? | Fixed points allow an immutable index that is rebuilt and swapped. Moving points make writes the main load and need a structure that updates in place, which is the next lesson |
| Is the query "everything within a radius", "the k nearest", or "the best matches near me"? | A radius is a filter, the k nearest needs no radius at all, and "best" needs a ranking stage after retrieval |
| What range of radii: 200 m on foot, 25 km by car? | One cell size cannot serve both without waste, which decides how the index is stored |
| Which filters come with it: category, open now, rating, a text query? | Filters decide which side of the query is more selective, and whether a search engine fits better than a purpose-built index |
| How fresh must changes be: a new shop, a permanent closure? | Minutes are enough for most data, so a change stream and snapshots can replace transactional index updates |
| How many places and searches, in how many regions? | The index is probably smaller than you expect. Traffic and latency, not capacity, shape the design |
| Is the user's location sensitive? | Yes. Decide early what is logged, cached and retained |
Scope the build to the common case, which is fixed places, a radius with a category filter, ranked results in pages, and owners who add and edit places. Say that reviews, photos and recommendations are separate services that this one only links to.
State assumptions out loud. They are illustrative and the interviewer may change them.
places: 200M (assumed), about 1 KB per record
records: 200M x 1 KB = ~200 GB in the database
index entry: 8 B hash + 8 B id + 4 B category and flags = ~20 B
index: 200M x 20 B = ~4 GB, which fits in one machine's memory
searches: 100M daily users x 5 = 500M a day
average: 500M / 86,400 s = ~5,800 a second
peak (x5): ~29,000 a second
per search: ~12 cells and ~300 candidates (measured below)
changes: 1% of places a month = 2M a month = under 1 a secondFour conclusions:
- The index fits in memory, so capacity is not why you shard. Four gigabytes is one machine. You add replicas for throughput and availability, and the bulky details (photos, hours, descriptions) stay in the database or a cache and are fetched for the twenty results you return.
- The system is read-heavy to an extreme. Under one change a second against thousands of searches means writes can arrive through a stream and a rebuild, and nothing needs to be transactional with the index.
- Time goes to the network and to everything around the lookup. A lookup in memory takes microseconds. Authentication, the round trip, ranking and fetching details decide the latency, so the lookup should be cheap but need not be clever beyond that.
- Traffic follows people. Dinner time in a big city is the peak, a few cells carry most of it, and the cache and the replicas should be placed where the people are.
One read call carries the traffic. The owner-facing writes are ordinary CRUD in another service.
| Call | Who calls it | Meaning |
|---|---|---|
GET /v1/places/nearby | Apps and websites | Search around a point with a radius and filters, and return a page |
GET /v1/places/{id} | Apps | The full details of one place |
POST /v1/places, PUT and DELETE on /v1/places/{id} | The owner portal | Add, edit or close a place |
- query
- lat, lon, radius (meters, at most 25000), category (optional), limit (default 20, at most 50), cursor (optional)
- note
- the cursor is the distance and id of the last result, so a page boundary does not shift when places are added. It is valid only with the same lat, lon and filters, and a user who moves starts a new search
- 200returns { "results": [ { "id": "p_8841", "name": "Cafe Alba", "lat": 37.7701, "lon": -122.4189, "distance_m": 212 } ], "next_cursor": "212.4:8841" }
- 400a coordinate out of range, or a radius above the maximum
- 429this client is over its rate limit
idbigint
PKnametext
latdouble
londouble
geohashtext
9 characters, derived from lat and lon, about 5 m cells
INDEXcategorytext
INDEXhourstext
opening intervals with an IANA time zone name
ratingreal
statustext
open, closed_permanently or hidden
versionbigint
bumped on every change, so replicas and caches can tell they are stale
updated_attimestamptz
The geohash column is what makes a region query a range scan. Search reads a copy of (hash, id, category) held in memory.
The geohash column is derived data, written by the same code that writes lat and lon, and the memory index is derived again from the table. If they ever disagree, the table wins and the index is rebuilt.
The obvious first design is a table with lat and lon columns, an index on each, and a bounding-box query:
SELECT id FROM places
WHERE lat BETWEEN 37.761 AND 37.779
AND lon BETWEEN -122.430 AND -122.410
AND category = 'cafe';A B-tree orders its entries along one dimension. The planner can range-scan the latitude index, which returns every place in a thin band that circles the planet, or the longitude index, which returns a thin band from pole to pole, and then filter the other column row by row. It can also intersect the two scans, which still reads both bands in full. A composite index on (lat, lon) does not fix it: inside the latitude band the entries are ordered by latitude first, so the longitudes are scattered through it and the engine cannot jump to the right stretch. In the experiment below, a search with a radius of 1 km in one metro area reads about 3,600 rows from its latitude band to find 130 results, and a table for the whole planet has far more places at any given latitude than one metro area does. The cost follows the size of the bands, not the size of the answer.
What is needed is one key where places that are close in space are close in the key's order, so that a region becomes a few key ranges. Space-filling curves do exactly that: they walk the plane in an order that mostly keeps neighbours together. Geohash, S2 and H3 all work this way, and they differ in the curve and in the shape of the cell.
A geohash is a base-32 string that names a rectangle. Start with the whole world as a box. Each bit halves the box: the first bit says whether the longitude is in the west or the east half, the next whether the latitude is in the south or the north half, then longitude again, and so on, alternating. Five bits make one base-32 character, so every extra character cuts the box into 32 smaller boxes. Two consequences carry most of the design:
- A prefix is containment. A longer hash that starts with a shorter one lies inside the shorter hash's box. A region query in any sorted store is therefore a prefix scan, and a coarser cell is just a shorter prefix of the same key.
- The length is a dial for the cell size. Choose the precision per query and store the finest one.
The code below is the whole encoder and decoder, plus the great-circle distance used for the exact check later. It is short because the idea is.
C# · Place, Geo
using System;
using System.Text;
public sealed record Place(int Id, double Lat, double Lon, string Category);
public static class Geo
{
private const string Alphabet = "0123456789bcdefghjkmnpqrstuvwxyz"; // base 32 without a, i, l and o
// A geohash interleaves the bits of longitude and latitude (longitude first), five bits per base-32 character. Every extra
// character cuts the cell into 32 smaller ones, and a longer hash that starts with a shorter one lies inside its cell.
public static string Encode(double lat, double lon, int precision)
{
double latMin = -90, latMax = 90, lonMin = -180, lonMax = 180;
var hash = new StringBuilder();
int bits = 0, value = 0;
bool evenBit = true; // even bits refine longitude, odd bits latitude
while (hash.Length < precision)
{
if (evenBit)
{
double mid = (lonMin + lonMax) / 2;
if (lon >= mid) { value = (value << 1) | 1; lonMin = mid; } else { value <<= 1; lonMax = mid; }
}
else
{
double mid = (latMin + latMax) / 2;
if (lat >= mid) { value = (value << 1) | 1; latMin = mid; } else { value <<= 1; latMax = mid; }
}
evenBit = !evenBit;
if (++bits == 5) { hash.Append(Alphabet[value]); bits = 0; value = 0; }
}
return hash.ToString();
}
// The box a hash names.
public static (double LatMin, double LatMax, double LonMin, double LonMax) Decode(string hash)
{
double latMin = -90, latMax = 90, lonMin = -180, lonMax = 180;
bool evenBit = true;
foreach (char c in hash)
{
int value = Alphabet.IndexOf(c);
for (int bit = 4; bit >= 0; bit--)
{
int on = (value >> bit) & 1;
if (evenBit) { double mid = (lonMin + lonMax) / 2; if (on == 1) lonMin = mid; else lonMax = mid; }
else { double mid = (latMin + latMax) / 2; if (on == 1) latMin = mid; else latMax = mid; }
evenBit = !evenBit;
}
}
return (latMin, latMax, lonMin, lonMax);
}
// Great-circle distance in meters.
public static double Haversine(double lat1, double lon1, double lat2, double lon2)
{
const double EarthRadius = 6_371_000;
double dLat = (lat2 - lat1) * Math.PI / 180, dLon = (lon2 - lon1) * Math.PI / 180;
double a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2)
+ Math.Cos(lat1 * Math.PI / 180) * Math.Cos(lat2 * Math.PI / 180) * Math.Sin(dLon / 2) * Math.Sin(dLon / 2);
return 2 * EarthRadius * Math.Asin(Math.Sqrt(a));
}
public static double WrapLon(double lon) => lon >= 180 ? lon - 360 : lon < -180 ? lon + 360 : lon;
}C# · The textbook example, and the prefix property.
using System;
using System.Diagnostics;
// The textbook example, and the prefix property.
Debug.Assert(Geo.Encode(57.64911, 10.40744, 11) == "u4pruydqqvj");
Debug.Assert(Geo.Encode(57.64911, 10.40744, 11).StartsWith(Geo.Encode(57.64911, 10.40744, 6)));
// Cell sizes at the equator: what each character of precision buys.
for (int precision = 4; precision <= 9; precision++)
{
var (latMin, latMax, lonMin, lonMax) = Geo.Decode(Geo.Encode(0.0001, 0.0001, precision));
double mid = (latMin + latMax) / 2;
Console.WriteLine($"precision {precision}: {Geo.Haversine(mid, lonMin, mid, lonMax),9:F1} m wide, {Geo.Haversine(latMin, 0, latMax, 0),9:F1} m high");
}
var (la0, la1, lo0, lo1) = Geo.Decode(Geo.Encode(0.0001, 0.0001, 6));
Debug.Assert(Math.Abs(Geo.Haversine((la0 + la1) / 2, lo0, (la0 + la1) / 2, lo1) - 1_223) < 5); // about 1.2 km wide
Debug.Assert(Math.Abs(Geo.Haversine(la0, 0, la1, 0) - 611) < 5); // about 0.6 km high
// Two points 14 m apart on either side of the prime meridian share no prefix at all: close does not mean the same cell.
string westOfGreenwich = Geo.Encode(51.5, -0.0001, 6), eastOfGreenwich = Geo.Encode(51.5, 0.0001, 6);
Console.WriteLine($"{westOfGreenwich} {eastOfGreenwich} {Geo.Haversine(51.5, -0.0001, 51.5, 0.0001):F1} m apart");
Debug.Assert(westOfGreenwich[0] != eastOfGreenwich[0]);
Debug.Assert(Geo.Haversine(51.5, -0.0001, 51.5, 0.0001) < 15);The first check is the classic published example, so the encoder agrees with everyone else's. The loop prints what each character buys:
| Precision | Cell size at the equator | About the size of |
|---|---|---|
| 4 | 39 km wide, 19.5 km high | a region |
| 5 | 4.9 km by 4.9 km | a town or a district |
| 6 | 1.2 km wide, 0.6 km high | a neighbourhood |
| 7 | 153 m by 153 m | a city block |
| 8 | 38 m wide, 19 m high | a building |
| 9 | 4.8 m by 4.8 m | a doorway |
The shapes alternate between square and two to one, because a character adds five bits and the bits alternate between longitude and latitude. The width also shrinks with the cosine of the latitude, so a precision 6 cell is 1.2 km wide at the equator, about 0.97 km in San Francisco and about 0.6 km at 60 degrees north. Cell sizes are not equal and not square, which is acceptable here because the search does an exact distance check at the end.
The last two lines of the sample show the property that causes the main bug. The points 14 m apart on either side of the prime meridian get the hashes gcpuzz and u10hbp, which share not even the first character. Close in space does not imply a shared prefix. Only the reverse is true. The same break appears at the equator and at the antimeridian, where the highest bits flip, and it appears in a milder form at every cell edge, which is the next section.
A person's own cell is not their neighbourhood. If they stand 5 m from the edge of a cell, half of what is within 100 m lies in the next one. So the search must find every cell the search circle touches and look in all of them. That set is the cover. The code below computes it by walking the grid of cells across the circle's bounding box and keeping the cells whose nearest point is inside the radius. It wraps longitude at the antimeridian and guards the poles, where a circle spans every longitude.
C# · Cells
using System;
using System.Collections.Generic;
public static class Cells
{
// Meters from a point to the nearest point of a cell (0 when the point is inside it).
private static double DistanceTo(double lat, double lon, string cell)
{
var (latMin, latMax, lonMin, lonMax) = Geo.Decode(cell);
double shift = lon - (lonMin + lonMax) / 2;
if (shift > 180) lon -= 360; else if (shift < -180) lon += 360; // measure the short way round
return Geo.Haversine(lat, lon, Math.Clamp(lat, latMin, latMax), Math.Clamp(lon, lonMin, lonMax));
}
// Every cell the circle touches: walk the grid of cells between the corners of the circle's bounding box and keep the
// cells whose nearest point is within the radius.
public static List<string> Cover(double lat, double lon, double radius, int precision)
{
double dLat = radius / 111_320.0;
double dLon = Math.Min(radius / (111_320.0 * Math.Max(Math.Cos(lat * Math.PI / 180), 1e-9)), 180);
var own = Geo.Decode(Geo.Encode(lat, lon, precision));
double height = own.LatMax - own.LatMin, width = own.LonMax - own.LonMin;
var south = Geo.Decode(Geo.Encode(Math.Max(lat - dLat, -89.9999), lon, precision));
var west = Geo.Decode(Geo.Encode(lat, Geo.WrapLon(lon - dLon), precision));
var cells = new HashSet<string>();
for (double y = (south.LatMin + south.LatMax) / 2; y - height / 2 <= Math.Min(lat + dLat, 89.9999); y += height)
for (double x = (west.LonMin + west.LonMax) / 2; x - width / 2 <= lon + dLon; x += width)
{
string cell = Geo.Encode(y, Geo.WrapLon(x), precision);
if (DistanceTo(lat, lon, cell) <= radius) cells.Add(cell);
}
return new List<string>(cells);
}
// The 3 x 3 block around a cell: the shortcut many tutorials teach.
public static List<string> Block9(double lat, double lon, int precision)
{
var (latMin, latMax, lonMin, lonMax) = Geo.Decode(Geo.Encode(lat, lon, precision));
double height = latMax - latMin, width = lonMax - lonMin, cy = (latMin + latMax) / 2, cx = (lonMin + lonMax) / 2;
var cells = new List<string>();
for (int dy = -1; dy <= 1; dy++)
for (int dx = -1; dx <= 1; dx++)
cells.Add(Geo.Encode(Math.Clamp(cy + dy * height, -89.9999, 89.9999), Geo.WrapLon(cx + dx * width), precision));
return cells;
}
}Three ways to choose the cells are common, so the experiment measures all three. A hundred thousand places are spread over a metro area about 44 km by 55 km, a hundred people search within 1 km of random points, and brute force supplies the true answer, which averages 130 places per search. For each precision the search uses the person's own cell only, the 3 x 3 block around it, or the exact cover.
C# · A circle at longitude 179.9999 touches cells on both sides of the antimeridian.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
// A circle at longitude 179.9999 touches cells on both sides of the antimeridian.
var acrossTheLine = Cells.Cover(0.0, 179.9999, 2_000, 5);
Debug.Assert(acrossTheLine.Any(c => Geo.Decode(c).LonMax < 0) && acrossTheLine.Any(c => Geo.Decode(c).LonMin > 0));
// 100,000 places spread over a metro area about 44 km by 55 km, and 100 people each searching within 1 km.
var random = new Random(7);
string[] categories = { "restaurant", "cafe", "pharmacy", "gym", "bank" };
var places = Enumerable.Range(0, 100_000)
.Select(id => new Place(id, 37.52 + random.NextDouble() * 0.5, -122.67 + random.NextDouble() * 0.5, categories[random.Next(categories.Length)]))
.ToArray();
var people = Enumerable.Range(0, 100).Select(_ => (Lat: 37.62 + random.NextDouble() * 0.3, Lon: -122.57 + random.NextDouble() * 0.3)).ToArray();
const double Radius = 1_000;
// The truth, by brute force: every place within the radius of each person.
var truth = people.Select(person => places.Where(place => Geo.Haversine(person.Lat, person.Lon, place.Lat, place.Lon) <= Radius).Select(place => place.Id).ToHashSet()).ToArray();
long trueTotal = truth.Sum(found => found.Count);
foreach (int precision in new[] { 5, 6, 7, 8 })
{
var cells = new Dictionary<string, List<int>>();
foreach (var place in places)
{
string cell = Geo.Encode(place.Lat, place.Lon, precision);
if (!cells.TryGetValue(cell, out var list)) cells[cell] = list = new List<int>();
list.Add(place.Id);
}
IEnumerable<int> Lookup(IEnumerable<string> cellIds) => cellIds.Distinct().Where(cells.ContainsKey).SelectMany(id => cells[id]);
long lookups = 0, candidates = 0, coverHits = 0, ownHits = 0, blockHits = 0, blockCandidates = 0;
for (int i = 0; i < people.Length; i++)
{
var (lat, lon) = people[i];
var cover = Cells.Cover(lat, lon, Radius, precision);
lookups += cover.Count;
var fromCover = Lookup(cover).ToList();
candidates += fromCover.Count;
coverHits += fromCover.Count(truth[i].Contains);
ownHits += Lookup(new[] { Geo.Encode(lat, lon, precision) }).Count(truth[i].Contains);
var fromBlock = Lookup(Cells.Block9(lat, lon, precision)).ToList();
blockCandidates += fromBlock.Count;
blockHits += fromBlock.Count(truth[i].Contains);
}
Console.WriteLine($"precision {precision}: cover {lookups / 100.0,6:F1} cells, {candidates / 100.0,5:F0} candidates, recall {coverHits / (double)trueTotal:P1} | own cell only {ownHits / (double)trueTotal:P1} | 3x3 block {blockCandidates / 100.0,5:F0} candidates, recall {blockHits / (double)trueTotal:P1}");
Debug.Assert(coverHits == trueTotal); // the cover never misses anyone
Debug.Assert(ownHits < trueTotal); // the own cell alone always does
Debug.Assert(precision == 5 ? blockHits == trueTotal : blockHits < trueTotal); // the 3 x 3 block works only while a cell is bigger than the radius
}
Console.WriteLine($"true results per search: {trueTotal / 100.0:F0}");
// For comparison, what a B-tree range scan on latitude alone reads: every place in the band of latitudes the circle spans.
long bandRows = people.Sum(person => places.Count(place => Math.Abs(place.Lat - person.Lat) <= Radius / 111_320.0));
Console.WriteLine($"latitude band only: {bandRows / 100.0:F0} rows per search");
Debug.Assert(bandRows / 100.0 > 10 * trueTotal / 100.0);| Precision | Cells in the cover | Candidates | Own cell only finds | 3 x 3 block finds (candidates) | Cover finds |
|---|---|---|---|---|---|
| 5 | 2.2 | 1,735 | 80.7% | 100% (6,975) | 100% |
| 6 | 11.5 | 280 | 18.6% | 92.8% (219) | 100% |
| 7 | 200.9 | 152 | 0.6% | 4.9% (6) | 100% |
| 8 | 5,624.6 | 134 | 0.0% | 0.1% (0) | 100% |
Read it in four steps:
- The own cell alone misses most results unless it is huge. At precision 6 it finds 18.6% of the places within 1 km. Even at precision 5, where a cell is about five times the radius, it finds 80.7%, and the missing fifth is everything across the nearest edge. That is the boundary problem in numbers.
- The 3 x 3 block is right only while a cell is at least as large as the radius in both directions. At precision 5 it finds everything, and it reads 6,975 candidates to return 130 places. At precision 6, where a cell is 0.6 km tall, it silently loses 7.2% of the results, and at precision 7 it finds 4.9%. A bug that returns plausible but incomplete answers is worse than a slow one, because nothing alerts anyone.
- The exact cover never misses. It found every true result at every precision (the assertion in the sample), because it takes its cells from the circle and not from the point.
- Finer cells trade candidates for lookups. The candidates fall from 1,735 to 134 as the precision goes from 5 to 8 (the true answer is 130), and the cells to look up grow from 2.2 to 5,625. The work is roughly cells plus candidates, since a hash lookup and a distance check cost about the same order, and it is lowest near precision 6: about 292, against 1,737, 353 and 5,759. Choose a cell about the size of the radius.
For scale, the latitude-only scan from the previous section reads 3,593 rows per search, 28 times the answer and 13 times the 280 candidates of the precision 6 cover.
A sorted store avoids the explosion at fine precisions in another way. A cover can mix precisions, using a coarse cell where the circle fully contains it and fine cells only along the edge, which turns thousands of cells into a handful of key ranges. S2's region coverer does this systematically.
One fine index for every radius
With the cover in hand, the index is a sorted list of (geohash, place) at the finest precision. The cell u4pru is the range of entries that start with u4pru, found by binary search. That is what a B-tree on a geohash column does in a relational database (WHERE geohash LIKE 'u4pru%' becomes a range scan), and it is how Redis's geospatial commands work, because they keep each point's geohash as the score of a sorted set. One fine index serves every radius through coarser prefixes, so there is no index per precision. PrecisionFor picks the finest precision whose cell is at least half as tall as the radius: 7 for 300 m, 6 for 1 km, 5 for 5 km and 4 for 20 km.
C# · A search index over one sorted list of (geohash, place), the same thing a B-tree on a…
using System;
using System.Collections.Generic;
using System.Linq;
// A search index over one sorted list of (geohash, place), the same thing a B-tree on a geohash column keeps for you. The
// hashes are stored at the finest precision any search needs, so one index serves every radius through prefix scans.
public sealed class GeoIndex
{
private const int Finest = 9; // cells of about 5 m
private readonly List<(string Hash, Place Place)> _sorted = new();
public GeoIndex(IEnumerable<Place> places)
{
foreach (var place in places) _sorted.Add((Geo.Encode(place.Lat, place.Lon, Finest), place));
_sorted.Sort((a, b) => string.CompareOrdinal(a.Hash, b.Hash));
}
// The finest precision whose cell is still at least half as tall as the radius (a character adds 2 or 3 bits of
// latitude, and 180 degrees is about 20,000 km, so cell height = 20,037 km / 2^bits).
public static int PrecisionFor(double radius)
{
for (int precision = Finest; precision > 1; precision--)
if (180.0 / (1 << (5 * precision / 2)) * 111_320 >= radius / 2) return precision;
return 1;
}
private int LowerBound(string prefix) // first entry whose hash is >= prefix
{
int low = 0, high = _sorted.Count;
while (low < high)
{
int mid = (low + high) / 2;
if (string.CompareOrdinal(_sorted[mid].Hash, prefix) < 0) low = mid + 1; else high = mid;
}
return low;
}
// Candidates come from one prefix scan per cell the circle touches, and the exact distance decides who stays. Results
// are ordered by (distance, id), so a cursor holding the last pair resumes exactly where the previous page ended.
public List<(Place Place, double Meters)> Search(double lat, double lon, double radius, int limit,
string category = null, (double Meters, int Id)? after = null)
{
var found = new List<(Place Place, double Meters)>();
foreach (string cell in Cells.Cover(lat, lon, radius, PrecisionFor(radius)))
for (int i = LowerBound(cell); i < _sorted.Count && _sorted[i].Hash.StartsWith(cell, StringComparison.Ordinal); i++)
{
var place = _sorted[i].Place;
if (category != null && place.Category != category) continue;
double meters = Geo.Haversine(lat, lon, place.Lat, place.Lon);
if (meters > radius) continue;
if (after is { } cursor && (meters, place.Id).CompareTo((cursor.Meters, cursor.Id)) <= 0) continue;
found.Add((place, meters));
}
return found.OrderBy(f => f.Meters).ThenBy(f => f.Place.Id).Take(limit).ToList();
}
}C# · One fine index must agree with brute force at every radius, with a category filter and…
using System;
using System.Diagnostics;
using System.Linq;
// One fine index must agree with brute force at every radius, with a category filter and with pages of 20.
Debug.Assert(GeoIndex.PrecisionFor(300) == 7 && GeoIndex.PrecisionFor(1_000) == 6 && GeoIndex.PrecisionFor(5_000) == 5 && GeoIndex.PrecisionFor(20_000) == 4);
var index = new GeoIndex(places);
foreach (double searchRadius in new[] { 300.0, 1_000.0, 5_000.0 })
{
int mismatches = 0, pagesRead = 0, resultsRead = 0;
for (int i = 0; i < 40; i++)
{
var (lat, lon) = people[i];
var expected = places.Where(place => place.Category == "cafe")
.Select(place => (place.Id, Meters: Geo.Haversine(lat, lon, place.Lat, place.Lon)))
.Where(t => t.Meters <= searchRadius).OrderBy(t => t.Meters).ThenBy(t => t.Id).Select(t => t.Id).ToList();
var seen = new System.Collections.Generic.List<int>();
(double Meters, int Id)? cursor = null;
while (true)
{
var page = index.Search(lat, lon, searchRadius, 20, "cafe", cursor);
if (page.Count == 0) break;
seen.AddRange(page.Select(r => r.Place.Id));
cursor = (page[^1].Meters, page[^1].Place.Id);
pagesRead++;
}
resultsRead += seen.Count;
if (!seen.SequenceEqual(expected)) mismatches++;
}
Console.WriteLine($"radius {searchRadius,5:F0} m, precision {GeoIndex.PrecisionFor(searchRadius)}: {resultsRead} cafes in {pagesRead} pages, mismatches {mismatches}");
Debug.Assert(mismatches == 0);
}For 40 searches at each radius the index returned exactly what brute force returned, page after page: 87 cafes in 35 pages at 300 m, 1,045 in 74 pages at 1 km and 25,861 in 1,311 pages at 5 km, with no mismatch. Two details are worth copying. The order is (distance, id), a total order, so a cursor that holds the last pair resumes exactly where a page ended and two places at the same distance cannot swap. And there is no offset, because a place added between two page requests would shift every later page (the pagination problem from API design). Deep pages repeat the candidate scan, so cap the total (a few hundred results is plenty for a person) and let ranking, not paging, bring the best ones forward.
A grid has one weakness that a geohash shares: its cells are the same size everywhere, and places are not spread evenly. A downtown block can hold thousands of restaurants and a county none. A cell size that suits downtown leaves the countryside as millions of empty cells (harmless in a sparse map, fatal in an array), and a size that suits the countryside puts thousands of places in each downtown cell, which every search must then scan.
A quadtree adapts. Start with one square for the whole map. When a square holds more than a chosen capacity of points, split it into four equal squares and push its points down. Repeat. Dense areas end up with many small squares and empty areas stay as a few large ones, so every leaf holds about the same number of points whatever the density.
The search for the k nearest places needs no radius. Keep a priority queue of squares and points ordered by their distance from the query point. Start with the root and repeatedly take the nearest item. If it is a point, it is the next nearest result, because everything still queued is at least as far away. If it is a square, replace it with its four children, or with its points when it is a leaf. Stop after k points. This best-first search is the standard nearest-neighbour method for tree indexes (Hjaltason and Samet).
C# · A point quadtree over a square of the plane (kilometers). A leaf splits into four when…
using System;
using System.Collections.Generic;
using System.Linq;
// A point quadtree over a square of the plane (kilometers). A leaf splits into four when it holds more than `capacity` points,
// so dense areas end up with small cells and empty areas stay as a few large ones.
public sealed class QuadTree
{
private readonly double _x, _y, _size;
private readonly int _capacity, _depth;
private List<(int Id, double X, double Y)> _points = new();
private QuadTree[] _children;
public QuadTree(double x, double y, double size, int capacity, int depth = 0)
{
_x = x; _y = y; _size = size; _capacity = capacity; _depth = depth;
}
public int Leaves => _children == null ? 1 : _children.Sum(child => child.Leaves);
public void Insert(int id, double px, double py)
{
if (_children != null) { Child(px, py).Insert(id, px, py); return; }
_points.Add((id, px, py));
if (_points.Count <= _capacity || _depth >= 24) return; // the depth cap keeps identical points from splitting forever
double half = _size / 2;
_children = new[]
{
new QuadTree(_x, _y, half, _capacity, _depth + 1), new QuadTree(_x + half, _y, half, _capacity, _depth + 1),
new QuadTree(_x, _y + half, half, _capacity, _depth + 1), new QuadTree(_x + half, _y + half, half, _capacity, _depth + 1),
};
foreach (var point in _points) Child(point.X, point.Y).Insert(point.Id, point.X, point.Y);
_points = null;
}
private QuadTree Child(double px, double py) => _children[(px >= _x + _size / 2 ? 1 : 0) + (py >= _y + _size / 2 ? 2 : 0)];
// Distance from a point to this cell (0 inside it): a lower bound for the distance to anything stored below.
private double DistanceTo(double px, double py)
{
double dx = Math.Max(Math.Max(_x - px, 0), px - (_x + _size)), dy = Math.Max(Math.Max(_y - py, 0), py - (_y + _size));
return Math.Sqrt(dx * dx + dy * dy);
}
// The k nearest points, best first. A priority queue holds cells and points keyed by distance, and the first point to
// come off it is the nearest one not yet returned, because every cell still queued is at least as far away.
public List<int> Nearest(double px, double py, int k, out int examined)
{
var queue = new PriorityQueue<(QuadTree Cell, int Id), double>();
queue.Enqueue((this, -1), DistanceTo(px, py));
var result = new List<int>();
examined = 0;
while (result.Count < k && queue.TryDequeue(out var item, out _))
{
if (item.Cell == null) { result.Add(item.Id); continue; }
if (item.Cell._children != null)
foreach (var child in item.Cell._children) queue.Enqueue((child, -1), child.DistanceTo(px, py));
else
foreach (var point in item.Cell._points)
{
examined++;
queue.Enqueue((null, point.Id), Math.Sqrt((point.X - px) * (point.X - px) + (point.Y - py) * (point.Y - py)));
}
}
return result;
}
}
// A fixed grid of square cells, searched in growing rings around the query point until the k-th best is provably final.
public sealed class FixedGrid
{
private readonly double _cell;
private readonly Dictionary<(int, int), List<(int Id, double X, double Y)>> _cells = new();
public FixedGrid(double cell) { _cell = cell; }
public void Insert(int id, double px, double py)
{
var key = ((int)Math.Floor(px / _cell), (int)Math.Floor(py / _cell));
if (!_cells.TryGetValue(key, out var list)) _cells[key] = list = new();
list.Add((id, px, py));
}
public List<int> Nearest(double px, double py, int k, out int examined)
{
int cx = (int)Math.Floor(px / _cell), cy = (int)Math.Floor(py / _cell);
var found = new List<(int Id, double Distance)>();
examined = 0;
for (int ring = 0; ring < 400; ring++)
{
for (int dx = -ring; dx <= ring; dx++)
for (int dy = -ring; dy <= ring; dy++)
{
if (Math.Max(Math.Abs(dx), Math.Abs(dy)) != ring || !_cells.TryGetValue((cx + dx, cy + dy), out var list)) continue;
foreach (var point in list)
{
examined++;
found.Add((point.Id, Math.Sqrt((point.X - px) * (point.X - px) + (point.Y - py) * (point.Y - py))));
}
}
// After `ring` rings, everything within this distance of the query point has been seen.
double safe = Math.Min(Math.Min(px - (cx - ring) * _cell, (cx + ring + 1) * _cell - px), Math.Min(py - (cy - ring) * _cell, (cy + ring + 1) * _cell - py));
found.Sort((a, b) => a.Distance.CompareTo(b.Distance));
if (found.Count >= k && found[k - 1].Distance <= safe) break;
}
return found.Take(k).Select(f => f.Id).ToList();
}
}The experiment compares the two on data with realistic unevenness: 200,000 places in a 100 km square, five dense town centres (each with 20,000 places within about half a kilometre), 6,000 more around each centre within a few kilometres, and the rest spread evenly. Each structure answers the 20 nearest places for four query points, and both are checked against brute force.
C# · 200,000 places in a 100 km square: five dense town centres (spread 0.5 km), 6,000 more…
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
// 200,000 places in a 100 km square: five dense town centres (spread 0.5 km), 6,000 more around each at 5 km, the rest even.
var townRandom = new Random(11);
double Gauss() => Math.Sqrt(-2 * Math.Log(1 - townRandom.NextDouble())) * Math.Cos(2 * Math.PI * townRandom.NextDouble());
var centres = new[] { (X: 20.0, Y: 25.0), (X: 70.0, Y: 30.0), (X: 45.0, Y: 60.0), (X: 80.0, Y: 80.0), (X: 25.0, Y: 80.0) };
var sites = new List<(double X, double Y)>();
foreach (var centre in centres)
{
for (int n = 0; n < 20_000; n++) sites.Add((centre.X + Gauss() * 0.5, centre.Y + Gauss() * 0.5));
for (int n = 0; n < 6_000; n++) sites.Add((centre.X + Gauss() * 5, centre.Y + Gauss() * 5));
}
while (sites.Count < 200_000) sites.Add((townRandom.NextDouble() * 100, townRandom.NextDouble() * 100));
sites = sites.Select(site => (Math.Clamp(site.X, 0, 99.999), Math.Clamp(site.Y, 0, 99.999))).ToList();
var tree = new QuadTree(0, 0, 100, capacity: 64);
var grid = new FixedGrid(1.0);
for (int id = 0; id < sites.Count; id++) { tree.Insert(id, sites[id].X, sites[id].Y); grid.Insert(id, sites[id].X, sites[id].Y); }
Console.WriteLine($"quadtree leaves: {tree.Leaves}, average {sites.Count / (double)tree.Leaves:F1} places each");
var queries = new[] { (Name: "town centre", X: centres[0].X, Y: centres[0].Y), (Name: "town edge", X: centres[0].X + 3, Y: centres[0].Y), (Name: "suburb", X: centres[0].X + 10, Y: centres[0].Y), (Name: "countryside", X: 95.0, Y: 5.0) };
foreach (var query in queries)
{
var viaTree = tree.Nearest(query.X, query.Y, 20, out int treeExamined);
var viaGrid = grid.Nearest(query.X, query.Y, 20, out int gridExamined);
var expected = Enumerable.Range(0, sites.Count)
.OrderBy(id => (sites[id].X - query.X) * (sites[id].X - query.X) + (sites[id].Y - query.Y) * (sites[id].Y - query.Y)).Take(20).ToList();
Console.WriteLine($"{query.Name,-12} quadtree examined {treeExamined,6} grid examined {gridExamined,6}");
Debug.Assert(viaTree.SequenceEqual(expected) && viaGrid.SequenceEqual(expected));
Debug.Assert(treeExamined < 200); // the tree's cost is flat
if (query.Name == "town centre") Debug.Assert(gridExamined > 100 * treeExamined); // the grid's is not
}| Query point | Quadtree examined | Fixed 1 km grid examined |
|---|---|---|
| Town centre | 98 | 19,484 |
| Town edge (3 km out) | 160 | 335 |
| Suburb (10 km out) | 123 | 106 |
| Countryside | 72 | 56 |
The tree produced 7,783 leaves holding 25.7 places each on average, and both structures returned the exact 20 nearest in every case. In the town centre the quadtree examined 98 places where the grid examined 19,484, because one grid cell there holds nearly all of them. The quadtree's cost stayed between 72 and 160 everywhere. The grid wins by a little in sparse areas (56 against 72), because it has no tree to walk. That asymmetry is the argument: the quadtree gives a flat cost, and the grid's cost follows the density.
A quadtree lives in memory and handles inserts easily, but deletes and moves are awkward: a removal may need to merge four leaves, and a moving point crosses leaf boundaries constantly. Static or slowly changing data such as businesses suits it, with a scheduled rebuild from the database and an atomic swap. Fast-moving data does not, which is why the ride-hailing design uses fixed cells. The relatives that live on disk are the R-tree (PostGIS) and the block k-d tree (Lucene and Elasticsearch).
Geohash is the simplest member of a family, and the others fix specific problems of it. S2, from Google, projects the sphere onto the six faces of a cube, divides each face as a quadtree down to 30 levels, and numbers the cells along a Hilbert curve, so a cell is a 64-bit integer, nearby cells have nearby numbers, and all the descendants of a cell fill one contiguous range of ids. A region becomes a handful of ranges at mixed levels, and cells stay roughly equal in size all over the globe. H3, from Uber, tiles the globe with hexagons (and twelve pentagons) at 16 resolutions. A hexagon's six neighbours are all the same distance away, which makes rings, smoothing and aggregation clean, at the price that children only approximately nest inside their parent.
| Index | How it divides the map | Strength | Watch for | Fits |
|---|---|---|---|---|
| Geohash | Rectangles along a Z-order curve | Plain string keys, prefix equals containment, works in any sorted store or hash map | Jumps at the big boundaries, cells narrow toward the poles | Fixed places, moving points, and anything where simple wins |
| Quadtree | Squares that split by count | A flat cost under uneven density, nearest-neighbour search comes naturally | In memory, awkward to shard, and heavy movement keeps restructuring it | Static or slow data with very uneven density |
| S2 | A cube projected onto the sphere, cells on a Hilbert curve | Even cells, better locality than Z-order, covers of any region at mixed levels | A bigger library, ids that are opaque | Global systems, polygons, stores that need range scans |
| H3 | Hexagons at 16 resolutions | Equal-distance neighbours, so rings and smoothing are clean | Approximate nesting, and points and rings more than exact regions | Aggregation, heat maps, surge pricing, moving fleets |
| R-tree (PostGIS, SQLite) | Bounding rectangles in a balanced disk-friendly tree | Real shapes, SQL, transactions, nearest-neighbour ordering | One node by default, sharding is your job | Data already in a relational database, polygons |
| Block k-d tree (Lucene, Elasticsearch) | A k-d tree over points in blocks | Geo filters combined with text and other filters in one engine | A search cluster to run | "Pizza near me": text plus place |
What to say in an interview: default to geohash or S2 cells in a sorted store or a hash map. Bring up a quadtree when the interviewer raises uneven density, H3 when the problem is about regions or a fleet, and the database's own spatial index when the data already lives there and one cluster is enough. The structure matters less than showing that you know the boundary problem, the cell-size trade-off, and why the exact distance check comes last.
The read path carries the traffic. The Search API validates the request (ranges, the radius cap), applies a rate limit, snaps the point to a cell and looks for that cell's candidate list in the cache. On a miss it asks the geo index for the cells of the cover and gets candidate ids with their coordinates and categories, computes exact distances, filters and sorts, takes a page, and only then fetches the details of those twenty places from a cache or the database.
The write path is slow on purpose. Owners write to the Places service, which validates and writes the database, the source of truth. A change stream (change data capture from the database's log, see replication and sharding) feeds the index builder, which produces immutable snapshots and small deltas for the replicas. Nothing in the read path ever waits for a write.
Replicate first. Every replica holds the whole index, about 4 GB for the key fields, and serves searches alone. Add replicas for throughput, spread them over zones and regions for availability, and put them behind a health-checked load balancer. Because a replica loads an immutable snapshot and swaps it in as a whole, readers take no locks and replicas never need to coordinate.
Shard only when you must, and then by area, not by id. The index is small, so the reasons are real but late: the per-place payload used in ranking grows (ratings, price, hours, an embedding: 200M places at 500 B is 100 GB), or data must stay in a region. Sharding by hash(id) sends every search to every shard and makes the slowest one decide the latency (see tail latency). Sharding by area, with coarse cells (4 characters, about 39 km by 20 km) assigned to shards through a small directory, lets a search touch one shard, or two to four at a boundary. The directory also lets you split a dense cell finer or give it its own shard with more replicas, because a downtown cell is hot, not the whole region.
Cache by cell, not by coordinates. Every phone reports a slightly different position, so a cache keyed by exact coordinates almost never hits. Key it by the cell instead, and store the candidates. The simulation sends 200,000 searches to 5,000 popular spots with skewed traffic (spot number n gets a share proportional to 1/n) and about 50 m of GPS error, and measures the hit ratio of an unbounded cache for each key:
C# · 200,000 searches around 5,000 popular spots. Traffic is skewed (spot number n gets a…
using System;
using System.Diagnostics;
using System.Linq;
// 200,000 searches around 5,000 popular spots. Traffic is skewed (spot number n gets a share proportional to 1/n), and every
// phone reports a position that is off by up to about 50 m.
var cacheRandom = new Random(21);
var spots = Enumerable.Range(0, 5_000).Select(_ => (Lat: 37.52 + cacheRandom.NextDouble() * 0.5, Lon: -122.67 + cacheRandom.NextDouble() * 0.5)).ToArray();
var cumulative = new double[spots.Length];
double running = 0;
for (int rank = 0; rank < spots.Length; rank++) cumulative[rank] = running += 1.0 / (rank + 1);
var searches = Enumerable.Range(0, 200_000).Select(_ =>
{
int spot = Array.BinarySearch(cumulative, cacheRandom.NextDouble() * running);
if (spot < 0) spot = ~spot;
return (Lat: spots[spot].Lat + (cacheRandom.NextDouble() - 0.5) * 0.0009, Lon: spots[spot].Lon + (cacheRandom.NextDouble() - 0.5) * 0.0012);
}).ToArray();
// Hit ratio of an unbounded cache: every search after the first for a key is a hit.
double HitRatio(Func<(double Lat, double Lon), string> keyOf) => 1.0 - searches.Select(keyOf).Distinct().Count() / (double)searches.Length;
double byCoordinates = HitRatio(search => $"{search.Lat:F5},{search.Lon:F5}");
double byCell8 = HitRatio(search => Geo.Encode(search.Lat, search.Lon, 8));
double byCell7 = HitRatio(search => Geo.Encode(search.Lat, search.Lon, 7));
double byCell6 = HitRatio(search => Geo.Encode(search.Lat, search.Lon, 6));
Console.WriteLine($"exact coordinates {byCoordinates:P1}, cell 8 {byCell8:P1}, cell 7 {byCell7:P1}, cell 6 {byCell6:P1}");
Debug.Assert(byCoordinates < 0.2 && byCell8 > byCoordinates && byCell7 > byCell8 && byCell6 > byCell7 && byCell7 > 0.9);Keyed by coordinates (to about a meter) the hit ratio is 12.3%. Keyed by an 8-character cell (38 m by 19 m) it is 76.1%, by a 7-character cell (153 m) 94.4%, and by a 6-character cell 98.4%. Two cautions keep this honest. The cached value must be the candidates for the cell expanded by the radius, meaning every place within the radius of any point of the cell, and the request must still apply the exact distance filter and the sort for the user's real position, otherwise a user at one corner gets the results that suit the centre. And the key needs a version (or the cell must be purged when a place in it changes), so a closed place leaves the cache within the freshness target. A side benefit: cell-level keys and logs reveal far less about where a person actually is.
Retrieval and ranking are two stages. Retrieval is about recall: get every plausible place near the user, a few hundred at most, and cap the candidates (the nearest 300, say) so one search in a dense city cannot return twenty-five thousand cafes. Ranking is about precision: score the candidates by distance (a decay, not a cliff at the radius), rating weighted by the number of reviews, whether the place is open now, price, and personal signals, then return the top page. Radius is a filter. It is not the ranking, and treating it as one makes the nearest mediocre place beat the better one a few streets away.
Filters change the plan. A category filter is selective in some places and not in others, so evaluate it on the candidates after the geographic scan, as the index above does. A text query ("sushi", a brand name) is often more selective than the geography, so the planner may start from an inverted index and apply a geographic filter afterwards, which is what a search engine with a geo field does (see search and inverted indexes). "Open now" needs each place's hours and time zone, evaluated on the candidates at query time. If filters multiply, the bespoke index stops being worth its upkeep and a search engine becomes the right tool.
The index is derived data, so the rule is simple: the database is the truth, and the index is rebuilt from it.
- Snapshots plus a delta. The builder produces an immutable sorted index every few hours and uploads it to object storage, and replicas load it and swap it in whole. Between snapshots a small mutable delta holds the last minutes of adds, edits and closures, with tombstones for removals, like the memtable of an LSM tree (see storage engines and indexes). A search reads the delta and the snapshot and lets the newer version win.
- Versions everywhere. Each place carries a version, each snapshot an epoch, and each cached list the version of what it was built from, so any layer can tell that it is stale.
- Closures matter more than openings. A place that is missing for ten minutes is a small flaw, and one that is closed but still shown sends someone to a locked door. Apply tombstones first and quickly.
- Index age is an SLI. Measure the age of the newest change that each replica has applied and alert when it passes the freshness target (see SLOs and error budgets). If the stream breaks, replicas keep serving the last good snapshot, which is stale but correct enough, instead of failing.
- Verify recall in production. Run a sample of live searches against a brute-force or second-implementation check offline and track recall (the fraction of true results returned). A cover bug is silent: the service answers every request and the results are quietly incomplete.
| Case | What goes wrong | Handle it |
|---|---|---|
| Near the antimeridian or a pole | A cover that does not wrap misses half of the circle, and cells at high latitudes are narrow | Wrap longitude, clamp latitude, and test the cover at 179.9999 degrees and near 90 |
| A very large radius | The cover explodes (5,625 cells at precision 8 for 1 km), or one query scans a country | Cap the radius, choose the precision from it, require a category for large areas, cap candidates |
| A very dense cell | One cell holds tens of thousands of places and every search scans them | Split finer (a longer prefix or quadtree leaves), cap candidates, rank before fetching details |
| Nothing nearby | An empty answer in a rural area, when the user wants the nearest | Support k nearest: widen the radius step by step up to a limit, or search best-first |
| GPS error | Phones are off by tens of meters, more indoors, and the app sorts on false precision | Treat distance as approximate, round it for display, send and use the accuracy radius |
| Distance computed in degrees | Results are stretched east to west: at 60 degrees north a degree of longitude is half as long as a degree of latitude | Use the haversine formula, or an equirectangular approximation at city scale |
| A stale cache or index | A closed place keeps appearing | A short TTL, a version in the cache key, tombstones in the delta, an alert on index age |
| A hot shard | A city's dinner rush overloads one shard | Split the cell finer, add replicas for that shard, serve stale cache entries under load |
| A large place (park, airport, mall) | One point misrepresents it, so a search near the entrance can miss it | Index entrances or a polygon (an S2 cover, an R-tree) and decide what "distance to a place" means |
| Location privacy | Raw coordinates in logs reveal homes and routines | Log the cell id at precision 6, keep it briefly, restrict access |
| Scraping | A crawler walks a grid of queries to copy the whole data set | Per-client and per-region rate limits (see rate limiting), caps on paging, detection of grid-shaped query patterns |
Interviewer follow-upL5Why not just index latitude and longitude separately?How to answer
A B-tree orders entries along one dimension. A range on latitude returns a band that circles the planet and a range on longitude one that runs from pole to pole, and the engine must filter the other column row by row or intersect two large scans, so the cost follows the size of the bands and not of the answer. In the simulation a 1 km search read about 3,600 rows to find 130. A space-filling curve gives one key where close places are close in order, so a region is a few ranges.
Interviewer follow-upL5What is the boundary problem, and how do you avoid it?How to answer
Close places can have hashes with no shared prefix (two points 14 m apart across the prime meridian share nothing), and a person near a cell edge has neighbours in the next cell. Searching only the user's own cell found 18.6% of the places within 1 km at precision 6. Compute the cover, every cell the circle touches, search all of them, and filter by exact distance. The 3 x 3 block shortcut works only while a cell is bigger than the radius in both directions.
Interviewer follow-upL5How do you choose the geohash precision?How to answer
About the size of the radius, so that the cover is a handful of cells and the candidates are a small multiple of the answer. For a 1 km radius that is 6 characters: 11.5 cells and 280 candidates for 130 results. Coarser cells read too many candidates (1,735 at precision 5), and finer ones need too many lookups (5,625 cells at precision 8). Store the finest hash once and derive the coarser ones as prefixes, so one index serves every radius.
Interviewer follow-upL6Geohash, quadtree, S2 or H3?How to answer
Say what each is good at. Geohash is simple and works in any sorted store. A quadtree adapts to uneven density and gives nearest-neighbour search naturally, but lives in memory and suffers when points move. S2 has even cells, a Hilbert curve with better locality, and region covers at mixed levels. H3 has equal-distance neighbours, which suits aggregation and fleets. Then choose for the problem: fixed places with uneven density (a quadtree or S2), moving points (fixed cells), aggregations (H3), data already in PostGIS or Elasticsearch (use their index).
Interviewer follow-upL6How would you shard the index, and why not by place id?How to answer
First point out that 4 GB fits on one machine, so replicate for throughput and availability. If you must shard (a payload that grew, data residency), shard by area: coarse cells assigned to shards through a directory, so a search touches one shard, or a few at a boundary. Hashing by id forces every search to visit every shard and wait for the slowest. The directory lets a dense cell be split or given extra replicas.
Interviewer follow-upL6How do you add "open now" and a text query?How to answer
Keep retrieval and ranking separate. Hours and the time zone are evaluated on the candidates at query time. A text query is often more selective than the geography, so a search engine with a geo field (an inverted index plus a geographic filter) can start from the text, or from the geography, whichever is smaller. If filters keep multiplying, move to the search engine instead of growing a custom index.
Interviewer follow-upL6How do you return the 20 nearest places when nothing is within the radius?How to answer
Do not use a radius at all. Search best-first over a tree, where the priority queue of cells and points ordered by distance yields the next nearest place, or widen the radius step by step (double it and use a coarser precision) and stop once 20 are found, which costs at most about twice the final search. A fixed grid with ring expansion works but its cost follows density: in the simulation it examined 19,484 places in a town centre where the quadtree examined 98.
Interviewer follow-upL6Every user is at a slightly different position. How do you cache?How to answer
Key by cell, not by coordinates. The hit ratio was 12.3% by coordinates and 94.4% by a 7-character cell in the simulation. Cache the candidates for the cell expanded by the radius, then apply the exact distance filter and the sort for the user's real position on every request. Version the key or purge by cell when a place changes, and keep a short TTL as the backstop.
Interviewer follow-upL7How do you know the index is correct in production?How to answer
Treat recall as a metric. Sample live searches and compare them with a brute-force or independent implementation, offline and continuously, because a wrong cover returns plausible, incomplete results and no error. Alert on the age of the newest applied change per replica, compare the content of replicas by checksum per coarse cell, and test the cover at the awkward places: the antimeridian, the poles, the equator and the prime meridian.
Interviewer follow-upL7Now the points move, like drivers. What changes?How to answer
The write rate becomes the problem (every driver reports every few seconds), so the immutable snapshot is replaced by a mutable in-memory map from cell to the points inside it, updated in place, and a quadtree is a poor fit because its structure would keep changing. Most updates do not change a point's cell, so the index is touched less often than the stream, and the data is ephemeral, so it can be rebuilt from the stream instead of being persisted. The ride-hailing lesson builds this.
- Clarify: fixed or moving points, radius or k nearest, the range of radii, filters, freshness, scale, privacy.
- Estimate: the index is a few gigabytes and fits in memory, the traffic is thousands of reads a second and almost no writes.
- Contract and model: one nearby call with a cursor, a places table with a derived geohash column.
- Explain why two indexes fail, then give the key: geohash (or S2) so a region is a few ranges.
- Draw the search: the cover, the prefix scans, the exact distance filter, the sort, the page. Name the boundary problem before the interviewer does.
- Choose the cell size from the radius, and show the trade-off between cells and candidates.
- Handle density with a quadtree or finer cells, and name S2 and H3 and what each fixes.
- Serve it: replicas first, shards by area if needed, a cache keyed by cell, snapshots plus a delta from a change stream.
- Close with failure modes: the antimeridian, dense cells, nothing nearby, stale closures, privacy, scraping.
A proximity service turns two dimensions into one sortable key so that a region becomes a few key ranges. A geohash does that with a base-32 string whose prefix means containment, and S2 and H3 are the same idea with better cells. The search computes the cover, every cell the circle touches, scans them all, and filters by exact distance, because the own cell alone found 18.6% of the results and the 3 x 3 block loses results as soon as a cell is smaller than the radius. A cell about the size of the radius keeps the cells and the candidates both small. A quadtree gives a flat cost under uneven density (98 places examined in a town centre against 19,484 for a grid) and suits static data, while moving points call for fixed cells. The index is a few gigabytes, so serve it from memory on replicas, shard by area only when forced, cache candidates by cell (94.4% hit ratio against 12.3% by coordinates), and keep it fresh with a change stream, immutable snapshots and a small delta.
Try answering out loud before you reveal each answer.
QuestionA user stands 5 m from the edge of their geohash cell. Why does searching only that cell fail, and what do you search instead?Reveal answer
The search circle crosses the edge, so everything on the other side is missed. In the experiment the own cell alone found 18.6% of the places within 1 km at precision 6, and 80.7% even at precision 5. Search the cover, every cell the circle touches (11.5 cells on average at precision 6), and then filter by exact distance. The 3 x 3 block is right only while a cell is at least as large as the radius: it found 100% at precision 5 but only 92.8% at precision 6.
QuestionWhy choose a cell about the size of the search radius?Reveal answer
Cells that are too coarse put too many places in each cell (1,735 candidates for 130 results at precision 5), and cells that are too fine make the cover explode (5,625 lookups at precision 8, for 134 candidates). The work is roughly the cells plus the candidates, and it is lowest near precision 6 for a 1 km radius. Because a prefix is containment, store the finest hash once and derive coarser cells for larger radii.
QuestionA downtown cell holds 19,000 places and the countryside holds a few. Why does a fixed grid struggle, and what does a quadtree change?Reveal answer
A fixed cell size cannot suit both. A size that suits the countryside makes the downtown cell enormous, and a nearest-neighbour search there examined 19,484 places in the experiment. A quadtree splits a square whenever it holds more than its capacity, so every leaf has about the same number of points, and a best-first search examined 98 places downtown and 72 in the countryside. The cost of the tree is that it lives in memory and is awkward when points move.
QuestionWhy is a cache keyed by exact coordinates nearly useless, and what is the fix?Reveal answer
Every phone reports a slightly different position, so keys almost never repeat: the hit ratio was 12.3%. Key by the cell instead (94.4% at 7 characters, 98.4% at 6) and cache the candidates for the cell expanded by the radius. Each request must still apply the exact distance filter and the sort for the real position, and the key needs a version or a purge so that a closed place does not linger.
QuestionWhy replicate this index instead of sharding it, and how would you shard it if you had to?Reveal answer
The key fields for 200 million places are about 4 GB, which fits in the memory of one machine, so the problem is read throughput and availability, and replicas solve both without any coordination. If the payload grows or data must stay in a region, shard by area (coarse cells assigned through a directory) so that a search touches one shard, and not by id, which sends every search to every shard.
- Wikipedia, Geohash (opens in a new tab): the encoding, the alphabet, the cell-size table and the edge cases (the example
u4pruydqqvjcomes from here). - Google, S2 Geometry (opens in a new tab): cells, the Hilbert curve and region covering, with the cell hierarchy (opens in a new tab) page.
- Uber, H3: Uber's Hexagonal Hierarchical Spatial Index (opens in a new tab) (2018) and the H3 documentation (opens in a new tab) for resolutions, cell areas and neighbours.
- Gisli Hjaltason and Hanan Samet, Distance Browsing in Spatial Databases, ACM Transactions on Database Systems, 1999: the best-first nearest-neighbour search used above.
- Hanan Samet, Foundations of Multidimensional and Metric Data Structures (2006): quadtrees, k-d trees and R-trees in depth.
- Antonin Guttman, R-Trees: A Dynamic Index Structure for Spatial Searching, SIGMOD 1984.
- PostGIS, spatial indexing (opens in a new tab) and nearest-neighbour ordering (opens in a new tab).
- Redis, Geospatial data (opens in a new tab) and GEOSEARCH (opens in a new tab).
- Elastic, the geo_point field type (opens in a new tab) and the geo-distance query (opens in a new tab).
- Chris Veness, Calculate distance, bearing and more between latitude and longitude points (opens in a new tab): the haversine formula and its limits.
- Alex Xu and Sahn Lam, System Design Interview, Volume 2 (ByteByteGo, 2022): the proximity service chapter, a common interview version of this problem.