The Problem#
"Pizza near me." "Coffee open now within 1 km." "Best-rated Thai restaurants in the Mission District." Every day, hundreds of millions of searches like these are answered by local-search products: Yelp, Google Maps local results, Tripadvisor, Foursquare, Apple Maps, and the "nearby" features inside delivery and travel apps. A proximity service takes a location and a query and returns relevant places nearby, ranked by some mix of relevance, distance and quality. It lets users open a place's page with its details and reviews, and lets them write reviews of their own.
The interesting part is the shape of the data and the traffic:
- Businesses rarely move. A restaurant's latitude and longitude are set when it opens and change almost never. New businesses appear at a rate of thousands per day, not thousands per second. The location data is static for practical purposes, the opposite of ride-hailing, where every driver moves every few seconds.
- Reads dwarf writes. Users search and browse far more than they write reviews, often a thousand times more. This is a read-scaling problem: indexes, replicas, caches and precomputation.
- Queries combine dimensions. A single search mixes geography (within 2 km), text ("pizza"), categories (restaurants, then Italian), numeric filters (rating at least 4, price level 2) and time (open now). It also needs ranking. Doing all of these at once, fast, is where the real design work lies.
- Aggregates must be cheap to read. Every search result shows an average rating and a review count. Computing those from millions of reviews on every query would be absurd, so they must be maintained incrementally.
Analogy. Imagine a tourist information desk in a big city. On the wall is a city map divided into grid squares, and under the desk is a box of index cards for each square, one card per business, with its name, category, hours and average rating written on it. When a visitor asks for "coffee near the cathedral", the clerk finds the cathedral's square, pulls the cards from that box and the eight boxes around it, keeps the coffee shops, checks which are open, and sorts them by rating and distance. The cards change only when a business opens, closes or updates its details. Rather than recount every review card each time someone asks, the clerk keeps a running tally of each business's ratings, updated whenever a review arrives. In busy squares downtown, the clerk splits the box into four smaller ones so no box gets too thick to flip through; that is the quadtree. If the desk gets too busy, the city opens more desks with photocopies of the same cards (replicas), and the most common answers are pinned to a noticeboard (caches).
This problem is common for mid-level and senior candidates because it rewards clear fundamentals:
- Why a normal B-tree index cannot answer "near me".
- How geohash and quadtree indexes work, and when to use each.
- How to combine geographic search with text and filters, usually with a search engine like Elasticsearch.
- How to maintain aggregates such as average ratings consistently and cheaply.
- How to enforce "one review per user per business".
- How to scale a read-heavy system with caching and replication rather than sharding.
At staff level the same question opens up into search ranking, place-name resolution (cities and neighbourhoods as polygons), review integrity and multi-region serving.
Clarifying Questions#
| Question | Why it matters | Assumed answer |
|---|---|---|
| What can users search by? | Defines the query model. | Name or free text, location (latitude and longitude plus a radius), and category. Filters for rating, price and open-now are nice to have. |
| What does a search return? | Result shape and ranking. | A ranked, paginated list of businesses with name, category, distance, average rating, review count and a thumbnail. |
| Can users search by place names such as cities or neighbourhoods? | Adds polygon handling. | Yes, as an extension: "in Brooklyn" or "in the Mission District". |
| How many users and businesses? | Sizing. | 100 million daily active users; 10 million businesses worldwide. |
| What latency target? | Index and caching choices. | Search under 500 ms end to end; p99 server time ideally under 200 ms. |
| Consistency needs? | Replication and cache strategy. | Eventual consistency is fine: a new review can take seconds to appear in search results and averages. The author should see their own review immediately. |
| Who adds and edits businesses? | Write-path scope. | Owners and admins, rarely. We focus on users but cover how updates propagate. |
| Reviews: what do they contain? | Data model and aggregation. | A mandatory 1 to 5 star rating and optional text. One review per user per business, editable. |
| Map view, recommendations, photos? | Scope. | Map view and personalised recommendations are out of scope for the core; photos are stored and served but not designed in depth. |
| Abuse and spam? | Integrity. | Out of scope for the core, but we discuss fake-review defences. |
Requirements#
Functional requirements#
- Search for businesses by name or text, location, and category, with optional filters (minimum rating, price level, open now) and pagination.
- View a business: its details and its reviews, paginated and sortable.
- Review a business: a 1 to 5 star rating with optional text. One review per user per business. Users may edit or delete it.
- Search by place name (extension): restrict a search to a predefined area such as a city or neighbourhood.
Below the line: admin tools for adding, updating and removing businesses (we cover the propagation path, not the tools); a map view with pins (briefly covered as a variant); personalised recommendations; photos and menus in depth; reservations and ordering.
Non-functional requirements#
- Low latency: search in under 500 ms end to end; business pages in under 200 ms.
- High availability: search and viewing should stay up even if the review-writing path is degraded. Availability matters more than strict consistency.
- Scale: 100 million daily active users and 10 million businesses, with read traffic far exceeding write traffic.
- Eventual consistency: search results and ratings may lag new reviews by seconds; authors see their own writes immediately.
Below the line: GDPR and data protection, full fault tolerance analysis, spam and abuse prevention. We touch on each later.
The framing to say out loud: this is a read-heavy system over mostly static data, so we can precompute and replicate aggressively. The hard parts are multi-dimensional search and keeping aggregates fresh without making writes expensive.
Capacity Estimation#
Rough numbers set the shape of the design. The goal is not precision; it is finding which resource is the bottleneck. (See Back-of-the-Envelope Estimation and Numbers Every Engineer Should Know.)
Traffic#
- Daily active users: 100 million.
- Searches: assume each active user runs about 5 searches a day (initial search, a refinement, a filter change, a "next page"). That is 500 million searches per day, or about 500M / 86,400 ≈ 5,800 searches per second on average. Local search is peaky: lunchtime and dinnertime in each time zone, Friday evenings, holidays. A peak factor of 3 gives roughly 17,000 to 20,000 searches per second at peak.
- Business page views: each search leads to one or two page views, so about 1 billion page views per day, or about 12,000 per second on average and roughly 35,000 at peak. Each page view also loads the first page of reviews.
- Review writes: the overwhelming majority of users never write reviews. Assume 1 percent of daily users write one review a day: 1 million reviews per day, about 12 per second on average and perhaps 50 per second at peak.
- Business updates: new businesses, hour changes, closures. Perhaps tens of thousands per day, well under 1 per second on average.
Read:write ratio. Roughly (500M + 1B) reads to 1M writes: about 1,500 to 1. This is the most important number in the estimate. It says: optimise reads ruthlessly, precompute anything a read needs, and accept extra work on the write path.
Storage#
Businesses. 10 million businesses. A record holds an id, name, address, latitude and longitude, category list, phone, website, hours, price level, average rating and review count, plus some attributes ("takes reservations", "wheelchair accessible"). Call it about 1 to 2 KB per business. That is 10 to 20 GB of core business data. Small enough to fit on a single database server, and in memory on a single large machine.
Reviews. If each business has 50 reviews on average (a skewed distribution: most have a handful, popular ones have thousands), that is 500 million reviews. At about 1 KB each (text averages a few hundred bytes, plus ids, rating and timestamps), that is about 500 GB. Growing by 1M reviews/day × 1 KB ≈ 1 GB/day, or about 365 GB per year. Manageable for a sharded relational database or a wide-column store, and large enough that we will think about partitioning it.
Photos. Photos dominate raw bytes: tens of millions of photos at hundreds of KB to a few MB each means tens to hundreds of TB. That lives in Object Storage and Blob Storage behind a Content Delivery Networks (CDN) and is not on the search path.
Geo index. This is the surprising one. An index entry needs only a business id (8 bytes), a latitude and longitude (16 bytes as doubles, or 8 as floats), and perhaps a geohash or cell id (8 bytes). Call it 32 to 64 bytes. 10 million × 64 bytes = 640 MB. Even with overhead for tree nodes, the entire geo index of every business on Earth fits comfortably in the RAM of one server.
What the numbers tell us#
- Data volume is not the problem. The business data and the geo index fit in memory on one machine. We do not need to shard the search data for size. We will replicate it for throughput and availability.
- Read throughput is the problem. 20,000 searches per second at peak, each combining geography, text and filters. A single database cannot do this; a fleet of read replicas or search nodes behind caches can.
- Writes are tiny. 12 to 50 review writes per second is trivial for a single primary database. The write path can afford to do extra work, such as updating aggregates and pushing changes to the search index, on every write.
- Reviews are the only data set that grows meaningfully, and they are read mostly per business, so partitioning reviews by business id is natural if we ever need to.
A quick sanity check on search-node sizing: if one Elasticsearch-style search node can serve on the order of 500 to 2,000 geo-filtered queries per second (it depends heavily on query complexity, shard size and hardware), then 20,000 peak QPS needs roughly 10 to 40 search nodes, plus headroom. Caching the most popular queries can cut that substantially. We will refine this in the read-scaling deep dive.
Core Entities#
- Business: a place users can find. Id, name, location (latitude, longitude), address, categories, hours, price level, attributes, and denormalised aggregates:
avg_rating,review_count. - Review: a user's opinion of a business. Id, business id, user id, rating (1 to 5), optional text, created and updated timestamps. Unique per (user, business).
- User: a person who searches and writes reviews. Id, name, profile; reviewing reputation is used later for spam scoring.
- Category: a node in a category tree ("Restaurants → Italian → Pizza"). Lets a search for "Restaurants" include all subcategories.
- Location (place): a named area such as a city, neighbourhood or postcode, stored as a polygon with a hierarchy (neighbourhood inside city inside region). Used for place-name search.
- Photo (supporting): an image attached to a business or review, stored in object storage.
API Design#
A simple REST API (see API Design Best Practices) is natural. Everything is read-mostly, cacheable and resource-shaped.
Search businesses
GET /businesses?query=pizza&lat=37.7599&lng=-122.4148&radius=2000
&category=restaurants&min_rating=4&price=1,2&open_now=true
&sort=relevance&cursor=eyJvIjoyMH0&limit=20
→ 200 {
"businesses": [
{ "id": "b_812", "name": "Tony's Pizza", "distance_m": 340,
"avg_rating": 4.6, "review_count": 1832, "price": 2,
"categories": ["pizza", "italian"], "open_now": true,
"thumbnail_url": "https://cdn.example.com/p/812/t.jpg" }
],
"next_cursor": "eyJvIjo0MH0"
}lat,lng,radius(metres): the search circle. Alternativelylocation_idfor place-name search (see below), or a map viewportbbox=minLng,minLat,maxLng,maxLat.query: free text matched against names, categories and possibly review text.category,min_rating,price,open_now: filters.sort: relevance (default), distance, rating or review count.cursor: opaque pagination token. Local search rarely goes deep (most users never pass page 2), so a capped offset encoded in the cursor is acceptable; we discuss pagination later.
View a business
GET /businesses/{business_id}
→ 200 { "id": "b_812", "name": "...", "address": "...", "lat": ..., "lng": ...,
"hours": [...], "avg_rating": 4.6, "review_count": 1832, "photos": [...] }List reviews for a business
GET /businesses/{business_id}/reviews?sort=newest&cursor=...&limit=20
→ 200 { "reviews": [ { "id": "r_1", "user": {...}, "rating": 5,
"text": "...", "created_at": "..." } ],
"next_cursor": "..." }Write a review
POST /businesses/{business_id}/reviews
Authorization: Bearer <token>
{ "rating": 4, "text": "Great crust, slow service." }
→ 201 { "id": "r_991", ... }
→ 409 { "error": "already_reviewed", "review_id": "r_455" } // one per userThe user id comes from the authentication token, never from the request body; otherwise anyone could post reviews as anyone else (see Authentication and Authorization). Edits use PUT /reviews/{review_id} and deletes DELETE /reviews/{review_id}, both checking that the caller owns the review.
Resolve a place name (for the "in Brooklyn" extension)
GET /locations?query=mission%20dis
→ 200 { "locations": [ { "id": "loc_sf_mission", "name": "Mission District",
"parent": "San Francisco, CA", "type": "neighborhood" } ] }The client picks a location and passes location_id=loc_sf_mission to the search endpoint.
High-Level Design#
We build the design one requirement at a time, starting with the simplest thing that works, then improving it.
1. Users can search for businesses#
The simplest version is a Search Service in front of a database that holds the businesses table. A client calls GET /businesses?... through an API Gateway (see API Gateway and Backend-for-Frontend), which handles authentication, Rate Limiting and Throttling and routing. The Search Service translates the request into a query against the database.
The naive query would be:
SELECT id, name, lat, lng, avg_rating, review_count
FROM businesses
WHERE lat BETWEEN :lat - :dlat AND :lat + :dlat
AND lng BETWEEN :lng - :dlng AND :lng + :dlng
AND category = 'restaurants'
AND name ILIKE '%pizza%';This works on a laptop with 10,000 rows. At 10 million rows and 20,000 queries per second it is a disaster, for reasons we develop in the deep dives:
- A B-tree index on
latcan narrow to a horizontal band of the globe, and one onlngto a vertical band, but the database can only use one of them efficiently for a range scan. The band for latitude alone in a 2 km radius contains every business at that latitude around the whole planet. ILIKE '%pizza%'with a leading wildcard cannot use a B-tree index at all, so it scans.- No ranking: the query returns matches but cannot sort by "relevance" in a meaningful way.
So the search path needs two specialised capabilities: a geospatial index to find businesses near a point, and a text index for name and category matching with relevance. We will introduce both, and eventually combine them in a search engine.
2. Users can view a business and its reviews#
Viewing a business is a primary-key lookup by business_id plus a query for the first page of reviews: WHERE business_id = ? ORDER BY created_at DESC LIMIT 20. A Business Service handles these. It reads the businesses table and a reviews table, both in the same relational database for now.
This is the easy case: a key lookup and an indexed range scan. At 35,000 page views per second at peak it becomes a caching problem rather than a database problem. Business details change rarely, so a cache with a TTL of minutes absorbs most reads (see Caching Strategies: Cache-Aside, Read-Through, Write-Through, Write-Behind).
3. Users can leave reviews#
A Review Service accepts POST /businesses/{id}/reviews, validates the rating (1 to 5) and text length, checks that the user has not already reviewed the business, and inserts a row into the reviews table.
Every search result and business page shows avg_rating and review_count. Computing them with SELECT AVG(rating), COUNT(*) FROM reviews WHERE business_id = ? on every read would be expensive for popular businesses with thousands of reviews, and catastrophic inside a search query that ranks hundreds of businesses. Instead, the Review Service updates denormalised aggregates on the business row in the same transaction as the review insert. Deep dive 4 explains exactly how to do that correctly.
We split the Review Service from the Business Service even though they share a database. The read and write paths have different scaling needs (35,000 reads per second versus 50 writes per second), different failure tolerances (search must stay up when reviews are degraded), and different deployment cadences.
4. Search uses a proper geo and text index#
To make search fast we move it off the primary database. We have two good options, and the deep dives compare them:
- Option A: PostgreSQL with PostGIS and full-text search on read replicas. A GiST index on the location column, a GIN index on a
tsvectorof names and categories, and B-tree indexes on filters. Simple and strongly consistent with the primary (subject to replica lag). - Option B: a dedicated search engine such as Elasticsearch or OpenSearch. It combines a geo index (BKD trees on
geo_pointfields), an inverted index for text with BM25 relevance scoring, and fast filters on keyword and numeric fields, all in one query. It is fed from the primary database via Change Data Capture and the Outbox Pattern.
At this scale and with rich queries (text plus geo plus filters plus ranking), Option B is the standard choice, with the relational database remaining the source of truth. The search index is a derived, rebuildable copy.
5. Users can search by place name#
For "pizza in the Mission District", the client first resolves the name to a location id via a Location Service that serves an autocomplete over a gazetteer (a table of named places with polygons). The search then filters to businesses inside that polygon. Deep dive 6 shows how to precompute membership so that this becomes a simple keyword filter rather than an expensive polygon intersection at query time.
The full high-level design#
Components:
- Client apps: web and mobile. Send the user's location (with permission) or a chosen place, and render results and business pages.
- CDN: serves static assets and photos from edge locations close to users. Photos are immutable once uploaded, so they cache perfectly.
- API Gateway: terminates TLS, authenticates tokens for write endpoints, applies per-user and per-IP rate limits (important against scraping, which is a real problem for local-search sites), and routes to services.
- Search Service: stateless. Parses and validates parameters, normalises the location (rounding, see caching), builds a search-engine query, checks the result cache, executes the query, and formats results. Can apply a light re-ranking step.
- Search result cache (Redis): caches result pages for popular (normalised) queries for a short TTL, such as 30 to 120 seconds. Absorbs the head of the query distribution: "restaurants near Times Square" is asked constantly.
- Search cluster (Elasticsearch replicas): holds a denormalised document per business: name, categories, location as
geo_point, rating, review count, price, hours encoding, location ids. Answers combined geo, text and filter queries with relevance scoring. Replicated for throughput. - Business Service: serves business pages and review lists. Reads from cache first, then read replicas.
- Business and review cache (Redis): cache-aside for business records and the first page of reviews per business.
- Review Service: the write path. Validates, enforces one-review-per-user, inserts the review and updates aggregates transactionally on the primary database.
- Primary DB (PostgreSQL or MySQL): source of truth for businesses, reviews, users, categories. Small enough for one primary with replicas; reviews can be partitioned by business id later.
- DB read replicas: serve business pages and review lists. Asynchronous replication with sub-second lag in normal conditions (see Database Replication).
- CDC stream (Kafka): captures committed changes from the primary's write-ahead log (for example with Debezium) or from an outbox table, and publishes them as events.
- Indexer workers: consume change events, build or update the business document in the search cluster (rating, review count, hours, name changes), and invalidate cache entries.
- Location Service and Gazetteer: autocomplete over named places and their polygons and hierarchy; used to resolve "Brooklyn" to an id.
- Object storage: holds photos; uploads go directly from clients via pre-signed URLs.
The key property of this design: every search and every page view can be served without touching the primary database. The primary only sees about 50 writes per second at peak. Search and reads scale horizontally by adding search replicas, database replicas and cache nodes.
Key Flows#
Flow 1: Search "pizza near me"#
- The client sends
GET /businesses?query=pizza&lat=37.7599&lng=-122.4148&radius=2000&open_now=true. - The API Gateway applies rate limits and forwards to the Search Service. Search is allowed for anonymous users, so authentication is optional.
- The Search Service validates inputs (radius capped at, say, 40 km; limit capped at 50), normalises the query text (lowercase, trim), and quantises the location to a grid cell of about 150 m so that nearby users produce the same cache key (deep dive 7).
- It checks the result cache with a key such as
search:v3:q=pizza:cell=9q8yy9m:r=2000:open=1:page=0. On a hit (often 30 to 60 percent of traffic for head queries in dense areas) it returns immediately, recomputing distances from the user's exact location in a few microseconds per result. - On a miss, it builds a search-engine query: a
geo_distancefilter (2 km around the point), a text match on name and categories, a filter for the open-now slot, and a scoring function that blends text relevance, distance decay, rating and review count. - The search cluster's coordinating node fans the query out to one copy of each shard, each shard returns its top hits, and the coordinator merges them.
- The Search Service writes the result page into the cache with a short TTL and returns it.
Flow 2: View a business page#
- The client calls
GET /businesses/b_812andGET /businesses/b_812/reviews?limit=20(or one combined call from a Backend-for-Frontend). - The Business Service checks the cache for
biz:b_812. On a miss it reads the row from a read replica and populates the cache with a TTL of, for example, 10 minutes. The same pattern applies toreviews:b_812:newest:page0. - Photos referenced on the page are loaded directly from the CDN.
Cache hit rates here are high: popularity follows a power law, so a small fraction of businesses receives most page views. A cache holding the hottest few hundred thousand businesses (a few hundred MB) can serve the large majority of requests.
Flow 3: Write a review#
- The client sends
POST /businesses/b_812/reviewswith a bearer token, rating 4 and text. - The gateway authenticates the token and passes the user id to the Review Service.
- The Review Service validates the input, then opens a transaction on the primary database:
INSERT INTO reviews (...). A unique constraint on (business_id, user_id) rejects a second review from the same user; the service returns 409 with the existing review id.UPDATE businesses SET rating_sum = rating_sum + 4, review_count = review_count + 1 WHERE id = 'b_812'.- Commit.
- The service invalidates
biz:b_812andreviews:b_812:*in the cache, and returns 201 with the new review, so the author sees it immediately. - Asynchronously, the change data capture pipeline reads the committed changes from the write-ahead log, publishes
review_createdandbusiness_updatedevents, and the indexer updates the business document in the search cluster with the new average and count. Search reflects the new rating within seconds.
Data Model#
The source of truth is a relational database. Businesses, reviews and users are naturally relational. We need transactions across a review and its business's aggregates, and a unique constraint for one-review-per-user. The data fits comfortably on a primary with replicas. (See Choosing a Database: A Decision Guide and Data Modeling.)
The second half of the model covers the reference data used for filtering: the category tree and the gazetteer of named places, each linked to businesses through a many-to-many table.
| Table / store | Key | Purpose | Notes |
|---|---|---|---|
businesses | id | Business details and denormalised aggregates | About 10M rows, 10 to 20 GB. Columns rating_sum and review_count (average computed as sum / count); geohash or PostGIS geography(Point) for geo queries. |
reviews | id; unique (business_id, user_id) | Reviews | About 500M rows, about 500 GB. Index (business_id, created_at DESC) for listing; index (user_id, created_at) for a user's profile. Partition by business_id hash if needed. |
users | id | Profiles and trust score | Trust score feeds spam detection. |
categories | id | Category tree | Small (a few thousand rows); cached entirely in memory by services. |
business_categories | (business_id, category_id) | Many-to-many | Denormalised into the search document as an array including ancestor categories. |
locations | id | Named places with polygons and hierarchy | Polygon in a PostGIS geography(MultiPolygon) column; tens of thousands to millions of rows. |
business_locations | (business_id, location_id) | Precomputed polygon membership | Computed when a business is created or moved, or when a polygon changes. |
| Search index | business id | Denormalised search document | geo_point, name (text), categories (keyword), avg_rating, review_count, price, open-hours slots, location_ids. |
| Caches | biz:{id}, reviews:{id}:..., search:... | Hot reads | TTLs of seconds to minutes; invalidated on writes. |
Two design choices worth defending in an interview:
- Store
rating_sumandreview_count, notavg_rating. A sum and a count can be updated with atomic increments and decrements, and the average is derived exactly. Storing only the average forces read-modify-write arithmetic that loses precision and is prone to lost updates. - Reviews keyed and indexed by business first. Almost every review read is "reviews for business X", so co-locating a business's reviews on one partition makes the hot query a single-partition range scan.
Deep Dives#
1. Static locations: why this changes everything#
The first thing to notice is that business locations are static. That single fact drives most of the design, and it is worth stating explicitly in an interview because it contrasts with problems like ride-hailing or live location sharing, where the same index must absorb millions of location updates per second.
What "static" buys us:
- Index structure freedom. Structures that are expensive to update but fast to query become viable. A quadtree can be built once from 10 million points and rebuilt nightly. A BKD tree, which Elasticsearch and Lucene use for geo points, is written once per segment and never modified in place. A sorted array of geohashes supports binary search with no tree overhead at all.
- Precomputation. Anything derivable from location can be computed at write time and stored: geohashes at several precisions, S2 or H3 cell ids, the list of neighbourhood and city polygons the business sits in, the time-zone of the business (needed for open-now), even "distance to the nearest transit station" if the ranking uses it.
- Aggressive caching. If the set of businesses in a cell changes only a few times per day, a cached answer for "restaurants in cell X" stays correct for a long time. Cache invalidation is easy because writes are rare and can carry explicit invalidations.
- Replication rather than sharding. The index is small (under 1 GB) and changes slowly, so every search node can hold a full copy. Adding throughput is "add another replica", with no repartitioning, no scatter-gather across geographic shards, and no hotspots at shard boundaries.
What still changes:
- Aggregates (
avg_rating,review_count) change continuously, at about 12 to 50 per second globally. These are numeric fields on the search document, updated in place (Elasticsearch partial updates re-index the document internally, which is fine at this rate). - Hours and status (temporarily closed, permanently closed) change occasionally and must propagate within minutes, since showing a closed restaurant as open is a bad experience.
- New businesses appear in thousands per day.
The right mental model: a mostly-immutable spatial index plus a small stream of attribute updates. We can design the geo structure for read speed and treat updates as a slow trickle through a change pipeline.
A useful comparison:
| Property | Proximity service (Yelp) | Ride-hailing (Uber) |
|---|---|---|
| Points | 10M businesses | A few million online drivers |
| Update rate | Thousands per day | Millions per minute |
| Index lifetime | Hours to days | Seconds |
| Best structure | Quadtree, BKD tree, sorted geohashes, PostGIS GiST | Geohash or H3 buckets in Redis, in-memory cell maps |
| Scale lever | Replicate the whole index | Shard by geography |
| Cache value | High | Almost none |
2. The geospatial index: from B-trees to geohash, quadtree and beyond#
This is the heart of the problem. (The full treatment is in Geospatial Indexing and Proximity Search; here we focus on the choices for a static business data set.)
Why a B-tree fails for proximity. A B-tree orders keys along one dimension. "Businesses within 2 km of (37.76, -122.41)" is a two-dimensional range: a box (or circle) in latitude and longitude. With a composite index on (lat, lng), the database can seek to the latitude band 37.742 to 37.778 efficiently, but within that band the rows are sorted by latitude first, so the longitude condition is checked row by row. The latitude band for 2 km covers a strip about 4 km tall that wraps the entire globe: every business at that latitude in Asia, Europe and the Americas. With two separate indexes, the database can intersect them with bitmap scans, but each still returns a huge candidate set. What we need is an index whose one-dimensional key preserves two-dimensional locality, or a tree that partitions the plane directly.
There are two families of solutions:
- Encode 2D into 1D: geohash, S2 cell ids, and other space-filling-curve keys. Nearby points get similar keys, so a normal B-tree or sorted structure works on them.
- Partition space with a tree: quadtrees, k-d trees, BKD trees, R-trees. The tree itself is the index.
Geohash
A geohash recursively bisects the world. Start with longitude from -180 to 180: is the point in the left or right half? That is one bit. Then latitude from -90 to 90: top or bottom half? Another bit. Alternate, and keep going. Interleaving longitude and latitude bits traces a Z-order (Morton) curve. Every 5 bits are encoded as one base-32 character, so each character subdivides a cell into 32 smaller cells.
| Geohash length | Approximate cell size (at the equator) |
|---|---|
| 1 | 5,000 km × 5,000 km |
| 3 | 156 km × 156 km |
| 4 | 39 km × 20 km |
| 5 | 4.9 km × 4.9 km |
| 6 | 1.2 km × 0.6 km |
| 7 | 153 m × 153 m |
| 8 | 38 m × 19 m |
| 9 | 4.8 m × 4.8 m |
The key property: points that share a prefix are in the same cell. "9q8yy" is a roughly 5 km square in San Francisco; every business whose geohash starts with "9q8yy" lies inside it. So with an ordinary B-tree index on a geohash column, the query "everything in cell 9q8yy" is a prefix range scan:
SELECT id, lat, lng FROM businesses
WHERE geohash >= '9q8yy' AND geohash < '9q8yz'; -- same as LIKE '9q8yy%'Choosing precision from the radius. For a search radius r, pick the longest geohash whose cell is at least as large as r, so that the 3×3 block of cells around the user's cell always covers the whole circle. For r = 2 km, length 5 (about 4.9 km cells) works: the circle around any point in the centre cell fits within the 3×3 block. For r = 500 m, length 6 works.
The boundary problem and the 3×3 trick. Two points a metre apart can have completely different geohashes if a cell boundary passes between them. At the largest boundaries, such as the equator or the prime meridian, they share no prefix at all. So searching only the user's own cell misses nearby businesses just across the line. The fix: compute the user's cell and its 8 neighbours, query all 9 prefixes, then post-filter by exact distance (the haversine formula) to drop candidates outside the circle. The 9 cells cover a square of 3 × cell width; the circle is inscribed somewhere inside it.
Cost of over-fetching. Nine 4.9 km cells cover about 216 km², while a 2 km circle covers about 12.6 km². So we read roughly 17 times more candidates than we need and discard most of them in the post-filter. In a city with 2,000 businesses per km², that is about 430,000 candidates for a radius-2 km query, which is far too many. Two fixes:
- Use a finer precision with more cells. Cover the circle with length-6 cells (1.2 × 0.6 km): roughly 30 to 40 cells, but they hug the circle much more tightly. This is the "covering" approach, and S2 does it natively.
- Combine with filters and ranking inside the index, so that only matching, high-scoring candidates are returned, not every business in the area. This is what a search engine does.
Redis GEO is a geohash index in disguise. GEOADD stores each member in a sorted set with a 52-bit interleaved geohash as its score; GEOSEARCH ... BYRADIUS computes the neighbouring cells, issues ZRANGEBYSCORE range queries on the integer scores, and post-filters by distance. It is excellent for millions of moving points. For static businesses, it is a fine cache of "id by location" but cannot apply text, category and rating filters in the same operation.
Quadtree
A quadtree partitions the plane adaptively. Start with one node covering the whole world. If a node holds more than a threshold of points (say 100 businesses), split it into four equal quadrants (NW, NE, SW, SE) and push the points down. Repeat. Dense Manhattan ends up with tiny leaves of a block or two; the Sahara ends up as one huge leaf.
The diagram shows the adaptive shape: the tree is deep where businesses are dense and shallow where they are sparse, so every leaf holds a bounded number of points regardless of where it is on the map. A geohash grid, by contrast, uses the same cell size everywhere, so a cell in midtown Manhattan may hold tens of thousands of businesses while a cell in Nevada holds none.
Querying a quadtree for a radius search:
- Start at the root. For each child whose rectangle intersects the search circle, descend.
- At each leaf that intersects, test every point against the exact distance.
- Collect the matches.
The cost is proportional to the depth (about log₄ of the number of leaves) plus the number of points in intersecting leaves. Because leaves have at most 100 points, a query in a dense area touches a handful of leaves and a few hundred candidates.
Sizing a quadtree for 10 million businesses. With a leaf capacity of 100, we need at least 100,000 leaves; in practice about 200,000 to 300,000 because many leaves are partly full. Total nodes are about 4/3 of the leaves, so roughly 300,000 to 400,000 nodes. Each leaf stores its points as (id, lat, lng): 24 bytes × 10M = 240 MB. Internal nodes need four child pointers and a bounding box: tens of bytes × 100,000 nodes = a few MB. The whole tree is roughly 250 to 300 MB in RAM. One server holds it easily; every search server can hold a copy.
Building and updating. Building from 10 million points takes seconds to a minute on one core: insert each point, splitting as needed, or bulk-build by sorting points and splitting recursively. Inserting a new business is O(depth); deleting one may leave a sparse node, which is fine. Since writes are rare, a common approach is:
- Each search server holds an in-memory quadtree built at startup from a snapshot (in a blob store) of all business ids and coordinates.
- New businesses and moves arrive through the change stream and are applied as incremental inserts.
- A nightly rebuild produces a fresh snapshot to clean up drift. Servers swap to the new tree using a blue/green swap: build in the background, then atomically flip a pointer.
- On server restart, load the snapshot and replay changes since the snapshot's timestamp from the change log. Startup takes about a minute, which is acceptable with enough replicas.
Quadtree problems to mention:
- Unbalanced depth. A pathological cluster (a mall with 300 businesses at almost the same coordinates) can force very deep splits. Cap the depth, and allow over-full leaves at the cap.
- Poor disk layout. A pointer-based quadtree is great in RAM but awkward on disk, because random pointer chasing causes random I/O. That is why disk-based systems prefer geohash keys in B-trees or R-trees with page-sized nodes.
- Midpoint splits ignore data. A quadtree always splits at the geometric midpoint. A k-d tree splits at the median point, alternating latitude and longitude, so each half holds the same count. That produces balanced trees, but rebalancing after inserts is awkward.
BKD trees (Lucene and Elasticsearch)
Lucene (and so Elasticsearch and OpenSearch) indexes geo_point fields with a block k-d tree (BKD). Each immutable index segment builds a k-d tree over its points, with leaf blocks of around 512 to 1,024 points stored contiguously on disk. Because segments are write-once, the tree is built once with perfectly balanced median splits; updates create new segments, and background merges rebuild trees. Queries such as geo_distance or geo_bounding_box walk the tree, skipping blocks whose bounding boxes fall outside the shape and bulk-accepting blocks entirely inside it. The BKD design is described by Procopiuc, Agarwal, Arge and Vitter in "Bkd-Tree: A Dynamic Scalable kd-Tree" (2003); Lucene's implementation is an adaptation of it. This is one reason a search engine is a natural home for our data: it gives a disk-friendly geo index alongside text and filters, maintained automatically.
R-trees and PostGIS
An R-tree (Guttman, "R-Trees: A Dynamic Index Structure for Spatial Searching", 1984) groups nearby objects into minimum bounding rectangles and nests them, like a B-tree whose keys are rectangles. Each node is a disk page. A query descends into any child whose rectangle intersects the search shape. R-trees handle shapes (polygons, lines) as well as points, which matters for place-name search, where neighbourhoods are polygons. Sibling rectangles can overlap, so a query may descend several paths. The R*-tree variant (Beckmann and colleagues, 1990) reduces overlap with smarter splits and reinsertion.
PostgreSQL's PostGIS extension implements R-tree-like indexes through the GiST (Generalized Search Tree) framework:
CREATE INDEX ON businesses USING GIST (location); -- location geography(Point)
SELECT id, name, ST_Distance(location, :pt) AS d
FROM businesses
WHERE ST_DWithin(location, :pt, 2000) -- metres, uses the GiST index
AND category_ids && ARRAY[12]
ORDER BY location <-> :pt -- KNN ordering via the index
LIMIT 20;ST_DWithin uses the index to find candidates whose bounding boxes are within range, then checks the exact distance. The <-> operator supports k-nearest-neighbour ordering directly from the index, which is ideal for "the 20 closest".
S2 and H3
- S2 (Google) projects the sphere onto the six faces of a cube and subdivides each face with a quadtree ordered along a Hilbert curve. The Hilbert curve preserves locality better than Z-order: consecutive cell ids are always adjacent cells. Cells are 64-bit integers at 31 levels, from about 85 million km² down to under 1 cm². S2's RegionCoverer computes a small set of cells of mixed sizes that tightly covers any circle or polygon, which turns a radius query into a handful of integer range scans on any sorted store. Cells are nearly equal in area worldwide, avoiding geohash's distortion near the poles, and S2 handles the antimeridian (longitude ±180) without special cases. MongoDB's
2dsphereindex uses S2 cells; Google has used S2 widely. - H3 (Uber) tiles the globe with hexagons at 16 resolutions. Every hexagon has six neighbours at equal distance, so "rings" of neighbours (
gridDisk(cell, k)) approximate circles well. That is great for aggregation and analytics (demand per hexagon, ratings density). H3 indexes do not have a space-filling-curve ordering, so a contiguous key range is not a contiguous area; lookups use explicit cell sets:WHERE h3_cell IN (...).
Which index should we choose?
| Option | Strengths | Weaknesses | Fit here |
|---|---|---|---|
| Geohash column + B-tree | Works in any SQL or KV store; simple; prefix scans | Boundary issue, over-fetch, distortion near poles | Good for a simple, DB-only solution |
| In-memory quadtree | Adaptive to density, very fast, simple code | Custom service to build and operate; RAM-only | Good when you need a custom geo service |
| PostGIS GiST | Mature, exact, KNN, polygons; transactional | Combining with rich text ranking is harder; scaling = replicas | Good up to moderate QPS |
Elasticsearch BKD (geo_point) | Geo + text + filters + scoring in one query; replicas | Eventually consistent copy; operational cost | Best fit at this scale |
| S2 / H3 cells | Even cells, tight coverings, analytics | Library dependency; H3 has no range ordering | Good for precomputed coverings and analytics |
The decision mostly comes down to two questions. Does the query combine geography with other conditions and ranking? Then a search engine or PostGIS keeps everything in one index pass. Is the data static or moving? Static data favours read-optimised structures that are rebuilt occasionally, while moving data favours structures with cheap in-place updates.
Recommendation. Use a search engine with a geo field for the main search path, because it combines everything the query needs. Mention that a quadtree or geohash index is the right answer if the interviewer wants you to build the geo layer yourself, and be ready to explain both in depth. The universal rule for all options: use the index to get candidates, then post-filter by exact distance.
3. Searching with text, categories and filters efficiently#
Real queries are never "everything within 2 km". They are "pizza within 2 km, rating at least 4, price 1 or 2, open now, sorted by relevance". The design question is how to evaluate several selective conditions at once without scanning. There is a progression of approaches, and walking through it is a good way to show depth.
Approach 1: separate indexes in the relational database
Put a B-tree on category, a B-tree on geohash, and a full-text index on name, then let the query planner combine them. PostgreSQL can intersect several index results with bitmap index scans (BitmapAnd), so this works better than people expect. But:
- The planner must estimate selectivity for each condition, and it often guesses wrong. "Restaurants" is not selective; "within 2 km in Manhattan" is very selective; "within 2 km in rural Montana" returns nothing.
ILIKE '%pizza%'cannot use a B-tree. Use a trigram index (pg_trgm, GIN) for substring and fuzzy matches, or atsvectorcolumn with a GIN index for word-based full-text search.- Relevance ranking (
ts_rank) is basic compared with a search engine's BM25 scoring, and blending it with distance and rating in SQL gets awkward.
A respectable middle ground on PostgreSQL is a single query that uses PostGIS for geography, a GIN index for text and category arrays, and simple scoring in ORDER BY:
SELECT b.id, b.name,
ST_Distance(b.location, :pt) AS dist_m,
b.rating_sum::float / NULLIF(b.review_count, 0) AS avg_rating
FROM businesses b
WHERE ST_DWithin(b.location, :pt, 2000)
AND b.search_vec @@ plainto_tsquery('english', 'pizza')
AND b.category_ids && :category_and_descendants
AND b.price_level = ANY(:prices)
AND b.rating_sum >= 4 * b.review_count
ORDER BY ts_rank(b.search_vec, plainto_tsquery('english', 'pizza'))
* exp(-ST_Distance(b.location, :pt) / 1500.0) DESC
LIMIT 20;This is a perfectly defensible answer for a moderate-scale system, especially because the data set is small enough to replicate to many read replicas. Its limits show up at tens of thousands of QPS with complex ranking, or when the product team wants typo tolerance, synonyms ("pizzeria" for "pizza") and multi-language analysis.
Approach 2: a search engine (Elasticsearch / OpenSearch)
A search engine stores one denormalised document per business and builds a separate optimised structure for each field type:
- Inverted index for text fields (name, category names, tags, maybe review snippets), with analysers for lowercasing, stemming, synonyms and multiple languages, and BM25 relevance scoring.
- BKD tree for the
geo_pointlocation field. - Doc values (columnar storage) and BKD trees for numeric fields (rating, review count, price), and inverted terms for keyword fields (category ids, location ids, open-hour slots).
The query engine evaluates each condition against its own index structure, producing iterators of matching document ids, and intersects them efficiently using skip lists. Filters (non-scoring conditions) are cached as bitsets. Scoring is computed only for documents that pass every filter. (See Elasticsearch and Search Systems.)
The important idea is the order of operations: cheap, cacheable filters shrink the candidate set first, and only the survivors pay for scoring. A query for "pizza" within 2 km in San Francisco might start with about 30,000 businesses inside the circle, drop to about 400 matching "pizza", then to about 150 open now with rating 4 or higher. Only those 150 are scored. Each shard returns its local top 20, and the coordinator merges them. With two shards, it merges 40 candidates to produce 20.
The business document:
{
"id": "b_812",
"name": "Tony's Pizza Napoletana",
"categories": ["pizza", "italian", "restaurants"],
"location": { "lat": 37.8003, "lon": -122.4091 },
"avg_rating": 4.6,
"review_count": 1832,
"price": 2,
"open_slots": [1130, 1131, 1132, 1133],
"location_ids": ["loc_sf", "loc_sf_north_beach"],
"status": "open"
}And the query:
{
"query": { "function_score": {
"query": { "bool": {
"must": [{ "multi_match": { "query": "pizza",
"fields": ["name^3", "categories^2"] } }],
"filter": [
{ "geo_distance": { "distance": "2km",
"location": { "lat": 37.7599, "lon": -122.4148 } } },
{ "range": { "avg_rating": { "gte": 4 } } },
{ "terms": { "price": [1, 2] } },
{ "term": { "open_slots": 1131 } },
{ "term": { "status": "open" } } ] } },
"functions": [
{ "gauss": { "location": { "origin": "37.7599,-122.4148",
"scale": "1km", "decay": 0.5 } } },
{ "field_value_factor": { "field": "review_count",
"modifier": "log1p", "factor": 0.1 } } ],
"score_mode": "multiply" } },
"size": 20
}filterclauses do not contribute to scoring and are cacheable. The geo filter, rating filter, price filter and open-now filter all go here.mustcontains the text match, which contributes a BM25 score. If the query is empty (pure "near me" browsing), usematch_all.function_scoremultiplies the text score by a Gaussian distance decay (a business 1 km away scores half of one at 0 km) and a dampened popularity factor. The exact blend is a product decision, tuned by experiments and, at scale, replaced by a learned ranking model.
Ranking: relevance, distance and quality
What does "best" mean for local search? It is a blend:
- Text relevance: does the business match "pizza"? A pizzeria named "Tony's Pizza" beats an Italian restaurant that mentions pizza once.
- Distance: nearer is better, but not linearly. A 4.8-star place at 1.2 km often beats a 3.1-star place at 300 m.
- Quality: average rating, but adjusted for review count, since a single 5-star review means little. A Bayesian average helps here (deep dive 4).
- Popularity and engagement: click-through rate, bookmarks, check-ins.
- Personalisation (out of scope): past behaviour, preferences.
A common production pattern is two-stage ranking: the search engine returns the top few hundred candidates using a cheap scoring function, then a re-ranker (often a gradient-boosted tree model) scores those few hundred with richer features in the Search Service. This keeps the expensive model off the full candidate set. We keep it simple in the core design and mention this as the evolution.
Open now
"Open now" is surprisingly tricky:
- Opening hours are in the business's local time zone, and the user's "now" must be converted to that zone, including daylight saving.
- Hours can wrap midnight (a bar open 18:00 to 02:00), have multiple intervals per day (lunch and dinner), and have holiday exceptions.
A clean index-friendly encoding: divide the week into 15-minute slots (7 × 24 × 4 = 672 slots) in the business's local time, and store the list of open slot numbers, or a bitmap, in the document. At query time, compute the current slot in the business's local time zone. If the search area spans a single time zone, which is almost always true for a few-kilometre radius, compute one slot number and filter open_slots = N. For wide searches spanning zones, compute one slot per zone and filter (tz = A AND slot = N) OR (tz = B AND slot = M). Holiday exceptions update the document from the change stream on the day.
The cost: up to 672 terms per document. In practice a typical business is open around 60 to 80 hours a week, so roughly 240 to 320 slot terms. Across 10 million businesses this is a few billion postings, compressed well by the inverted index. An alternative is to store weekly intervals as integer ranges (minutes since the start of the week) with a range field type, which some engines support efficiently.
Pagination
Local search rarely goes deep: very few users go past page two. So:
- Offset pagination capped at, say, 10 pages is fine. The cursor encodes the offset (and a query fingerprint, so a cursor cannot be reused with different filters).
- Deep pagination in a search engine is expensive: page 50 means every shard must produce its top 1,000 and the coordinator merges them. Elasticsearch caps
from + sizeat 10,000 by default for this reason. For deep traversal (exports, crawlers), usesearch_afterwith a sort tiebreaker. - Because ratings can change between pages, results may shift slightly. That is acceptable for this product.
Categories as a hierarchy
A search for "Restaurants" should include "Pizza" and "Thai". Rather than expanding the category tree at query time, denormalise ancestors into the document at index time: a pizzeria's categories field contains pizza, italian, restaurants and food. A category filter then becomes one term lookup. The category tree is small (a few thousand nodes), cached in memory by the indexer.
4. Efficiently calculating and updating average ratings#
Every search result shows an average rating and a review count. Reads happen about 20,000 times per second; reviews arrive about 12 to 50 times per second. Precompute on write, read for free.
The wrong approaches
- Compute on read:
SELECT AVG(rating) FROM reviews WHERE business_id = ?for every business in every search result. Twenty businesses per search × 20,000 searches per second = 400,000 aggregate queries per second, some over thousands of rows. Impossible. - Store only
avg_ratingand update it with application arithmetic: read the average and count, compute(avg × count + new) / (count + 1), and write back. Two concurrent reviews both read the old values; one update is lost (see Concurrency Control and Database Locking). Floating-point drift also accumulates over millions of updates. - Periodic batch recomputation only: a nightly job computes averages. Correct, but a new review does not show up in the rating for up to a day, which feels broken to the author.
The right approach: atomic sum and count
Store rating_sum (integer) and review_count (integer) on the business row, and update both with atomic increments in the same transaction as the review insert:
BEGIN;
INSERT INTO reviews (id, business_id, user_id, rating, body, created_at)
VALUES (:id, :biz, :user, :rating, :body, now());
UPDATE businesses
SET rating_sum = rating_sum + :rating,
review_count = review_count + 1
WHERE id = :biz;
COMMIT;- Atomic: the
UPDATE ... SET x = x + ntakes a row lock, so concurrent reviews serialise on the business row and none is lost. - Exact: integers do not drift. The average
rating_sum / review_countis computed when read or when indexing. - Consistent: the review and the aggregate commit together; either both happen or neither does.
Edits adjust the sum by the difference: rating_sum = rating_sum + (:new - :old), with review_count unchanged. Deletes subtract: rating_sum = rating_sum - :old, review_count = review_count - 1. Read the old rating inside the same transaction with SELECT ... FOR UPDATE on the review row so that a concurrent edit cannot race.
Is the row lock a hotspot? At 50 reviews per second globally, contention on any single business is negligible. Even a viral business getting 10 reviews per second is fine: each transaction holds the lock for a millisecond or two. Contrast this with a like counter on a celebrity post at 10,000 per second, where you would need sharded counters (see Pattern: Dealing with Contention). It is worth saying in the interview that you checked and contention is not a problem at this write rate.
The sequence shows why atomic increments are safe. Each UPDATE reads the latest committed value under the row lock, so B's increment applies on top of A's. With read-modify-write in the application, both would have read the same old sum, and one review would vanish from the aggregate.
A rating histogram is a nice touch: store counts per star (stars_1 ... stars_5). The business page shows the distribution bar chart, and the sum and count derive from it: count = Σ stars_i and sum = Σ i × stars_i. Same atomic-increment technique.
Alternative: asynchronous aggregation
If reviews lived in a different database from businesses (for example, reviews in Cassandra or DynamoDB for scale), a cross-store transaction is not available. Then:
- Insert the review.
- Publish a
review_createdevent via an outbox or CDC (see Change Data Capture and the Outbox Pattern). - An aggregator consumer applies the increment to the business's aggregates.
This requires idempotent application: the consumer may see an event twice after a retry, and a naive +rating would double-count. Track applied review ids, or make the update conditional on a per-business version (see Idempotency and Safe Retries). The aggregate lags by seconds. At our write rate the synchronous transactional approach is simpler, so we prefer it, but this variant matters if the interviewer pushes on sharding reviews.
Reconciliation
Even with transactions, bugs, manual data fixes and restored backups can drift aggregates away from the truth. A nightly reconciliation job recomputes SUM(rating), COUNT(*) per business from the reviews table (on a replica or the analytics warehouse) and corrects mismatches, emitting a metric for how many it fixed. A nonzero count points to a bug worth investigating.
Bayesian average: displaying fair ratings
A new restaurant with one 5-star review has an average of 5.0; an established one with 2,000 reviews averaging 4.7 is clearly the better bet. Sorting by raw average promotes noise. A Bayesian average shrinks each business's average toward a prior:
bayes_avg = (C * m + rating_sum) / (C + review_count)
m = global mean rating (e.g. 3.9)
C = confidence constant, roughly the typical review count (e.g. 20)
One 5-star review: (20*3.9 + 5) / 21 = 3.95
2,000 reviews, avg 4.7: (20*3.9 + 9400) / 2020 ≈ 4.69Use the Bayesian average for ranking, and still display the raw average and count to users, because a displayed rating that does not match the reviews feels dishonest. Compute the Bayesian value in the indexer and store it as a separate field (rank_rating). Alternatives are the lower bound of a Wilson score interval or a Bayesian approach over the full star distribution; any of them beats sorting by the raw mean.
5. Ensuring one review per user per business#
The requirement looks trivial, and the naive implementation is subtly broken.
The naive check-then-insert:
existing = SELECT 1 FROM reviews WHERE user_id = :u AND business_id = :b
if not existing:
INSERT INTO reviews ...Two requests from the same user (a double tap on "Submit", a retry after a timeout, or two devices) run concurrently. Both SELECTs see no existing row, and both INSERTs succeed: two reviews, and the aggregate counted twice. An application-level check is a race condition, not a guarantee.
The fix: a database-enforced unique constraint.
ALTER TABLE reviews
ADD CONSTRAINT one_review_per_user UNIQUE (business_id, user_id);Now the database guarantees it: the second concurrent INSERT blocks on the unique index entry until the first commits, then fails with a unique-violation error. The service catches that error and returns 409 Conflict with the id of the existing review, so the client can offer "edit your review". Because the review insert and the aggregate update are in the same transaction, a failed insert rolls back without touching rating_sum. Use INSERT ... ON CONFLICT (business_id, user_id) DO NOTHING RETURNING id in PostgreSQL to detect the conflict without an exception.
Why (business_id, user_id) and not (user_id, business_id)? Both enforce the same uniqueness. The column order matters for which queries the index also serves: (business_id, ...) leads with the column we partition by and list by. We keep a separate index on (user_id, created_at) for "my reviews".
Idempotency for retries. A unique constraint stops duplicates, but a client retrying after a timeout on a successful write receives 409 instead of the original 201. That is acceptable, since the client can fetch the existing review. For a cleaner contract, accept an Idempotency-Key header and store the response for a few hours, returning the same 201 for a repeated key (see Idempotency and Safe Retries).
What if reviews are sharded? The unique constraint only works if both conflicting rows would land on the same shard. Sharding reviews by business_id keeps all reviews for a business, and so every possible duplicate, on one shard, where the local unique index enforces the rule. Sharding by review_id would scatter them and break the guarantee; you would need a separate uniqueness table keyed by (business_id, user_id). This is a good example of choosing the partition key so that invariants stay local (see Partitioning and Sharding).
In a key-value store such as DynamoDB, make the primary key itself enforce uniqueness: partition key business_id, sort key user_id, and write with a condition expression attribute_not_exists(user_id). A second write fails the condition atomically. The cost: listing reviews by recency needs a secondary index on (business_id, created_at) (see Amazon DynamoDB in Practice).
Beyond the constraint: the "one person" problem. A unique constraint stops one account reviewing twice. It does not stop one person with ten accounts. That is the spam and fraud problem (deep dive 12): device fingerprints, account age, reputation and anomaly detection.
6. Searching by predefined location names#
"Pizza in the Mission District" or "hotels in Brooklyn" does not have a centre and radius. It has a named area with an irregular boundary. Using a circle around the centroid of Brooklyn would include parts of Manhattan and Queens and miss Brooklyn's edges. We need polygon containment.
Option 1: polygon intersection at query time
Store each place's boundary polygon. At query time, fetch the polygon and ask the index for businesses inside it: PostGIS ST_Contains(polygon, location), or Elasticsearch geo_shape or geo_polygon queries. This works, but:
- City and neighbourhood polygons can have thousands of vertices (coastlines, rivers), making point-in-polygon tests expensive, especially across many candidates.
- Every query pays the geometry cost again, for data that almost never changes.
Option 2 (preferred): precompute membership at write time
Since both businesses and place boundaries are static, compute which places each business is in when the business is created or moved, and store those location ids on the business:
- The gazetteer (a
locationstable) holds each named place: id, name, type (country, region, city, neighbourhood, postcode), parent id, and polygon. - When a business is indexed, run a point-in-polygon lookup against the gazetteer's spatial index (PostGIS GiST on polygons) to find all containing places. A business in the Mission might yield
[loc_us, loc_ca, loc_sf, loc_sf_mission, loc_zip_94110]. - Store the list as
location_idsin the business row and the search document. - A place-name search becomes a simple term filter:
{ "term": { "location_ids": "loc_sf_mission" } }. That is as cheap as a category filter.
When polygons change (a city redraws a neighbourhood boundary, or the gazetteer adds new places), run a backfill job for affected businesses: query the businesses inside the old polygon's or new polygon's bounding box, recompute their memberships and re-index them. Thanks to the spatial index this touches only businesses near the change.
Resolving the name: the Location Service
Users type "mission dis". The Location Service provides autocomplete over place names: a prefix index such as a trie or an Elasticsearch completion field or search_as_you_type over the gazetteer, ranked by population or search popularity and biased toward the user's current location. Typing "Springfield" from Illinois should suggest Springfield, IL before Springfield, MA. The client then sends the chosen location_id to the search endpoint. (The autocomplete mechanics are the same as in the search-autocomplete case study.)
Because membership was computed when each business was indexed, the search cluster never sees a polygon at query time. It sees one more term filter, which is as cheap as filtering by category.
Ambiguity and hierarchy:
- Names are ambiguous: there are dozens of Springfields, and "Chinatown" exists in many cities. Always show the parent ("Chinatown, San Francisco") and resolve by id, not by name.
- Places nest: a neighbourhood is inside a city, inside a county, inside a state. Storing all ancestors in
location_idsmeans a search in "San Francisco" matches businesses tagged with any SF neighbourhood, without a hierarchical query. - Places overlap: postcodes cross neighbourhood boundaries. That is fine, because membership is a set.
Combined with distance ranking. With a place filter instead of a radius, distance from what? Use the user's location if it is inside or near the area, otherwise the polygon's centroid or a "representative point", or sort by rating or relevance alone.
Where does gazetteer data come from? Public sources such as OpenStreetMap boundaries, government census and postal data, and commercial providers. Neighbourhood boundaries are often informal and disputed, so many products curate their own. Treat it as a periodically refreshed reference data set with its own versioning.
Viewport search ("search this area")
A closely related query: the user pans the map and taps "search this area". The input is a bounding box rather than a circle or polygon: a geo_bounding_box filter in Elasticsearch, or ST_MakeEnvelope with && in PostGIS. Remember the antimeridian: a box from longitude 170 to -170 crosses ±180 and must be split into two boxes. Deep dive 11 covers map-specific concerns such as clustering pins.
7. Scaling reads to 20,000+ searches per second#
With a 1,500:1 read:write ratio, read scaling is the main scaling problem. The playbook is in Pattern: Scaling Reads. The layers, from the outside in:
Each layer removes a share of the traffic before it reaches a more expensive layer. The primary database sees only writes and replication.
Layer 1: CDN and client
- Static assets and photos come from the CDN. Photos are immutable (a new photo gets a new key), so they cache forever at the edge.
- Search responses are personal to a location and usually not CDN-cached. Some products cache public, anonymous "browse" pages (such as "Best pizza in San Francisco" landing pages, which also matter for SEO) at the CDN for minutes.
- Client-side caching: the app keeps the last results; returning to the list after viewing a business does not re-query.
Layer 2: search result cache with quantised keys
Exact latitude and longitude make every query unique: two users standing 10 m apart send different coordinates, so a naive cache key never hits. Quantise the location: round the query point to a cell (geohash length 7, about 150 m, or an S2 cell at a similar level), and use the cell plus the normalised query plus filters as the key:
key = "search:v3:" + geohash7(lat, lng) + ":" + normalise(query)
+ ":" + radius_bucket + ":" + filters_hash + ":" + page- Shifting the origin by up to about 150 m barely changes a 2 km result set; recompute exact distances from the true location when serving.
- Radius buckets (500 m, 1 km, 2 km, 5 km, 10 km, 25 km) instead of arbitrary radii further increase sharing.
- TTL of 30 to 120 seconds. Ratings and hours drift slowly, so the result is "fresh enough". Stale open-now flags are the main risk; compute open-now when serving from cached hours, or keep the TTL under the 15-minute slot size.
- Hit rates: query popularity follows a heavy-tailed distribution. In dense cities at mealtimes, a large share of queries are "restaurants", "coffee", "pizza" and similar head terms in a limited number of cells. Hit rates of 30 to 60 percent are plausible for the head; the tail ("vegan gluten-free ramen open late") always misses. Even a 40 percent hit rate removes 8,000 QPS from the search cluster at peak.
- Protect against stampedes on popular keys at expiry with request coalescing or a short lock, and jitter TTLs (see Cache Failure Modes: Stampedes, Hot Keys and Penetration).
Layer 3: the search cluster
Because the index is small (10 million documents; maybe 20 to 50 GB including text and slot terms), we choose a layout optimised for throughput, not size:
- Few primary shards (for example 2 to 5) so that each query fans out to few shards. Fewer shards mean lower coordination overhead and lower tail latency. A single-shard index is possible if it fits; it gives the lowest fan-out.
- Many replicas. Each replica serves queries independently. Need more QPS? Add replicas and nodes. With 5 shards and 9 replicas (10 copies), 50 shard copies spread across about 25 nodes.
- All data in memory. Ensure the index files fit in the OS page cache so that queries never touch disk.
- Adaptive replica selection (Elasticsearch has it) routes each shard request to the copy with the best recent response times, smoothing out slow nodes.
Alternatively, partition by geography. Index per region (North America, Europe, Asia) so that queries go to one regional index. That reduces per-query work but adds routing complexity; at 10 million documents it is optional. It becomes attractive when combined with multi-region serving (deep dive 10).
Capacity math. Suppose one node handles 1,000 typical geo-plus-text queries per second for a single shard copy at acceptable latency. That depends on hardware and query shape, so measure; it is not a constant. Peak is 20,000 QPS with a 40 percent cache hit rate, leaving 12,000 QPS to the cluster. With 5 shards, each query costs 5 shard-requests: 60,000 shard-requests per second. At 1,000 per node per second that is 60 nodes; with a single-shard index, 12 nodes. This is why fewer shards and more replicas wins for a small, read-heavy index. Add 30 to 50 percent headroom for node failure and growth (see Capacity Planning and Load Testing).
Layer 4: business pages from cache and replicas
- Cache-aside in Redis for
biz:{id}(TTL 10 minutes, explicit invalidation on update) andreviews:{id}:newest:p0(first page, TTL 1 to 5 minutes, invalidated on new reviews). - Read replicas behind the cache. With a 90 percent cache hit rate, 35,000 peak page views become 3,500 database reads per second, comfortably served by a few replicas.
- Hot keys: a viral business can receive tens of thousands of requests per second for one key, which concentrates on a single Redis shard. Mitigate with a small in-process cache (a few seconds TTL) in each Business Service instance, or by replicating hot keys under several suffixes (see Distributed Caching with Redis and Memcached).
What we do not need
- No sharding of the search data for size. It fits.
- No complex write scaling. 50 writes per second.
- No strong consistency on the read path. Seconds of lag are fine; read-your-writes for the author is handled specially (deep dive 9).
Saying these explicitly shows you sized the problem rather than reaching for every scaling technique by reflex.
8. Serving business pages, reviews and photos#
The business page is the second-hottest path. It combines several reads: business details, the first page of reviews (with author names and avatars), photo thumbnails, the rating histogram, and maybe "people also viewed".
Assembling the page. A Backend-for-Frontend endpoint (GET /businesses/{id}/page) assembles everything in one round trip: fetch the business from cache, fetch the first review page from cache, batch-fetch the authors (MGET user:{id}), and attach CDN photo URLs. One request from a mobile client instead of four saves hundreds of milliseconds on high-latency networks.
Review listing and sorting.
- Newest first: index
(business_id, created_at DESC); keyset pagination withWHERE business_id = ? AND (created_at, id) < (:c, :id) ORDER BY created_at DESC, id DESC LIMIT 20. Keyset pagination is stable and does not slow down on deep pages, unlikeOFFSET. - Highest or lowest rated: index
(business_id, rating, created_at). - Most helpful / recommended: a precomputed
quality_scoreper review (helpful votes, author reputation, length, recency), recomputed asynchronously and indexed as(business_id, quality_score DESC). Yelp's product separates "recommended" reviews from others using automated software; the details of their algorithm are not public. - Search within reviews ("reviews mentioning 'patio'"): index review text in the search engine with
business_idas a filter field. It is a separate index from the business index.
Large businesses. A landmark might have 50,000 reviews. Listing is still a single-partition range scan, and the first page is cached. Deep pages are rarely visited; keyset pagination makes them cheap anyway.
Photos.
- Upload: the client requests a pre-signed URL from a Photo Service and uploads directly to object storage, so the app servers never handle bytes. An event triggers a pipeline that generates thumbnails at several sizes, runs content moderation, and records the photo row.
- Serving: thumbnails and full-size images come from the CDN with long cache lifetimes; keys include a content hash so updates are new objects.
Caching and invalidation summary:
| Data | Cache | TTL | Invalidation |
|---|---|---|---|
| Business details | Redis biz:{id} | 10 min | On business update event |
| First page of reviews | Redis reviews:{id}:{sort}:p0 | 1 to 5 min | On review create, edit or delete for that business |
| User profile snippets | Redis user:{id} | 1 h | On profile update |
| Search results | Redis search:... | 30 to 120 s | TTL only (too many keys to target) |
| Photos | CDN | Days to forever | New key per version |
Search results are not invalidated on writes: a single review can affect thousands of cached search keys (every query whose results include that business), and tracking that mapping costs more than it is worth. The short TTL bounds staleness instead. This is a deliberate trade-off (see Cache Eviction and Invalidation).
9. The write path: keeping the search index and caches consistent#
The relational database is the source of truth; the search index and caches are derived views. The design question is how changes flow from one to the others without losing updates or serving stale data for long.
Why not dual-write?
The tempting approach: the Review Service writes to the database, then calls Elasticsearch to update the document. Problems:
- If the service crashes between the two writes, the index never learns about the change.
- If the Elasticsearch call fails and is retried later, two concurrent updates can arrive out of order, and an older rating overwrites a newer one.
- Every writer (Review Service, Business admin tools, backfills) must remember to dual-write correctly.
Change data capture
Instead, capture committed changes from the database's log:
- Debezium (or a similar connector) tails the PostgreSQL write-ahead log (via logical replication) or the MySQL binlog, and publishes every committed row change to Kafka topics such as
db.businessesanddb.reviews, keyed by business id. - Indexer workers consume the
businessestopic. For each change they build the full denormalised document for the business: read the current row (or use the after-image in the event), computeavg_ratingandrank_rating, expand categories to ancestors, compute open slots, look uplocation_ids, and upsert it into the search index. - The indexer also invalidates caches (
biz:{id}), making invalidation a side effect of the same reliable stream.
Ordering and idempotency. Kafka preserves order per partition, and keying by business id keeps all changes to one business in order. Indexing the full document (not a delta) makes the operation idempotent: replaying an event produces the same document. To guard against out-of-order writes, for example after a consumer rebalance, use Elasticsearch external versioning with the database's commit position or a per-row version number: the index rejects any write with a lower version than the stored one. (See Change Data Capture and the Outbox Pattern.)
Lag. End to end, from commit through WAL, Kafka, indexer and index refresh, is typically a second or a few seconds. Elasticsearch makes new writes searchable after a refresh, every 1 second by default. For a read-heavy index you might lengthen it to 5 to 30 seconds to reduce segment churn, at the cost of a little extra staleness.
Full rebuilds. Because the index is derived, we can rebuild it from scratch: create a new index, bulk-load from a database snapshot (10 million documents takes minutes to an hour, depending on resources), replay the CDC stream from the snapshot's log position until caught up, then atomically switch an index alias from the old index to the new one. This is how mapping changes, analyser changes and ranking-field changes are deployed safely: blue/green for indexes.
Read-your-writes for review authors
A user posts a review and immediately sees the business page. If the page is served from a replica or cache that has not caught up, their review is missing: "Did it fail?" Fixes, in order of preference:
- Return the created review in the POST response and have the client insert it into the displayed list locally. Cheapest and most robust.
- Invalidate the business's review caches synchronously in the write path, then have the next read go to the primary (or a replica known to be caught up) for a few seconds for that user. Track "this user wrote at log position X" in their session, and route their reads to a replica that has replayed past X, or to the primary.
- Search results can stay eventually consistent: a rating change of 0.01 in search for a few seconds is invisible.
(See Consistency Models for read-your-writes and monotonic reads.)
Business updates and closures
Owners and admins edit hours, phone numbers and status. These go through a Business admin service to the primary database and flow through the same CDC path. Closures are the most important update to propagate: a "permanently closed" flag should remove the business from search results within minutes. Search queries filter status = open, so a re-index with the new status hides it immediately after refresh.
10. Sharding, partitioning and multi-region#
Do we need to shard?
- Businesses: 10 to 20 GB. No.
- Search index: tens of GB. Shard lightly for parallelism if useful, mostly replicate.
- Reviews: about 500 GB growing at about 365 GB per year. A single well-provisioned PostgreSQL or MySQL server can hold a few TB, so it fits for several years. When it outgrows one node, or if write throughput or vacuum and backup times become a problem, partition reviews by
business_id.
Why business_id?
- The dominant read, "reviews for business X sorted by date", hits one partition.
- The uniqueness invariant
(business_id, user_id)stays local to a partition (deep dive 5). - The aggregate update (
businesses.rating_sum) is co-located if businesses are partitioned the same way. - The secondary read, "reviews by user U", becomes scatter-gather. Serve it from a separate, asynchronously maintained index keyed by
user_id(a global secondary index), since it is a rare, non-critical query.
Hot partitions: a famous business with 100,000 reviews is still small: 100 MB on one partition. Hash partitioning on business_id spreads businesses evenly (see Consistent Hashing).
Geographic sharding of the search index? Splitting by region (or by geohash prefix) means a query typically hits one shard, which is attractive. The costs: queries near region boundaries must hit two shards; the regions are uneven (New York versus Wyoming); and resharding is painful. With an index this small, replicating the whole index is simpler. Geographic splitting makes sense mainly when tied to multi-region deployment.
Multi-region deployment
With users worldwide, serving from a single region adds 100 to 250 ms of round-trip latency for distant users, eating much of the 500 ms budget.
- Read path everywhere: deploy search clusters, caches and read replicas in each major region (for example US, Europe, Asia-Pacific). Each region can hold the full index (it is small) or its own region's businesses plus a copy of the rest for travellers.
- Write path in one primary region: reviews at 50 per second can all go to one primary database; cross-region write latency of 100 to 200 ms is acceptable for posting a review. CDC fans changes out to every region's indexers.
- Failover: if the primary region fails, reads continue everywhere from local copies (slightly stale), and writes are either queued at the edge or the primary is promoted in another region (see Disaster Recovery and Backups and Multi-Region and Global Data).
A region losing its search cluster can fall back to another region's cluster at higher latency, which keeps availability high. The read path is stateless and replicated, so the system degrades gracefully.
11. Map views and marker clustering#
The core requirements exclude the map, but interviewers often ask "what about showing results on a map?"
- Viewport queries: the client sends a bounding box (and a zoom level). Use a
geo_bounding_boxfilter, return the top N by ranking, not all businesses in the box. At city zoom, a box may contain 50,000 businesses; we return 50 to 100 pins. - Clustering pins: at low zoom levels, individual pins overlap. Cluster server-side with a geohash grid aggregation (Elasticsearch
geohash_gridorgeotile_gridaggregations): return a count per cell and the centroid (geo_centroidsub-aggregation), and the client renders "253" bubbles. As the user zooms in, the precision increases and clusters split. Client-side clustering libraries work for a few thousand points. - Caching tiles: cluster results for popular map tiles (at zoom level z, tile x, y) are highly cacheable because they do not depend on the exact user location, only on the tile. This is the same idea as quantised search keys.
- Re-query on pan: debounce pan events (for example 300 ms) and skip re-querying if the new viewport is mostly inside the previous one.
12. Reviews integrity: spam, fake reviews and abuse#
Review fraud is the existential risk for a review platform: if ratings can be bought, they are worthless. Out of scope for the core design, but a senior answer should sketch the defences.
Threats:
- Fake positive reviews from owners, friends or paid review farms.
- Fake negative reviews from competitors.
- Review bombing: a sudden wave of negative reviews after a viral news story.
- Incentivised reviews: "a free dessert for 5 stars".
- Spam and abusive content: links, ads, hate speech.
Defences, layered:
- Write-path checks (synchronous, cheap): rate limits per user, device and IP; minimum account age or verified phone for reviewing; text classifiers for spam and abuse; duplicate-text detection (the same text posted to many businesses).
- Asynchronous scoring: a pipeline scores each review using features such as the author's history and trust score, device and network fingerprints shared with other accounts, burstiness (many reviews for one business in a short window), geographic plausibility (did the user ever appear near the business?), and the review graph (clusters of accounts that review the same set of businesses). Low-confidence reviews are held for moderation, shown but excluded from the average, or labelled "not recommended".
- Aggregate protection: compute the displayed rating from trusted reviews only, or weight reviews by author trust. The aggregation math from deep dive 4 extends naturally: keep
trusted_rating_sumandtrusted_review_countalongside the raw values. - Anomaly alerts: when a business's review velocity or average shifts sharply, freeze new reviews temporarily and show a notice, a technique some platforms use during review bombing.
- Human moderation and reporting: user reports feed a moderation queue, with decisions logged for appeals and model training.
Only reviews in the Published state count toward the trusted aggregate. Every state transition is an event that updates trusted_rating_sum and trusted_review_count with the same delta arithmetic as edits and deletes, so the displayed rating always matches the set of reviews users can see.
Scraping is the other abuse vector: competitors and aggregators crawl search results. Rate limits per IP and per account, bot detection at the edge, and capped pagination all help (see Security Fundamentals for System Design).
Privacy. User locations sent in search requests are sensitive. Do not log precise coordinates long-term: round them or drop them after use, and honour data-deletion requests for reviews and accounts (GDPR, CCPA). Deleting a user's account triggers deletion or anonymisation of their reviews and a recomputation of affected aggregates, using the same decrement path as a normal review delete.
Bottlenecks and Failure Modes#
| Failure / hotspot | Impact | Mitigation |
|---|---|---|
| Search cluster node fails | Fewer copies serve queries; latency rises on the remaining nodes | Many replicas per shard, adaptive replica selection, 30 to 50 percent headroom, automatic shard reallocation |
| Whole search cluster down in a region | Search unavailable in that region | Fail over to another region's cluster; as a last resort, degrade to a PostGIS query on read replicas for simple "near me" searches |
| CDC pipeline lag or outage | New reviews and closures do not appear in search; ratings drift | Alert on consumer lag; the primary database keeps working; replay from the retained Kafka offsets or WAL position once recovered; full rebuild via alias swap if needed |
| Out-of-order index updates | Older rating overwrites a newer one | Key events by business id; full-document upserts with external versioning |
| Cache stampede on a popular search key | Burst of identical queries hits the cluster at expiry | Request coalescing, jittered TTLs, early refresh of hot keys |
| Hot business page (viral) | One Redis shard overloaded | In-process cache for a few seconds; replicate hot keys; CDN-cache anonymous page JSON briefly |
| Dense areas (Manhattan, Tokyo) | Geo candidates explode; slow queries | Push filters and scoring into the engine, return top N only; finer cell coverings; cap radius by density |
| Sparse areas (rural) | Empty results for a small radius | Auto-expand the radius in steps (2 km, 10 km, 50 km) and show "results further away" |
| Duplicate review submissions | Double-counted ratings | Unique constraint on business and user, same-transaction aggregate update, idempotency keys |
| Aggregate drift from bugs or manual fixes | Displayed ratings wrong | Nightly reconciliation job with a mismatch metric |
| Primary database failure | Review writes fail | Synchronous standby with automatic failover; reads unaffected (replicas, caches, search); queue writes client-side and retry |
| Review bombing or fake reviews | Ratings manipulated | Trust-weighted aggregates, velocity anomaly detection, temporary review freezes, moderation |
What Interviewers Expect#
Mid-level.
- Gathers requirements and estimates well enough to notice that reads dominate and data is small.
- Produces a clean API and a working high-level design: services, a database, caching.
- Explains why a B-tree on latitude and longitude does not work, and proposes a geospatial index (geohash or quadtree) with the neighbour-cell trick and distance post-filtering.
- Stores average ratings rather than computing them on read.
- Uses a unique constraint for one review per user.
Senior.
- Compares geohash, quadtree, PostGIS and a search engine with clear trade-offs, and justifies a choice for this workload.
- Designs combined text, geo and filter queries, including open-now and category hierarchies, with ranking that blends relevance, distance and quality.
- Implements rating aggregation correctly: atomic sum and count in one transaction, handling edits and deletes, with a reconciliation job; knows why Bayesian averages matter for ranking.
- Keeps the search index consistent through CDC rather than dual writes, and handles ordering, idempotency and rebuilds.
- Scales reads with quantised cache keys, few shards and many replicas, and explains the capacity math.
- Handles place-name search by precomputing polygon membership.
Staff+.
- Frames the whole design around "static data, read-heavy, small index: replicate rather than shard", and pushes back on unnecessary complexity.
- Discusses multi-region serving, failure isolation between the read and write paths, and graceful degradation.
- Goes deep on ranking: two-stage retrieval and re-ranking, offline evaluation and A/B testing, position bias.
- Treats review integrity as a first-class concern: trust scoring, anomaly detection, and incentives.
- Covers operability: index migrations with aliases, CDC lag SLOs, reconciliation metrics, cost of replicas versus cache.
Deep Dive: Building an in-memory quadtree for 10 million businessesShow
If the interviewer asks you to build the geo layer yourself instead of using a search engine, a point quadtree with bucketed leaves is the classic answer. Here is the core in TypeScript, kept short:
type Pt = { id: number; lat: number; lng: number };
type Box = { minLat: number; minLng: number; maxLat: number; maxLng: number };
const CAP = 100, MAX_DEPTH = 24;
class QNode {
pts: Pt[] = [];
kids: QNode[] | null = null;
constructor(public box: Box, public depth: number) {}
insert(p: Pt): void {
if (this.kids) return this.child(p).insert(p);
this.pts.push(p);
if (this.pts.length > CAP && this.depth < MAX_DEPTH) this.split();
}
split(): void {
const { minLat, minLng, maxLat, maxLng } = this.box;
const mLat = (minLat + maxLat) / 2, mLng = (minLng + maxLng) / 2;
this.kids = [
new QNode({ minLat: mLat, minLng, maxLat, maxLng: mLng }, this.depth + 1),
new QNode({ minLat: mLat, minLng: mLng, maxLat, maxLng }, this.depth + 1),
new QNode({ minLat, minLng, maxLat: mLat, maxLng: mLng }, this.depth + 1),
new QNode({ minLat, minLng: mLng, maxLat: mLat, maxLng }, this.depth + 1),
];
for (const p of this.pts) this.child(p).insert(p);
this.pts = [];
}
child(p: Pt): QNode {
const mLat = (this.box.minLat + this.box.maxLat) / 2;
const mLng = (this.box.minLng + this.box.maxLng) / 2;
return this.kids![(p.lat >= mLat ? 0 : 2) + (p.lng >= mLng ? 1 : 0)];
}
search(q: Box, out: Pt[]): void {
const b = this.box;
if (q.minLat > b.maxLat || q.maxLat < b.minLat ||
q.minLng > b.maxLng || q.maxLng < b.minLng) return; // no overlap
if (this.kids) { for (const k of this.kids) k.search(q, out); return; }
for (const p of this.pts) out.push(p); // caller post-filters by haversine
}
}How a radius query uses it. Convert the circle to a bounding box: Δlat = r / 111,320 m per degree, and Δlng = r / (111,320 × cos(lat)) because meridians converge toward the poles. Call search(box), then keep only candidates whose haversine distance is at most r. The box overshoots the circle by a factor of 4/π (about 27 percent) in area, so roughly one candidate in five is discarded.
k-nearest instead of radius. For "the 20 closest", use a best-first traversal: a priority queue of nodes ordered by the minimum possible distance from the query point to the node's box. Pop nodes, expand children, and push points with their exact distances; stop when the 20th best point found is closer than the next node's minimum distance. This finds the true nearest neighbours without guessing a radius. It adapts automatically: in Manhattan it stops after a few hundred metres, and in rural Nevada it searches tens of kilometres.
Memory layout for speed. The pointer-based tree above is clear but cache-unfriendly in a garbage-collected runtime: 10 million small objects stress the heap. A production version flattens it:
- Sort all points by their quadtree leaf (equivalently, by a Z-order key at the leaf's depth), and store them in parallel typed arrays:
Float64Array lat,Float64Array lng,Int32Array id. For 10 million points that is 80 + 80 + 40 = 200 MB, contiguous. - Store nodes in an array, where each leaf holds a
[start, end)range into the point arrays and each internal node holds the index of its first child. - A query touches a few contiguous slices, which is fast and prefetch-friendly.
Persistence and startup. Write the flattened arrays to a single binary file (a "snapshot") in object storage after each nightly rebuild. A server starting up downloads the file (about 200 to 300 MB, seconds on a fast network), maps it into memory, and replays changes since the snapshot from the CDC topic. There is no expensive tree build at startup.
Updates between rebuilds. Keep a small delta structure: a second in-memory quadtree, or just a list, holding businesses added or moved since the snapshot, plus a tombstone set of removed or moved ids. A query searches both structures, drops tombstoned ids, and merges. When the delta grows large, or nightly, rebuild and swap. This is the same "immutable base plus small mutable delta" idea that log-structured storage engines and Lucene segments use.
Why this is rarely the final answer. The quadtree solves geography only. Text matching, categories, ratings and open-now still need to be evaluated, either by scanning candidates (fine for a few hundred) or by building more indexes, at which point you are reinventing a search engine. A good interview answer shows you can build it, then explains why you would use Elasticsearch, OpenSearch or PostGIS in production unless there is a strong reason (extreme latency, custom ranking at the geo level, cost).
Deep Dive: Geohash encoding, neighbours and SQL queriesShow
Encoding. The algorithm alternates bisections of longitude and latitude, emitting one bit each time, and maps each group of 5 bits to the base-32 alphabet 0123456789bcdefghjkmnpqrstuvwxyz (no a, i, l, o):
const B32 = "0123456789bcdefghjkmnpqrstuvwxyz";
function geohash(lat: number, lng: number, len: number): string {
let lo = [-90, -180], hi = [90, 180]; // [lat, lng]
let bit = 0, ch = 0, even = true, out = "";
while (out.length < len) {
const d = even ? 1 : 0; // even bits: longitude
const mid = (lo[d] + hi[d]) / 2;
const v = even ? lng : lat;
if (v >= mid) { ch = (ch << 1) | 1; lo[d] = mid; }
else { ch = ch << 1; hi[d] = mid; }
even = !even;
if (++bit === 5) { out += B32[ch]; bit = 0; ch = 0; }
}
return out;
}Each character adds 5 bits, alternating which dimension gets 3 and which gets 2. Length 1 gets 3 longitude bits and 2 latitude bits (45° × 45°, square); length 2 has 5 of each (11.25° × 5.625°). That is why even-length geohashes have cells about twice as wide as they are tall, and odd-length cells are roughly square at the equator.
Neighbours. To find the 8 neighbours of a cell, decode its centre, step by one cell width and height in each direction, and re-encode at the same length. (Libraries also offer a lookup-table method that adjusts the last character and carries into the prefix.) Wrap longitude at ±180 and clamp latitude at the poles.
Querying 9 cells in SQL. With a B-tree index on geohash:
SELECT id, name, lat, lng
FROM businesses
WHERE (geohash >= '9q8yy' AND geohash < '9q8yz')
OR (geohash >= '9q8yv' AND geohash < '9q8yw')
-- ... 7 more ranges for the other neighbours ...
AND category_id = 12;
-- then in the service: keep rows where haversine(:lat, :lng, lat, lng) <= :rAdjacent cells in Z-order often form contiguous ranges, so the 9 prefixes can usually be merged into fewer ranges. A composite index on (category_id, geohash) lets "pizza within 2 km" be a handful of tight range scans: equality on the category first, then the geohash range. This is the classic trick to make a relational database answer filtered proximity queries without PostGIS, and it is worth knowing for key-value stores too. In DynamoDB, a partition key of geohash5 and a sort key of geohash9#business_id gives you "all businesses in this 5 km cell" as a single partition query.
Haversine. The exact great-circle distance on a sphere of radius R = 6,371 km:
a = sin²(Δφ/2) + cos φ1 · cos φ2 · sin²(Δλ/2)
d = 2R · asin(√a)where φ is latitude and λ is longitude in radians. For distances of a few km, the equirectangular approximation x = Δλ · cos(φm), y = Δφ, d = R · √(x² + y²) (φm the mean latitude) is accurate to well under 1 percent and cheaper. That is useful when post-filtering hundreds of thousands of candidates. The Earth is slightly oblate, so a spherical formula is off by up to about 0.5 percent compared with ellipsoidal models; irrelevant for "near me".
Worked example: precision choice. User at (40.7580, -73.9855), Times Square, searching a 1 km radius.
- Length 6 cells are about 1.2 km × 0.6 km. At 40.7° latitude, the east-west width shrinks by cos(40.7°) ≈ 0.76 to about 0.9 km. The 0.6 km height is smaller than the 1 km radius, so a 3×3 block of length-6 cells (about 2.7 km × 1.8 km) does not fully cover a 2 km diameter circle vertically.
- So use length 5 (about 4.9 km × 4.9 km at the equator, about 3.7 km × 4.9 km here) with 3×3 neighbours, or cover the circle with roughly 10 to 15 length-6 cells.
- Times Square density: midtown Manhattan has thousands of businesses per km². A length-5 3×3 block (about 160 km² here) could hold hundreds of thousands of candidates. The covering approach with length-6 cells reads about 6 to 8 km² of cells, roughly 20 times fewer candidates. Precision choice is a real performance lever in dense cities, which is why S2's adaptive coverings and engines with BKD trees beat a fixed 3×3 grid.
Deep Dive: The latency budget for one search, in numbersShow
The requirement is search in under 500 ms end to end. Where does the time go? A plausible budget for a user on a mobile network:
| Step | Typical time | Notes |
|---|---|---|
| Client to edge (TLS already warm) | 20 to 80 ms | Mobile radio and last-mile latency dominate; HTTP/2 or HTTP/3 connection reuse avoids repeated handshakes |
| Edge to regional API gateway | 5 to 30 ms | Same-continent backbone |
| Gateway: auth, rate limit, routing | 1 to 3 ms | Rate-limit check is a Redis round trip, about 0.5 ms in-region |
| Search Service: parse, quantise, cache lookup | 1 to 2 ms | Redis GET about 0.5 ms |
| Search cluster query (cache miss) | 10 to 60 ms | Coordinator fan-out to shards, BKD geo filter, inverted-index text, scoring, merge |
| Hydration and formatting | 2 to 5 ms | Distances, thumbnails, open-now display |
| Response back to client | 20 to 80 ms | Payload around 10 to 20 KB compressed |
| Total | about 60 to 260 ms | Leaves headroom for tail latency and rendering |
The server-side portion is only about 15 to 70 ms. Most of the 500 ms budget is the network, which is why multi-region deployment (deep dive 10) matters more than micro-optimising queries for distant users.
Where tail latency comes from:
- Fan-out: a query to 5 shards waits for the slowest. If each shard copy has a 1 percent chance of a 200 ms garbage-collection pause, a 5-shard query hits one about 5 percent of the time. Fewer shards reduce this, and so does adaptive replica selection. Hedged requests (sending a second copy after the p95 latency) are another option, at extra load.
- Dense-area queries: Manhattan's 2 km radius contains tens of thousands of businesses; scoring all of them is slower. Cap candidate counts with a cheaper first pass, or shrink the default radius by density.
- Cold caches after deploys: new nodes have empty page caches and filter caches. Warm them with replayed traffic before taking production load.
Index size worked example. 10 million documents. Per document: name and categories (around 100 bytes of text, maybe 200 bytes of postings), geo point in BKD (about 8 to 16 bytes), numeric doc values (about 20 bytes), keyword fields (location_ids 5 terms, categories 4 terms), and around 280 open-slot terms (each posting a few bytes compressed, say 1 KB). That is roughly 1.5 KB per document, or 15 GB per copy including overheads. That fits in memory on a 64 GB node, leaving room for the JVM heap. Dropping the slot terms in favour of integer range fields would shrink it substantially; that is a design choice to measure.
Cache memory. Suppose 2 million distinct hot search keys in a 2-minute window, each storing 20 result ids with a few fields (about 2 KB). That is 4 GB in Redis. Business cache: 1 million hot businesses × 2 KB = 2 GB. Review first pages: 500,000 × 10 KB = 5 GB. A small Redis cluster of a few nodes holds everything with replication.
Deep Dive: How real local-search systems approach thisShow
Precise internals of commercial systems are rarely public, so treat these as directional and verify against the companies' own publications before relying on any detail.
- Yelp has written on its engineering blog about moving core business search to Elasticsearch, and later about building Nrtsearch, an open-source search engine built on Apache Lucene, to reduce cost and improve scaling for its search workloads. The general architecture, a relational source of truth plus a Lucene-based search tier with geo, text and ranking, matches the design above. Yelp also publicly describes "recommendation software" that decides which reviews are recommended, as part of its anti-fraud approach.
- Google developed the S2 geometry library, which uses Hilbert-curve-ordered cells on a cube projection; it is widely used in Google's geo products and was open sourced. Google's local results draw on its Places data.
- Uber open sourced H3 (hexagonal hierarchical spatial index) in 2018. It is used heavily for marketplace analytics, which is a good reason to use it when aggregating ratings or demand by area.
- MongoDB's
2dsphereindex is built on S2 cells, and Redis has offered GEO commands (geohash-encoded sorted sets) since version 3.2. - PostGIS powers many location features in companies that prefer to keep search in PostgreSQL; GiST spatial indexes and KNN ordering with
<->are mature and well understood. - Lucene moved its geo points to BKD trees in the 6.x line, which is why Elasticsearch
geo_pointqueries are much faster than older geohash-prefix implementations.
The common thread is the same: cell encodings or spatial trees for candidate generation, exact distance for filtering, and a separate ranking step.
Deep Dive: Failure walkthroughsShow
1. The CDC connector stops for 40 minutes. What users see: new reviews appear on business pages (the Business Service reads replicas and caches that are invalidated synchronously by the Review Service), but search results show stale ratings and review counts, and a business closed by its owner still appears as open. Detection: consumer-lag alert on the indexer group; "time since last indexed event" metric over a threshold of a few minutes. Recovery: restart the connector from its stored log position. PostgreSQL retains WAL for the replication slot, so no changes are lost; watch the disk, because a stuck slot makes WAL grow without bound. The indexer catches up at thousands of documents per second, clearing the 40-minute backlog of perhaps 100,000 changes in under a minute. Lesson: CDC lag is an SLO with an alert, and the replication slot is a disk-space risk to monitor.
2. A bad ranking deploy. A new function-score weight makes distance dominate; users in cities see poor-quality results. Nothing errors. Detection: online metrics, not error rates. Click-through rate on the top 3 results, "searched again within 30 seconds" rate, and conversion to business-page views all drop. Recovery: ranking parameters live in configuration behind a feature flag; roll back instantly. Future changes go through an A/B test with guardrail metrics first. Lesson: search quality regressions are silent. Monitor behavioural metrics.
3. Search cluster loses a node during peak dinner time. Shards on that node lose a copy; the cluster promotes replicas and starts copying data to restore the replica count. That copying competes with query I/O. Mitigation: enough headroom that N-1 nodes serve peak; throttle recovery bandwidth; with the index in memory, the main cost is network copy. Latency rises slightly; nothing fails.
4. A celebrity tweets about a small café.
Page views for one business jump from 10 per minute to 5,000 per second. The Redis key biz:b_123 becomes hot; review writes jump to tens per second for one business (some of them fake).
Mitigation: in-process cache for hot keys; the row lock on the business for aggregate updates handles tens of writes per second fine; the integrity pipeline flags the velocity anomaly and may hold new reviews for moderation.
5. The primary database fails over. A synchronous standby is promoted in about 30 seconds. During that window, review writes fail with retryable errors; the client retries with its idempotency key. Search and page views continue from the search cluster, caches and replicas. The CDC connector reconnects to the new primary; with logical replication slots this needs care, because slots historically were not carried over on failover. Newer PostgreSQL versions add failover slot support, and teams must verify their setup. Some events may need a resync: a reconciliation run, or replaying a time window with idempotent full-document indexing.
Deep Dive: A 45-minute interview planShow
| Minutes | What to do |
|---|---|
| 0 to 5 | Clarify: search inputs, filters, place names, review rules, scale (100M DAU, 10M businesses), latency (under 500 ms), consistency (eventual). |
| 5 to 9 | Estimate: about 6k average and 20k peak search QPS, about 12 reviews/s, 1,500:1 read:write; data small (business data 20 GB, geo index under 1 GB, reviews 500 GB). Conclusion: replicate, cache, precompute. |
| 9 to 13 | Entities and API: search with cursor, business, reviews, POST review with 409 on duplicate. |
| 13 to 22 | HLD: gateway, Search, Business, Review services, primary DB with replicas, search cluster fed by CDC, caches, Location Service. |
| 22 to 32 | Deep dive 1: geo index. B-tree problem, geohash with 3×3 and post-filter, quadtree, then search engine with geo plus text plus filters. |
| 32 to 39 | Deep dive 2: rating aggregation (sum and count in one transaction, edits, reconciliation, Bayesian ranking) and one review per user (unique constraint, shard by business). |
| 39 to 43 | Deep dive 3: read scaling with quantised cache keys, few shards and many replicas, capacity math; place names via precomputed location ids. |
| 43 to 45 | Failure modes and what you would add: multi-region, spam defences, ranking evolution. |
Common pitfalls to avoid:
- Sharding the search index by geography before noticing that the whole index fits in RAM.
- Computing averages on read, or updating an average with read-modify-write.
- Relying on an application check for one-review-per-user.
- Dual-writing to the database and search index.
- Forgetting the cell-boundary problem with geohashes, or forgetting to post-filter by exact distance.
Deep Dive: Observability for a proximity serviceShow
Golden signals per service (see Observability: Logs, Metrics and Traces):
- Search: QPS, p50, p95 and p99 latency split into cache hit and cache miss, error rate, zero-result rate.
- Search cluster: query latency per shard, rejected requests (thread-pool queue full), heap and garbage-collection pauses, refresh and merge times.
- Business Service: cache hit ratio per key type, replica latency, hot-key detection.
- Review Service: write latency, 409 duplicate rate (a spike may mean a client retry bug), transaction aborts.
Pipeline health:
- CDC lag in seconds (commit time to indexed time), per topic.
- Replication slot WAL retention in bytes.
- Indexer error rate and dead-letter queue size.
- Reconciliation mismatches per night (should be near zero).
Search quality:
- Click-through rate at positions 1 to 3, and "search again" rate.
- Zero-result rate by area. Rural areas may need automatic radius expansion.
- Freshness: a sample of businesses where index fields are compared with the database.
Traces across gateway, Search Service, cache and cluster show where slow requests spend time. Tag them with the geohash-4 of the query so that dense-area slowness is visible.
Deep Dive: Evolving ranking from hand-tuned scores to learned modelsShow
The hand-written function_score in deep dive 3 is a fine start, but its weights are guesses. Mature local-search products move to learning to rank, and the infrastructure for that is a design topic in its own right.
Stage 1: candidate generation (retrieval). The search engine applies the hard constraints (geo, filters, status) and a cheap score, and returns the top 200 to 500 candidates. This stage must be fast and must have high recall: if a great result is not in the candidate set, no re-ranker can rescue it. Tune it by measuring how often the businesses users eventually click appear in the candidate set.
Stage 2: re-ranking. The Search Service, or a dedicated ranking service, computes richer features for each candidate and scores them with a model, typically gradient-boosted trees such as LambdaMART, a well-known learning-to-rank method from Microsoft Research (Burges and colleagues, around 2010):
- Query-business text match features (BM25 on name, on categories, on review text).
- Distance, and distance relative to the median distance of the candidates (in a dense city 1 km is far; in a suburb it is near).
- Bayesian rating, review count, review recency, photo count.
- Historical click-through rate for this business on similar queries, smoothed for low-traffic businesses.
- Context: time of day (breakfast places in the morning), day of week, the user's platform.
Re-ranking 300 candidates with a tree ensemble of a few hundred trees costs on the order of a millisecond or a few milliseconds on one core, so it fits easily in the latency budget. Features must be precomputed and fetched in bulk: store per-business features in the search document, or in a key-value feature store read with one batched call.
Training data and position bias. Labels come from user behaviour: clicks, calls, direction requests, bookmarks, and reservations. But users click what is shown at the top, regardless of quality. That is position bias, and training naively on clicks teaches the model to reproduce the old ranking. Standard remedies: small randomised interleavings to estimate how much position alone drives clicks, inverse-propensity weighting of clicks by position, or using stronger signals than clicks (a call or directions request after a click).
Evaluation.
- Offline: replay logged queries and measure NDCG (normalised discounted cumulative gain) or mean reciprocal rank against behavioural labels before shipping.
- Online: A/B tests on success metrics (sessions ending in a call, directions or reservation) with guardrails (latency, zero-result rate, "searched again" rate). Interleaving experiments, which mix results from two rankers in one list and see which ranker's results get clicked, detect differences with far less traffic than A/B tests.
Fairness to new businesses. A model trained on clicks favours businesses that already have clicks: a rich-get-richer loop. Products counter it with explicit exploration (occasionally boosting newer businesses with few reviews), Bayesian smoothing of click-through rates, and separate "new and noteworthy" placements.
Why it matters for the system design. Learned ranking adds three components to the architecture: a feature pipeline (batch jobs and streaming updates writing per-business features into the search document or a feature store), a ranking service with a model registry and safe rollout, and an event logging pipeline that records impressions, positions and outcomes for training. None of these touch the write path for reviews, which is why the read-heavy, replicate-everything core design accommodates them without restructuring.
Deep Dive: Variants interviewers ask aboutShow
"Find the 10 nearest gas stations, however far." A radius query fails in sparse areas. Use k-nearest-neighbour search: PostGIS ORDER BY location <-> :pt LIMIT 10 walks the GiST index best-first; Elasticsearch can sort by _geo_distance with a generous radius filter that expands in steps; a quadtree does a best-first traversal. Expanding the radius (2 km, then 10 km, then 50 km) until enough results appear is the simple, practical version.
"Nearby friends" (moving users, not static businesses). The data is now dynamic: millions of location updates per minute and privacy-sensitive. The design flips toward ride-hailing: an in-memory cell index (geohash or H3 buckets in Redis), short TTLs on positions, and pub/sub per cell or per friend so updates are pushed rather than queried. The static-data assumptions of this page no longer hold.
"Search along a route." "Coffee on my way to the airport" needs a corridor search: buffer the route polyline by a few hundred metres into a polygon (or a sequence of S2 cells covering it), filter by that, and rank by detour time rather than straight-line distance, which needs a routing engine.
"Delivery radius" instead of the user's radius. For food delivery, each restaurant defines the area it serves, often an irregular polygon or a travel-time isochrone. The query reverses: "which restaurants' service areas contain my point?" Index the service-area shapes (Elasticsearch geo_shape, PostGIS polygons) and query by point containment, or precompute covering cells per restaurant and look up the user's cell. This is the bridge to the food-delivery case study.
Key Takeaways#
- Static locations plus a read-heavy workload (about 1,500:1) define the design: precompute on write, replicate the index, cache aggressively, and keep the primary database for writes only.
- B-trees cannot answer 2D proximity. Use geohash or S2 cells (1D keys that preserve locality), or spatial trees (quadtree, k-d and BKD, R-tree). Always query the neighbouring cells and post-filter by exact distance.
- The whole geo index for 10 million businesses fits in under 1 GB, so scale by replication, not sharding.
- A search engine (Elasticsearch or OpenSearch) combines a BKD geo filter, inverted-index text matching, numeric and keyword filters, and scoring in one query. PostGIS is a solid alternative at moderate scale.
- Open-now is a time-zone-aware weekly slot or range encoding; category hierarchies and place-name membership are denormalised into the document, so they become simple term filters.
- Ratings: store
rating_sumandreview_countand update them atomically in the review's transaction. Handle edits and deletes as deltas, reconcile nightly, and rank by a Bayesian average. - One review per user is a database unique constraint on
(business_id, user_id), and the shard key must keep that invariant local. - Keep derived views consistent with CDC, not dual writes: ordered by business id, full-document upserts, external versioning, alias-swap rebuilds, and read-your-writes for the author.
- Read scaling: quantise locations into cache keys, use few shards and many replicas, and protect hot keys. Most of the 500 ms budget is network, so deploy the read path in multiple regions.