System design interview: design a proximity service
A proximity service answers "what is near me?": given a latitude, a longitude and a radius, it returns the closest businesses or places, ranked. The design turns on one choice, how to index two-dimensional positions so a search touches a few small areas instead of every row, and the usual answers are geohash prefixes, a quadtree or a cell library such as S2 or H3.
By Evin JohnPublished 9 min read
1. Clarify the requirements
The prompt often arrives as "design Yelp" or "design a nearby restaurants feature". Narrow it to the search itself, then confirm who writes data and how fresh it must be.
- Functional: search by location and radius (say 0.5, 1, 2, 5 or 20 km) with an optional category; return up to a page of results sorted by distance or a blend of distance and rating; view one place's details; owners add, edit or remove a place.
- Non-functional: search answers in well under 200 ms at the server, stays available during a regional failure, and handles lunchtime and evening peaks. A new or edited place may take minutes, even until the next day, to appear in search.
- Out of scope unless asked: reviews and photos, the ranking model itself, turn-by-turn directions (see design Google Maps), and people who move (see nearby friends).
2. Estimate the scale
| Quantity | Assumption | Result |
|---|---|---|
| Searches | 50 million daily users, 6 searches each | 300 million a day, about 3,500 a second on average; plan for 4x at peak, about 14,000 |
| Places | 100 million businesses and points of interest | the whole catalogue |
| Detail storage | about 2 KB per place (name, address, hours, category, rating) | about 200 GB: one database with replicas, or a few shards |
| Location index | about 64 bytes per entry (ID, geohash, latitude, longitude, overhead) | about 6.4 GB: fits in memory on a single ordinary server |
| Edits | 500,000 changes a day | about 6 writes a second |
The read-to-write ratio is enormous and the index fits in RAM. That means you do not need to shard the index for size; you replicate it for throughput and place copies near users.
3. Define the API
GET /v1/search/nearby?lat=51.5007&lng=-0.1246&radius_m=1000&category=cafe&limit=20&cursor=...
-> 200 { results: [ { id, name, lat, lng, distance_m, rating } ], next_cursor }
GET /v1/places/{id} -> full record
POST /v1/places -> create (owner, authenticated)
PUT /v1/places/{id} DELETE /v1/places/{id}Cap the radius on the server. A client that asks for 500 km around a city centre should get the 20 km result, not a scan of a country.
4. Sketch the data model
| Table | Key fields | Access pattern |
|---|---|---|
| places | place_id (primary key), name, category, lat, lng, address, hours, rating, updated_at | point reads by ID, rare writes; cached heavily |
| geo_index | geohash (prefix-searchable), place_id, lat, lng | range scans on a prefix, rebuilt or patched from places |
A relational database suits the places table: the rows are small, the schema is stable and the write rate is tiny. The index can be a table with a B-tree on the geohash column (a prefix search becomes a range scan), a Redis structure, or an in-memory structure inside each search server.
5. Index the locations
Two plain columns, latitude and longitude, each with its own index, do not solve the problem: the database can narrow by one coordinate, then it must intersect a band of the whole planet with another band. You need an index where nearby points sit close together on disk or in memory.
| Approach | How it works | Good at | Watch out for |
|---|---|---|---|
| Even grid | Split the map into fixed squares; store each place under its square | Trivial to build | A downtown square holds thousands of places, a desert square none |
| Geohash | Interleave longitude and latitude bits, write them in base32; longer strings mean smaller cells | Prefix search in any ordered store, easy to shard and cache by prefix | Neighbours across a cell edge can share no prefix at all |
| Quadtree | Split a square into four children whenever it holds more than K places | Cells follow density, so each leaf returns a similar number of results | Built in memory; updates need care; rebuilding takes time |
| S2 or H3 cells | Libraries that map the sphere to hierarchical cells (squares on a cube for S2, hexagons for H3) | Accurate coverage of a circle with a handful of cells | An extra dependency the interviewer may ask you to explain |
Cell sizes for geohash follow from the bit count. Widths shrink toward the poles (by the cosine of the latitude), so the radius a nine-cell search can cover depends on where the user is.
| Length | Cell at the equator (width x height) | Largest radius covered: equator / around 50 degrees latitude |
|---|---|---|
| 4 | 39 km x 20 km | about 19 km / 19 km |
| 5 | 4.9 km x 4.9 km | about 4.8 km / 3 km |
| 6 | 1.2 km x 0.6 km | about 600 m / 600 m |
| 7 | 153 m x 153 m | about 150 m / 95 m |
The edge problem. Two cafes 14 metres apart on either side of the prime meridian get geohashes that start with different letters. Pick a precision whose cell's shorter side, measured at the user's latitude, is at least the radius; then search the point's cell plus its eight neighbours, and filter the candidates by true distance. A 1 km search in London therefore needs length 5, not 6.
import math
BASE32 = "0123456789bcdefghjkmnpqrstuvwxyz"
def encode(lat, lng, length=6):
lat_lo, lat_hi, lng_lo, lng_hi = -90.0, 90.0, -180.0, 180.0
bits, even, out, ch = 0, True, [], 0
while len(out) < length:
if even: # even bits split longitude
mid = (lng_lo + lng_hi) / 2
ch = ch * 2 + (lng >= mid)
lng_lo, lng_hi = (mid, lng_hi) if lng >= mid else (lng_lo, mid)
else: # odd bits split latitude
mid = (lat_lo + lat_hi) / 2
ch = ch * 2 + (lat >= mid)
lat_lo, lat_hi = (mid, lat_hi) if lat >= mid else (lat_lo, mid)
even, bits = not even, bits + 1
if bits == 5:
out.append(BASE32[ch]); bits, ch = 0, 0
return "".join(out)
def cell_size(length): # degrees of latitude, longitude
return 180 / 2 ** (5 * length // 2), 360 / 2 ** ((5 * length + 1) // 2)
def cells_to_search(lat, lng, length=6):
dlat, dlng = cell_size(length)
return {encode(lat + i * dlat, lng + j * dlng, length)
for i in (-1, 0, 1) for j in (-1, 0, 1)}
def km_between(lat1, lng1, lat2, lng2): # haversine
p1, p2 = math.radians(lat1), math.radians(lat2)
dp, dl = p2 - p1, math.radians(lng2 - lng1)
a = math.sin(dp / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(dl / 2) ** 2
return 2 * 6371 * math.asin(math.sqrt(a))
encode(51.4779, -0.0001) # 'gcpuzg'
encode(51.4779, 0.0001) # 'u10hb5': 14 m away, no shared prefixQuadtree in numbers. With a leaf limit of 100 places, 100 million places need at least a million leaves. Storing eight-byte IDs in the leaves is about 0.8 GB, plus a modest amount for internal nodes, so each search server can hold the whole tree. A search walks down to the leaf holding the point, then adds neighbouring leaves until it has enough candidates.
A defensible pick: geohash in a sorted store when you want simple operations and easy sharding by prefix; a quadtree when density varies wildly and you want each lookup to return a similar number of candidates. Either way, the final distance check is a plain haversine filter on a few hundred candidates.
6. The architecture
- Clients
- Mobile app
- Web
- Edge
- CDN for static map assets
- Load balancer
- Read path
- Location search service (index in memory)
- Detail cache
- Write path
- Places service
- Primary database plus read replicas
- Index pipeline
- Change stream or batch job
- Index snapshot store
- Snap the queryChoose a precision from the radius, compute the nine cells, and read their entries from the in-memory index.
- Filter and rankDrop candidates outside the true radius, score the rest by distance and rating, keep the top page.
- Fill detailsBatch-read names and ratings for those IDs from the cache; on a miss, read a replica and fill the cache.
7. Deep dives
- Too few results. In a village a 500 m search may return nothing. Widen in steps: drop one geohash character (a cell roughly 32 times larger) or climb one quadtree level, until the page is full or the radius cap is hit.
- Freshness. An owner edit writes the places table at once. The index catches up from a change stream within minutes, or in a nightly rebuild. Showing the detail page from the database means the address is right even when the pin is briefly stale.
- Scaling reads. Add search servers, each with a full index copy. Shard only if the index outgrows memory, and then by geohash prefix, accepting that a search near a shard edge must ask two shards.
- Hot areas. A stadium or a city centre at lunch concentrates load on a few cells. Because each server holds every cell, hot spots spread across the fleet; cache popular query results by rounded position and radius for a minute.
- Multiple regions. Serve each continent from nearby servers with their own index copy. Edits go to one primary region and replicate; a few seconds of lag is invisible in search. More on that trade in consistency and CAP.
8. What breaks, and what you do about it
| Failure | Effect | Mitigation |
|---|---|---|
| Bad index snapshot shipped | Search returns places in the wrong city | Validate counts and sample queries before switching; keep the previous snapshot for instant rollback |
| Search server restarts | It must load several GB before serving | Load from a local snapshot file, join the load balancer only when warm |
| Primary database down | Owners cannot edit | Search keeps working from replicas and the in-memory index; queue edits or show a retry message |
| Detail cache cold after deploy | Replica load spikes | Warm the cache with the most viewed places; limit concurrent misses per key |
| Query at the poles or the date line | Neighbour cells wrap or shrink | Normalise longitude, clamp latitude, cover such regions with test cases |
9. Trade-offs to discuss
- Geohash or quadtree. Geohash works in any ordered key-value store and shards by prefix; a quadtree balances result counts but is a custom in-memory structure you must build, ship and patch.
- Batch or streaming index updates. A nightly rebuild is simple to verify and roll back; streaming keeps pins fresh at the cost of more moving parts.
- Precompute or compute ranking. Ranking by a stored score is fast; personalised ranking adds a call per search. Say which one you mean before the interviewer asks.
10. How to talk through it in the interview
Fictional example
- Interviewer
- A user stands right on a geohash cell boundary. Do they miss the restaurant across the street?
- Candidate
- Not with my lookup. I pick a precision whose cell, measured along its shorter side at that latitude, is at least the search radius, then I read the user's cell and the eight around it. That covers every point within the radius, and a haversine check removes the ones that are outside it.
- Interviewer
- Why not just use a radius query in the database?
- Candidate
- A geospatial index in the database would work at small scale. At 14,000 searches a second I would rather serve from memory on stateless servers that I can add freely, and keep the database for edits.
- Spend your estimate on one conclusion: the index fits in memory, so replicate it.
- Explain the edge problem and the nine-cell fix without being prompted.
- Keep IDs from the index separate from details from the cache; it shows you thought about both paths.
Practicing this design with Natively
Geospatial prompts reward candidates who can draw a grid and explain it at the same time, which is hard to rehearse silently. Run a mock with a friend over a call and let Natively transcribe both voices; ask it for a diagram of the search path when you get stuck and compare its layout with yours, or capture a screenshot of your whiteboard and ask what is missing. Reading the transcript afterwards shows whether you ever stated the radius cap or the freshness answer.
Questions people ask
How do you find nearby places efficiently?
Index positions so that nearby points sit together, for example by geohash prefix or in a quadtree. A search reads the cell that holds the user plus the cells around it, then filters the few hundred candidates by true distance and ranks them.
What is the geohash boundary problem?
Two points a few metres apart can fall into cells whose geohashes share no prefix, for example on either side of the prime meridian. Searching the user's cell and its eight neighbours, with a cell at least as large as the radius, covers every point in range.
Geohash or quadtree in a system design interview?
Geohash is simpler to store in any sorted key-value store and to shard by prefix. A quadtree adapts cell size to density, so each lookup returns a similar number of results, but it lives in memory and needs rebuilding or careful updates. Either is a sound answer if you explain the trade-off.
Does the location index need to be sharded?
Usually not for size. A hundred million places at about 64 bytes each is a few gigabytes, which fits in memory, so you replicate the index to many stateless search servers for throughput and shard only if it outgrows a machine.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
