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 Published 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

Back-of-envelope numbers for a large local search product (assumed figures)
QuantityAssumptionResult
Searches50 million daily users, 6 searches each300 million a day, about 3,500 a second on average; plan for 4x at peak, about 14,000
Places100 million businesses and points of interestthe whole catalogue
Detail storageabout 2 KB per place (name, address, hours, category, rating)about 200 GB: one database with replicas, or a few shards
Location indexabout 64 bytes per entry (ID, geohash, latitude, longitude, overhead)about 6.4 GB: fits in memory on a single ordinary server
Edits500,000 changes a dayabout 6 writes a second
Back-of-envelope numbers for a large local search product (assumed figures). Scroll sideways on a small screen.

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}
Search returns IDs, positions and a few display fields; details come from a second call.

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

Two stores with very different access patterns
TableKey fieldsAccess pattern
placesplace_id (primary key), name, category, lat, lng, address, hours, rating, updated_atpoint reads by ID, rare writes; cached heavily
geo_indexgeohash (prefix-searchable), place_id, lat, lngrange scans on a prefix, rebuilt or patched from places
Two stores with very different access patterns. Scroll sideways on a small screen.

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.

Ways to index positions
ApproachHow it worksGood atWatch out for
Even gridSplit the map into fixed squares; store each place under its squareTrivial to buildA downtown square holds thousands of places, a desert square none
GeohashInterleave longitude and latitude bits, write them in base32; longer strings mean smaller cellsPrefix search in any ordered store, easy to shard and cache by prefixNeighbours across a cell edge can share no prefix at all
QuadtreeSplit a square into four children whenever it holds more than K placesCells follow density, so each leaf returns a similar number of resultsBuilt in memory; updates need care; rebuilding takes time
S2 or H3 cellsLibraries 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 cellsAn extra dependency the interviewer may ask you to explain
Ways to index positions. Scroll sideways on a small screen.

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.

Geohash length, cell size and the radius nine cells always cover
LengthCell at the equator (width x height)Largest radius covered: equator / around 50 degrees latitude
439 km x 20 kmabout 19 km / 19 km
54.9 km x 4.9 kmabout 4.8 km / 3 km
61.2 km x 0.6 kmabout 600 m / 600 m
7153 m x 153 mabout 150 m / 95 m
Geohash length, cell size and the radius nine cells always cover. Scroll sideways on a small screen.

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 prefix
Geohash encoding, the nine cells to scan, and the distance filter (run with python3).

Quadtree 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

  1. Clients
    • Mobile app
    • Web
  2. Edge
    • CDN for static map assets
    • Load balancer
  3. Read path
    • Location search service (index in memory)
    • Detail cache
  4. Write path
    • Places service
    • Primary database plus read replicas
  5. Index pipeline
    • Change stream or batch job
    • Index snapshot store
Search and edit paths in a proximity service. Mobile and web clients call a load balancer. Search requests go to a stateless location search service whose servers each hold a copy of the location index in memory; the service returns place IDs and distances, then fills display fields from a cache in front of the places database. Owner edits go to a separate places service that writes to the primary database. A change stream or nightly job rebuilds the index and ships new snapshots to the search servers.
  1. Snap the queryChoose a precision from the radius, compute the nine cells, and read their entries from the in-memory index.
  2. Filter and rankDrop candidates outside the true radius, score the rest by distance and rating, keep the top page.
  3. 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 modes to raise before the interviewer does
FailureEffectMitigation
Bad index snapshot shippedSearch returns places in the wrong cityValidate counts and sample queries before switching; keep the previous snapshot for instant rollback
Search server restartsIt must load several GB before servingLoad from a local snapshot file, join the load balancer only when warm
Primary database downOwners cannot editSearch keeps working from replicas and the in-memory index; queue edits or show a retry message
Detail cache cold after deployReplica load spikesWarm the cache with the most viewed places; limit concurrent misses per key
Query at the poles or the date lineNeighbour cells wrap or shrinkNormalise longitude, clamp latitude, cover such regions with test cases
Failure modes to raise before the interviewer does. Scroll sideways on a small screen.

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

The geohash edge follow-up
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.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP