System Design

Problem Breakdowns

Design Yelp (Nearby Places)

Most answers spend the interview on geohash and quadtrees. Places don't move, and everything search needs about 250 million of them fits in one machine's memory. So the design is about ranking what is near and copying one small index everywhere, not about splitting the map.

"Design Yelp" usually turns into "design a geospatial index" within five minutes. The candidate picks geohash or a quadtree, reads the cell around the user and its eight neighbours, and spends the next twenty minutes finding places near a point. Geospatial indexing works that part through. In this problem it's the easy part, because places don't move.

Compare it with ride-hailing. In Uber, 500,000 drivers each send a position every 4 seconds, and the index exists to keep up with 125,000 writes a second. Here, 250 million places change about 100 times a second between them, and every search reads hundreds of places at once.

So the index barely changes, and it's small. The hard part comes after the cells. A search for "ramen, open now, under $$" has to combine a location with text and filters. It has to rank the matches by more than distance, and check opening hours in each place's own time zone.

Places barely change, and everything search needs about all 250 million of them fits in one machine's memory. So treat the search index as a read-only copy. Build it in one place, copy the whole thing to every search machine, and spend the design on ranking, not on splitting the map.

Three decisions follow from that. The index isn't sharded. Changes reach it from the database's log, and the whole index is rebuilt every night. And anything that depends only on where a place is, such as how far a search should reach, is worked out ahead of time.


Understanding the problem

The general method for this part of the interview is in The First Five Minutes: Requirements.

A user stands on a corner in Midtown Manhattan, or pans a map over rural Montana, and asks for places: "coffee", "ramen open now", or nothing at all. The service returns about 20 places, ranked, each with its rating, price level, distance and a photo. Tapping one opens its page, with hours, photos and reviews. Users write reviews and add photos, and owners correct their hours.

Five kinds of system get called "nearby search", and each one is designed differently.

  1. Moving points, such as drivers and couriers. The index has to take a write every few seconds per point. Uber designs that one, and the food delivery breakdown, still to come, adds couriers.
  2. Maps and routing: map tiles, directions and travel times. Not this.
  3. Delivery coverage: which restaurants deliver to this address. That's a question about shapes, not points, and geospatial indexing works it through.
  4. Search over documents, built on an inverted index. This design uses one, but only over the fields of a place.
  5. Local search over places that stay put: near a point or in a map view, filtered and ranked, with pages, reviews and photos. This is the one we're designing.

Functional requirements

Core:

  1. Search. Near a point within a radius, or inside the map's current view. An optional text query, and filters for category, open now, price level and minimum rating. Results are ranked, 20 to a page.
  2. A place's page. Its details, hours, photos and rating, and its reviews, newest first.
  3. Reviews and photos. A user rates a place from 1 to 5 stars with some text, and uploads photos.
  4. Add or change a place. Owners and editors add places and correct their details, such as hours.

Out of scope, deliberately:

  • Directions, travel times and map tiles.
  • Ads and sponsored results.
  • Reservations, waitlists and ordering.
  • Ranking personalised to each user.
  • Delivery zones and couriers, which the food delivery breakdown will cover.

Non-functional requirements

  1. Scale. 250 million places worldwide, about the size of the places dataset Google described in 2025. 100 million daily users, each making about 5 searches and opening about 3 place pages a day. The user figures are assumptions.
  2. Latency. A p99 under 100 ms for a search and for a place page, measured at the service. The p99 is the latency that 99 percent of requests beat. Photos come from a content delivery network (CDN) and aren't in this budget.
  3. Freshness. Search may be up to a minute behind the database. A changed opening time is searchable within a minute. A new review shows on its page to its author at once, and the rating change reaches search within minutes of the review being recommended.
  4. Availability. Search keeps working when the database's primary is down. Reviews and edits may fail for those minutes.

Requirement 3 carries the design. If search had to reflect every write the moment it commits, the index would take writes on the request path and every copy would have to agree. A minute lets the index be a copy, built away from the request path and copied freely. Here is how lopsided the traffic is.

Back of envelopeReads against writes
The question is how many times the index is read for
each time it changes, because that decides what the
design can afford to copy. Peaks use the course's 5x.

Reads
  searches      100M users × 5 a day        =  500M/day
                500M / 86,400               ≈   5,800/s
                at peak, × 5                ≈  29,000/s
  place pages   100M users × 3 a day        =  300M/day
                300M / 86,400 × 5           ≈  17,400/s

Writes
  reviews       22M a year, Yelp's 2025 figure
                22M / 365 / 86,400          ≈     0.7/s
  place edits   250M places, each changed about once a month
                250M / 30 / 86,400          ≈      96/s

Places touched, both as daily averages
  a search ranks about 500 candidates (deep dive 2)
  read          5,800 × 500                 ≈    2.9M/s
  written       96 + 0.7                    ≈     100/s
  ─────────────────────────────────────────────────────────
Search reads about 29,000 places for every place that
changes. Copying the index costs almost nothing in write
work, so the design can copy it as often as reads need.

The set up

Core entities

  • Place. A location, categories, a price level, opening hours with a time zone, and a rating. The place is the only interesting entity. Search reads almost every field of it, and it changes about once a month.
  • Review. A place, an author, 1 to 5 stars, text, and a status: pending, recommended, not recommended or removed.
  • Photo. A place, an uploader, and the key of its bytes in object storage.
  • User. An account that writes reviews and uploads photos.
  • Index document. A copy of one place holding only what search filters, ranks and shows. It's built from the other four and never written by a client.

System interface

GET /v1/search?lat=40.7580&lng=-73.9855&radius=1000&q=ramen
    &category=japanese&open_now=true&price=1,2&min_rating=4&limit=20

GET /v1/search?bounds=40.748,-73.997,40.768,-73.974&q=coffee&limit=20

→ 200 {
    "results": [
      { "id": "pl_8f3k2", "name": "Menkoi Ramen", "lat": 40.7593, "lng": -73.9845,
        "distance_m": 167, "rating": 4.5, "review_count": 1240, "price": 2,
        "open_now": true, "photo": "https://img.example.com/p/8f3k2/t.jpg" }
    ],
    "radius_used": 280,
    "next_cursor": "eyJzIjo0LjMxLCJpZCI6InBsXzhmM2syIn0"
  }

GET /v1/places/pl_8f3k2
GET /v1/places/pl_8f3k2/reviews?cursor=...

POST /v1/places/pl_8f3k2/reviews
Idempotency-Key: 6c2f81d4-0e7b-4a59-9b3e-5d17a2c0f86e
{ "stars": 4, "text": "..." }
→ 201 { "review_id": "rv_31x9", "status": "pending" }

POST /v1/places/pl_8f3k2/photos
→ 200 { "photo_id": "ph_77k1", "upload_url": "https://bucket.s3.../raw/ph_77k1?X-Amz-Signature=..." }

PATCH /v1/places/pl_8f3k2
{ "hours": [{ "day": "fri", "opens": "18:00", "closes": "02:00" }], "timezone": "America/New_York" }

Three things to note.

The radius is a suggestion, and the answer says what it used. Yelp's API documents its radius parameter this way: the search may use a smaller radius in dense cities and a larger one where businesses are sparse. The parameter itself accepts up to 40 km. radius_used tells the client which area the list covers, and deep dive 2 works out where it comes from.

