Ch.40: Yelp System Design: The Missing Café

Outline

Transcript

0:00 Fictional case: Nora searches within 300 meters. Azul is open across the street, 140 meters away. Missing. The app sends her 1.8 kilometers away. It's right there. That's almost impressive. Is the app measuring from another planet? Worse: it never checked Azul. They straddle a map-cell border. That leaves the café outside the lookup, inside her circle. That border bug opens our full architecture map. Across the top: Nora's request, every map cell her circle touches, a directory selecting the layout, candidate storage, then exact distance filtering.

0:34 And underneath, what keeps the café's stored location current? Place edits, a database and durable change log, a worker updating the search index, and a repair sweep comparing it with the source record. What's the thread through both paths? Reach every place her circle can include, then keep each stored copy current. One request may touch four smaller search areas, called leaves; one move repairs two locations. We'll follow that request and a broken move, then return to this same diagram. Every box will answer one of those two promises.

1:08 Before we choose the boxes, what exactly has to be true for Nora? The functional requirements are open cafés inside her radius, ranked by measured distance, with at most 50 results. When Azul moves or closes, its obsolete location must disappear. No reviews, routes, or ads here. And our non-functional requirements: chosen P 99 under 300 milliseconds; place changes indexed within 1 minute. I'd probably accept that freshness window. Would you accept missing Azul to hit the latency target? No. Fail the exact request explicitly.

1:41 We won't silently omit Azul to meet a stopwatch. Let's hear it: how can we find Azul across that border? First, take that border. H three, the hexagonal map-grid library, can select cells whose centers sit inside a polygon. But Nora's circle enters a neighbor without reaching its center. We need every touched cell, not just every inside center. What does center-only selection miss? Like a room search that checks where the dining tables stand. You'd skip the café standing in the doorway. And the doorway is exactly where Azul lives.

2:12 The official H three docs describe overlap modes in the experimental region API. Our cover uses an outer polygon containing the circle, then includes overlapping cells. That gives us extra candidates to filter, without silently excluding Azul. That overlap rule raises another trap. I pictured the hierarchy as perfectly nested shapes. Is replacing several child cells with their parent equally safe? Actually, no. H three's docs distinguish logical parenthood from approximate geometric containment. A child hexagon can stick a corner outside its parent polygon.

2:45 Azul can sit in that sliver. Wait, really? Yes. Like a smaller box with a corner poking one centimeter through a cutout in the larger box: it belongs inside, but its footprint escapes. Use the true child geometry when proving the cover. A parent ID organizes storage; its outline doesn't certify every child's footprint. Oh, wow. Membership isn't footprint. The family tree is correct and the drawing still lies. That gives us a boundary test worth keeping. So that sliver separates cover from distance.

3:17 For example, Azul at 140 meters survives. A shop at 420 meters may share a touched cell, but fails Nora's 300-meter test. Which calculation makes that decision? The exact distance. We'd rather open an extra drawer than lose the right café. Does a real database support that two-stage check? Yeah. PostGIS, PostgreSQL's geospatial extension, documents an index-aware box check followed by within-distance testing. Its geography coordinates measure distance in meters. The docs are linked in the description.

3:49 The result is deliberate overfetch followed by a precise answer. Once geometry is right, downtown cost bites. Suppose one cell holds 100,000 places. An interviewer says, “Hash it across more workers.” That's where many of us go first; hot sounds kind of like a distribution problem. True, it can be. But every worker still scans its share. Together they read the original pile. The common misconception is that hashing reduces the total scan. What would actually shrink Nora's pile? So we need smaller geographic drawers before hiring more clerks.

4:23 Exactly. Split dense regions into spatial leaves, meaning smaller search areas. Nora opens only leaves her circle intersects. Then hash buckets can distribute a busy leaf's remaining work. Now we can lower scan cost without truncating candidates. That drawer split creates a rollout race. We have all seen a migration work perfectly until one request reads half the new layout. How do we keep Azul from falling between parent and children? Build the children while the parent stays live, carrying changes into both.

4:53 Suppose we create four leaves: publish the new directory snapshot only after all four catch up. What if only three are ready? Then Azul could fall through the missing 4th. Each query needs one whole layout, not whichever pieces answered first. Yeah. Think of a street atlas: one complete edition, never loose pages from two editions. Each query pins its snapshot. Old readers finish before the parent retires. The result is one complete layout per lookup. With the layout pinned, can Nora and Amir reuse a nearby shortlist?

