Ch.31: Airbnb System Design: When the Calendar Lies
Transcript
0:00 Take Maya, an Airbnb host who blocks her home from Friday through Monday. Her calendar turns gray and says saved. 5 seconds later, Leo searches those nights. They are still green, so he taps Book. Which screen is lying? Maya's screen confirms that authority accepted her change. Leo sees a delayed search snapshot. Let that snapshot go stale, but force Book to recheck current facts and claim the dates in one listing-scoped transaction. So the green card may be wrong, but Book still has to be right.
0:29 Okay, show me how. Now the finished map has two paths. Maya and external feeds enter through the Calendar Command API, which writes the authoritative Calendar Store. In that same transaction, it also records a message to send later. A projector turns those facts into the flattened availability copy used by search and caches. Wait, give me the split in plain English. Which path is allowed to be stale, and which one actually grants ownership? Search may read that projected copy. Book returns to authoritative calendar state before creating ownership.
1:00 A reconciler compares versions so delayed copies cannot hide forever. We will return to this map with Maya's update moving through it. Before choosing boxes, separate the functional requirements from the non-functional requirements. First, every closed night retains why it is closed. Support and the booking path need more than “available equals false.” Maya can set a repeating default, override one date or range, and see her saved change immediately. External calendars can contribute busy ranges without overwriting her intent.
1:30 Leo can search by check-in and checkout, inspect a listing, and attempt a booking. If availability changed after search, he gets a clear rejection and fresh alternatives, not a confirmation we later cancel. Now the boxes have jobs. Next, scale turns those functions into constraints. For our fictional load, read traffic dominates: 50 million searches a day versus one million calendar mutations and 300,000 booking attempts across eight million listings. Search targets a few hundred milliseconds and may trail authority by 5 seconds.
2:02 A product manager could reasonably ask, “Maya saw Saved. Why is Leo still seeing green?” 5 seconds is acceptable only if that card cannot create ownership. The hard invariant is never confirming overlapping stays for one listing and the same nights. We keep the correctness transaction local to one listing. Payment, pricing, fraud, recommendations and geographic ranking stay outside this design. One narrow boundary protects search latency without weakening booking correctness. With scale bounded, the audit trail exposes a common mistake.
2:32 A hurried schema review says, “Just store one boolean per date.” For example, Airbnb's public help, linked in the description, lists host settings, synced calendars, unpaid bookings and confirmed reservations as distinct reasons a night may be blocked. Oh, that boolean would lose both the reason and the owner. Worse, an “open” tap could overwrite a reservation block. So our source of truth stores facts separately. Default rules describe normal hosting. Explicit exceptions open or close named dates.
3:01 Imported busy intervals carry their source. Reservations carry ownership. Availability becomes a calculation with precedence. A host exception can beat a default rule, but not a confirmed reservation or legal block. The result tells support and booking both the answer and the reason that won. Once reasons survive, define the unit they cover. Consider Leo checking in Friday and out Monday. He owns Friday, Saturday and Sunday nights, written as the half-open interval Friday inclusive, Monday exclusive. Hold on. “Through Monday” sounds like Monday night is included.
3:33 That wording is the trap. Another guest may check in Monday without overlap. We evaluate in the listing's local calendar, not as three piles of UTC hours. A daylight-saving shift changes a day's length, not the booked-night count. PostgreSQL uses this lower-inclusive, upper-exclusive form for date ranges too. Three nights, one unambiguous conflict test. Now we can store the intent. Those local-night boundaries lead to command storage. Nightly rows are tempting because they are easy to query. But “weekends are open through December” should remain one compact rule, not hundreds of authored decisions.
4:11 Maya's Friday-through-Monday block becomes one explicit exception. A reservation stays separate because it owns a guest's nights and has a different lifecycle. One small calendar-head row holds the listing's current calendar version. Every accepted command increments it, giving the system a common name for “Maya's latest truth.” That version is the handoff from commands to reads. Now reads can ask how fresh they are. That compact model makes one honest read path tempting. My first thought is: for every search candidate, load its rules, expand recurrences over Leo's range, merge exceptions, imported blocks and reservations, then decide. Yeah, imagine Rome returns 10,000 candidates for one weekend.
4:54 One search now fans into 10,000 recurrence expansions before ranking anything, so the correct request burns the latency budget. And caching final answers will not rescue it; arbitrary dates create too many keys. Pay expansion once per change, not once per search. Because read-time expansion is too expensive, project the next 18 months into nightly states. That is about 550 bits for open or closed, roughly 70 bytes before reasons and metadata. The exact horizon is a product choice, not an Airbnb fact.
5:27 The payload is almost annoyingly small. The projector expands Maya's defaults, overlays exceptions and hard blockers, then writes nightly bits plus reason codes tagged with the calendar version. A rule change rebuilds only the affected listing and dates. I like the bounded promise. It avoids 1,000 permanent recurrence instances while keeping search cheap. Beyond the horizon, refuse the date or evaluate on demand instead of pretending the projection reaches forever. Now move that bounded projection into production.
5:58 Take a concrete case: Maya taps Block. The command service authenticates her, validates the local-date range, writes the exception, advances version 104 to 105, and commits its event record in the same transaction. Then it returns success. But the projector has not applied 105 yet. If Maya refreshes, do we show the old green copy and undermine her confidence? No. Her response carries version 105 and the affected range. The host calendar reads authoritative facts or overlays that committed result until the projector reaches 105.
6:29 The result is immediate host trust without synchronous search. With Maya's screen pinned to 105, Leo's faster path can remain derived. Search gets plausible listings, batch-reads flattened availability vectors and keeps the ones whose requested nights are open. It ranks and may cache those survivors with each projected calendar version. Leo's green card says only, “This snapshot looked open.” In his case, that snapshot is version 104. That versioned snapshot creates the central race: Maya has committed 105 while Leo still holds 104.
7:01 Disabling Book whenever a cache might be stale would destroy availability, but trusting 104 would violate the invariant. Send 104 with the booking request. It tells us what Leo saw, helps explain a rejection and measures projection lag. It cannot authorize success. Version is evidence, not authority. Good. Leo clicks Book with that evidence. Open the gate against current state. That evidence leads to the authority check. What does Book see now? Book loads Maya's calendar head and sees 105, not 104, then evaluates Friday through Monday against current rules, exceptions, synced blocks and reservation ownership.
7:34 Maya's explicit block wins over her default open rule, so the booking stops before payment. Leo gets “Those dates just changed,” plus the version and conflict reason needed to refresh the listing. Thank goodness. The stale card costs Leo a retry, not Maya her home. But current authority can still race. Suppose two booking workers both read the dates as open. What makes one of them lose? Both command paths first lock the same authority row for that listing. Under that lock, each rechecks the range, writes either the host exception or reservation blocker, advances the version and commits.
8:09 PostgreSQL's exclusion constraint adds protection against reservation overlap. Another database could use an equivalent serialized conditional write. The technology is optional; the shared listing serialization is not. One claim commits; the other retries. Now race that against Maya. Once guest-versus-guest is safe, imagine Maya's block and Leo's booking reaching different servers at the same instant. Which user deserves priority? Product can choose a policy, but the backend needs one deterministic fact.
8:38 In our design, commit order at the listing authority wins. If Maya's block commits first, Leo's transaction sees it and fails. If Leo's reservation commits first, Maya's request sees the new reservation and reports the conflict. It does not silently cancel him or paint over his ownership. She can block the remaining dates or use the explicit cancellation workflow outside this episode. That may disappoint one user, but commit order preserves one auditable history instead of two incompatible successes.
9:07 With 1 weekend serialized, Maya asks a nastier edit: “Block this Saturday only, then close every future Saturday starting next month, but do not rewrite the past.” The one-off block is one exception. The future policy starts a new rule version on its effective date; old weekends keep the rule that actually governed them. Projection recomputes only that future window as version 106. Support sees two authored decisions, not 1,000 fake edits. Next, recurring rules meet external calendars. Airbnb recommends syncing calendars to help avoid double bookings. Give each imported busy interval the external event ID and revision; replaying the same revision is harmless.
9:48 Sure, that helps replay. I kept wanting sync to close this gap, but I think it cannot create one atomic decision spanning both marketplaces. A stale poll also cannot remove a newer imported block because the source revision only moves forward. Our authority safely applies everything observed. Cross-site sync reduces conflicts; it does not create a global transaction across companies. Measure import age and show hosts when a feed is delayed instead of promising impossible immediacy. External lag is one boundary; event ordering inside our system is another.
10:20 Walk me through it. If 105 arrives before delayed 104, how does the old event fail to repaint Maya's weekend green? For example, event 105 triggers a full rebuild from current authoritative facts, not a range delta. The consumer writes that listing's rebuilt horizon and applied-through marker, watermark 105, together. Only then may it ignore 104. Oh, right. The full rebuild is what makes the ratchet honest. Snapshot 105 already contains every committed fact through 105, so a late 104 cannot pull the projection backward.
10:53 Wait, something just clicked. The ratchet handles an old event, but not an event that never arrives. That missing-event gap leads to reconciliation. The reconciler compares the Calendar Store's current version with each copy's last-applied version, its watermark. Saving the calendar change and its message together makes absence less likely; the comparison makes it visible. For example, if authority says 105 and a derived copy says 104, enqueue a rebuild from source facts. Track projection age, listings with version gaps, external-feed age, and how often booking rejects a stale search.
11:29 Yeah. Keep the winning reason too. Support can answer, “This was Maya's host block,” rather than stare at a false boolean. In an incident, a spike in safe rejections exposes a sick projector before ownership is harmed. So where is Maya's version 105 at each point on that map? Now place Maya's 105 on the complete map. Authority accepts it first; her screen reads it immediately; projection later turns future search gray. Leo's 104 may stay green briefly, but Book checks current authority and rejects it.
11:59 If projection misses 105 entirely, reconciliation rebuilds the copy. One map, one deliberate asymmetry: discovery may lag; ownership may not. Finally, the resolved end-to-end map compresses into four interview decisions. I would model reasons, not one boolean; use listing-local half-open ranges; materialize a bounded read horizon; and recheck authority inside the ownership transaction. Then name the tradeoff honestly. Discovery may trail for a few seconds because the consequence is a rejected click.
12:30 Ownership must use current state because the consequence is two guests for one home. Maya's calendar was not a decorative grid after all. It was a command surface over rules, projections and one hard invariant. And the green result was never the booking. Thanks for listening to Learning Podcasts.