A search returns a page, never everything in the area. Yelp's API stops at 240 results across all pages, and Google's Nearby Search returns at most 20. With the depth capped, each search keeps a fixed-size list of its best places while it scores. The cursor carries the last score and place ID, so page 2 carries on from where page 1 stopped. Inverted indexes explains why an offset fails for deep pages.

Photo bytes never pass through our servers. The API returns a pre-signed URL, a link signed with our credentials that lets the client upload one object straight to object storage. Section 3 walks the upload.


High-level design

1. Search near a point or in a viewport

A search does four things in order. It finds the places inside the area, drops the ones a filter rejects, gives each survivor a score, and returns the 20 best. The first two steps pick the candidates, and the last two rank them.

The ranking makes this different from the nearest-K query in geospatial indexing. PostGIS's ORDER BY location <-> point LIMIT 20 walks outward from the point and stops after 20, because distance is the order. Here the order mixes distance, rating and how well the text matches, so a 4.7-star ramen bar 600 m away should beat a 3-star one next door. A search ranked by anything other than distance can't stop after the 20 nearest. Nearly every candidate in the area gets a score, and the number of candidates is what a search costs.

The best results are not the nearest ones
The user, in blue, searches inside the dashed circle. The three nearest places, in grey, are 200 to 250 m away and closed or rated under 3.5. The top three results, in green and numbered (1), (2) and (3), are 400 to 650 m away. A search that stopped after the nearest places would never reach them.The user, in blue, searches inside the dashed circle. The three nearest places, in grey, are 200 to 250 m away and closed or rated under 3.5. The top three results, in green and numbered (1), (2) and (3), are 400 to 650 m away. A search that stopped after the nearest places would never reach them.
A ranked search has to score the candidates in the circle, not only the nearest few. The user, in blue, searches inside the dashed circle. The three nearest places, in grey, are 200 to 250 m away and closed or rated under 3.5. The top three results, in green and numbered (1), (2) and (3), are 400 to 650 m away. A search that stopped after the nearest places would never reach them.

Can one machine hold what search reads?

Search doesn't read a place's whole row. It reads the fields it filters on, the fields it ranks on, and the few it shows in a result.

Back of envelopeThe index, per place and in total
The question is whether one machine can hold everything
search reads, or whether the index has to be split. Field
sizes are assumed, for a compressed search index.

Per place
  location, a point in the geo tree               ≈  10 B
  category, price, rating, review count,
    popularity, time zone, as columns             ≈  20 B
  opening hours, next three days (deep dive 4)    ≈  40 B
  text: name, categories and about 40 terms
    taken from reviews, about 2 B a posting       ≈  90 B
  shown in the result: name, address, photo key   ≈  90 B
  place ID, the point again for distance, and
    features for the learned model (deep dive 3)  ≈  40 B
  ─────
  live document                                   ≈ 290 B
  deleted copies waiting for a merge, ~10%        ≈  30 B
  per place                                       ≈ 320 B

All of it
  250M places × 320 B                             ≈  80 GB

One search machine with 256 GB of memory
  tonight's index, in the filesystem cache        =  80 GB
  tomorrow's, loaded beside it at the switch      =  80 GB
  left for the process                            =  96 GB
  ─────────────────────────────────────────────────────────
One machine holds the whole index, with room for the next
night's copy beside it. The index doesn't need splitting
to fit.

Review text stays out. Yelp puts the average recommended review at about 460 characters, so 330 million reviews hold about 150 GB of text before any index is built, nearly twice the index above. An offline job picks about 40 terms per place from its reviews, such as the dishes people mention, and only those go in. A separate review index serves search inside reviews.

Where does the ranked search run?

Each candidate needs its filters checked and its score computed, about 14.5 million times a second at peak: 29,000 searches times 500 candidates. So where do the four steps run, and how many machines share one search?

Naive

Postgres, with PostGIS and full-text search, on read replicas

This is tempting. Geospatial indexing keeps points that stay put in Postgres with PostGIS, and Postgres has full-text search too. One data store holds the places, every write is visible at once, and nothing needs keeping in step. Read replicas take the searches off the primary.

It breaks on the two numbers that inverted indexes says to watch. The first is how many rows a common search matches. Take "restaurants open now" in a 1 km circle in Midtown, at an assumed 2,000 places per km², a third of them restaurants. That's about 2,100 rows, and Postgres reads every one to rank it. The second is rarity. Postgres ranks text by each row's own words and doesn't know how rare a word is across the table, so "ramen" counts for no more than "food".

And each replica is a full copy of the 600 GB database (section 2), kept in order to serve 80 GB of place fields. Postgres stays in the design as the system of record.

Senior

A search engine with geo fields, split into shards

Elasticsearch or OpenSearch holds one document per place. The location is a geo_point, which Elasticsearch indexes in a BKD tree, short for block k-d tree. That tree splits the map into smaller and smaller boxes where points are dense. Category and price are exact values, rating and review count are numbers, and the text fields go through analysis and are scored with BM25, the standard text relevance score.

The text term and the exact-value filters are lists of places, and the engine intersects them with the places the geo tree returns. Range checks such as rating and open now are made on each surviving candidate, from its columns. Scoring runs on the machine that holds the data, with a function such as a Gaussian decay on distance, and only the top 20 leave it. This is the standard answer, and Yelp moved its core business search to Elasticsearch in 2017.

By default the index is split into shards by a hash of each document's ID, and each shard has replicas. That's the cost. Every search goes to every shard, and each shard pays its own fixed work to run the query and send back its best results. Partitioning and sharding prices that fan-out. And shards move between nodes as nodes come and go. Yelp's 2021 post describes that last cost: shard placement left some nodes hot and others cold, and scaling was hard enough that the team always provisioned for peak.

Elasticsearch's replicas also index every change themselves, which OpenSearch can avoid by copying segment files instead. At 100 changes a second, that cost is small here.

Staff

One whole copy on every machine

Question the premise that 250 million documents need splitting. The worksheet says 80 GB, and that fits in one machine's memory. So don't shard. Every search machine holds the whole index, and one search runs on one machine from start to end.

This isn't one Elasticsearch shard, which Elasticsearch's guidance keeps to 10 to 50 GB and under 200 million documents. It's the model Yelp built Nrtsearch on, its own engine on Lucene, the library under Elasticsearch. Lucene keeps an index as a set of segments, files that never change once written, and it can search several segments at once on different cores.

The copies are made by copying files. One machine, the primary, takes every change and writes it into new segments. The other machines never index anything. They pull each new segment from the primary. A machine that starts up downloads the latest snapshot of the index from object storage, then catches up from the primary.

Yelp moved several search uses to Nrtsearch and reported p50, p95 and p99 latency 30 to 50 percent lower, and infrastructure costs up to 40 percent lower for some uses. Yelp still splits its business index into geographic clusters, and each cluster holds its piece whole.