5:25 Candidate IDs, yes; a final answer, no. Their precise centers still differ. The cache records the directory snapshot and each touched leaf's change counter. The snapshot identifies the layout; the counter identifies mutations inside a leaf. Why keep those identities separate? So basically snapshot 12 is the shelf label; leaf counter seven is the inventory revision. What makes that second number trustworthy? Exactly. When Azul closes, the index worker changes its stored row and increments the leaf counter in the same database transaction.

5:56 Moves and membership changes follow that rule too. Reads use these stored rows within our 1-minute freshness target. That leaves no uncounted change inside a leaf. With that counter, I think we're nearly there. Walk me through a cache hit where Azul moves halfway through the read. First, pin the directory and compare cached leaf counters with current ones. For example, Azul's leaf is at seven, so the IDs look reusable. Fetch the rows, then read those counters again. Seven became eight. What now?

6:30 Discard and retry. Ah, that's the check I almost skipped. We verify before and after, bracketing the work rather than trusting one lucky glance. Right. Unchanged counters prove a stable projection during the fetch. The directory remains separately pinned. Now we can test exact distance and open status. That read proof leads to the write failure. Imagine Azul moving across town. Nora sees two pins: the new location accepted version 82, while old-location deletion timed out. How does a retry finish both sides?

7:02 The authoritative place row and an outbox instruction commit together. AWS documents that handoff pattern. Our instruction names both locations. Like one work order with two checkboxes: add the new pin, retire the old one? Yep. A retry checks them independently. And if the destination already applied 82? Its version comparison rejects the duplicate write. The old-location entry still accepts a removal marker at 82. Nice. One instruction, two comparisons, one surviving café. The retry fills the missing half instead of repeating the successful half.

7:34 That removal leaves a tombstone in the old-location drawer: a deletion note marked 82. Azul's new pin stays live. But what happens when cleanup removes that note and stale open 81 arrives at the old drawer? Don't let absence count as permission. The updater reloads Azul's authoritative row by place ID and applies its current version and location, rather than the stale payload. It sees the newer move and keeps the old-location entry empty. Azul's new-location entry remains live. Oh, that's good. Cleanup changes how we check, not which update wins.

8:10 That means the café can't sneak back just because we emptied the drawer. With late events handled by that source reload, test a crash. For example, in this incident the projector acknowledges Azul's move, then crashes before removing the obsolete entry. The stream reports zero lag. What repairs a change that delivery thinks is finished? Replay follows the delivery record, so it can miss this. Reconciliation checks both locations against the authoritative row. That's a nasty failure: zero lag, two café pins.

8:41 Yep. The destination stays, and the stale copy goes. Replay audits the mail log; reconciliation audits the filing cabinet. Ah, a clean delivery record still leaves us work. If those pins disagree with the source, repair storage; if delivery is behind, replay. Now operators can choose the matching recovery path. That state check leaves a product decision. For example, Nora's circle needs four leaf queries. One times out. A product manager says, 'Three answered. Can we show those while we wait?' Sure, for a best-effort map.

9:14 I used to treat partial results as harmless. But can three answered leaves prove the 4th empty? No. Like searching a four-room house: three empty rooms don't prove nobody's home. The missing leaf could contain Azul. Right. Our exact endpoint retries within the latency budget, then returns a retryable region-unavailable error. An approximate endpoint can show three leaves, but marks the result incomplete and names the unavailable region. Yeah, otherwise 'nothing nearby' could mean 'we never looked there.'

9:45 That is the contract we can defend in an architecture review. With that contract settled, rehearse Nora's request: cover her circle, pin the directory, validate every touched leaf, then filter by meters and status. Which version of the data did we prove complete? The validated projection. It may trail an edit by up to 1 minute; exact geometry doesn't make the asynchronous index instantaneous. We report that age contract and monitor it. Right. Complete over the stored data we checked, fresh within the minute we promised.

10:15 Now we can test those separately. Now return to the original architecture map. The cover reaches Azul across the border. The directory bounds the work, and counter checks protect cached reads before the exact filter admits the café. Below it, the database and outbox preserve the move. Version checks finish both indexed locations; source reloads defeat stale events; reconciliation repairs a copy that delivery left wrong. Right. Find the nearby café, and keep its stale pin from coming back. Those are the two promises Nora needed.

10:45 Thanks for listening to Learning Podcasts.