Design Proximity Search

How to design a nearby-places search with reviews, including geohash and quadtree indexes, combining text with location, and keeping ratings correct.

Case study22 minLesson 1 of 8
On this page
  1. Clarify the problem
  2. Estimate the scale
  3. Define the API (optional)
  4. Model the data
  5. High-level design
  6. Deep dives
  7. Bottlenecks and failures
  8. What a strong answer sounds like
  9. Follow-up questions

A proximity search service lets a user find businesses near a location, filtered by words such as "pizza", sorted by relevance and rating, and then open a business to read and write reviews.

Interviewers ask it because it combines four problems that each need a different answer. Finding places near a point needs a spatial index, a single query has to mix location with text and filters, the read traffic is hundreds of times larger than the write traffic, and the average rating has to stay correct when two people review the same place at the same moment. The steps follow A Framework for Any Design.

Clarify the problem

The first five minutes
Interviewer

Design a service that finds businesses near a user and lets people review them.

You

I assume users search by location, category and keywords, open a business page and write a star rating. Can one user review a business more than once?

Interviewer

Each user gets one review per business, and they can edit it later.

You

How many businesses, users and searches should I plan for?

Interviewer

Assume 50 million businesses, 100 million daily users who search about 5 times a day each, and 2 million new reviews a day.

You

Then the system is read-heavy, and I will aim for search results in about 200 ms. A new review can take a few seconds to show up in search, but a rating must never lose a review. I will leave out photos, ads and owner tools.

Functional requirements. Users can search near a point by category and keywords, with filters for open now, price and minimum rating. They can view a business page with its reviews. They can add, edit or delete their one review of a business.

Non-functional requirements. Search responds in under 200 ms at the 99th percentile. A new business or review becomes searchable within a minute. Every review is counted in the rating exactly once.

Out of scope. Photos (see Design Photo Sharing), ads and owner dashboards are not part of this design.

Estimate the scale

The estimates use 86,400 seconds a day and a peak of 3 times the average.

  • Searches. 100 million users × 5 searches is 500 million a day. Divided by 86,400 that is about 5,800 a second, or about 17,000 a second at peak.
  • Business page views. Assuming 2 page views per search, there are 1 billion views a day, about 11,600 a second or 35,000 at peak.
  • Review writes. 2 million a day is about 23 a second, or 70 at peak. Reads outnumber writes by (500 million + 1 billion) ÷ 2 million, which is 750 to 1.
  • Storage. 50 million businesses at 2 KB each take 100 GB. Assuming 1 billion existing reviews at 1 KB each, reviews take 1 TB.
Estimate: How big is the search index?

Each business is one search document holding its name, categories, location, hours, price and rating. About how much memory does the index need?

You know
  • 50 million businesses
  • About 500 bytes per search document
  • Reviews are not in the index, only each business's rating

Show the working
  1. 50 × 106 × 500 B = 25 × 109 B = 25 GB
  2. The coordinates alone take 50 million × 24 B (id, latitude and longitude) = 1.2 GB

Estimate 25 GB (anything from 8 GB to 80 GB is a good answer)

25 GB fits in the memory of one server, so extra index machines are added as full copies to handle more queries, not to split the data.

Your turn: Define the API

Write the search, business page and review endpoints. How can the API make "one review per user" natural and safe to retry?

Compare with a model answer

Search is a GET with a point, a radius, keywords and filters, paged with a cursor. The review is a PUT addressed by business and user, so sending it twice has the same effect as sending it once.

Define the API Optional

Optional in the interview. Sketch the API only if the interviewer asks, if an API choice shapes the design, or if time permits. Otherwise say "I'll skip the detailed API unless you want it" and go to the data model.

HTTP API
GET /search?lat=40.7128&lng=-74.0060&radius_m=2000
           &q=pizza&category=restaurants&open_now=true&min_rating=4&cursor=...
  200 { "results": [ { "id": "b_81", "name": "Luigi's", "rating": 4.6,
                       "review_count": 312, "distance_m": 450 }, ... ],
        "next_cursor": "..." }
  400 Bad Request   radius over 50 km, or no location
 
GET /businesses/{id}                   page data, cacheable for 60 s
GET /businesses/{id}/reviews?sort=recent&cursor=...
 
PUT /businesses/{id}/reviews/me        create or replace my review
  body: { "rating": 5, "text": "..." }
  200 { "rating": 5, "business_rating": 4.60, "review_count": 311 }
  400 Bad Request   rating not 1 to 5
  404 Not Found     no such business