Shards against whole copies
On the left, the index is split four ways. One search goes to all four shards, each pays its own fixed cost, and the reply waits for the last of them, in red (1). On the right, every machine holds all 80 GB. One search goes to one machine and is answered there (2). The primary writes segments and the replicas copy them (3).On the left, the index is split four ways. One search goes to all four shards, each pays its own fixed cost, and the reply waits for the last of them, in red (1). On the right, every machine holds all 80 GB. One search goes to one machine and is answered there (2). The primary writes segments and the replicas copy them (3).
A whole copy answers alone, and every shard adds its own fixed work. On the left, the index is split four ways. One search goes to all four shards, each pays its own fixed cost, and the reply waits for the last of them, in red (1). On the right, every machine holds all 80 GB. One search goes to one machine and is answered there (2). The primary writes segments and the replicas copy them (3).

The trade, sized with the formula's costs from deep dive 1. One search needs about 1 ms of fixed work to parse it, find the radius and build the reply, plus 0.5 ms of scoring. On a whole copy that's 1.5 ms of CPU. Split four ways, a coordinator still does the 1 ms once, but each shard adds its own fixed work, say 0.3 ms. That's 1 + 4 × 0.3 + 0.5 = 2.7 ms, nearly twice the CPU, and it grows with every shard added.

What you give up. Every machine needs memory for all 80 GB, Montana included, and a new machine copies 80 GB before it serves. There's also a ceiling, and Yelp's 2023 post on its Nrtsearch gateway puts it in index sizes. An index of tens of GB is fine and hundreds isn't, because the replicas keep columns in memory and download the whole index when they start. Deep dive 1 covers what to do past that.

Which geo index, for points that stay put?

Geospatial indexing compares geohash, S2, H3, quadtrees and R-trees. Its first question is whether the points move, and here they don't. That changes one trade.

A tree that adapts to density splits its cells where points are crowded, so cells are small in Midtown and huge in Montana. For drivers that's awkward, because every move reshapes the tree. Lucene's BKD tree adapts the same way, and it's built once for each segment, when the segment is written. Segments never change, so the tree never needs rebalancing. So the engine's own geo field is the right index here, and there's no separate geo service to build.

Fixed cells still appear outside the engine, as S2 cells, because their IDs never change and each cell sits exactly inside its parent. They key the table of search radii in deep dive 2, the cache keys in deep dive 5 and the counts a zoomed-out map shows. H3 has no job here: it suits adding up values per hexagon, such as demand.

2. A place's page

A place's page is a read by ID: the place, its newest reviews and its photos. Nothing on it needs the search index, so it reads the system of record.

Which data store, and what actually forces it

Back of envelopeThe system of record
The question is whether the data behind the pages and
the writes needs more than one database primary. Row
sizes are assumed.

Storage
  places     250M × 1 KB                          =  250 GB
  reviews    330M × 700 B, Yelp's 460-character
             average plus the other columns        ≈  230 GB
  photos     rows only, one per review assumed
             330M × 200 B                          ≈   66 GB
  users      100M × 500 B                          =   50 GB
  ─────────────────────────────────────────────────────────
  total, before indexes                            ≈  600 GB

Throughput
  writes     about 100/s
  reads      17,400 pages/s × 3 to 4 queries
                                    ≈  52,000 to 70,000/s

Against the course's figures for one relational primary:
  writes     5,000 to 20,000/s           100/s is 2% at most
  one table  comfortable to ~500 GB      the largest is 250 GB
  reads      50,000 to 100,000/s each    one or two replicas

One primary takes every write with room to spare.
Nothing here forces a distributed database.

So the system of record is one Postgres primary with read replicas, and relational suits it for two reasons. A review and the rating change it causes must commit together (section 3). And owners and moderators look places up by many columns.

PostGIS also answers the one geographic question the write side asks: is a new place a duplicate of one already within 50 m? At a few writes a second, that's the job geospatial indexing gives PostGIS.

data storewhat goes in itwhat forces it
Postgres, one primary, read replicas in each regionplaces, hours, reviews, photo rows, users600 GB and 100 writes a second; a review and its rating change commit together
search index, one whole copy per machineone 320-byte document per place14.5 million candidates scored a second, 80 GB in total
Kafka, a partitioned logevery change to the tables a document is built from, and to reviewsthe indexer rebuilds documents from it, and replays it after each night's build (section 4)
object storage, such as S3photo bytes, each night's index snapshot and derived fieldsbytes that never change, served through a CDN

The tables

-- Postgres, the system of record
places (
  place_id      bigint primary key,
  name          text not null,
  location      geography(point) not null,
  timezone      text not null,            -- an IANA name, such as America/New_York
  categories    int[] not null,
  price         smallint,                 -- 1 to 4
  rating_sum    int not null default 0,   -- recommended reviews only
  rating_count  int not null default 0,
  updated_at    timestamptz not null
)
create index places_location on places using gist (location);

place_hours (
  place_id      bigint,
  day_of_week   smallint,                 -- in local time, 1 is Monday
  opens         time,
  closes        time,                     -- before opens when it runs past midnight
  primary key (place_id, day_of_week, opens)
)

special_hours (
  place_id      bigint,
  local_date    date,
  opens         time,                     -- both null: closed all day
  closes        time,
  primary key (place_id, local_date)
)

reviews (
  review_id     bigint primary key,
  place_id      bigint not null,
  user_id       bigint not null,
  stars         smallint not null,
  body          text not null,
  status        text not null,            -- pending, recommended, not_recommended, removed
  created_at    timestamptz not null,
  unique (user_id, place_id)
)
create index reviews_by_place on reviews (place_id, created_at desc, review_id desc)
  where status = 'recommended';

photos (
  photo_id      bigint primary key,
  place_id      bigint not null,
  object_key    text not null,
  state         text not null,            -- pending, ready
  created_at    timestamptz not null
)
create index photos_by_place on photos (place_id, created_at desc) where state = 'ready';

Four things to note.

The rating is a sum and a count, never an average. An average can't take a review away again, and a sum and a count can. Both change in the same transaction as a review's status or stars, which section 3 builds.

Hours are local times with a zone name. America/New_York, never an offset from Coordinated Universal Time (UTC), because the offset changes twice a year. Deep dive 4 turns these rows into what search checks.

One review per user per place. The unique key makes a user edit their review instead of adding a second one, which also stops one account from stacking ratings.

The partial indexes hold only what a page lists. A page lists recommended reviews and ready photos, so pending and hidden rows stay out of both indexes. The viewer's own review is fetched by the unique key instead.

The queries that carry the product

-- 1. A place's page: the row, a page of reviews, and the viewer's own review
SELECT * FROM places WHERE place_id = $1;

SELECT review_id, user_id, stars, body, created_at
FROM reviews
WHERE place_id = $1 AND status = 'recommended'
  AND (created_at, review_id) < ($cursor_time, $cursor_id)
ORDER BY created_at DESC, review_id DESC
LIMIT 20;

SELECT review_id, stars, body, status FROM reviews
WHERE user_id = $viewer AND place_id = $1;       -- in any status

-- 2. A review moves into recommended: status and totals move together
BEGIN;
UPDATE reviews SET status = 'recommended'
WHERE review_id = $1 AND status IN ('pending', 'not_recommended')
RETURNING place_id, stars;
-- only if a row came back:
UPDATE places SET rating_sum = rating_sum + $stars,
                  rating_count = rating_count + 1
WHERE place_id = $place_id;
COMMIT;

-- 3. A review leaves recommended: un-recommended, removed or deleted
BEGIN;
UPDATE reviews SET status = $new_status
WHERE review_id = $1 AND status = 'recommended'
RETURNING place_id, stars;
-- only if a row came back:
UPDATE places SET rating_sum = rating_sum - $stars,
                  rating_count = rating_count - 1
