Design: proximity service (Yelp)
Index mostly static businesses by geohash cell; a search reads the user's cell plus its 8 neighbors from cache or read replicas, filters by exact distance, and widens the cell when results are few.
Fundamentals you'll use
How it works
- Reads dominate: assume ~5.8k searches/s over 200M businesses that rarely change.
- A geohash column turns nearby search into an indexed prefix lookup that any database can serve.
- Pick the precision whose cell is at least as large as the radius, then read 9 cells.
- Cache candidates per cell, not per user position: every user inside a cell shares the entry.
- Too few results? Drop one geohash character, a 32× larger cell, and search again.
Check yourself
Answer to mark it learned; your answers aren't scored.
Your nearby search caches results under nearby:{lat}:{lng}:{radius} using the phone's full GPS precision. The cache is large, yet its hit rate is 2% and the replicas are saturated. What do you change?
Go deeper
Full explanation
Requirements
Functional: given a position and a radius (0.5 to 10 km, say), return nearby businesses, optionally filtered by category or open now; owners add and edit businesses; users open a business page. Non-functional: search answers in ~100 ms (assumed target), high availability, and results may lag an edit by hours.
Scale (assumed): 100M daily users × 5 searches ≈ ~5.8k searches/s on average, over 200M businesses that rarely change. Reads outnumber writes by orders of magnitude.
Questions I'd ask:
- A few fixed radius options, or any radius?
- How soon must a new or edited business appear?
- Distance only, or text search and ranking too?
API and data model
GET /search/nearby?lat&lng&radius&category returns a page of {business_id, name, distance}; GET, POST and PUT /businesses/{id} serve pages and owners. Two tables: business(id, name, lat, lng, category, hours…), the source of truth, and geo_index(geohash, business_id, lat, lng), one row per business with an index on geohash.
Architecture
Two stateless services. The business service writes to the primary database. The location service only reads: it serves the geo index from a cache keyed by cell, backed by read replicas. A search picks the geohash precision that fits the radius, reads the user's cell and its 8 neighbors, filters the candidates by exact distance, ranks and paginates. Cells and their trade-offs are taught in Geospatial indexing (geohash, S2, H3).
The hard parts
- Choosing the index. A geohash is a plain indexed string: any database serves it and any cache can key on it. A quadtree adapts to density but lives in each server's memory. S2 covers arbitrary shapes with cells of mixed sizes. For static points and a few radii, I pick geohash.
- Too few results. In sparse areas the 9 cells hold almost nothing: drop one geohash character, a 32× larger cell, and search again up to a maximum radius.
Unlike Design: ride hailing (Uber, Lyft), where drivers move every few seconds and the index is write-heavy and in memory, this data is nearly static, so replicas and caches do the work.
Code Nearby search: precision, 9 cells, exact filter, expansion
import math
import pygeohash as pgh
# Geohash cell (width, height) in km at the equator, by precision
CELL_KM = {4: (39.1, 19.5), 5: (4.9, 4.9), 6: (1.2, 0.61)}
def precision_for(radius_km: float, lat: float) -> int:
# Finest cell at least as large as the radius: then 3x3 cells cover the circle
shrink = math.cos(math.radians(lat)) # cells get narrower away from the equator
fits = [p for p, (w, h) in CELL_KM.items() if min(w * shrink, h) >= radius_km]
return max(fits, default=4)
def block_3x3(cell: str) -> list[str]:
rows = (pgh.get_adjacent(cell, "top"), cell, pgh.get_adjacent(cell, "bottom"))
return [*rows, *(pgh.get_adjacent(c, side) for c in rows for side in ("left", "right"))]
def cell_members(cell: str) -> list[tuple[str, float, float]]:
if (hit := cache.get(f"cell:{cell}")) is not None:
return hit # shared by every user inside this cell
rows = replica.query("SELECT business_id, lat, lng FROM geo_index "
"WHERE geohash LIKE %s", cell + "%") # prefix = any coarser cell
cache.set(f"cell:{cell}", rows, ttl=jittered(86_400)) # static data: long TTL
return rows
def nearby(lat: float, lng: float, radius_km: float, want: int = 20) -> list[tuple[float, str]]:
p = precision_for(radius_km, lat)
while True:
cells = block_3x3(pgh.encode(lat, lng, precision=p))
found = sorted((d, biz) for c in cells for biz, blat, blng in cell_members(c)
if (d := haversine_km(lat, lng, blat, blng)) <= radius_km)
if len(found) >= want or p == 4: # cells are coarse; the distance filter is exact
return found[:want]
p, radius_km = p - 1, radius_km * 4 # sparse area: 32x larger cell, wider radiusReal example
A user in downtown São Paulo searches coffee within 500 m. Precision 6 gives cells of ~1.2 km × 0.6 km; the service reads the user's cell and its 8 neighbors, all cache hits, and gets ~700 candidates with coordinates. The exact distance filter keeps 85, the category filter 23, and the first 20 load their details from the business cache.
The same search in a small town finds 2 results, so the service retries at precision 5 (~4.9 km cells) with a wider radius, finds 14 and returns them sorted by distance.
Trade-offs +3 · −3
+ You gain
- A search is 9 key lookups plus an in-memory filter: easy to cache and to scale with replicas.
- Stateless services over static data: any replica or cache node can answer any query.
- Geohash needs no special database: an indexed string column is enough.
− You pay
- Fixed cells ignore density: downtown cells return thousands of candidates, rural ones almost none.
- Edits show up late unless every write also invalidates the cell keys it affects.
- Rich filters and relevance ranking outgrow the cell lookup and need a search engine.
Use it when
Read-heavy search over points that rarely move: restaurants, stores, ATMs, charging stations, real-estate listings.
Avoid it when
Moving objects that need freshness within seconds (Design: ride hailing (Uber, Lyft)), or polygon queries such as delivery zones, which need S2 coverings or PostGIS.
Numbers to know 5
- Load (assumed): 100M daily users × 5 searches ÷ 86,400 s ≈ ~5.8k searches/s on average.
- Geohash cells at the equator: 4 characters ≈ 39.1 × 19.5 km, 5 ≈ 4.9 × 4.9 km, 6 ≈ 1.2 km × 609 m.
- Each geohash character adds 5 bits: one character less is a 32× larger cell.
- Geo index (assumed): 200M entries × ~30 B ≈ ~6 GB, small enough to keep entirely in memory.
- S2 average cell area: level 12 ≈ 5.07 km², level 13 ≈ 1.27 km², level 14 ≈ 0.32 km².
Common pitfalls 4
- Caching by the user's exact coordinates: every request is a new key and the hit rate is ~0.
- Invalidating only the new cell when a business moves: the old cell keeps listing it until the TTL expires.
- Skipping the exact distance filter: the corners of the 3×3 block lie far outside the radius.
- One precision for every radius: a 5 km search over 6-character cells reads more than 100 cells.
Interview questions 3
Answer out loud first, then reveal.
Geohash, quadtree or S2: which do you pick here?Show answer
Geohash, because the data is static points and the radii are few. It is a plain indexed column, so the database, the replicas and the cache all work unchanged, and a prefix query gives me coarser cells for free. A quadtree adapts to density but lives in each server's memory, which complicates deploys and edits. I'd reach for S2 if I needed polygons, like delivery zones. If density skew hurt, I'd first cap candidates per cell.
An owner changes their address. When do users see it?Show answer
First I'd agree on the freshness the product needs; hours is usually fine. The write goes to the primary; the business service then deletes the old and the new cell keys and the business key, so the next search refills them. A lagging replica can refill the cache with the old row, so I delete again after a short delay and keep a TTL as backstop. If minutes mattered, I'd update caches from a stream of change events.
How is this different from finding nearby drivers?Show answer
The index is the same idea, cells; the workload is the opposite. Drivers move, so that index takes hundreds of thousands of writes per second, lives in memory and expires stale entries. Businesses stay put: writes are rare, so I keep the index in a database, serve it from read replicas and cache whole cells for a day. Here the hard parts are density skew and ranking, not write throughput.
Deep dive 3
Geohash vs quadtree vs S2
Geohash: a string column with a B-tree index. A prefix query serves any coarser precision, and it works in any database or cache. Cell sizes are fixed, so a downtown cell returns thousands of candidates and a rural one almost none. Quadtree: an in-memory tree that splits a cell when it holds too many points (say 100), so every leaf has a similar count and k-nearest search is natural. The cost is operational: each server builds the tree at startup, so deploys must be rolling, and edits need a rebuild or careful in-place updates. S2: covers any region, a circle or a polygon, with cells of mixed levels; best for geofences and tight coverings. For static points and a handful of radii, geohash in the database is the simplest thing that works. Move on when density skew hurts.
Caching by cell and read replicas
Two caches, both keyed by things that rarely change. cell:{geohash} holds a list of (business id, lat, lng): enough to filter and rank without loading any business. Every user in the cell shares it, unlike a key built from raw coordinates, which almost never repeats. business:{id} holds the details shown in results. On an edit, the business service updates the primary and deletes the affected cell and business keys; a long jittered TTL is the backstop (Caching strategies). Size check (assumed): 200M index entries × ~30 B ≈ ~6 GB, so the whole geo index fits in one cache node's memory. Misses go to read replicas; a few seconds of replication lag is invisible when the product tolerates hours (Replication).
Filters, ranking and search engines
Distance alone is rarely the product. With light filters (category, open now), filter the candidates after the distance pass: a few hundred rows in memory. When users combine text, many filters and relevance ranking (rating, reviews, price), move the query to a search engine that indexes coordinates next to the text and applies a distance filter inside the same query. Yelp built Nrtsearch, its own Lucene-based engine, to replace Elasticsearch (2021): a primary indexes and replicas pull the finished segments, the same read-replica shape as here. At the other end, PostGIS is enough while the data fits one database server: ST_DWithin answers radius queries using a spatial index. Whatever the engine, cap the candidates per query so one dense cell can't blow the latency budget.