DELETE /businesses/{id}/reviews/me

The API decision to discuss is using PUT .../reviews/me instead of POST .../reviews. If a phone retries a POST after a timeout, the server may create a second review. A PUT names the user's single review of that business, so a retry replaces it with identical content, and a primary key enforces "one review per user".

Your turn: Model the data

Sketch the business and review records. Where does the rating live, and what answers "places near this point"?

Compare with a model answer

Use a relational database with reviews keyed by business and user, and a running sum of stars and a count of reviews on each business row. A separate search index, fed from the database's change stream, answers the location and text queries.

Model the data

Source of truth
businesses
  business_id   BIGINT PRIMARY KEY
  name          VARCHAR(200)
  categories    TEXT[]            -- ["restaurants", "pizza"]
  lat, lng      DOUBLE
  hours         JSON              -- weekly opening intervals
  price_level   SMALLINT
  rating_sum    BIGINT            -- total stars of all reviews
  rating_count  INT               -- number of reviews
  -- about 2 KB per row
 
reviews
  business_id   BIGINT
  user_id       BIGINT
  rating        SMALLINT          -- 1 to 5
  text          TEXT
  updated_at    TIMESTAMP
  PRIMARY KEY (business_id, user_id)   -- one review per user, enforced

A review write changes two rows that must succeed or fail together, so the source of truth is a relational database, partitioned by business_id once it outgrows one machine, so that a business and its reviews live on the same partition. Geometry, text and ranking go to a search index with geographic support (see search systems), which is built from the database.

Your turn: High-level design

Sketch a search, a page view and a review write. How does a new review reach search?

Compare with a model answer

Three services sit behind a gateway. Search reads only the index, page views read through a cache, and reviews write to the database in one transaction. A change stream updates the index a few seconds later.

High-level design

Each path has its own service and store, so a surge in searches cannot slow down review writes.

Search reads the index, pages read through a cache, and a review write updates the database and then deletes the cached page. A change stream feeds the index.Phone or browser to API gateway (HTTPS); API gateway to Search service; API gateway to Business service; API gateway to Review service; Search service to Search index replicas (geo + text); Business service to Page cache (get page); Business service to Business DB (on miss); Review service to Business DB (one transaction); Review service to Page cache; Business DB to Indexer (change stream), asynchronous; Indexer to Search index replicas (update doc), asynchronous.Phone or browserAPI gatewaySearch serviceBusiness serviceReview serviceSearch indexreplicasPage cacheBusiness DBIndexerHTTPSgeo + textget pageon missone transactionchange streamupdate doc

request and replyasynchronous message