WHERE place_id = $place_id;
COMMIT;

-- 4. Before adding a place: is it already here?
SELECT place_id, name FROM places
WHERE ST_DWithin(location, ST_MakePoint($lng, $lat)::geography, 50);

Query 1 runs most often, 52,000 to 70,000 reads a second at peak with the photo list, on replicas except for a viewer's own review just after they post it. Queries 2 and 3 are the ones an interviewer pushes on, usually by asking what happens when two reviews of one place land at once. Postgres takes a row lock for each UPDATE, so the two changes to the totals run one after the other and neither is lost. The status condition on each move makes a repeated move change nothing.

The search itself runs on a search machine, not in Postgres:

filter   place within radius_used of (lat, lng)
         category = japanese, price in (1, 2), rating >= 4
         an opening interval contains now (deep dive 4)
match    "ramen" in name, categories and review terms
score    text match × adjusted rating × distance decay (deep dive 3)
rerank   the top 100 with the learned model (deep dive 3)
return   top 20, then a cursor of (score, place_id)

3. Reviews and photos

A review is a row in reviews. The hard part is what it does to the place's rating, which every search reads for every candidate.

How does a review change the rating?

Yelp computes a business's star rating from its recommended reviews only, and its recommendation software decides which reviews those are. The software runs after a review is written, and Yelp says the reviews it recommends for a business can change over time. So when should a review change the rating, and how?

Naive

Average the stars when the page is read

SELECT avg(stars) FROM reviews WHERE place_id = $1 is always right and stores nothing extra. For a page view it's tolerable: a place with 2,000 reviews reads 2,000 rows.

Search kills it. Every candidate needs its rating to be scored, and search scores 14.5 million candidates a second. The rating has to be a stored number that the index copies.

Senior

A sum and a count, changed with the insert

Store rating_sum and rating_count on the place, and add to both in the same transaction that inserts the review. The average is one division, the index copies two numbers, and a deleted review subtracts its stars. Concurrent reviews are safe, because each UPDATE adds to the row under its lock. Most review systems run this.

The cost is that a review counts the moment it's written, before anything has checked it.

Staff

Count a review when it is recommended, not when it is written

Question the premise that a review should count on arrival. Requirement 3 asks for the rating within minutes of a review being recommended, not of its being written. A new review is inserted as pending and changes no totals.

The classifier reads each new review from the change stream (section 4). It scores most of them within seconds. A review from a new account, or one of a sudden burst on one place, stays pending until there's more signal. That signal, such as what the account does next, can take hours to arrive. The totals change only when a status moves into or out of recommended.

Sized with Yelp's 2024 report: about a fifth of some 21 million reviews were not recommended or were removed. Counted on arrival, about 4.4 million reviews a year, 12,000 a day, would move a rating and later be taken back out. A burst of paid reviews would lift a place in search until the classifier had seen enough to judge it.

A burst of fake reviews, counted two ways
Time runs left to right, for a place with 72 reviews averaging 3.6. Forty 5-star reviews from new accounts land in an hour (1). Counted on arrival, in red, the rating jumps from 3.6 to 4.1, and the place ranks higher in search until the classifier, hours later, has enough signal to mark them not recommended (2). Held as pending and counted only when recommended, in green, the rating never moves (3).Time runs left to right, for a place with 72 reviews averaging 3.6. Forty 5-star reviews from new accounts land in an hour (1). Counted on arrival, in red, the rating jumps from 3.6 to 4.1, and the place ranks higher in search until the classifier, hours later, has enough signal to mark them not recommended (2). Held as pending and counted only when recommended, in green, the rating never moves (3).
Holding new accounts' reviews as pending keeps the burst out of the rating. Time runs left to right, for a place with 72 reviews averaging 3.6. Forty 5-star reviews from new accounts land in an hour (1). Counted on arrival, in red, the rating jumps from 3.6 to 4.1, and the place ranks higher in search until the classifier, hours later, has enough signal to mark them not recommended (2). Held as pending and counted only when recommended, in green, the rating never moves (3).

What you give up. A new review doesn't move the rating until it's classified, hours later for a new account. The classifier is now on the write path, so while it's down, reviews still save but ratings stop changing. A place under a burst can also have its rating frozen and a notice put on its page while a person looks.

Every change to a review's status or stars goes through a transaction that moves the totals with it, and each is guarded by the status it expects.

  • Into recommended, query 2 adds the stars and 1.
  • Out of recommended, when the classifier changes its mind or a moderator removes the review, query 3 subtracts them. Deleting a review first locks its row with SELECT ... FOR UPDATE, then runs query 3 and the DELETE in the same transaction, so the classifier can't recommend it in between. Deleting an account does the same for each of its reviews.
  • A recommended review edited from 2 to 5 stars adds the difference, 3, to rating_sum in the same transaction as the edit, which reads the old stars and status with SELECT ... FOR UPDATE. An edit to a review in any other status changes no totals.

Deep dive 8's nightly drift check catches anything these miss.

The page always shows the viewer their own review of the place, in any status, through the third read in query 1. For a window after they post it, set from the replicas' lag p99, that read goes to the primary, because a replica may not have the row yet. Every other read stays on replicas.

Photos

A photo takes three steps, as in object and blob storage.

  1. The API inserts a photos row in state pending, picks the object key, and returns a pre-signed URL for that one key that expires in minutes.
  2. The client uploads the bytes straight to object storage.
  3. The bucket's event reaches a worker. It checks the image, writes a small thumbnail for search results and a larger size for the page, and moves the row to ready.

The CDN serves every size, and deep dive 1 shows those bytes are the largest load in the system.

4. Add or change a place

An owner changes Friday's hours. The place service checks the change, writes it to place_hours, and tells the owner it's saved. The owner's own dashboard reads Postgres, so they see the change at once.

How does a change reach the index?

The edit is committed in Postgres, and every search machine in every region has to see it within a minute. So what carries a committed change from the database to the index, without losing one or applying two out of order?

Naive

The service writes Postgres, then the index

The place service commits the row, then sends the new document to the search primary. It's one more call in code the team already owns, and the change is searchable about a second later, after the index's next refresh.

It breaks when two writers race or one dies. Two editors save the same place 50 ms apart, the database commits A then B, and the index receives B then A. The database says B and the index says A until someone edits the place again. A service that dies between the two writes leaves the index without the change at all.

Senior

Read the database's log, and index from it

Change data capture reads Postgres's write-ahead log with Debezium into Kafka. Capture every table a document is built from: places, place_hours, special_hours and photos, plus reviews for the classifier. photos is set to REPLICA IDENTITY FULL, so even a delete event carries the place ID. Debezium writes one topic per table, and nothing orders one topic against another.

So the indexer doesn't apply an event's contents. It sends each event to a worker chosen by the event's place ID, so one worker handles all of a place's events, one at a time. Debezium's events don't carry their own transaction's commit position, so the worker makes its own mark. When the event arrives, it takes the primary's current log position, L, and every change the event describes committed before L. It reads the place's current rows from a Postgres replica in its own region once that replica has replayed past L, or from the primary, and rebuilds the whole document.

