Yelp / a Proximity Service
The classic "find things near me" problem — worked through the TOGAF ADM phases so the geo-index choices in Phase D fall out of the requirements, not the other way around.
Yelp / proximity service, the ADM way, in 30 seconds
- Why TOGAF here: it forces business intent → requirements → data/app → technology in order, so the geo-index you reach for in Phase D is a consequence, not a reflex.
- A (Vision): fast, reliable "what's near me" search; principles — read-optimized, horizontally scalable, freshness-tolerant.
- B (Business): two capabilities — search nearby places (dominant) and add a review (secondary, write path).
- C (Data/App): place records keyed by id plus a spatial index over location; a stateless search tier; an async review path.
- D (Technology): the real meat — geohashing or a quadtree/grid to index by location, searching the user's cell plus neighbors, handling dense vs sparse areas, the places store, and caching.
- E–H: ship search first, reviews later; govern with latency and freshness SLOs.
- The lesson: "read-optimized, search is dominant" (Phase A/B) is exactly why Phase D is a precomputed spatial index with reviews pushed off the critical path.
Like folding a map into squares before you search it
Imagine a giant paper map of the whole country covered in thousands of restaurant pins, and someone asks 'what's near this spot?' The slow way is to measure the distance from that spot to every single pin — exhausting, and it gets worse as more pins are added. What a person actually does is fold the map into a grid of squares, find the square the spot sits in, and only look at pins in that square and the ones touching it. You ignore the entire rest of the country instantly.
That folding is the whole idea behind a proximity service. Instead of comparing a point against millions of places, you label every place with the square (cell) it falls in, ahead of time. Then 'near me' becomes 'look in my square and its neighbors' — a handful of quick lookups instead of a nationwide scan. Everything in Phase D is about choosing how to draw those squares and how to search them.
What makes it hard — the problem before the solution
- Distance isn't a simple sort key. You can't put 'nearness to an arbitrary point' in a normal database index, because the point changes every query — so a naive design scans everything.
- The world is unevenly packed. A downtown block holds thousands of places; a rural county holds a dozen. One fixed grid makes dense cells slow and sparse cells empty.
- Edges of a cell are tricky. The closest restaurant might sit just across a cell boundary, so you can't only look in your own square — you have to check the neighbors too.
- Reads crush writes. People search constantly and add reviews rarely, so the search path must be fast and the write path must never slow it down.
Why work proximity search through TOGAF?
"Find places near me" sounds simple until you ask how do you search by distance at scale without scanning every row. That's a genuinely interesting spatial-indexing problem, which makes it a great place to watch the ADM do its job: the discipline of order stops you from blurting "use a geohash!" before you've established that search is read-dominant and freshness-tolerant. By the time Phase D picks a spatial index, that choice is defending a requirement you wrote down two phases earlier.
Phase A — Architecture Vision
Intent: agree what we're building, for whom, and the principles that will constrain every later choice.
- Vision: a service that, given a user's location, returns nearby places (restaurants, shops) quickly and reliably, at city-to-global scale.
- Stakeholders: searchers (want instant, relevant results near them); businesses (want to be found and reviewed); the company (wants low cost per query).
- Principles (the constraints that cascade): read-optimized first (searches vastly outnumber edits); horizontally scalable (no single box holds the whole map); freshness-tolerant (a new review or a slightly stale rating appearing a few seconds late is fine).
Phase B — Business Architecture
Intent: model the business capabilities and value streams before any technology talk.
- Value stream: open the app → share location → see nearby places ranked by distance/rating → pick one → maybe leave a review.
- Capability 1 — Search nearby places: very high volume, must be fast, tolerant of slight staleness.
- Capability 2 — Add / read reviews: lower volume write path; must be durable but must never slow a search.
- Capability 3 — Manage place data: businesses create/update listings; rare writes, read constantly.
Impact: search dominates traffic and sets the non-functional targets; reviews are a secondary write path that must stay off the critical read path. That asymmetry, found here in Phase B, is what drives the Phase D index and the decoupling of the review flow.
Phase C — Information Systems Architecture (Data & Application)
Intent: define the data and application architecture, and the gap from today (today = nothing; greenfield).
Data architecture
- Core entity: a
place— id, name, category, latitude/longitude, aggregate rating, review count. - Secondary entity: a
review— id, placeId, userId, stars, text, createdAt; many reviews per place. - Access pattern: the dominant query is "places within radius R of (lat, lng)" — a spatial range query, not a key lookup and not a join.
- Conclusion: the place store wants a spatial index over location (see Indexing); reviews are a simple append-and-aggregate shape (see SQL vs NoSQL). The access pattern chose the data model, not the other way around.
-- A place carries a precomputed cell so 'near me' is a cell lookup, not a scan.
CREATE TABLE place (
place_id BIGINT PRIMARY KEY,
name TEXT,
category TEXT,
lat DOUBLE NOT NULL,
lng DOUBLE NOT NULL,
geo_cell CHAR(8) NOT NULL, -- geohash prefix = the square it sits in
rating_avg REAL, -- maintained async by the review pipeline
review_count INT
);
-- THE index that makes proximity fast: group places by their cell.
CREATE INDEX idx_place_cell ON place (geo_cell);
-- Reviews are a separate append-and-aggregate shape, off the hot search path.
CREATE TABLE review (
review_id BIGINT PRIMARY KEY, place_id BIGINT, user_id BIGINT,
stars SMALLINT, body TEXT, created_at TIMESTAMP
);Application architecture
- Stateless search tier so it can scale horizontally per the Phase A principle; it reads the spatial index and ranks results.
- Separation of search (hot) from reviews (write path) so each scales independently and a burst of reviews can't stall search.
- An asynchronous review-ingest path, decoupled via a queue, that updates aggregate ratings without touching search latency.
Phase D — Technology Architecture (the core)
Intent: choose the concrete technologies and the physical/deployment design that realize Phase C — and justify each one against the principles and requirements. This is where a technical interviewer spends most of the time, so we'll cover every step.
D1 — Estimate the load (sizing drives technology)
# 100M searches/day
search_per_sec = 100_000_000 / 86_400 # ~1,160 searches/sec
# Reviews are secondary: ~1 review per 500 searches
review_per_sec = search_per_sec / 500 # ~2-3 writes/sec
# Places: ~50M worldwide, ~1 KB each -> ~50 GB of place data
# Reviews: ~1B rows, ~1 KB each -> ~1 TB
# Verdict: read-heavy by ~400:1; index must answer 'near me' without a full scan
# -> precomputed spatial index + cached hot cells (set in D2/D4)The numbers confirm the Phase B asymmetry quantitatively: a roughly 400:1 search:write ratio and a dataset where the hard part isn't size but answering a spatial query fast. Those two facts dictate the next steps.
D2 — The spatial index (the heart of the design)
| Option | How | Pros | Cons |
|---|---|---|---|
| Geohashing | Encode (lat,lng) into a short string prefix; shared prefix = nearby. | Simple, string-indexable, fits any KV/SQL store; neighbors are prefix lookups. | Fixed grid; cell sizes don't adapt to density; edge cases at cell boundaries. |
| Quadtree / grid | Recursively split space; dense areas split deeper, sparse areas stay coarse. | Adapts to density; balanced leaf sizes. | More complex to build and rebalance; trickier to shard. |
- Core idea: index every place by its location cell, not just its id, so "near me" becomes "look in a few cells" instead of scanning the whole table.
- To find nearby places: compute the user's cell, then read that cell plus its neighboring cells (a geohash has 8 neighbors; a grid has adjacent tiles) so results near a cell boundary aren't missed.
- Then filter precisely: candidates from those cells are filtered by true great-circle distance and ranked by distance and rating.
- Decision: start with geohashing for its simplicity and store-agnostic indexing; reach for a quadtree/grid if density variance hurts — which leads straight to D3.
# Index every place under its geohash cell (D2): nearby == shared prefix.
def add_place(index, place):
cell = geohash_encode(place.lat, place.lng, precision=6) # ~1.2km cell
index.setdefault(cell, []).append(place)
def search_nearby(index, lat, lng, radius_m):
cell = geohash_encode(lat, lng, precision=6)
# Read the user's cell PLUS its 8 neighbors so boundary places aren't missed.
candidates = []
for c in [cell] + geohash_neighbors(cell):
candidates.extend(index.get(c, []))
# Prefix lookups give candidates; filter precisely by true distance.
hits = [p for p in candidates
if haversine(lat, lng, p.lat, p.lng) <= radius_m]
return sorted(hits, key=lambda p: (-p.rating, p.distance))Why a precomputed cell index, and why not just scan or a plain DB index?
The tempting shortcut is to skip the spatial index entirely: 'the database already has indexes — just filter by latitude and longitude.' But an ordinary B-tree index sorts on one dimension at a time. A query like 'within 2 km of here' is two-dimensional, so a lat/lng index can narrow one axis but still scans a huge band on the other. And scanning every row is a non-starter at 50 million places. Pre-labeling each place with a cell collapses the two-dimensional 'near' question into a one-dimensional lookup — 'which cell, plus neighbors' — which any store can serve fast.
| Approach | What it buys | The gap it can't fill |
|---|---|---|
| Full scan + distance per row | Trivial to write; always correct. | Checks every place on every query — melts the moment the dataset or traffic grows. |
| Plain lat/lng B-tree index | Uses the database you already have. | One-dimensional sort can't express 2-D 'nearness'; still scans a wide band on the other axis. |
| Precomputed cell index (chosen) | Turns 'near me' into a few cell lookups; store-agnostic; cacheable. | Fixed cells don't adapt to density (fixed in D3) and need neighbor-cell reads at boundaries. |
D3 — Handling dense vs sparse areas
- The problem: a fixed geohash precision gives a downtown cell thousands of places and a rural cell almost none — one is slow, the other is empty.
- Dense areas: use a finer cell (longer geohash prefix) so each cell stays small and fast; a search may read more neighbor cells but each is cheap.
- Sparse areas: use a coarser cell (shorter prefix) so a search still finds enough candidates without widening the radius many times.
- The adaptive answer: a quadtree encodes exactly this — it splits dense regions deeper and leaves sparse ones coarse, keeping leaf cells balanced. Choose it when real-world density skew makes fixed geohash cells uneven.
D4 — The places store & caching the hot path
- Places DB: a store holding place records with the spatial index on location (see Indexing); it's read far more than written, so optimize for reads.
- Shard by region/cell so the global map isn't on one node (see Sharding); cell-based sharding keeps most "near me" searches on a single shard.
- Cache hot cells: popular areas (a city center at dinnertime) get queried constantly, so put an in-memory cache in front of the index (see Caching) — a cache-aside layer with a short TTL absorbs the repeat traffic.
- Replicate each shard (see Replication) so a node loss doesn't take the map offline.
D5 — Reviews: the secondary write path
- A new review is published to a queue (see Message queues); workers persist it and update the place's aggregate rating off the critical path.
- Idempotency on review submission (see Idempotency) so a retried post doesn't double-count stars.
- Freshness is tolerant: a review appearing in aggregates a few seconds later is fine — eventual consistency is an accepted trade (see Consistency models), exactly as Phase A allowed.
D6 — The edge & cross-cutting concerns
- Front the service with a reverse proxy / load balancer (see Load balancing) and a rate limiter (see Rate limiting) so scrapers can't hammer the search API.
- Observability: trace the search path and alert on p99 latency and cache hit-rate (see Distributed tracing).
- API shape: a simple
search(lat, lng, radius, category)endpoint — pick a style per API styles.
def search(lat, lng, radius_m, category=None):
cell = geohash_encode(lat, lng, precision=6)
key = f"cell:{cell}:{category}"
# 1. Dinner-rush downtown cells are queried constantly -> serve from cache.
cached = cache.get(key)
if cached is not None:
return rank_for(cached, lat, lng)
# 2. Miss: read the cell + neighbors from the (possibly sharded) index.
candidates = index.read_cells([cell] + geohash_neighbors(cell), category)
# 3. Filter to the true radius, cache the small candidate set briefly.
near = [p for p in candidates if haversine(lat, lng, p.lat, p.lng) <= radius_m]
cache.set(key, near, ttl=30) # short TTL: freshness-tolerant (Phase A)
return rank_for(near, lat, lng)Scaling & bottlenecks — what breaks first
Turn the dial up and a proximity service fails in a predictable order. The write path is deliberately tiny, so the first thing to buckle is almost always a hot cell — the dense, popular square everyone queries at once.
| Breaks first as you scale | The symptom | The fix |
|---|---|---|
| A hot cell (dense + popular) | Downtown at dinnertime: one cell takes a flood of identical queries. | Cache hot cells with a short TTL; replicate the shard owning that cell; precompute popular results. |
| Density skew in the index | Some cells are huge and slow, others empty and wasteful. | Switch those regions to finer/coarser cells, or adopt a quadtree that adapts to density (D3). |
| Cross-shard boundary searches | A search near a shard edge must read cells on two shards, doubling work. | Overlap/replicate boundary cells; route by cell so most searches stay on one shard. |
| Review aggregation lag | Ratings update slowly when a place suddenly gets many reviews. | Batch rating updates off the queue; it's freshness-tolerant, so a few seconds of lag is acceptable. |
Phases E & F — Opportunities, Solutions & Migration Planning
- Greenfield, so sequence by risk: ship search over a geohash index against a single replicated store first; add hot-cell caching; introduce cell sharding as the map grows.
- Reviews second, behind the queue, so they never block the launch of the core search experience.
- Swap geohash for a quadtree only if density skew proves it necessary — an independently shippable, reversible step, same strangler-fig / expand-contract spirit as the TOGAF commerce scenario.
Phases G & H — Governance & Change Management
- Governance (G): define SLOs (e.g. search p99 < 100ms, 99.9% availability), set per-client query quotas, and review that the build still honors the Phase A principles.
- Change management (H): adding filters (price, cuisine, open-now) or a new ranking signal is a bounded change, not a re-architecture — because search, indexing, and reviews were kept on clean boundaries.
A proximity service is the gateway to a whole family of location problems — it's the piece ride-hailing and delivery reuse the moment they ask "who/what is near this point?"
Why it matters
- It shows that "search by distance at scale" is really an indexing problem, solved by precomputing a spatial structure instead of scanning rows.
- It makes the read-vs-write asymmetry concrete: search is hot, reviews are a decoupled side channel.
- It's directly reusable — the same cell search powers matching drivers to riders and couriers to orders.
If ignored
- You scan every place per query and melt under load, because no spatial index was built.
- Fixed cells make downtown slow and the countryside empty, because dense/sparse skew was never handled.
- Reviews land on the search path and a write burst stalls every searcher's results.
Where it fits
- Phase D is the technical core — geohash/quadtree index, neighbor-cell search, density handling, places store, hot-cell caching.
- Earlier phases (A–C) supply the read-optimized, freshness-tolerant constraints; later phases (E–H) handle rollout and keep it honest.
- It sits beside the interview framework as a reusable building block for any location-based system.
Related topics
- Indexing: the spatial index is the Phase D heart of this design
- Caching: hot-cell caching realizes 'read-optimized first'
- Sharding: cell/region sharding scales the global map
- Design Uber / ride-hailing: reuses this exact cell search to match drivers to riders
Interview lens
Questions it unlocks
- Design Yelp / a "places near me" service.
- How do you search by location at scale without scanning every row?
- How would you index geospatial data — geohash vs quadtree?
60-second answer
I'd frame it as an ADM walk so every choice is traceable. Phase A sets principles — read-optimized, horizontally scalable, freshness-tolerant. Phase B finds two capabilities: search nearby places (dominant) and add reviews (a secondary write path). Phase C sees the dominant query is a spatial range search, so the place store needs a spatial index and reviews are a decoupled append-and-aggregate flow. Then Phase D is the real design: index every place by a location cell using geohashing, and answer 'near me' by reading the user's cell plus its neighbors, then filtering by true distance. Handle dense-vs-sparse areas with finer or coarser cells — or a quadtree that adapts to density. Shard by cell, cache hot cells, replicate for durability, and push reviews onto a queue so they never touch search latency. E–H ship search first then reviews, governed by latency SLOs. Every Phase D mechanism traces back to the read-optimized principle.
Common traps
- Jumping to "use a geohash" before establishing that search is read-dominant and the query is a spatial range.
- Ignoring dense-vs-sparse density skew, so downtown cells are slow and rural cells are empty.
- Letting the review write path land on the latency-critical search path.