Search reads the index, pages read through a cache, and a review write updates the database and then deletes the cached page. A change stream feeds the index.
Search, open a page, write a review, lose an index replicaUse the arrows or ← → keys
  1. Search, open a page, write a review, lose an index replica, step 1Phone or browser to API gateway; API gateway to Search service; API gateway to Business service; API gateway to Review service; Search service to Search index replicas; Business service to Page cache; Business service to Business DB; Review service to Business DB; Review service to Page cache; Business DB to Indexer, asynchronous; Indexer to Search index replicas, asynchronous.Phone or browserAPI gatewaySearch serviceBusiness serviceReview serviceSearch indexreplicasPage cacheBusiness DBIndexer
    radius
    2 km

    1Mia searches for "pizza", open now, within 2 km. The gateway sends the request to any stateless search server.

  2. Search, open a page, write a review, lose an index replica, step 2Phone or browser to API gateway; API gateway to Search service; API gateway to Business service; API gateway to Review service; Search service to Search index replicas; Business service to Page cache; Business service to Business DB; Review service to Business DB; Review service to Page cache; Business DB to Indexer, asynchronous; Indexer to Search index replicas, asynchronous.Phone or browserAPI gatewaySearch serviceBusiness serviceReview serviceSearch indexreplicas9 cellsPage cacheBusiness DBIndexer
    radius
    2 km
    cells
    9

    2The search server sends one query to one index replica. The geo filter turns her point into her precision-5 geohash cell plus its 8 neighbours.

  3. Search, open a page, write a review, lose an index replica, step 3Phone or browser to API gateway; API gateway to Search service; API gateway to Business service; API gateway to Review service; Search service to Search index replicas; Business service to Page cache; Business service to Business DB; Review service to Business DB; Review service to Page cache; Business DB to Indexer, asynchronous; Indexer to Search index replicas, asynchronous.Phone or browserAPI gatewaySearch serviceBusiness serviceReview serviceSearch indexreplicas140 matchPage cacheBusiness DBIndexer
    radius
    2 km
    matches
    140
    returned
    20

    3The index keeps the 140 places within exactly 2 km that match "pizza" and are open, and returns the top 20.

  4. Search, open a page, write a review, lose an index replica, step 4Phone or browser to API gateway; API gateway to Search service; API gateway to Business service; API gateway to Review service; Search service to Search index replicas; Business service to Page cache; Business service to Business DB; Review service to Business DB; Review service to Page cache; Business DB to Indexer, asynchronous; Indexer to Search index replicas, asynchronous.Phone or browserAPI gatewaySearch serviceBusiness serviceReview serviceSearch indexreplicasPage cacheBusiness DBIndexer
    returned
    20
    db reads
    0

    4Name, rating and distance come straight from the index documents, so this search makes no database read.

  5. Search, open a page, write a review, lose an index replica, step 5Phone or browser to API gateway; API gateway to Search service; API gateway to Business service; API gateway to Review service; Search service to Search index replicas; Business service to Page cache; Business service to Business DB; Review service to Business DB; Review service to Page cache; Business DB to Indexer, asynchronous; Indexer to Search index replicas, asynchronous.Phone or browserAPI gatewaySearch serviceBusiness serviceReview serviceSearch indexreplicasPage cachehitBusiness DBIndexer
    rating
    4.60 (310)

    5She opens Luigi's. The page is in the cache, so it returns in about a millisecond.

  6. Search, open a page, write a review, lose an index replica, step 6Phone or browser to API gateway; API gateway to Search service; API gateway to Business service; API gateway to Review service; Search service to Search index replicas; Business service to Page cache; Business service to Business DB; Review service to Business DB; Review service to Page cache; Business DB to Indexer, asynchronous; Indexer to Search index replicas, asynchronous.Phone or browserAPI gatewaySearch serviceBusiness serviceReview serviceSearch indexreplicasPage cacheBusiness DB+5 stars, +1Indexer
    rating_sum
    1,426 → 1,431
    rating_count
    310 → 311

    6She gives it 5 stars. One transaction inserts her review and adds 5 to the star sum and 1 to the review count on Luigi's row.

  7. Search, open a page, write a review, lose an index replica, step 7Phone or browser to API gateway; API gateway to Search service; API gateway to Business service; API gateway to Review service; Search service to Search index replicas; Business service to Page cache; Business service to Business DB; Review service to Business DB; Review service to Page cache; Business DB to Indexer, asynchronous; Indexer to Search index replicas, asynchronous.Phone or browserAPI gatewaySearch serviceBusiness serviceReview serviceSearch indexreplicasPage cacheBusiness DBdelta 0Indexer
    rating_sum
    1,431
    rating_count
    311

    7Her phone times out and retries the PUT. Her review already exists, so the retry is an edit from 5 stars to 5 stars and changes nothing.

  8. Search, open a page, write a review, lose an index replica, step 8Phone or browser to API gateway; API gateway to Search service; API gateway to Business service; API gateway to Review service; Search service to Search index replicas; Business service to Page cache; Business service to Business DB; Review service to Business DB; Review service to Page cache; Business DB to Indexer, asynchronous; Indexer to Search index replicas, asynchronous.Phone or browserAPI gatewaySearch serviceBusiness serviceReview serviceSearch indexreplicasrating 4.60Page cachekey deletedBusiness DBIndexer
    rating
    1,431 ÷ 311 = 4.60

    8After the commit, the review service deletes Luigi's cached page, and a few seconds later the indexer updates the search document.

  9. Search, open a page, write a review, lose an index replica, step 9Phone or browser to API gateway; API gateway to Search service; API gateway to Business service; API gateway to Review service; Search service to Search index replicas; Business service to Page cache; Business service to Business DB; Review service to Business DB; Review service to Page cache; Business DB to Indexer, asynchronous; Indexer to Search index replicas, asynchronous.Phone or browserAPI gatewaySearch serviceBusiness serviceReview serviceSearch indexreplicas1 replica downPage cacheBusiness DBIndexer
    peak searches/s
    17,000

    9An index replica dies. Every replica holds the whole 25 GB index, so the search service retries on another one.