The indexer also enforces order itself. The change data capture page refuses an older write with Elasticsearch's external versions, and Nrtsearch has no such check. So the indexer keeps, for each place and each index, the position L its document was last read at, and refuses a write read at an older one. The check, the index write and recording L happen under one per-place lock, so a worker still finishing an old write after the place's events have moved can't land behind a newer one. A new index starts with an empty table of its own. It's 250 million entries of about 16 bytes, 4 GB, in a key-value table on the indexer's own disk.

This is what most teams run, and it meets requirement 3. The cost is in the fields no edit changes. Each place's terms from reviews and its popularity come from offline jobs. Pushing them through the index means rewriting most of the 250 million documents, and inverted indexes prices that: every rewrite leaves a deleted copy for merges to clean up.

Staff

Rebuild the whole index every night, and stream only today's changes on top

Question the premise that the index is a long-lived thing you keep patching. It's a derived copy of 250 million rows that fits on one machine. So build it from scratch every night, with every derived field computed fresh, and use the stream only for the hours in between.

The build writes each place's derived fields, its review terms and popularity, to a file in object storage. The indexer loads that file into a table on its disk, so a document it rebuilds during the day carries last night's derived fields. Both paths call one document-building library, and a nightly job builds a sample of documents both ways and compares them.

The snapshot and the stream have to meet at one point, or edits go missing. The build creates a replication slot, and Postgres exports a snapshot of the database at exactly the position P where that slot's stream begins. The build reads every table inside that snapshot, then drops the slot, because an open slot keeps the database's log from being cleared. The new index then replays the stream from a few minutes before the snapshot was taken. Debezium sends a transaction's changes only once it commits, so every change committed after P reaches Kafka after that moment. Starting early is harmless, because an extra event only rebuilds a place from current rows.

The nightly build, and the stream on top
Time runs left to right, from 01:00 to 06:00. At 02:00 the build reads the snapshot exported at position 8,410 (1). It builds, tests and uploads the new index by 03:10 (2). The search primary loads it and replays the stream from a few minutes before the snapshot, which covers the changes made during the build, in orange, while it keeps applying the same stream to the old index (3). Each replica loads and warms the new index, and switches once the new index has caught up with the stream. Only then does the primary drop the old one (4).Time runs left to right, from 01:00 to 06:00. At 02:00 the build reads the snapshot exported at position 8,410 (1). It builds, tests and uploads the new index by 03:10 (2). The search primary loads it and replays the stream from a few minutes before the snapshot, which covers the changes made during the build, in orange, while it keeps applying the same stream to the old index (3). Each replica loads and warms the new index, and switches once the new index has caught up with the stream. Only then does the primary drop the old one (4).
The old index keeps taking changes until the last replica has switched. Time runs left to right, from 01:00 to 06:00. At 02:00 the build reads the snapshot exported at position 8,410 (1). It builds, tests and uploads the new index by 03:10 (2). The search primary loads it and replays the stream from a few minutes before the snapshot, which covers the changes made during the build, in orange, while it keeps applying the same stream to the old index (3). Each replica loads and warms the new index, and switches once the new index has caught up with the stream. Only then does the primary drop the old one (4).

The switch follows from there. The build runs a fixed set of test searches against the new index and uploads it. The search primary loads it and replays the stream, while it keeps applying the stream to the old index. Each replica downloads the new index beside the old one, 160 GB on a 256 GB machine, and reads it once so its filesystem cache isn't cold. Once the new index has caught up with the stream, the replica switches. Only when every replica has switched does the primary drop the old index.

Size the build with the course's figure of 5,000 to 20,000 documents a second for one indexing node. 250 million documents take 3.5 to 14 hours on one node, or 21 to 83 minutes on ten nodes building parts in parallel. Ten machines for an hour a night keep every derived field less than a day old.

What you give up. A failed build leaves yesterday's index serving with the stream still applied, so only the derived fields go a day stale. A mistake in the build reaches every machine by morning, which the test searches are there to catch. And every replica needs memory for two copies for a few minutes a night.


Deep dives

1. How many servers, and what actually needs scaling?

Section 1 decided on one whole copy per search machine. The remaining question is how many machines, and whether search is the part that grows at all.

Back of envelopeSearch machines, and the bytes beside them
The question is what sets the size of the fleet. Costs
per search and payload sizes are assumed.

Search, per query
  formula: ~500 candidates at ~1 µs each      ≈  0.5 ms CPU
  learned model: top 100 at ~20 µs each       ≈    2 ms CPU
  parse, find the radius, build the reply     ≈    1 ms CPU
  ─────
  per search                                  ≈  3.5 ms CPU
  a core gives 1 s of CPU each second, so one 32-core
  machine kept under 60% busy serves
                  32 × 0.6 / 0.0035           ≈   5,500/s
  (the course's working range for a search node
   is 5,000 to 30,000 a second)

Search machines, three regions
  normal share     29,000 / 3                 ≈   9,700/s
  one region lost  29,000 / 2                 =  14,500/s
  serving machines 14,500 / 5,500             →  3 a region,
                   one in each zone
  plus the search primary                     →  1 a region
  total            (3 + 1) × 3                =       12

Photos, sent by the CDN at peak
  a search page    20 thumbnails × 15 KB      =   300 KB
  a place page     10 photos × 60 KB          =   600 KB
  29,000 × 300 KB + 17,400 × 600 KB
                   8.7 GB/s + 10.4 GB/s       ≈  19 GB/s
                   × 8 bits                   ≈ 150 Gbps
  ─────────────────────────────────────────────────────────
Search, the part the interview spends its time on, fits
on 12 machines. Both grow with users, and the photos, at
150 Gbps, are by far the larger bill.

So the CDN carries the system's largest load, and photo storage and transfer are the bill that grows fastest. The rest is small. The place service and the review service keep no state and scale on request rate. Postgres is one primary and a replica or two per region. The indexer and the nightly build are a handful of machines.

Latency has room to spare too. 3.5 ms of CPU on one machine, plus a load balancer and a network hop inside the region, leaves most of the 100 ms budget for queueing.

The index has a ceiling, and it's memory. Doubling the places, or putting review text in the index, would push it towards the hundreds of GB that Yelp's gateway post says is too much for one cluster. Then split it by area, as Yelp does. Its gateway gives each cluster a bounding box and also indexes the businesses near the boundary, what the post calls a "fudge factor".

That margin is where splitting by area hurts. Yelp's 2021 post says its largest geographic shards turned out to be "extremely dense", and some searches cover tens of square miles. Keeping each search inside one shard would then mean copying a lot of data into the margins. So delay the split: a bigger machine first, review text kept in its own index, and areas only when neither is enough.

2. Manhattan and Montana: how far should a search reach?

A search with no text, such as "restaurants open now", needs a radius before it can find candidates. The same radius is wrong at both ends of the map.

Back of envelopeOne radius, three places
The question is how many candidates a fixed 1 km radius
gives, and what radius would give about 500. Densities
are assumed.

  area of a 1 km circle      π × 1²              ≈  3.14 km²

Candidates within 1 km
  Midtown Manhattan   2,000 per km² × 3.14       ≈  6,300
  a suburb               50 per km² × 3.14       ≈    160
  rural Montana        0.05 per km² × 3.14       ≈   0.16

