Nearby Places Lookup: Architecting a Proximity Search Backend
System DesignModel answerLast updated
Design a read-heavy backend that returns places within a given radius of a coordinate, covering spatial indexing, caching, API shape, capacity math, and availability.
Nearby Places Lookup
You are asked to design the backend for a "what's near me?" feature. A client sends its current latitude and longitude, and the service returns the places (points of interest, or POIs) that lie within a chosen distance of that spot.
Functional requirements
- Accept a coordinate pair and a search radius (for example 5 km) and return all matching places.
- Each result includes the place name and its exact coordinates.
Non-functional requirements
- Search latency under 100 ms.
- High availability.
- The place catalog changes rarely, so the workload is overwhelmingly reads.
Scale assumptions
- 10 million places worldwide.
- 1 million daily active users.
- Read-to-write ratio of about 1000:1.
What your answer should cover
- Data model: how coordinates are stored and which indexing strategy makes radius queries fast.
- API design: the endpoint and response shape for a proximity search.
- Architecture: the main components (load balancer, application servers, cache, datastore) and how reads and writes flow through them.
- Trade-offs: compare candidate approaches such as geohash, quadtree, and a spatial database extension like PostGIS, and justify your pick.
Back up your design with rough capacity numbers, and say what you would do differently if the scale grew by 10x or 100x.
Hints
Hint 1
Do the sizing before choosing a design: estimate the memory needed for an index of 10M (id, lat, lng) entries and the peak queries per second. Does the data need partitioning, or only replication?
Hint 2
A plain B-tree on latitude and another on longitude cannot answer a 2D box query efficiently. Think about what property a spatial index must preserve, and how a geohash or a tree-based structure turns 2D proximity into something cheap to look up.
Hint 3
A cell-based lookup returns candidates, not final answers. Remember to check neighboring cells (points near a cell edge can be close but have a different prefix) and to apply an exact distance filter at the end. Then think about dense versus sparse regions.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify and size the problem
Questions worth asking: Is there a maximum radius (assume 50 km, default 5 km)? Is ordering by distance required (yes, by default)? Is category filtering needed (assume yes)? How fresh must updates be (minutes is acceptable)?
Back-of-envelope numbers
| Quantity | Estimate |
|---|---|
| Places | 10M |
| Full record (~1 KB each) | ~10 GB |
| Index entry (id, lat, lng, cell key, ~40 B) | ~400 MB |
| Searches | 1M users x ~5/day = 5M/day, about 60 QPS average, about 600 QPS peak |
| Writes | well under 1 per second |
The key conclusion: the spatial index fits in the RAM of one machine. We need replication for availability and throughput, but not sharding. Jumping straight to "partition by region across many nodes" without this math is a common mistake.
Why naive queries fail: WHERE lat BETWEEN a AND b AND lng BETWEEN c AND d with separate single-column indexes can only use one dimension well, so it scans a whole latitude band (hundreds of thousands of rows). A full scan with trigonometric distance math over 10M rows takes seconds. We need an index that preserves 2D locality.
2. API
GET /v1/places/nearby?lat=37.7749&lng=-122.4194&radius_m=5000
&category=restaurant&sort=distance&limit=20&cursor=...
Response:
{
"results": [
{"id": "p_123", "name": "Corner Cafe", "lat": 37.7765, "lng": -122.4172,
"distance_m": 254, "category": "cafe"}
],
"next_cursor": "..."
}
Validate lat in [-90, 90], lng in [-180, 180], and radius at most 50 km. Writes go through a separate internal admin API, not the hot read path.
3. Data model
The source of truth is a relational table (PostgreSQL):
id,name,category,rating,updated_atlat,lngas double precision (single-precision floats lose accuracy around the meter level)geohash(12 chars, computed on write) with a prefix-friendly index, or alternatively a PostGISgeography(Point)column with a GiST index
Geohash in brief: interleave the bits of longitude and latitude and base32-encode them. Nearby points usually share a prefix, so a 2D box query becomes a few 1D prefix lookups. Rough cell sizes: 5 characters is about 5 x 5 km, 6 characters about 1.2 x 0.6 km. Pick the precision whose cell is roughly the size of the search radius.
Serving index: Redis GEO (a sorted set scored by a 52-bit geohash) or an in-process index on each search server. A command such as GEOSEARCH ... BYRADIUS 5 km ASC COUNT 20 handles cell covering and distance filtering.
4. Architecture
Client -> CDN/edge -> Load balancer -> Search service (stateless, N replicas)
|
+---------------------------+----------------------------+
Result cache Geo index (replicated) Place detail cache
(cell+radius+category) (id -> record)
|
built from PostgreSQL primary + read replicas
Admin writes -> Postgres -> change stream (CDC) -> index updaters
Read path
- Snap the query to a coarse key (cell + radius + category) and check the result cache. With static data, hit rates in dense areas are high.
- On a miss, ask the geo index for candidate IDs: the query cell plus its 8 neighbors.
- Compute exact haversine distances, drop anything beyond the radius, and sort.
- Hydrate details from the detail cache, falling back to a replica.
Everything is in memory, so latency is roughly 5 to 20 ms.
Write path: write to Postgres, publish the change through CDC, update the index (add, move, or remove) and invalidate the detail cache. Staleness is seconds. A nightly full rebuild from Postgres acts as a consistency backstop.
Availability
- Stateless services behind the load balancer, spread across zones.
- Redis with replicas and automatic failover.
- Multiple regions, each with a full index copy (400 MB is cheap to replicate).
- If the cache tier fails, fall back to PostGIS read replicas: slower but still correct.
5. Trade-offs
| Approach | Pros | Cons |
|---|---|---|
| Geohash (B-tree or Redis GEO) | Simple, works on any store, easy to cache and shard by prefix | Fixed grid ignores density; edge-of-cell problem; cells narrow near the poles |
| Quadtree (in memory) | Adapts to density (split a node when it exceeds K points); good for k-nearest | Custom code; must be rebuilt or synced across replicas; harder to persist |
| PostGIS (GiST/R-tree) | Exact ST_DWithin, polygon queries, mature | Disk-backed database on the hot path; needs replicas and caching |
| S2 / H3 | Uniform cells, good coverings | Extra library and concepts |
Recommendation: PostGIS as the source of truth, an in-memory or Redis GEO index replicated per region for serving, and a result cache in front. Be honest that a few PostGIS read replicas could already handle 600 QPS; the cache and in-memory index are justified by latency headroom and cost, not strict necessity.
6. Follow-ups and pitfalls
- Dense vs. sparse areas: a fixed grid returns thousands of candidates in a big city and almost none in rural areas. Fix by using adaptive precision (start fine and widen the cell until enough results) or a quadtree that splits by density.
- Cell boundaries: always query neighboring cells, since two close points can have different prefixes.
- Antimeridian and poles: handle longitude wraparound at plus or minus 180 degrees.
- Growth by 100x: the index becomes about 40 GB. Then shard by top-level cell prefix or S2/H3 cell, and keep hot cells cached.
- Common mistakes: skipping the capacity math, sharding unnecessarily, forgetting the final exact-distance filter, using plain lat/lng B-trees, and not describing failure behavior.