1 / 9

Deep dives

Geospatial index for finding nearby places

An index on latitude alone is not enough, because it finds every business in a thin band around the whole planet and the database must then check each one. The index has to group points by area. Design Ride Sharing introduces geohash cells and neighbour cells; here the points are businesses, which almost never move.

Geohash cells. A geohash divides the map into rectangular cells and gives each cell a string, where a longer string means a smaller cell inside the cell named by its prefix. Any sorted index can therefore answer "all places in this cell", and updating or sharding it is straightforward. The weakness is that cells have a fixed size, so a downtown cell can hold thousands of places while a rural cell holds none. A common workaround is to use a longer prefix in dense areas, which means a query there reads many small cells instead of one large one, and the service has to know which precision applies to each area.

The precision is chosen from the search radius. The user's cell plus its 8 neighbours form a 3 × 3 block that covers any circle whose radius is at most the shorter side of one cell. A precision-6 cell is about 1.2 km × 0.6 km, which is too small for a 2 km radius, while a precision-5 cell is about 4.9 km on each side at the equator. You search all 9 cells and then filter by exact distance, because a place 50 metres away can sit in the next cell.

Quadtree. A quadtree starts with one square for the whole map and splits any square holding more than a set number of places, for example 100, into four. Dense areas end up with many small squares and empty areas with a few large ones. A search finds the leaf containing the user and collects neighbouring leaves until it has enough places. With at most 100 places per leaf, 50 million places need at least 500,000 leaves, which fits in memory. Since places rarely move, the tree can be built offline and shipped to every search server. The cost is that you maintain this code yourself.

Geo support in a search engine or database. A search engine can index a geographic point field, and a relational database can use a spatial extension. Both handle cells, neighbours and exact distance for you, and the search engine can also match text and apply filters in the same query, which this problem needs.

Ways to index 50 million places
OptionGood atBad atPick it when
Geohash cellsAny sorted index can query a cell, and the index is easy to shard and update.Cells have a fixed size, so dense areas overflow and sparse areas stay empty.You are building the index yourself on top of a key-value or relational store.
Quadtree in memoryCells follow the density of places, and a search for the nearest 20 places is a natural walk over the tree.You write the code to build, distribute and update the tree.Places rarely move and the query is closer to "nearest 20" than to "within 2 km".
Geo support in a search engine or database Usual defaultCells, neighbours and exact distance are handled in the same query as text and filters.You have less control over the cells.This problem, using a search engine because the query also needs text and ranking.

Scaling reads with index replicas and a page cache

The 25 GB index fits in memory on every search machine, so you run several replicas, each a full copy, and a single replica answers every query. If one replica handles about 1,000 queries a second, the peak of 17,000 searches a second needs 17 replicas, so you run about 20 for headroom.

Business pages go through a cache. Every review commit deletes the page's cached key, and a 60-second expiry covers a lost deletion.

Keeping the average rating correct

The risk is a lost update. Suppose Luigi's has 10 reviews totalling 40 stars, and Ana gives 5 stars while Ben gives 1 star at the same moment. The correct result is 46 stars over 12 reviews. If each request reads the row, calculates in the application and writes back, both read (40, 10), Ana writes (45, 11) and Ben then writes (41, 11). The row ends at 11 reviews and Ana's review is lost.

Recompute from all reviews. After each write, run AVG(rating) over the business's reviews. The answer is exact, but a business with 50,000 reviews means reading 50,000 rows for every new review, and concurrent recomputations still need ordering. It suits only small data or a nightly repair job.

Atomic update in the review transaction. Store the star sum and the review count on the business row, and in the same transaction as the review change them with rating_sum = rating_sum + 5, rating_count = rating_count + 1. The database serializes updates to that row, so no update is lost. Reviews of the same business briefly wait for each other, which is fine at this write rate. This is the approach to choose in an interview.

Events aggregated later. Each review publishes an event and a worker adds them up, so there is no lock on the business row. The total lags, and a redelivered event is counted twice unless the worker removes duplicates. It is worth it only for a business with thousands of reviews a second.

Create or replace a review while keeping the rating exact
BEGIN;
-- 1. lock the business row: reviews of this business now take turns
SELECT 1 FROM businesses WHERE business_id = 81 FOR UPDATE;
-- 2. my old review, if any
SELECT rating FROM reviews WHERE business_id = 81 AND user_id = 7;  -- 3, or none
INSERT INTO reviews (business_id, user_id, rating, text, updated_at)
     VALUES (81, 7, 5, '...', now())