Radius that holds 500 places, r = √(500 / (π × density))
  Midtown             √(500 / 6,283)             ≈  280 m
  suburb              √(500 / 157)               ≈  1.8 km
  rural Montana       √(500 / 0.157)             ≈   56 km,
                      capped at 40 km, which holds about 250
  ─────────────────────────────────────────────────────────
A fixed radius scores 6,300 candidates in Midtown and
finds nothing in Montana. The right radius differs about
200 times between the two.

So how does a search find about the right number of candidates in both places, without running several queries to get there?

Naive

Use the radius the client sends

The client sends 1 km, and the search uses 1 km. It's simple, and a user who asked for 1 km gets what they asked for.

The worksheet breaks it at both ends. Midtown scores 6,300 candidates per search, more than 12 times the 500 the fleet is sized for. Rural Montana returns an empty page.

Senior

Widen in rings until the page fills

Start small and double the radius until a page of results comes back, the ring search from geospatial indexing. That page keeps rings for a grid of moving points and uses nearest-K for places that stay put. A ranked search can't use nearest-K, so it comes back to rings.

Start at 250 m. Midtown fills its page at once, with about 390 candidates, and the empty countryside widens until it finds enough. This works everywhere and needs nothing stored.

The cost is repeated queries where places are sparse. From 250 m, rural Montana doubles six to eight times before it fills a page, so one search there runs seven to nine queries, each a full filter pass. A suburb runs two or three.

Staff

Work out each cell's radius ahead of time

Question the premise that the radius has to be found at query time. It depends only on where places are, so it can be worked out once a night. The build runs a nearest-500 query from the centre of each S2 cell and records the distance to the 500th place. Every search machine keeps that table of radii. A search looks up the user's cell and runs once with that radius: 280 m in Midtown, 1.8 km in the suburb and 40 km in Montana.

The table is small. S2 level 13 cells average 1.27 km², and there are 402 million of them on Earth. At 2 bytes a radius, a table covering every one of them is about 800 MB, and only cells near places need an entry.

A narrow filter still empties a page sometimes. "Ethiopian" within 280 m of a Midtown corner may find nothing. So the search widens from the cell's radius, doubling at most a few times. That's one or two extra queries on the narrow searches, instead of six to eight on every search in the countryside.

What you give up. Search reach depends on a nightly table, so a new mall stays on the old radius until the next build. And in Midtown a 4.9-star place 600 m away is outside a broad search, which is the trade Yelp's API documents when it calls the radius a suggestion.

A map view sets its own area, so it needs no radius. A view zoomed out over a whole state can hold millions of places, though. So the map shows counts per cell there, and the list ranks places only once the view is small enough.

3. Ranking: distance, rating and text

Once a search has its candidates, they need an order. The obvious orders are each wrong in a way users notice quickly.

Naive

Sort by distance, or by average stars

Each needs only one sort key, and public APIs offer both. Google's Nearby Search ranks by popularity unless you ask for distance, and Yelp's API lets you ask for rating.

Distance alone puts the closed 2-star deli next door above everything. Raw stars put a place with one 5-star review above a place with 900 reviews averaging 4.4. Yelp's API documentation names the single review as the problem. Its rating sort uses an adjusted rating, "similar to a Bayesian average", so that businesses with a single review don't skew the results.

Senior

An adjusted rating, blended with distance and text

A Bayesian average adds m imagined reviews at the overall mean C to every place's own reviews. A place with few reviews stays near C, and a place with many keeps its own average. Then one score combines it with how well the text matched and a decay on distance. Elasticsearch's Gaussian decay is one: it scores a place at its origin 1.0, and a place scale metres away 0.5.

Back of envelopeThree places, sorted raw and adjusted
The question is how strong the pull towards the mean
should be. C is about 3.8, the average rating Yelp users
gave in 2023. m = 10 is assumed.

adjusted = (C × m + sum of stars) / (m + n)

  place X   n = 1,    average 5.0, sum 5
            (38 + 5) / (10 + 1)            ≈  3.91
  place Y   n = 12,   average 4.75, sum 57
            (38 + 57) / (10 + 12)          ≈  4.32
  place Z   n = 900,  average 4.4, sum 3,960
            (38 + 3,960) / (10 + 900)      ≈  4.39
  ─────────────────────────────────────────────────────────
Raw, the order is X, Y, Z. Adjusted, it is Z, Y, X. One
review barely moves a place, and 900 reviews keep their
average. Y and Z are close, so m decides between them:
set it near the review count at which an average starts
to mean something for that category.

This is the standard answer. The cost is the distance term. One scale for the whole world is wrong in both of deep dive 2's places. With a 1 km scale, every place in a 280 m Midtown search scores almost the same on distance. In Montana, everything past a few km scores almost zero. Either way, distance stops doing its job.

Staff

Measure distance against the local density

Question the premise that distance is a number of metres. To a user, a place is far if it's farther than the other places they could choose. Deep dive 2 already measured that for every cell, as the radius that holds about 500 places. So set the decay's scale to half the cell's radius. In Midtown, a place 140 m away scores 0.5. In Montana, a place 20 km away does.

The same decay, scaled to each place
Each curve is the distance score, from 1.0 at the user down towards 0. The red curve uses one 1 km scale everywhere: it is nearly flat across Midtown's 280 m and nearly zero across Montana's 40 km. The green curves use half of each cell's radius, so both fall to 0.5 halfway out.Each curve is the distance score, from 1.0 at the user down towards 0. The red curve uses one 1 km scale everywhere: it is nearly flat across Midtown's 280 m and nearly zero across Montana's 40 km. The green curves use half of each cell's radius, so both fall to 0.5 halfway out.
Distance counts the same against the choices nearby, wherever the user is. Each curve is the distance score, from 1.0 at the user down towards 0. The red curve uses one 1 km scale everywhere: it is nearly flat across Midtown's 280 m and nearly zero across Montana's 40 km. The green curves use half of each cell's radius, so both fall to 0.5 halfway out.

The blend's weights then come from what users choose, not from a guess. Log which result each search led to, and fit a model to it offline. Yelp's 2021 post gives its existing machine-learned ranking code as one reason to build its engine on Lucene.

Scoring runs in two passes to keep the cost bounded. The formula above scores all 500 candidates, and the learned model re-ranks only the top 100. Deep dive 1 counts both passes in the fleet.

What you give up. The meaning of "far" now changes with the nightly table, so a ranking can shift with no change to any place near it. And a learned model needs logging, offline training and a way to compare it with the last one before it ships.

4. "Open now", in the place's own time zone

"Open now" sounds like a comparison of two times. But the place's time zone may not be the user's, its hours can run past midnight, the clocks change twice a year, and holidays have hours of their own.

The first instinct is to convert each place's hours to UTC once, when they're saved, and compare against the current UTC time. That's right until the clocks change. A New York café that opens at 9:00 opens at 14:00 UTC in winter and 13:00 UTC in summer. Stored once in January, its summer hours are an hour late for eight months, and "open now" says it's closed from 9:00 to 10:00 every morning.

So the tables hold local times and the zone name. Two more cases come from the hours themselves. A bar open Friday from 18:00 to 02:00 runs past midnight, so its closing time is earlier than its opening time. Yelp's API marks such a range with is_overnight. And special hours for a date, such as a holiday, override the regular ones, as Yelp's API also documents.

Checking all of that per candidate, at query time, means time-zone arithmetic 14.5 million times a second. A query can do it once per zone instead, but a map view can cross a zone boundary, and special hours need a second lookup.

Hours change rarely, so the nightly build resolves all of it ahead of time. For each place it applies the zone rules, the overnight ranges and any special hours, and writes the place's actual open intervals in UTC for the next three days. "Open now" is then one comparison of numbers: is the current UTC minute inside one of the intervals? An edit to a place's hours recomputes its intervals through the change stream within the minute.

Weekly hours, and the intervals search checks
A New York bar is open Friday 18:00 to 02:00 local time. Converted to UTC once, in January, the stored range runs from 23:00 to 07:00 UTC, in red, an hour late after the clocks go forward. It says closed for the first hour of the evening and open for an hour after closing. The nightly build, in green, writes Friday 22:00 to Saturday 06:00 UTC for a summer weekend, from the zone rules for that date.A New York bar is open Friday 18:00 to 02:00 local time. Converted to UTC once, in January, the stored range runs from 23:00 to 07:00 UTC, in red, an hour late after the clocks go forward. It says closed for the first hour of the evening and open for an hour after closing. The nightly build, in green, writes Friday 22:00 to Saturday 06:00 UTC for a summer weekend, from the zone rules for that date.
The build turns local rules into plain UTC intervals for the next three days. A New York bar is open Friday 18:00 to 02:00 local time. Converted to UTC once, in January, the stored range runs from 23:00 to 07:00 UTC, in red, an hour late after the clocks go forward. It says closed for the first hour of the evening and open for an hour after closing. The nightly build, in green, writes Friday 22:00 to Saturday 06:00 UTC for a summer weekend, from the zone rules for that date.

Three days of one or two intervals a day, at 8 bytes an interval, is about 40 bytes a place, the figure in section 1's worksheet. Three days rather than one gives the build two nights of slack. If it fails two nights running, one day of intervals is left, and that has to page someone.

Precomputing also freezes the zone rules for three days. So when a new release of the time zone database changes a zone, the indexer recomputes the intervals of that zone's places the same day, through the same library. The same intervals answer "open at 20:00 tonight", which Yelp's API offers as open_at.

5. Caching by cell and viewport

The search tier holds its whole index in memory, so a cache of results in front of it saves little CPU. The cache that helps is at the edge, in the CDN's points of presence (PoPs) near the user. It suits logged-out searches: not personalised, and repeated by many people. A logged-in user's search skips it and goes to a search machine.

It only works if two users' requests produce the same key, and raw coordinates never do. A latitude to six decimal places differs between two people on the same corner, and a map view's four bounds differ with every pan. Keyed on those, every request is new and the hit rate is zero, the failure CDNs and edge compute calls key cardinality.

So snap the inputs before they become a key. A point becomes the S2 cell that holds it, at a level about half as wide as the search radius there: level 16, about 140 m across, in Midtown. A map view becomes the smallest block of map tiles that holds it at its zoom level. The text and filters are lowercased and sorted. Users on one corner, or panning over the same few streets, now share keys.

Snapping requests to shared keys
Two users stand 120 m apart in the same purple cell, and their searches snap to one key (1). Two map views, panned a few streets apart, fit inside the same block of tiles, outlined in purple, and snap to another key (2). Each entry holds what those requests share, and a function at the edge finishes each request with its own point or view (3).Two users stand 120 m apart in the same purple cell, and their searches snap to one key (1). Two map views, panned a few streets apart, fit inside the same block of tiles, outlined in purple, and snap to another key (2). Each entry holds what those requests share, and a function at the edge finishes each request with its own point or view (3).
Requests a few metres apart share one cached entry. Two users stand 120 m apart in the same purple cell, and their searches snap to one key (1). Two map views, panned a few streets apart, fit inside the same block of tiles, outlined in purple, and snap to another key (2). Each entry holds what those requests share, and a function at the edge finishes each request with its own point or view (3).

A cached entry can't hold one user's top 20, because two users in a cell stand at different points. So it holds what they share. For a cell, that's every candidate within the radius of any point in the cell, with its formula score before distance and its location. In Midtown, with a 280 m radius and 140 m cells, that's every place within about 380 m of the cell's centre, about 900. For a block of tiles, it's the block's top 500 places by score.

A small function running in the PoP finishes each request, the edge compute that CDNs and edge compute describes. It keeps the places inside the user's own radius or view, multiplies in the distance from the user's exact point, and returns the top 20. For a point, that matches the search machine's formula pass, because only the distance term depends on where the user stands.

Two things are lost at the edge. The learned model doesn't run there, so a cached answer is a little less well ranked. And a map view's answer is close rather than exact, since the block is a little larger than the view.

A time to live (TTL) of 30 seconds needs no invalidation. The stream and the index take a few seconds more, so a cached answer stays inside requirement 3's minute, and a place that opens at 9:00 shows as open by 9:01. The cached response carries nothing about the user, so one user's data never lands in another user's response.

Place pages cache the same way for logged-out readers, also for 30 seconds. The photos are the cache that's required: without the CDN, 150 Gbps would leave our own servers.

6. Multi-region

The service runs in three regions so that a user is served from one near them and a region can fail. For each kind of data, decide whether every region holds all of it, and where its writes land.

The search index is the easy part, because it's small and read-only. At 80 GB, every region holds the whole thing, and a search in any region never leaves it. Each night's build is uploaded once and copied to object storage in the other two regions. Each region runs its own search primary and indexer, reading a copy of the change stream that Kafka's MirrorMaker makes, and finding its place in it by time.

Postgres has one primary, in one region, and it accepts every write. A review from Europe makes one round trip to it, 60 to 200 ms between continents by consistency models, and only a few writes a second need that. Each region has read replicas for its place pages and for its indexer.

Photos are the largest data, so only part of them is copied. Each region's object storage holds a copy of the sizes the CDN serves, the thumbnail and the page size. The originals stay in the write region, with a backup in a second one.

Writes in one region, a whole copy everywhere
The write region holds the one Postgres primary, and reviews and edits from the other regions cross to it, in blue (1). Debezium reads its log into Kafka, MirrorMaker copies the stream to each region, and each region's indexer rebuilds documents from Postgres rows in its own region for its own search primary (2). The nightly snapshot and the served photo sizes are copied to each region's object storage (3), and Postgres keeps a read replica in each region.The write region holds the one Postgres primary, and reviews and edits from the other regions cross to it, in blue (1). Debezium reads its log into Kafka, MirrorMaker copies the stream to each region, and each region's indexer rebuilds documents from Postgres rows in its own region for its own search primary (2). The nightly snapshot and the served photo sizes are copied to each region's object storage (3), and Postgres keeps a read replica in each region.
Every region reads locally, and every write goes to one place. The write region holds the one Postgres primary, and reviews and edits from the other regions cross to it, in blue (1). Debezium reads its log into Kafka, MirrorMaker copies the stream to each region, and each region's indexer rebuilds documents from Postgres rows in its own region for its own search primary (2). The nightly snapshot and the served photo sizes are copied to each region's object storage (3), and Postgres keeps a read replica in each region.
Back of envelopeWhat a whole copy in each region costs
The question is whether copying to every region is cheap
enough to do without thinking about it.

  search index         80 GB × 12 machines      ≈ 960 GB of memory
  nightly snapshot     80 GB × 2 other regions  = 160 GB a day
  change stream        100 changes/s × 2 KB × 2 = 400 KB/s
  Postgres replicas    600 GB × 3 regions       ≈ 1.8 TB
  photo sizes          330M × (15 + 60) KB
                         × 2 other regions      ≈  50 TB
  ─────────────────────────────────────────────────────────