ON CONFLICT (business_id, user_id)
     DO UPDATE SET rating = 5, text = '...', updated_at = now();
-- 3. new review: +5 stars, +1 review.  edit from 3 to 5: +2 stars, +0.
UPDATE businesses SET rating_sum = rating_sum + 2, rating_count = rating_count + 0
 WHERE business_id = 81;
COMMIT;

This is safe because every review of business 81 first locks the business row, so the transactions run one after another, and at the read committed isolation level the second one sees the first one's committed data. The primary key stops one user from creating two reviews even if two requests race. The row stores the sum and the count instead of the average, because an average cannot be updated by a delta.

Combining words, filters and location in one query

A query such as "wood-fired pizza, open now, 4 stars or more, within 2 km" has three parts, and running them as separate steps wastes work in both orders. Filtering by location first fetches thousands of downtown places to keep 20, and matching the text first finds every pizza place in the world.

Send one query to the search index instead. The filters and the geographic condition cut down the candidates, the words are matched against the inverted index, and the engine scores what remains. A simple score multiplies the text relevance by a distance decay and a rating factor, so a 4.8-star place at 1.5 km can rank above a 4.1-star place at 300 m. Opening hours are stored as minutes of the week in local time, so "open now" is one numeric comparison.

Bottlenecks and failures

At 10 times the traffic there are 170,000 searches a second, which needs about 200 index replicas. You then split them into regional clusters that each hold only their region's index, because a search almost never crosses a continent.

When this failsWhat happensWhat you do
A search index replicaThe queries sent to it fail.The search service retries on another replica, because each replica holds the full index.
The indexer or the change streamNew reviews and places stop reaching search.Search keeps working with older data, and the indexer resumes from its saved position in the stream when it restarts.
The page cacheAll 35,000 page reads a second at peak go to the database.Provide read replicas sized for that load, plus a short-lived cache in the business service.
A database primaryReview writes for its partition fail until a failover completes.Keep a synchronous replica with automatic failover.

What a strong answer sounds like

LevelWhat the answer does
JuniorFilters a table of coordinates with a distance formula and adds a spatial index only when asked about 50 million rows.
MidUses a geohash or a quadtree with neighbouring cells, keeps the search index separate from the database, and caches pages.
SeniorReplicates the in-memory index instead of sharding it, combines location, filters and text in one query, keeps ratings exact with a sum and a count, and says which data is allowed to lag.
Going deep on the indexStrong answer
Interviewer

How would you shard the geo index?

You

At first I would not shard it. The index is about 25 GB, so every node can hold a full copy, each query touches one machine, and about 20 replicas cover 17,000 searches a second. If it outgrew memory I would shard by region, because a search almost never crosses a continent, and give big-city shards more replicas.

Interviewer

And if you had to build the spatial part yourself?

You

I would build a quadtree with about 100 places per leaf, offline, and ship it to every node. For a 2 km search I would collect the leaves that touch the circle and filter by exact distance.

Follow-up questions

What if fewer than 20 places are found within 2 km?

Widen the radius in steps, for example from 2 km to 5 km and then 10 km, and repeat the query until there are enough results or you reach a maximum radius. You cap the number of steps to keep latency bounded.

How do you search when the user pans a map?

The client sends the corners of the visible map instead of a point and a radius, and the geo field filters by that bounding box. You cap the box size, because a box covering a whole country would match millions of places. When the map is zoomed far out, you return clusters with a count for each cluster instead of individual places.

Should a place with one 5-star review rank above one with 300 reviews at 4.7?

No. A single review says little about a place, so rank by an adjusted rating that pulls small samples toward the site-wide average, for example (sum + 10 × site average) ÷ (count + 10).

Search shows an older rating for Luigi's than its page does. Is that a bug?

No, it is expected. Search reads a copy in the index that the indexer updates a few seconds after the commit, while the page cache is cleared as soon as the review commits.

A review is removed as fake. What changes?

Hide the review in a transaction like the one for writing a review, which subtracts its stars from the sum and 1 from the count and then deletes the cached page. A nightly job that recomputes the sums from the reviews catches any drift.

Self-review: proximity search0 of 12

After your attempt, tick what you really did. Be strict: "I thought about it" is not "I said it out loud".

Before drawing

Numbers and interfaces

Design and depth

Failure