The photos are most of it, and copying only the served
sizes keeps them to 50 TB. Splitting the places by region
would save about two-thirds of the index copies, some
640 GB of memory, which doesn't pay for a split.

Data residency rules can still force a split, such as keeping one country's reviews in its own region. That's a legal requirement, and the numbers above don't create one.

When the write region fails, search everywhere keeps answering from its last index, with nothing missing but the changes since. Reviews and edits fail until a replica in another region is promoted. Multi-region and disaster recovery covers what that costs: the reviews written inside the replication lag at the moment of failure are stranded in the failed region. The promotion also breaks the stream, because Debezium's replication slot was on the failed primary, and changes around the failover can be missed. So after a promotion, pause the indexers. Once Debezium streams from the new primary, reset the per-place positions, which the new primary's log doesn't continue, resume, and run the nightly build at once. In that order, every edit is in the new snapshot or the new stream.

7. Fake reviews, briefly

People fake ratings because a rating decides rank. Section 3 already holds the defence. A review counts only once it's recommended, reviews from new accounts and sudden bursts wait as pending, and a place under a burst can have its rating frozen. Yelp says the reviews its software recommends can change as it learns more, so the classifier re-scores old reviews too, and each change moves the totals through query 2 or 3. The one-review-per-user key stops the cheapest attack, one account rating a place many times.

8. How do you know it is working?

During an incident you need four answers quickly. Are searches coming back empty? How far behind is the index? Is "open now" about to go wrong? Do ratings still match the reviews?

  • Empty and short pages, per region and per density band. A rise only in sparse cells points at the density table. A rise everywhere points at the index.
  • Index lag, from commit to searchable. A canary edit is written to Postgres every minute and searched for on every machine. Beside it, the age of the index each machine loaded, which should never pass a day.
  • Hours of open intervals left. Normally between 48 and 72. Below 48, a build has failed. Below 24, "open now" is a day from being wrong.
  • Rating drift. A nightly job recomputes every place's sum and count from its recommended reviews and counts the mismatches, which should be zero.

Label these by region and by density band, never by place or user. 250 million places would be 250 million time series.


Final design

The final design, with the path of one search
Blue is the user and their requests, purple the search path, orange the data stores and the change stream, teal the services beside search, yellow the nightly build and its table, and grey the other two regions. The badges 1 to 5 follow one search, and 6 to 8 follow a review and the updates to the index.Blue is the user and their requests, purple the search path, orange the data stores and the change stream, teal the services beside search, yellow the nightly build and its table, and grey the other two regions. The badges 1 to 5 follow one search, and 6 to 8 follow a review and the updates to the index.
Every search machine holds the whole index, and every write goes to one database. Blue is the user and their requests, purple the search path, orange the data stores and the change stream, teal the services beside search, yellow the nightly build and its table, and grey the other two regions. The badges 1 to 5 follow one search, and 6 to 8 follow a review and the updates to the index.

One search, and the writes that change what it sees:

  1. The app sends the search to the nearest region. If the request is logged out and its snapped key is cached, the PoP answers it there. An edge function keeps the places in the user's radius and ranks them with the exact distance.
  2. The search service looks up the user's S2 cell in the density table for radius_used and the distance scale, and sends the search to one search machine.
  3. That machine holds the whole index. It finds the places within the radius, matches the text, and checks category, price, rating and an open interval containing now.
  4. On the same machine, the formula scores each candidate by text match, adjusted rating and distance decay. The learned model re-ranks the top 100, and the machine returns the top 20 with a cursor.
  5. The app loads the thumbnails from the CDN, which reads them from the region's object storage.
  6. A review is inserted as pending in the Postgres primary. The classifier reads it from the change stream, and when it recommends the review, one transaction changes its status and the place's rating_sum and rating_count.
  7. Debezium reads that change from the log into Kafka. The indexer takes the primary's log position and rebuilds the place's document from current rows and last night's derived fields. It writes it to the search primary unless a newer read got there first, and the replicas copy the new segment.
  8. Each night the build reads a snapshot exported at position P, and writes a new index, the derived fields, the open intervals and the density table. Each search primary loads the index and replays the stream from a few minutes before the snapshot, while still feeding the old one. Each replica warms the new index and switches once it has caught up.

The numbers behind the shape: 250 million places at about 320 bytes make an 80 GB index, so a search never leaves one machine. At about 3.5 ms of CPU a search, 12 machines across three regions, three serving and one primary in each, handle 29,000 searches a second at peak. Search reads about 29,000 places for each one written, and the photos, at 150 Gbps, are the largest load.


What is expected at each level

How interviewers turn what they see into these levels is in How a System Design Interview Is Scored.

Mid-level

Breadth matters more than depth at this level, and it's fine to be led.

You should explain why a B-tree on latitude and longitude doesn't serve "nearby", and describe one cell scheme with its neighbouring cells and a distance check. You should keep places in a relational database and search them through a search engine. Photos go in object storage behind a CDN, and the rating is stored rather than averaged from the reviews on every read.

You aren't expected to raise a radius per cell, segment copies or overnight hours without being asked. You are expected to answer sensibly when asked "a place has one 5-star review, where does it rank?"

Senior

You drive the structure, and three things should come up without prompting.

The ratio of reads to writes, and what it allows. Say that the index is a copy fed from the database's log, how each change is applied in order, and how far behind the index may be.

Ranked isn't nearest. Say that the candidates in the area all get scored, so the candidate count is the cost, and that density makes a fixed radius wrong at both ends.

A rating that survives few reviews. A sum and a count kept right through every status change, an adjusted average, and what sets the strength of the adjustment.

Three things are disqualifying: a B-tree on latitude and longitude, sorting by raw average stars, and opening hours stored in UTC.

Staff+

A correct design is still the bar. A staff+ answer also decides what not to build.

Size the index before splitting it. About 320 bytes a place, 80 GB, one whole copy per machine, and the ceiling at hundreds of GB where splitting by area starts.

Find the binding load. Twelve search machines against 150 Gbps of photos.

Work out ahead of time what doesn't move. A radius per cell, open intervals for the next three days, and a whole index rebuilt every night that meets the stream at the snapshot's position.

Count a review when it's recommended, and size what counting on arrival would let through.

Be able to say what you would not build. No sharded search cluster with scatter-gather for an 80 GB index. No separate quadtree service when the engine's geo field already adapts to density. No forced refresh of the index on every write when requirement 3 allows a minute. No result cache in front of an index that is already in memory. No database that accepts writes in every region for 100 writes a second. No migration from geohash to H3 when the problem was a radius chosen without the density. A team could spend a quarter on any one of these.


Sources

The figures about Yelp, Google and the tools below come from these sources, read for this page. User counts, densities, row sizes and per-search costs are assumptions, stated in the worksheets that use them.

Spot a mistake, or something unclear? . Or get in touch.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.