The Problem#
We want to build a booking platform like Airbnb (homes) or Booking.com (hotels). A guest types "Lisbon, 12–15 June, 2 adults", sees a list and a map of places that are free on those nights, compares prices and reviews, picks one, pays, and gets a confirmed reservation. Hosts and hotels list their places, keep a calendar of which nights are free, set prices, get paid after the stay, and read reviews.
On the surface it is a catalogue with a "Book" button. What makes it a staff-level problem is that several very different workloads share the same data:
- Search is read-heavy, geographic and date-dependent. A guest does not ask "show me listing 42". They ask "which of the 50,000 places in this city are free on all three of these nights, fit 2 guests, cost under €150 and are in this part of the map?", and they want the answer, ranked well, in a few hundred milliseconds. Guests run dozens of searches for every booking.
- Booking must never double-book. Two guests clicking "Book" on the last free room for the same nights in the same second must not both succeed. One gets the room; the other gets a clear "no longer available". This needs strong consistency on a small, hot piece of data: the calendar of one listing.
- Availability changes all the time. Hosts block dates, hotels push rate and inventory updates many times a day from their own systems, other platforms sync calendars. The search index must follow quickly, or guests see places that are no longer free.
- Money moves in two directions. The guest pays at booking; the host is paid after check-in; cancellations trigger refunds under a policy. That is a multi-step workflow across external payment providers, and every step must be correct and auditable.
- Trust is the product. Guests book a stranger's home based on reviews and photos. Reviews must come only from real stays, resist retaliation and feed the ranking.
- Ranking decides who earns money. Which places appear first drives most bookings. It is a machine-learning problem with physical limits: a listing can be booked at most 365 nights a year.
A helpful analogy: picture a huge paper diary for every room in the world, one page per night. Search is someone flipping through millions of diaries at once looking for rooms whose pages are blank for 12, 13 and 14 June. Booking is writing a name on those three pages in pen, and it must be impossible for two people to write on the same page at the same moment. Everything else (prices, payments, reviews, ranking) is written in the margins of that diary.
The hard parts are:
- Search by location and dates: a geo index plus a date filter over millions of calendars, at thousands of queries per second.
- Availability calendar storage: a model that is fast to search, cheap to update and safe to book against.
- Reservation without double booking: concurrency control on the nights of one listing, holds during payment and idempotent retries.
- Pricing: nightly prices, fees, discounts, taxes and currency, quoted consistently from search to checkout.
- Payments and payouts: charge, hold, refund and pay out to hosts with a ledger that always balances.
- Reviews and ranking: trusted reviews, ratings that mean something, and a ranking model that learns from bookings.
- Caching availability: making search fast without ever letting a stale cache cause a double booking.
Background: a few terms used in this design#
- Listing. One bookable place: a whole home, a private room, or (for hotels) a room type such as "Double room with sea view" that has several identical physical rooms behind it.
- Host. The person or company that offers a listing. A hotel is a host with many room types and a professional system of its own.
- Night, stay. Bookings are counted in nights. A stay from 12 June to 15 June is three nights: the 12th, 13th and 14th. Check-out day is not a night of the stay, so another guest can check in the same day.
- Availability calendar. For each listing and each future night, whether it can be booked (and, for room types, how many units are left), plus the price and rules for that night.
- Inventory. For hotels, the count of rooms of a type available on a night. A home listing has an inventory of exactly one.
- Hold. A short-lived reservation of the nights while the guest completes payment, released automatically if they do not finish.
- Instant Book vs request to book. With instant booking, a valid payment confirms the stay at once. With request to book, the host must accept within a time window; until then the nights are held.
- Channel manager. Software that hotels use to push rates and availability to many booking sites at once, and to receive bookings from them.
- iCal sync. A simple calendar feed format that many hosts use to export and import blocked dates between platforms. It is polled, not pushed.
- Quote. A computed price breakdown for one listing, dates and guests: nightly total, fees, taxes, discounts, in the guest's currency, valid for a limited time.
- PSP (payment service provider). A company such as Stripe, Adyen or Braintree that charges cards and wallets on our behalf.
- Payout. Money we send to the host after the stay starts, minus our fees.
- Ledger. An append-only, double-entry record of every money movement, used for reconciliation and audit.
- Overbooking. Selling more rooms than exist, betting that some guests cancel or do not show. Some hotels do this deliberately; home platforms do not.
- NDCG (normalised discounted cumulative gain). A standard measure of ranking quality that rewards placing the relevant item (here, the booked listing) near the top.
Clarifying Questions#
| Question | Assumed answer |
|---|---|
| Homes, hotels or both? | Both. Homes are single-unit listings; hotels have room types with several units each |
| How many listings? | About 10 million bookable listings (homes plus hotel room types) worldwide |
| How many bookings? | About 1.5 million bookings a day, averaging 3 nights each |
| How far ahead can guests book? | Up to 2 years (730 nights per calendar) |
| Pay at booking or at the stay? | Charge at booking by default; some hotel rates are "pay at the property", which we support as a variant |
| Instant booking or host approval? | Both: instant booking for most listings, request to book with a 24-hour response window for the rest |
| Cancellations? | Yes, with per-listing policies (flexible, moderate, strict, non-refundable) that decide the refund |
| Overbooking allowed? | Never for homes. Hotels may set a small overbooking allowance per room type |
| Dynamic pricing? | Hosts set base and per-night prices; we suggest prices and can apply them automatically if the host opts in |
| Reviews? | Both sides review after a completed stay; reviews stay hidden until both are written or the window closes |
| Calendar sync with other sites? | Yes: iCal import and export for homes, push APIs for hotel channel managers |
| Regions and currencies? | Global; prices displayed in the guest's currency; payouts in the host's currency |
Requirements#
Functional requirements#
- Listings: hosts create and edit listings with location, photos, amenities, capacity, house rules and policies; hotels manage room types with unit counts.
- Calendar and pricing management: hosts block and open nights, set base prices, per-night overrides, minimum and maximum stay, discounts and fees; hotels and channel managers push rates and inventory through an API.
- Search: guests search by place (a city, a neighbourhood, a map area or a point with a radius), dates, guests and filters (price, type, amenities, Instant Book), and see ranked results with total prices and a map.
- Listing details: photos, description, amenities, reviews, a calendar of open nights and a price quote for chosen dates.
- Booking: guests book with instant confirmation or by request; the system never double-books a night (beyond a hotel's explicit overbooking allowance).
- Payments, refunds and payouts: charge the guest, refund according to the cancellation policy, and pay the host after check-in, all recorded in a ledger.
- Reservations: guests and hosts view, change and cancel reservations; both get notifications.
- Reviews: after a completed stay, guest and host review each other; ratings feed listing pages and ranking.
Non-functional requirements#
- No double booking: strong consistency for the calendar of a listing at the moment of booking. This is the one non-negotiable.
- Search latency: p99 under 500 ms for a results page, including availability, prices and ranking.
- Booking latency: confirmation within 2–3 seconds, most of it spent at the payment provider.
- Freshness: a calendar change becomes visible in search within a few seconds; the booking path always reads the source of truth.
- Availability: 99.95% for search and listing pages; 99.99% target for the booking path, which earns the money.
- Scale: about 5,000 searches per second and 15,000 listing-page reads per second at peak; bookings around 20 per second on average and a few hundred per second at peak.
- Durability and auditability: no booking or payment is ever lost; every money movement is in the ledger.
- Security and compliance: card data handled by the PSP (we never store full card numbers), local tax collection, privacy laws, and access controls on guest and host data.
Capacity Estimation#
Start from bookings, because the business is sized by them, then work outwards to searches and calendar data.
Bookings.
- 1.5 million bookings a day, 3 nights each: 4.5 million nights sold a day.
- 1.5 M / 86,400 ≈ 17 bookings per second on average. Bookings bunch around evenings and big events (a festival opening its dates, a holiday weekend), so plan for 200 per second at peak.
- Booking is the low-volume, high-value path. Its challenge is correctness, not throughput.
Searches.
- Guests search many times per booking (changing dates, moving the map, adding filters). Assume about 70 searches per booking: about 100 million searches a day, 1,200 per second on average and 5,000 per second at peak.
- Each search must check availability for every candidate in the area. In a big city with a map zoomed out, that can be 5,000–50,000 listings. Say 5,000 on average: 5,000 searches per second × 5,000 candidates = 25 million availability checks per second at peak. This number drives the design of the availability index.
- Each results page shows prices for perhaps 20 cards and up to a few hundred map pins: up to 1.5 million price computations per second at peak. Pricing must be cheap and in memory.
Listing pages and quotes.
- About 3 listing views per search session step: 300 million a day, 3,500 per second on average, 15,000 per second at peak.
- With dates chosen, each view computes a quote; quotes are cheap if the calendar and price rules are cached.
Calendar updates.
- About 8 million home listings change their calendar about once a day (blocks, price edits, bookings).
- About 2 million hotel room types are updated by channel managers far more often, say 50 times a day each, as hotels change rates through the day.
- Total: about 110 million updates a day, 1,300 per second on average and 10,000 per second at peak (bulk pushes after a hotel changes a whole season).
Storage.
| Data | Calculation | Size |
|---|---|---|
| Listings metadata | 10 M × 10 KB | 100 GB |
| Photos | 7 M home listings × 25 photos × 3 MB (original plus resized copies), hotels extra | about 0.5–1 PB in object storage |
| Calendar, one row per listing-night | 10 M × 730 nights × about 100 bytes on disk | 730 GB, about 1.5 TB with indexes |
| Calendar, sparse (only overrides and booked ranges) | about 10× smaller | about 100–150 GB |
| Availability bitmaps for search | 10 M × 730 bits | about 0.9 GB |
| Units-left counters for hotel room types | 2 M × 730 nights × 1 byte | about 1.5 GB |
| Nightly prices for search | 10 M × 730 × 4 bytes (dense) | 29 GB (far less if sparse) |
| Reservations | 1.5 M a day × 1 KB | 550 GB a year |
| Reviews | 0.75 M a day × 1 KB | 270 GB a year |
| Ledger entries | 1.5 M bookings × about 6 entries × 200 bytes | 1.8 GB a day, 650 GB a year |
| Search impression logs (for ranking) | 100 M searches × 20 impressions × 200 bytes | 400 GB a day |
Two numbers stand out:
- The whole world's availability fits in about 1 GB of bitmaps. That makes an in-memory availability index cheap: every search node can hold all of it, or a geographic shard of it.
- The source of truth for calendars is modest (well under 2 TB), so a sharded relational database is a natural fit, with strong transactions where it matters.
Payments and payouts.
- 17 charges per second on average, a few hundred at peak; 1.5 million payouts a day, batched.
- Refunds and changes: perhaps 10–20% of bookings.
| Quantity | Average | Peak |
|---|---|---|
| Searches | 1,200/s | 5,000/s |
| Availability checks inside search | 6 M/s | 25 M/s |
| Listing page views | 3,500/s | 15,000/s |
| Calendar updates | 1,300/s | 10,000/s |
| Bookings | 17/s | 200/s |
| Calendar source of truth | about 1.5 TB | |
| Availability bitmaps | about 1 GB |
The system is strongly read-heavy: hundreds of searches and page views for each booking. Optimise reads aggressively, but keep the write path for bookings simple, transactional and correct.
Core Entities#
- User: a guest, a host or both; profile, verification status, payout details (for hosts, held by the payment provider).
- Listing: a home or a hotel room type; location (latitude, longitude, address, area ids), capacity, amenities, photos, rules, cancellation policy, Instant Book flag, unit count (1 for homes).
- CalendarNight: (listing, night) with units total, units reserved, blocked flag, price override, minimum stay rule. Stored sparsely: missing rows mean "default".
- PriceRule: base nightly price, weekend price, length-of-stay discounts, cleaning fee, extra-guest fee, currency.
- Quote: listing, dates, guests, full price breakdown, currency, expiry, signature.
- Hold: listing, nights, guest, expires_at; reserves the nights while payment completes.
- Reservation: listing, guest, check-in, check-out, guests, status (pending payment, pending host, confirmed, cancelled, completed), total price, policy snapshot.
- Payment: reservation, PSP reference, amount, currency, status (authorised, captured, refunded, failed).
- LedgerEntry: a debit or credit to an account (guest, platform fees, host payable, taxes payable) for one money movement.
- Payout: host, amount, currency, reservations covered, status.
- Review: reservation, author, subject (listing or guest), ratings per category, text, visibility state.
API Design#
# Search and browse (public, cacheable at the edge for anonymous users)
GET /v1/search?place_id=lisbon|bbox=minLat,minLng,maxLat,maxLng|lat=..&lng=..&radius_km=..
&checkin=2027-06-12&checkout=2027-06-15&guests=2
&price_max=150&type=entire_home&amenities=wifi,kitchen&instant_book=true
¤cy=EUR&cursor=...
-> { results: [{ listing_id, title, photo_url, rating, review_count, lat, lng,
total_price, nightly_price }], map_pins: [...], next_cursor }
GET /v1/listings/{id} -> details, photos, amenities, rating summary
GET /v1/listings/{id}/calendar?from=..&to=.. -> open nights, min stay per night
GET /v1/listings/{id}/reviews?cursor=..
# Quote and book (authenticated)
POST /v1/quotes { listing_id, checkin, checkout, guests, currency }
-> { quote_id, nights, subtotal, fees, taxes, discounts, total, currency, expires_at }
POST /v1/reservations Idempotency-Key: <uuid from client>
{ quote_id, payment_method_token, message_to_host? }
-> 201 { reservation_id, status: "confirmed" | "pending_host" }
-> 409 { error: "dates_unavailable" } | 410 { error: "quote_expired" }
GET /v1/reservations/{id}
POST /v1/reservations/{id}/cancel -> refund amount per policy
POST /v1/reservations/{id}/accept | /decline (host, for request to book)
# Host and partner management
PUT /v1/listings/{id}/calendar { ranges: [{ from, to, available?, price?, min_stay? }] }
POST /v1/partners/ari { updates: [{ room_type_id, from, to, units?, rate?, closed? }] }
GET /v1/listings/{id}/ical -> exported calendar feed
# Reviews
POST /v1/reservations/{id}/reviews { ratings: { cleanliness: 5, ... }, text }
# Payment provider callbacks
POST /v1/webhooks/psp (signed by the PSP)Design notes:
- Search takes dates, because without dates the results would include places that cannot be booked. A dateless search is still allowed (browsing) and then skips the availability filter.
- Place can be a named area or a map box. Named areas ("Lisbon", "Alfama") resolve to stored shapes; a map box is what the guest sees when dragging the map.
- Quotes are explicit objects with an expiry. The checkout page books against a quote, so the guest pays exactly the price they saw, and the server can detect when it changed.
- The idempotency key is generated by the client before the first submit. Double clicks, retries after timeouts and mobile reconnects all reuse the same key, so the server creates at most one reservation (see Idempotency and Safe Retries).
- 409 and 410 are normal outcomes, not errors to hide: "someone just booked these dates" and "the price changed, here is the new quote".
- Partner updates are batched ranges, not single nights, because a hotel changing a season's rate would otherwise send hundreds of requests.
High-Level Design#
We build the design one requirement at a time, then put it together.
1) Hosts create and edit listings#
- The listing service owns listing metadata: title, description, location, capacity, amenities, rules, policies. It is a normal CRUD service over a relational database (see PostgreSQL in Practice).
- Photos go straight from the app to object storage with pre-signed upload URLs, then a resizer creates thumbnails and several widths. Guests load them from a CDN, which is where most of the bytes of this product travel (see Content Delivery Networks (CDN)).
- Every change is published as an event (with change data capture or an outbox), and a search indexer updates the search index within seconds.
- On save, the service geocodes the address once into latitude and longitude, assigns the listing to its named areas (city, neighbourhood) and stores a slightly blurred public location, so the map does not reveal the exact house before booking.
2) Hosts and partners manage calendars and prices#
- The calendar service is the single writer for calendars and the source of truth for which nights are free. It accepts range updates ("block 1–7 August", "price €180 on Fridays in July") and translates them into calendar rows.
- Hotels push availability, rates and inventory (often called ARI updates) through a partner API, usually via a channel manager. Updates are batched and coalesced (Deep Dive 10).
- Home hosts who list elsewhere connect iCal feeds; a poller fetches them periodically and blocks the nights booked on other platforms.
- Every committed change emits an event. The availability index and the price cache consume these events and update their in-memory copies within a second or two.
3) Guests search by place and dates#
A search runs as a short pipeline:
- Resolve the place. "Lisbon" becomes a stored shape; a dragged map becomes a bounding box.
- Retrieve candidates from the search index: listings inside the shape that match static filters (guests, type, amenities, price band). The index uses a geo structure (geohash, quadtree or S2 cells) for fast spatial filtering (see Geospatial Indexing and Proximity Search).
- Filter by availability with the in-memory availability index: drop candidates not free on every night of the stay, or whose minimum-stay rules do not fit.
- Price the survivors: total for the stay, including fees, in the guest's currency.
- Rank the top few hundred with a learned model, using features about the listing, the query and the guest.
- Return a page of results and map pins.
The search index (Elasticsearch or OpenSearch; see Elasticsearch and Search Systems) is good at steps 1–2. Steps 3–4 are done outside it, because availability and prices change too often to keep re-indexing documents (Deep Dive 2).
4) Guests view a listing and get a quote#
- Listing details are read-mostly and served with cache-aside from Redis (see Caching Strategies: Cache-Aside, Read-Through, Write-Through, Write-Behind); photos come from the CDN.
- The quote service computes the full price breakdown for the chosen dates and returns a signed quote with an expiry of, say, 30 minutes. It reads the price rules from the price cache and checks open nights against the calendar service (a fresh read, not the search index).
5) Guests book#
- The reservation service validates the quote, then in one database transaction marks the nights as held and creates the reservation in "pending payment" state. Calendar rows and reservations for a listing live in the same database shard, so this is a local ACID transaction, not a distributed one.
- The concurrency control in that transaction is what prevents double booking (Deep Dive 3).
- It then asks the payment service to authorise the card. On success, the reservation becomes confirmed (Instant Book) or pending host (request to book). On failure, the hold is released.
- The outcome is written to an outbox in the same transaction and published to the event log for notifications, the availability index and analytics (see Distributed Transactions: 2PC, Sagas and Outbox).
6) Payments, refunds and payouts#
- The payment service talks to one or more PSPs. It authorises at booking, captures when appropriate, refunds on cancellation and records every step in the ledger.
- The payout scheduler releases money to hosts after check-in (for example, a day later, so problems at arrival can be handled first), grouped into batches per host and currency.
- Reconciliation compares the ledger with PSP and bank reports every day.
7) Reviews after the stay#
- When a stay ends, the review service opens a review window for both sides. Reviews are hidden until both sides have written one or the window closes.
- The rating aggregator maintains per-listing summaries (count, average per category) used on listing pages and as ranking features.
The full high-level design#
Components:
- API gateway: authentication, rate limits, routing; anonymous search traffic can be cached at the edge for short periods.
- Search service: orchestrates place resolution, candidate retrieval, availability filtering, pricing and ranking.
- Search index: Elasticsearch or OpenSearch holding listing documents with geo points, area ids and static attributes.
- Availability index: in-memory bitmaps and counters per listing-night, fed from calendar events, sharded by region and replicated.
- Listing service and listings DB: listing metadata and the rating summary; Redis cache in front.
- Calendar service and calendar DB: source of truth for nights, inventory and price rules, sharded by listing id.
- Quote and pricing service: price breakdowns with fees, taxes, discounts and currency conversion.
- Reservation service: holds, bookings, changes and cancellations, with local transactions on the listing's shard.
- Payment service and ledger: PSP integration, idempotent charges and refunds, double-entry ledger, payouts, reconciliation.
- Review service: double-blind reviews, moderation, rating aggregation.
- Ranking service and feature store: scores candidates with a learned model; features computed offline and online.
- Event log (Kafka): carries calendar, reservation, payment and review events to every consumer (see Apache Kafka in Practice).
- Notifications: emails, push and in-app messages for bookings, changes and reminders.
- Object storage and CDN: photos and static assets.
Key Flows#
Flow 1: Search with dates#
Flow 2: Instant booking#
Flow 3: Two guests race for the last nights#
Flow 4: Request to book with a host decision#
Flow 5: Guest cancels and gets a refund#
Data Model#
The core tables, on the shard that owns the listing:
CREATE TABLE calendar_nights ( -- sparse: only nights that differ from defaults
listing_id bigint NOT NULL,
night date NOT NULL,
units_total smallint NOT NULL DEFAULT 1,
units_reserved smallint NOT NULL DEFAULT 0,
overbook_allow smallint NOT NULL DEFAULT 0, -- hotels only, 0 for homes
blocked boolean NOT NULL DEFAULT false,
price_override integer, -- minor units, null = use price rule
min_stay smallint,
PRIMARY KEY (listing_id, night),
CHECK (units_reserved <= units_total + overbook_allow)
);
CREATE TABLE reservations (
reservation_id uuid PRIMARY KEY,
listing_id bigint NOT NULL,
guest_id bigint NOT NULL,
stay daterange NOT NULL, -- [checkin, checkout)
units smallint NOT NULL DEFAULT 1,
single_unit boolean NOT NULL, -- true for homes
status text NOT NULL, -- held, pending_host, confirmed, cancelled, completed
quote_id uuid NOT NULL,
total_minor bigint NOT NULL,
currency char(3) NOT NULL,
idempotency_key uuid NOT NULL UNIQUE,
hold_expires_at timestamptz,
policy_snapshot jsonb NOT NULL
);
-- Belt and braces for homes: no two live reservations of one listing may overlap.
-- Requires the btree_gist extension.
ALTER TABLE reservations ADD CONSTRAINT no_double_booking
EXCLUDE USING gist (listing_id WITH =, stay WITH &&)
WHERE (single_unit AND status IN ('held', 'pending_host', 'confirmed'));| Data | Store | Why |
|---|---|---|
| Listings metadata | PostgreSQL, read replicas, Redis cache | Relational, moderate size, read-heavy |
| Calendars and reservations | PostgreSQL sharded by listing id | Strong local transactions for booking; a booking touches one listing |
| Search documents | Elasticsearch or OpenSearch | Geo queries, filters, full text |
| Availability for search | Custom in-memory index (bitmaps and counters), rebuilt from events | 25 M checks per second at peak, about 1 GB of data |
| Price rules for search | In-memory cache fed by events | 1.5 M price computations per second |
| Ledger | PostgreSQL, append-only tables | Double-entry correctness, audit, strong transactions |
| Reviews | PostgreSQL (or a wide-column store at larger scale) | Simple access by listing and by reservation |
| Events | Kafka | Fan-out of calendar, reservation, payment and review changes |
| Photos | Object storage plus CDN | Large immutable blobs |
| Search logs and training data | Data lake (object storage plus Spark) | Batch training of ranking and pricing models |
| Online features | Key-value store (Redis or Cassandra) | Low-latency feature reads during ranking |
See Choosing a Database: A Decision Guide for the general method behind these choices.
Deep Dives#
1. Search by location: places, map boxes and the geo index#
A guest expresses location in three ways, and the system has to handle all three:
- A named place: "Lisbon", "Alfama", "near the Eiffel Tower", "Lake Tahoe".
- A map viewport: the rectangle the guest sees after dragging and zooming the map.
- A point and a radius: "within 2 km of this conference centre".
Step 1: resolve the place
Named places are resolved with a place service that stores, for each place, an id, names in many languages, a type (country, city, neighbourhood, landmark, region) and a shape: a polygon or multipolygon for areas, a point for landmarks. Shapes come from open data (for example, OpenStreetMap boundaries) or commercial providers, plus hand-drawn polygons for areas that have no official border ("Lake Tahoe" or "the Algarve coast").
A typed query goes through autocomplete first ("Lis" suggests Lisbon, Lisburn, Lismore), so most searches arrive with a place id rather than raw text.
Step 2: find candidates inside the shape
There are two ways to search inside a named area:
| Approach | How it works | Pros | Cons |
|---|---|---|---|
| Shape at query time | Send the polygon in the query; the index tests each listing point against it | Any shape works, including new ones | Polygon tests cost CPU; complex shapes with thousands of vertices are slow |
| Area ids at index time | When a listing is saved, compute which places contain it and store their ids on the document (area_ids: [portugal, lisbon, alfama]) | The query is a fast term filter, like any other attribute | When a place's shape changes, re-tag the affected listings |
For named places the area-id approach wins: the set of places is fixed and slowly changing, listings rarely move, and term filters are the cheapest thing a search index does. Shapes are still used at query time for map viewports, which are arbitrary rectangles, and for radius queries.
How the index finds points in a rectangle or circle
A plain B-tree index on latitude and another on longitude does not help much: it can narrow one dimension but then has to scan everything in that band. Geo indexes split two-dimensional space so that nearby points are close in the index:
- Geohash: interleave the bits of latitude and longitude into one string. Points sharing a prefix are in the same cell. A rectangle query becomes a handful of prefix ranges. Simple, works in any key-value store; cells are rectangles that distort near the poles.
- Quadtree: split the world into four squares, and split each square again when it holds too many points. Dense cities get small cells, empty oceans stay as one big cell. Good when density varies a lot, which it does for listings.
- S2 cells: Google's library projects the sphere onto a cube and numbers cells along a space-filling curve. Cells have similar sizes everywhere, and any region can be covered by a small set of cell ranges. Airbnb's search ranking paper describes using level-12 S2 cells as a location feature, which shows how natural these cells are as units of "neighbourhood".
- BKD trees and R-trees: what Elasticsearch/Lucene (BKD) and PostGIS (R-tree via GiST) actually use. They split space adaptively by the data and answer rectangle and distance queries efficiently.
See Geospatial Indexing and Proximity Search for how each structure works in detail. In practice we let the search engine do this: Elasticsearch's geo_point with a geo_bounding_box or geo_distance filter, combined with term filters for area ids, guests and amenities.
Why the listing count per query matters
A guest zoomed out over all of Portugal matches perhaps 100,000 listings. We cannot check availability, price and rank for all of them in 500 ms at 5,000 searches per second. So the retrieval step is bounded:
- Retrieve at most a few thousand candidates, chosen by a cheap first-stage score stored in the index (overall quality, recent booking rate, a rough location prior for the place).
- Apply availability and price filters to those candidates.
- If too few survive (a sold-out weekend), fetch the next batch of candidates and repeat.
This two-stage shape (cheap retrieval, expensive ranking on a small set) is the standard pattern for every large search system.
Map pins and clustering
The map shows pins for results. Showing 5,000 pins is unreadable and slow to transfer. Options:
- Show pins only for the current results page plus the next few pages (a few hundred).
- Cluster pins at low zoom levels: aggregate counts per grid cell (geohash or S2 cell at a zoom-dependent level) with the index's aggregation features, and show "320" bubbles that split as the guest zooms in.
- Re-run the search when the map moves, with a short debounce on the client (300–500 ms after the guest stops dragging) to avoid a request per pixel.
Location privacy
Hosts do not want the exact house shown to anyone browsing. Store the precise point privately and index a blurred point (randomly offset by up to a few hundred metres, stable per listing so it does not jump). Show the exact address only after a confirmed booking. Area-id tagging uses the precise point, so a listing just inside a neighbourhood border is still tagged correctly.
Index sizing
- 10 million listing documents at about 5 KB each (text, attributes, area ids, first-stage score): 50 GB, about 150 GB with replicas.
- Shard by geography (for example, by continent or by large country groups), so most queries hit one shard group and a hot region (Europe in summer) can get extra replicas. Each shard group is replicated 3–5 times for read throughput.
- Documents are updated when listing details change (a few million times a day, about 50 per second on average), not when calendars change. That keeps indexing load low; the frequently changing data lives in the availability index (Deep Dive 2).
2. The availability calendar: storing nights so that search and booking are both fast#
The calendar answers two very different questions:
- Booking: "Can I take nights 12, 13 and 14 June of listing 42, right now, for certain?" One listing, a few nights, must be exact and transactional.
- Search: "Of these 8,000 listings, which are free on all of 12, 13 and 14 June and allow a 3-night stay?" Thousands of listings per query, 25 million checks per second at peak, can be a second or two behind.
No single representation is ideal for both, so we keep a transactional source of truth for booking and a derived in-memory index for search.
The source of truth: options
| Model | Shape | Strengths | Weaknesses |
|---|---|---|---|
| One row per listing-night | (listing, night, units_reserved, price, rules) | Simple locking of exact nights; conditional updates per night; easy hotel counts | 7.3 billion rows if dense; needs a rolling job to add new nights |
| Ranges | Reservations and blocks as date ranges; free nights are the gaps | Compact; matches how hosts think ("block August"); exclusion constraints prevent overlaps | Harder for hotel unit counts; "free nights" is derived |
| Bitmap per listing | 730 bits, one per night | Tiny, fast to test a whole stay at once | Not a transactional store; no prices or counts |
We combine the first two:
- Reservations are ranges,
[checkin, checkout)in adaterangecolumn. For single-unit homes, a PostgreSQL exclusion constraint makes overlaps impossible at the database level, the same idea the PostgreSQL documentation shows with its room-reservation example (EXCLUDE USING GIST (room WITH =, during WITH &&)). - Calendar rows are sparse per-night rows that exist only where something differs from the defaults: a blocked night, a price override, a minimum-stay rule, or, for hotels, a units-reserved count. A home with no special rules and no bookings has zero rows. This cuts storage by roughly 10× and removes the need for a nightly job to create future rows.
- On booking, the transaction upserts rows for the stay's nights and updates them atomically (Deep Dive 3).
Nights, time zones and the "half-open" stay
- A night belongs to the listing's local date. 12 June means the night starting on 12 June in Lisbon time, whatever time zone the guest is in. Store dates, not timestamps, and do all date arithmetic in the listing's zone.
- Stays are half-open:
[12 June, 15 June)includes the nights of 12, 13 and 14, not 15. Back-to-back stays (one guest leaves on the 15th, the next arrives on the 15th) do not overlap. PostgreSQL's built-indaterangeuses exactly this[)convention by default. - Getting this wrong produces the classic bug where same-day turnovers are blocked, or the opposite, where two guests are booked into the same night.
Rules that make availability more than "free or not"
A night can be free and still not bookable for a given stay:
- Minimum and maximum stay: "at least 3 nights", often different on weekends or holidays.
- Check-in and check-out days: "check-in only on Saturdays" for weekly rentals.
- Advance notice and preparation time: "at least 2 days' notice", "block one night after each stay for cleaning".
- Booking window: "only 6 months ahead".
- Legal night caps: some cities limit short-term rentals. For example, Amsterdam allows hosts to rent their home for up to 30 nights a year, to groups of at most four. The platform must count nights per year and stop selling once the cap is reached.
These rules are part of the calendar model and must be checked both in search (to avoid showing places that cannot be booked for those dates) and in booking (authoritatively).
The availability index for search
For search, we keep per listing:
- A 730-bit availability bitmap: bit i is 1 if night (today + i) can be sold.
- For hotel room types, a units-left byte per night instead of a bit.
- Rule summaries: minimum stay per night (a small array or run-length encoding), allowed check-in weekdays, notice period.
Checking a 3-night stay is a bit operation: build a mask with 3 bits set at the right offset and test (bitmap & mask) == mask. With 64-bit words, most stays touch one or two words. That is a few nanoseconds per listing, so 25 million checks per second fit comfortably on a handful of cores; in practice the cost is dominated by memory access, which is why the index is laid out as one contiguous array per shard.
// Is listing free for [start, start + nights)? offsets are days from today
function isFree(bits: BigUint64Array, start: number, nights: number): boolean {
let i = start;
let left = nights;
while (left > 0) {
const word = i >> 6, bit = i & 63;
const take = Math.min(64 - bit, left);
const mask = ((1n << BigInt(take)) - 1n) << BigInt(bit);
if ((bits[word] & mask) !== mask) return false; // some night is taken or blocked
i += take; left -= take;
}
return true;
}
// Then check rules: minStay[start] <= nights, check-in weekday allowed, notice period.Size: 10 million listings × 92 bytes ≈ 0.9 GB, plus hotel counters and rule summaries, a few GB in total. Every search node can hold all of it, or the shard for its region.
Keeping the index fresh
- The calendar service publishes an event for every committed change, with the listing id, the affected nights and a version number (a per-listing counter incremented in the same transaction).
- Index nodes apply events in version order per listing and ignore older versions that arrive late. A missed event is detected as a gap in versions and repaired by re-reading the listing's calendar.
- On start-up, a node loads a snapshot (written every few minutes to object storage) and replays events from the log since the snapshot's offset. Start-up takes a minute, not an hour.
- Freshness target: a change is visible in search within about two seconds at the 99th percentile.
Why not put availability in the search engine documents?
It is tempting to store "available nights" as a field on each Elasticsearch document and filter on it. The problem is write volume:
- 110 million calendar updates a day, peaking at 10,000 per second, would each re-index a whole document. In Lucene-based engines an update is a delete plus a new write, followed by merges. At this rate the index spends its life rewriting documents, search latency suffers and refresh lag grows.
- The data is tiny and changes constantly, while the rest of the document is large and changes rarely. Separating them follows a general rule: keep fast-changing, small data out of slow-changing, large indexes.
The trade-off is a join at query time (retrieve ids from the index, then filter in the availability index), which costs a few milliseconds and is far cheaper than constant re-indexing.
3. Reservation without double booking#
This is the deep dive every interviewer asks about. The goal: when several requests compete for overlapping nights of the same listing, at most the available number of units is ever sold for any night, under any interleaving, retry or crash.
Why the naive version fails
Request A: SELECT nights 12..14 for listing 42 -> all free
Request B: SELECT nights 13..15 for listing 42 -> all free
Request A: INSERT reservation (12..15)
Request B: INSERT reservation (13..16) -> nights 13 and 14 sold twiceBoth requests read before either writes. This check-then-act race happens under the default isolation level of most databases (read committed), and the window is real: at 200 bookings per second with popular listings on a festival weekend, it happens daily. See Concurrency Control and Database Locking for the underlying theory.
Options
| Approach | How it works | Pros | Cons |
|---|---|---|---|
| Pessimistic row locks | SELECT ... FOR UPDATE on the night rows, then check and write | Simple mental model | Rows must exist to be locked (sparse model needs upsert first); deadlocks if two requests lock nights in different orders |
| Atomic conditional update | UPDATE ... SET units_reserved = units_reserved + 1 WHERE ... AND units_reserved < limit and check the row count | One statement, no separate read, works for hotel counts | Must update every night and verify all rows changed |
| Exclusion constraint | The database rejects overlapping ranges for the same listing | Impossible to violate, even by buggy code | Single-unit listings only; needs PostgreSQL range types |
| Optimistic version check | Read with a version, write only if the version is unchanged, retry on conflict | No locks held | Many retries when contention is high |
| Serializable isolation | Let the database detect conflicting transactions | Correct by construction | Aborts under contention; needs retry logic; not all databases do it efficiently |
| Distributed lock (for example, in Redis) | Lock "listing 42" for a few seconds while booking | Serialises access across services | A lock with a timeout can expire mid-operation; must not be the only guard |
What we choose
For hotel room types (counts): an atomic conditional update over all nights in one transaction.
BEGIN;
-- Make sure a row exists for every night (sparse model), without overwriting.
INSERT INTO calendar_nights (listing_id, night, units_total)
SELECT 42, d::date, 12 FROM generate_series('2027-06-12', '2027-06-14', interval '1 day') d
ON CONFLICT (listing_id, night) DO NOTHING;
-- Take one unit on every night only if each still has room. Rows are touched in night order.
UPDATE calendar_nights
SET units_reserved = units_reserved + 1
WHERE listing_id = 42
AND night >= '2027-06-12' AND night < '2027-06-15'
AND NOT blocked
AND units_reserved < units_total + overbook_allow;
-- Application checks: rows updated must equal 3 (the number of nights). If not, ROLLBACK -> 409.
INSERT INTO reservations (reservation_id, listing_id, guest_id, stay, units, single_unit,
status, quote_id, total_minor, currency, idempotency_key,
hold_expires_at, policy_snapshot)
VALUES ($1, 42, $2, daterange('2027-06-12', '2027-06-15'), 1, false,
'held', $3, $4, 'EUR', $5, now() + interval '15 minutes', $6);
INSERT INTO outbox (topic, payload) VALUES ('reservation.held', $7);
COMMIT;Why it is safe:
- The
UPDATEtakes row locks on each night it modifies and re-checks the condition after acquiring the lock. Two concurrent transactions on the same night serialise on that row; the second sees the first's increment and fails the condition if the room is full. - The row count check turns "some nights updated" into an all-or-nothing outcome: if any night is full, the whole transaction rolls back.
- Deadlocks: two transactions locking overlapping nights in different orders can deadlock. Updating rows in a consistent order (by night) avoids most of them; the database detects any remaining ones and aborts one transaction, which the service retries once.
- The
CHECKconstraint on the table is a second line of defence: even a buggy code path cannot pushunits_reservedpast the limit.
For single-unit homes: the same conditional update with units_total = 1, plus the exclusion constraint on reservations. The constraint costs a GiST index insert per booking (cheap at 200 per second) and makes double booking impossible even if someone adds a code path that forgets the calendar update.
Distributed locks are not needed for correctness here, because the database is the single place where the nights live. A short Redis lock per listing can still help as a contention filter in front of the database (fail fast when someone else is booking the same listing this second), but the database checks remain the real guard. See Pattern: Dealing with Contention for the general trade-offs.
Holds: reserving nights during payment
The guest has not paid yet when the transaction above commits. We therefore write the reservation as held with an expiry (15 minutes is typical for checkout; much longer for request to book):
- While held, the nights count as taken: nobody else can book them, and search treats them as unavailable.
- If payment succeeds, the reservation moves to confirmed. If it fails or the guest abandons checkout, the hold is released.
- A sweeper job runs every minute: it finds holds past
hold_expires_atand releases them in a transaction (status to expired, decrement the nights, outbox event). An index on(status, hold_expires_at)keeps the sweep cheap. - Race between expiry and payment: the payment may succeed just as the sweeper releases the hold. The confirm step therefore uses a conditional update,
UPDATE reservations SET status = 'confirmed' WHERE id = $1 AND status = 'held'. If it finds the hold already expired, it tries to re-take the nights; if they are gone, it refunds the payment automatically and tells the guest. This is rare but must be handled.
Holds are the same idea as seat holds in ticketing, with one difference: a home listing's whole inventory is one unit, so a hold blocks the listing completely for those nights. Keep holds short and release them promptly when a guest leaves checkout.
Idempotency
- The client sends an
Idempotency-Keywith the booking request. Thereservations.idempotency_keycolumn is unique. - A retry with the same key returns the existing reservation (whatever its status) instead of creating a new one.
- The same key, combined with a step suffix, is passed to the PSP for the authorisation, so a retried payment call does not charge twice.
- Airbnb has published an engineering post titled "Avoiding Double Payments in a Distributed Payments System", a sign that this is a real production problem, not an interview abstraction.
What about the stale search index?
The availability index is a second or two behind. A guest may click a listing that was just booked. That is acceptable: the booking path never trusts the index. The conditional update reads the source of truth, and the guest gets "these dates were just booked" with alternatives. The goal is to make that rare (well under 1% of booking attempts), not impossible.
4. The booking workflow: states, payments and failure handling#
A booking is a multi-step process: hold nights, authorise payment, maybe wait for the host, capture payment, confirm, notify, later pay out. Each step can fail or time out. The design question is how to coordinate them.
The reservation state machine
Each transition is a conditional update on the current status (WHERE status = 'held'), so two concurrent events (a host accepting just as the timer fires) cannot both win. Every transition writes an outbox event in the same transaction.
Local transaction, not a distributed one
The calendar and the reservations of a listing live on the same database shard. Holding nights and creating the reservation is therefore a single local ACID transaction. We avoid:
- Two-phase commit across a calendar database and a reservation database: it adds latency and blocks if the coordinator fails, for no benefit when we can co-locate the data.
- A saga for the core hold: sagas give up isolation, so another request could see half-applied state, which is exactly what we must prevent for inventory.
Payment, by contrast, involves an external system we cannot put in our transaction. So the overall flow is a short saga around a local transaction:
- Local transaction: hold nights, create reservation (held).
- External call: authorise payment (idempotent).
- Local transaction: confirm (or release on failure).
- Compensation: if step 3 cannot confirm (hold expired and nights gone), refund the payment.
See Pattern: Multi-Step Processes and Workflows and Distributed Transactions: 2PC, Sagas and Outbox for the general techniques.
Failure cases worth naming
| Failure | What happens | Handling |
|---|---|---|
| Service crashes after the hold commits, before calling the PSP | Hold sits until expiry | Sweeper releases it after 15 minutes; client retry with the same key resumes the flow |
| PSP call times out | We do not know if the card was charged | Query the PSP by idempotency key; never assume failure and retry with a new key |
| PSP authorised, but our confirm write fails | Money held, reservation still "held" | Retry confirm; a reconciliation job matches PSP authorisations to reservations every few minutes |
| Webhook arrives before our own response | Payment status updated out of order | Webhooks and responses both apply idempotent, status-conditional updates |
| Host never answers a request | Nights blocked, card authorised | Durable timer fires at 24 hours: release nights, void authorisation |
| Hold expires while the guest is on the PSP's 3-D Secure page | Payment succeeds after expiry | Re-take nights if free; else auto-refund and apologise |
Durable timers
Request-to-book windows, hold expiries, review windows and payout dates are all "do X at time T if state is still Y". Options:
- A sweeper scanning an indexed
due_atcolumn every minute. Simple and robust; good enough for holds. - A delay queue (messages that become visible at a time) for per-event timers.
- A durable workflow engine (Temporal, AWS Step Functions) that models the whole booking as a workflow with timers and retries. Worth it when the workflow grows many branches (instalments, deposits, host approvals, identity checks).
Whatever the mechanism, the action must be conditional on the current state, because the timer can fire after the state already changed.
5. Pricing and quotes#
The price a guest sees is not one number stored somewhere. It is computed from many inputs, and the computation must give the same answer in search, on the listing page and at checkout, or guests lose trust.
What goes into a price
| Component | Example | Who sets it |
|---|---|---|
| Nightly base price | 120 EUR | Host (or a pricing tool) |
| Per-night overrides | 180 EUR on festival nights | Host or calendar rules |
| Weekend price | +20% Friday and Saturday | Host |
| Length-of-stay discount | -10% for 7+ nights, -25% for 28+ | Host |
| Early-bird or last-minute discount | -5% if booked 3+ months ahead | Host |
| Cleaning fee | 40 EUR per stay | Host |
| Extra-guest fee | 15 EUR per night above 2 guests | Host |
| Guest service fee | A percentage of the subtotal | Platform |
| Taxes | City tourist tax per person per night; VAT on fees | Jurisdiction rules |
| Currency conversion | EUR shown to a guest paying in USD | FX rate snapshot |
Rule order matters
A tiny worked example. Three nights, two of them weekend nights, base 120 EUR, weekend +20%, 7-night discount not applicable, cleaning 40 EUR, guest fee 14% of subtotal, city tax 3 EUR per person per night for 2 guests:
- Nights: 120 + 144 + 144 = 408 EUR
- Subtotal with cleaning: 448 EUR
- Guest fee: 0.14 × 448 = 62.72 EUR
- City tax: 3 × 2 × 3 = 18 EUR
- Total: 528.72 EUR
If the discount were applied after the cleaning fee instead of before, or the fee computed on nights only, the total changes. The order must be one documented function, versioned, used by every caller. Two implementations (one in search, one in checkout) will drift and show different numbers.
Search prices are estimates; quotes are promises
- In search, computing an exact price for 1.5 million candidates per second at peak is too expensive. The search index stores a precomputed nightly price summary (for example, a typical price per night and per-night overrides for the next months). Search shows a price that is right for most cases, and is labelled with what it includes.
- On the listing page, the Pricing Service computes an exact quote for the chosen dates and guests: every line item, taxes, the FX rate used.
- The quote is signed (an HMAC over its contents) and has an expiry (for example, 30 minutes). At checkout, the booking service verifies the signature and expiry instead of trusting the client's price.
- If the host changed their price after the quote was issued, we honour the quote until it expires. That is a business decision, but a common one: it means "the price you saw is the price you pay".
type Quote = {
quoteId: string; listingId: string; checkIn: string; checkOut: string; guests: number;
lines: { kind: "nights" | "cleaning" | "guest_fee" | "tax"; amountMinor: number }[];
totalMinor: number; currency: string; fxRateId?: string; pricingVersion: number;
expiresAt: string; signature: string; // HMAC over all fields above
};
function verifyQuote(q: Quote, now: Date, key: Buffer): boolean {
const { signature, ...body } = q;
return hmacSha256(key, canonicalJson(body)) === signature && new Date(q.expiresAt) > now;
}Money handling
- Store amounts as integers in minor units (cents) with a currency code. Never floats: 0.1 + 0.2 is not 0.3 in floating point.
- Currencies differ in minor units (JPY has none, some have three). Keep a currency table.
- FX snapshot: when converting, record the rate id used in the quote. Refunds later use the same rate (or a clear policy), so a guest is not surprised by exchange swings.
- Rounding: round each line item once, with a documented rule, and compute the total from rounded lines so the receipt adds up.
Dynamic pricing
Most hosts are not pricing experts, so platforms offer price suggestions. A KDD 2018 paper from Airbnb by Peng Ye and colleagues, "Customized Regression Model for Airbnb Dynamic Pricing", describes their approach in three stages:
- A booking probability model: for a listing, a night and a price, how likely is it to be booked?
- A regression model with a custom loss that predicts a good price, trained on whether past prices led to bookings (too high and the night went unbooked; too low and money was left behind).
- Personalisation on top for each host's preferences.
The paper notes the core difficulty: unlike hotels, no two listings are identical, so you cannot simply copy a competitor's price. These models power host-facing features (price tips and an automatic pricing option). For our design, the important point is architectural: suggested prices are produced offline or in batch (daily per listing per night), written as price rules, and flow through the same pricing function. The booking path never calls a model.
Hotels: rate plans
Hotels add a layer on top: one room type can have several rate plans (refundable, non-refundable at -15%, breakfast included, member rate). Each rate plan has its own price per night and its own cancellation policy. Partners send them through the ARI feed. The data model gets a rate_plan table under each room type, and the quote names the rate plan chosen.
6. Payments, ledgers and payouts#
A booking platform is a marketplace: it collects money from guests and pays hosts, minus its fees. That makes payments more than "charge a card".
Authorise, then capture
- Authorisation asks the card issuer to reserve the amount. The money is not moved yet.
- Capture moves the money. You capture when the booking is confirmed (immediately for instant book, after host acceptance for request to book).
- Authorisations expire (often around 7 days for cards, depending on the network and issuer). For bookings made months in advance, platforms typically either capture at booking or split into a deposit now and the remainder closer to the stay, re-authorising as needed.
- Void cancels an authorisation that was never captured (host declined): no money moved, no refund needed.
The ledger
Every money movement is recorded in a double-entry ledger: each transaction has entries that sum to zero across accounts. A worked example for a 528.72 EUR booking with a 62.72 EUR guest fee, a 3% host fee (13.44 EUR on the 448 EUR host subtotal) and 18 EUR tax:
| Account | Debit | Credit |
|---|---|---|
| PSP receivable (money coming from the card network) | 528.72 | |
| Guest payable / funds held for the stay | 528.72 | |
| At check-in + 24 h: Guest payable | 528.72 | |
| Host payable | 434.56 | |
| Platform revenue (guest fee + host fee) | 76.16 | |
| Tax payable | 18.00 |
The checks are mechanical: debits equal credits in every transaction (528.72 = 434.56 + 76.16 + 18.00). An append-only ledger lets finance answer "where is every cent" and makes bugs visible: if an account's balance goes negative when it should not, something is wrong.
Payouts after check-in
- Hosts are paid after the guest checks in (for example, about 24 hours later). This protects guests: if the place does not exist or is not as described, the money has not left.
- A payout job runs daily: find stays that started yesterday, compute host payable per host and currency, batch them, and send them to the payout provider (bank transfer, PayPal and similar).
- Payouts are idempotent too: each payout has an id, and the job records "payout X for reservations A, B, C" before sending, so a crash and rerun does not pay twice.
- Long stays (a month or more) are often paid out monthly.
Refunds and cancellations
- Cancellation computes the refund from the policy snapshot stored on the reservation (never the listing's current policy, which the host may have changed).
- Before capture: void the authorisation. After capture: issue a refund through the PSP, idempotently, and write reversing ledger entries.
- Partial refunds are common: "refund all nights except the first" under a moderate policy.
- Host cancellations refund the guest fully and may add penalties to the host's next payout.
Webhooks and reconciliation
- PSPs report asynchronous events (capture settled, refund failed, chargeback opened) by webhook. Handlers verify signatures, deduplicate by event id, and apply status-conditional updates.
- Webhooks can be lost or delayed. A reconciliation job downloads the PSP's settlement report daily and compares it with the ledger. Any mismatch (money we think we have but the PSP does not, or vice versa) goes to a queue for investigation.
- Chargebacks: a guest disputes a charge with their bank months later. The platform records a dispute, collects evidence (reservation, messages, check-in data), and may recover the amount from a future host payout depending on the outcome.
Multi-currency
Guests pay in their currency; hosts are paid in theirs. The platform takes FX risk between booking and payout. Options: lock the rate at booking (platform absorbs swings), or convert at payout (host absorbs them). Either way, record the rate used. The full design of a payment system is its own case study; see the payment system case study in this section.
7. Reviews you can trust#
Reviews drive bookings. Their design is mostly about trust: only real guests can review, people cannot be pressured, and the scores are fair to new listings.
Who can review, and when
- Only a completed stay unlocks a review. The review row references the reservation, and the API rejects reviews for reservations that are not completed.
- One review per side per reservation: a unique constraint on
(reservation_id, author_role). The guest reviews the place; the host reviews the guest. - A review window opens at check-out and closes after a fixed period (two weeks is a common choice). A durable timer closes it.
Double-blind publishing
If the host's review were visible before the guest wrote theirs, the guest might soften criticism to avoid a bad review in return (or retaliate). Airbnb's approach is double-blind: neither review is shown until both are submitted or the window closes. In the design:
- Each review is stored with
published = false. - When the second side submits, a transaction publishes both.
- When the window timer fires, any submitted review is published alone.
- Once published, a review cannot be edited by its author (only a short response from the other side is allowed). This prevents "I will change my review if you refund me".
Aggregation
-
The listing's rating is maintained incrementally: on publish, update
rating_sumandrating_counton a listing stats row, and emit an event so the search index updates. -
A raw average is unfair to small counts: one 5-star review beats a listing with 400 reviews averaging 4.9. For ranking (not display), use a Bayesian average:
score = (C × m + Σ ratings) / (C + n)
where m is the platform-wide mean (for example, 4.7), C is a prior weight (for example, 10 reviews' worth), and n the listing's count. A listing with one 5-star review scores (10 × 4.7 + 5) / 11 ≈ 4.73; one with 400 reviews at 4.9 scores ≈ 4.90.
-
Display usually shows the raw average once a listing has a few reviews, and "New" before that.
-
Category ratings (cleanliness, accuracy, check-in, communication, location, value) are aggregated the same way.
Moderation
- Automatic checks on submit: profanity, personal data (phone numbers, emails), links, and policy violations, using a classifier plus rules. Flagged reviews go to human review before publishing.
- Extortion and retaliation reports from hosts or guests are reviewed by support, who can remove a review.
- Reviews are part of the trust and safety pipeline: a pattern of bad reviews can trigger investigations of a listing.
Storage is simple: a few hundred million rows, read mostly by listing id with newest first. A relational table with an index on (listing_id, published_at DESC) and a cache of the first page per listing is enough.
8. Search ranking: from hand-tuned scores to deep learning#
Retrieval gives us a few thousand available listings that fit the map and filters. Ranking orders them. On a two-sided marketplace, ranking decides which hosts get bookings, so it is the most valuable model in the company. Airbnb has published unusually detailed papers on its ranking, which makes it a good real-world story to tell in an interview.
The published history
The paper "Applying Deep Learning to Airbnb Search" by Malay Haldar and colleagues (arXiv 2018) describes the journey:
- A hand-written scoring function at first: manual weights for price, reviews, quality and so on.
- Gradient boosted decision trees (GBDT) brought a large step up in bookings. Then gains flattened out after many iterations.
- A simple neural network (one hidden layer of 32 ReLU units, trained with a squared-error loss) reached parity with the trees but did not beat them.
- Lambdarank-style pairwise training: instead of predicting a score per listing, train on pairs from the same search (a booked listing versus a listing that was shown but not booked) and weight each pair's loss by how much swapping them would change the ranking quality metric (NDCG). This directly optimises the order, which is what matters.
- Combining models: feeding tree outputs and factorisation machine predictions into the network.
- A deeper network: two hidden layers (127 and 83 ReLU units), 195 input features, and about ten times the training data (around 1.7 billion pairs). This became the production model.
The lesson the authors stress is that the deep model's win came less from network architecture and more from features, data volume and fixing data bugs.
Ranking quality: NDCG
For a ranked list, discounted cumulative gain rewards relevant items more when they appear higher:
DCG = Σ over positions i of (2^rel(i) − 1) / log2(i + 1)
NDCG divides by the DCG of the ideal order, so it is between 0 and 1. In search logs, relevance is derived from what the guest did: booked > contacted the host > long view > click > impression only. Offline, a model is judged by NDCG on held-out searches; online, by bookings in an A/B test.
Features that matter
Typical features (the paper lists many of these by category):
- Listing: price (and the host's price relative to the platform's suggested price), number and average of reviews, booking history, amenities, capacity, photos quality, host responsiveness and acceptance rate.
- Query: number of nights, guests, how far ahead the trip is, the destination.
- Listing × query: distance from the map centre (taken as a log offset so it is smooth), how well the listing matches the guest's filters.
- Guest: past bookings, price range, preferred types (with privacy care).
Two practical lessons from the paper:
- Normalise features to similar ranges: (x − mean) / std for roughly normal features, and log((1 + x) / (1 + median)) for heavy-tailed ones like price and review counts. Networks train poorly on raw values spread over orders of magnitude.
- Check feature distributions. Smooth histograms are expected; spikes or odd shapes revealed bugs (for example, prices in the wrong currency, or monthly prices for long stays shown as if nightly).
Failures that teach
- Listing id as a feature (an embedding per listing) overfit. The reason is structural: a listing can be booked at most 365 nights a year, so there is never enough data per id to learn a reliable embedding, unlike a video that can be watched millions of times.
- Multi-task learning (also predicting long views to get more signal) increased long views but did not increase bookings. Optimising a proxy is not the same as optimising the goal.
- Dropout hurt rather than helped in their setup; they reported Xavier initialisation, the LazyAdam optimiser and a batch size of 200 as what worked.
Embeddings
A separate KDD 2018 paper, "Real-time Personalization using Embeddings for Search Ranking at Airbnb" by Mihajlo Grbovic and Haibin Cheng, describes listing embeddings learned from sequences of listings that users click in a session (the same idea as word2vec, where listings play the role of words). Listings that are clicked together end up close in vector space. These power similar listings carousels and real-time personalisation: if a guest has clicked three loft apartments in the last minutes, boost listings near those in embedding space.
Bias and cold start
A follow-up paper, "Improving Deep Learning for Airbnb Search" (Haldar and colleagues, arXiv 2020), organises improvements around architecture, position bias and cold start:
- Position bias: listings at the top get clicked and booked partly because they are at the top. If you train on raw logs, the model learns "whatever was ranked high is good" and freezes the current order. Fixes include adding position as a training feature (and setting it to a constant at serving time) or using randomised exploration.
- Cold start: a new listing has no reviews or bookings, so a model trained on history ranks it low, it gets no bookings, and it never gets data. Remedies: estimate engagement for new listings from similar listings nearby, and give new listings controlled exposure.
Serving the ranker
- Ranking runs inside the search path: the Search Service retrieves about 1,000-3,000 candidates, fetches features (from the index document and a feature store), and scores them. The paper describes a Java search server with a custom neural-network scoring library (instead of a general framework) to keep latency low.
- For training, logs of searches and features feed Spark pipelines and TensorFlow. The paper reports that moving training input from CSV to Protobuf with the TensorFlow Dataset API gave around a 17× training speedup and raised GPU utilisation from roughly 25% to roughly 90%.
- Latency budget: about 50-100 ms for scoring 1,000+ candidates on CPU is realistic for a small network (two layers, a few hundred features).
- Two-stage ranking helps when the model grows: a cheap model ranks thousands, the expensive one re-ranks the top few hundred.
More than one objective
Ranking is not only "most likely to be booked". On a marketplace, a booked request that the host then declines is a bad outcome for both sides. Airbnb's papers mention an ecosystem of models: predicting the chance the host accepts the request, the chance the guest rates the stay highly, and so on. The final score combines these. Every change goes through A/B tests measured on bookings (and on guest and host outcomes), not on offline metrics alone. For how such a platform works, see the experimentation platform case study.
9. Caching: what to cache, and what never to cache#
Search and listing pages are read-heavy (about 1,000 read requests per booking), so caching is essential. But stale availability or price data in the wrong place causes double bookings or angry guests. The rule: cache freely on the read path, never on the write path.
Layers
| Data | Where cached | TTL / invalidation | Why that is safe |
|---|---|---|---|
| Photos, static JS/CSS | CDN | Long, versioned URLs | Immutable content |
| Listing details (title, amenities, description) | Redis, plus CDN for public pages | Minutes; invalidate on host edit event | Changes rarely; staleness is cosmetic |
| Popular search results (city, dates, guests) | Redis, keyed by normalised query | 30-60 seconds | Search is an estimate; booking re-checks |
| Availability bitmaps | Search node memory | Updated by calendar events in about a second | Same: estimate only |
| Listing calendar for the page | Redis | Short TTL plus delete on calendar event | Guest sees near-current calendar; booking re-checks |
| Quotes | Not cached; computed and signed | Expire in 30 minutes | The quote itself is the promise |
| Booking path reads | Never cached | n/a | Must read the source of truth under lock |
Invalidation by events
- Every calendar change (booking, cancellation, host block, partner update) produces an event through the outbox. Consumers: the search index updater, the calendar cache invalidator, and the listing page cache.
- Delete, don't update, cache entries on change: an update can race with a concurrent read-and-fill and leave an old value; a delete followed by a fill from the database is simpler. Add a short TTL as a safety net in case an event is lost.
- Versioned keys help:
cal:{listing}:{version}. Readers fetch the current version number (cheap), and stale versions simply age out.
Stampedes and hot keys
- Stampede: a popular query's cache entry expires and 2,000 requests per second all miss and hit the search cluster at once. Fix with request coalescing (one request recomputes; others wait for it) and early, randomised refresh before expiry.
- Hot keys: a listing featured on a TV show gets 50,000 page views per minute. Its cache key lands on one Redis shard. Fix with a small in-process cache (a few seconds) on each Listing Service instance, or by replicating the hot key under several suffixes.
- Penetration: requests for listings that do not exist (scrapers) miss the cache every time. Cache negative results briefly, and rate-limit by client.
See Caching Strategies: Cache-Aside, Read-Through, Write-Through, Write-Behind and Cache Failure Modes: Stampedes, Hot Keys and Penetration for the general patterns.
When the cache fails
If Redis is down, the read path falls back to the database replicas and the search index, with load shedding: degrade gracefully (show fewer results, skip personalisation) rather than overload the primary database that bookings depend on. The booking path is unaffected because it never used the cache.
10. Frequent calendar updates and syncing with other platforms#
Hosts and hotels update availability constantly. Many hosts list the same home on several platforms; hotels use channel managers that push the same rooms to every booking site. This creates a write stream and a correctness problem.
The volume
From the capacity estimate: about 110 million calendar changes a day, 10,000 per second at peak. The changes are bursty: a hotel chain's channel manager may push updates for thousands of properties at once after a revenue manager changes rates.
Ingesting partner updates (ARI)
- Partners send ARI messages (availability, rates, inventory) over an API. The Partner Gateway authenticates the partner, validates the message, and acknowledges quickly.
- Messages go into a Kafka topic partitioned by property id, so updates for one property are applied in order.
- An applier consumes them and writes to the calendar database in batches: one transaction per property per batch.
- Coalescing: if three updates for the same room type and night arrive within a second, only the last matters. The applier merges them before writing, which can cut write volume a lot during bursts.
- Ordering and idempotency: messages carry a partner sequence number or timestamp per property. The applier ignores messages older than the last applied one for that key.
A full-sync option (the partner sends all inventory for the next N days) repairs drift; it runs nightly or on demand.
iCal for homes
Many hosts sync calendars between platforms using iCal feeds: each platform exports a URL listing blocked dates, and imports the others' URLs.
The weakness of iCal is that it is polled. If another platform takes a booking and we poll every few hours, there is a window in which both platforms can sell the same night. That is the main source of real double bookings for multi-listed homes, and no database constraint on our side can prevent it because the other booking happened elsewhere.
Mitigations:
- Adaptive polling: poll feeds of listings with upcoming check-ins and recent changes more often (every 15-30 minutes), quiet feeds less often (every few hours). Use conditional requests (ETag, If-Modified-Since) so unchanged feeds cost little.
- Push integrations with channel managers for professional hosts, which update within seconds.
- Conflict handling: when an import blocks nights that already have a confirmed reservation on our side, we cannot undo either booking automatically. Flag it to the host immediately, and to support, with a rebooking flow for the guest.
Protecting the booking database from update bursts
- Calendar writes from partners and the booking path share the same rows. Partner bursts must not starve guest bookings. Use separate worker pools with limits, and have the applier back off when database latency rises.
- Partner updates that set a night's
units_totalbelow what is already reserved are rejected for that night (the CHECK constraint enforces this), and reported back to the partner.
11. Sharding, scaling and multiple regions#
Shard the booking data by listing
Everything that must be consistent for one booking (a listing's calendar nights and its reservations) is keyed by listing_id. Sharding by listing keeps every booking transaction on one shard, so it stays a local transaction.
- With roughly 200 bookings per second at peak and 10,000 calendar updates per second, a handful of PostgreSQL shards (for example, 8-16, each with replicas) is enough for throughput. The reason to shard is mostly data size and operational headroom, not raw write rate.
- Use many logical shards (for example, 1,024) mapped onto fewer physical databases, so you can move logical shards to new machines without re-hashing every listing.
- Hot listings do not create hot shards here: even a viral listing only gets a few booking attempts per second, which one shard handles easily.
See Consistent Hashing for mapping keys to shards with minimal movement.
Queries that cut across shards
- "My trips" (reservations by guest) would require visiting every shard. Instead, maintain a guest reservations index: a table keyed by
guest_id(on its own shards) fed by reservation events. It is eventually consistent by a second or so, which is fine because the guest just saw the confirmation page. - Host dashboards across many listings: same idea, keyed by host id.
- Finance and analytics: from the event stream into a warehouse, never by querying the booking shards.
Search scales separately
- The search index is sharded too, but by geography or by document hash, and is replicated for read throughput.
- Geography-based routing (a search in Lisbon goes only to the shards covering Portugal) reduces fan-out; hash-based sharding spreads hot cities evenly but every query fans out. A common compromise is to partition by large region and hash within a region.
- At 5,000 searches per second at peak and maybe 30 ms per shard query, a few dozen search nodes per region with replicas is a reasonable estimate. Add replicas, not shards, when read QPS grows.
Multiple regions
- Reads (search, listing pages, photos) are served from the region nearest the guest. The search index and caches are replicated to each region, fed by the event stream.
- Writes for a listing go to one home region for that listing, usually the region nearest the listing (a Paris flat is homed in Europe). A guest in Tokyo booking that flat pays one cross-region round trip (about 200-250 ms), which is acceptable within a 2-second booking budget.
- Why not multi-primary writes for bookings? Two regions accepting bookings for the same nights at the same time would need cross-region coordination anyway to avoid double booking. Single-home per listing is simpler and correct.
- Failover: if a region fails, its listings' home moves to a standby region with synchronous or near-synchronous replicas. Bookings for those listings pause for the failover time (minutes); search keeps working everywhere.
See Multi-Region and Global Data for the trade-offs between these designs.
12. Hotels versus homes#
The same platform can sell both, but they differ in ways that touch the data model and the booking logic.
| Aspect | Home (one unit) | Hotel |
|---|---|---|
| Inventory | One listing, one unit per night | Room types with a count per night (for example, 12 "Double Deluxe") |
| Booking check | Is every night free? | Does every night have at least one unit left? |
| Which room? | The whole place | The hotel assigns the room number at check-in |
| Prices | Host rules | Rate plans per room type, often from a revenue management system |
| Source of truth | Our calendar (plus iCal imports) | Often the hotel's own system, via channel manager |
| Confirmation | Instant book or host approval | Usually instant; sometimes confirmed by the partner's system |
| Overbooking | Never | Sometimes, deliberately |
Unit allocation
For hotels we sell a count, not a specific room. That makes the hold simple (decrement a counter per night) and leaves room assignment to the hotel. For a platform managing apartments with several identical units (a serviced apartment building), you may need to assign a specific unit so the guest does not have to change rooms mid-stay. That turns into a small interval scheduling problem: pick a unit whose calendar is free for the whole stay, preferring units that leave fewer unsellable gaps (for example, avoid leaving a single free night between two bookings).
Overbooking math
Hotels often allow selling a few percent more rooms than they have because some guests do not show up or cancel late. A rough model: if each of n sold rooms independently no-shows with probability p, the number of guests who arrive is binomial. With 100 rooms, p = 5%, and 104 rooms sold:
- Expected arrivals: 104 × 0.95 = 98.8.
- Standard deviation: √(104 × 0.95 × 0.05) ≈ 2.2.
- The chance that more than 100 guests arrive (so someone is "walked" to another hotel) is about P(arrivals ≥ 101), roughly 1 − Φ((100.5 − 98.8) / 2.2) ≈ 1 − Φ(0.77) ≈ 22% (the exact binomial sum gives about 23%).
So even 4% overbooking makes a walk fairly likely on any given night at 5% no-shows. Revenue managers trade the revenue of filling no-show rooms against the cost of walking a guest (paying for another hotel, and goodwill). In the design, overbooking is a per-night allowance (overbook_allow) set by the hotel or its revenue system, never by the platform for homes. The CHECK constraint uses units_total + overbook_allow, so the guard stays in the database.
When the partner is the source of truth
For hotels connected through a channel manager, the hotel's own property management system holds the real inventory. Our copy can lag. Two options:
- Trust our copy and send the booking to the partner asynchronously. Fast for the guest, but occasionally the partner rejects (room already sold on another channel) and we must rebook or refund.
- Confirm with the partner synchronously before confirming to the guest. Slower (partner APIs can take seconds) and dependent on the partner's uptime, but fewer failed bookings.
Many platforms do the first for well-behaved partners with fast ARI updates, and the second for partners with a history of rejections.
Bottlenecks and Failure Modes#
| Failure / hotspot | Impact | Mitigation |
|---|---|---|
| Two guests book overlapping nights at the same moment | Double booking, the worst failure in the product | Atomic conditional update per night in one transaction, row count check, CHECK constraint, and an exclusion constraint for single-unit listings |
| Search index lags behind the calendar | Guests click listings that were just booked; failed checkouts | Booking path never trusts the index; target index freshness of 1-2 s; show "just booked" with alternatives; track failed-attempt rate as an SLO |
| PSP times out during authorisation | Unknown whether the card was charged; risk of double charge or lost booking | Idempotency key per payment step; query the PSP by key before retrying; reconciliation job against PSP reports |
| Hold expires while payment is completing | Paid guest without nights, or nights released to another guest | Status-conditional confirm; re-take nights if free; automatic refund and apology if not |
| iCal sync lag with other platforms | Same night sold on two platforms | Adaptive polling, conditional GETs, push integrations for professional hosts, conflict alerts and rebooking support |
| Partner ARI bursts (chain-wide rate changes) | Calendar write spikes slow guest bookings | Kafka buffer partitioned by property, coalescing, separate worker pools, backpressure when DB latency rises |
| Popular query cache entry expires | Stampede on the search cluster | Request coalescing, early randomised refresh, short TTLs with jitter |
| Viral listing page | Hot cache key on one Redis shard | In-process cache for a few seconds, key replication, CDN for the public page |
| Booking shard primary fails | Bookings for listings on that shard pause | Synchronous standby with automatic failover; many logical shards so blast radius is small; search continues |
| Ranking model or feature store slow | Search latency over budget | Timeouts with fallback to a simpler model or index-time score; two-stage ranking; capacity tests before launches |
| Region outage | Guests in that region and listings homed there affected | Reads from other regions' replicas; failover of listing home regions; bookings for affected listings pause for minutes |
| Price shown in search differs from checkout | Distrust, abandoned checkouts, regulatory risk (fees must be shown honestly in some markets) | One pricing function used everywhere; signed quotes; show totals with fees early; monitor the search-to-quote price gap |
What Interviewers Expect#
Mid-level. Gets the core design right: listings in a database, a search service with a geo index and date filter, and a booking service that writes reservations. Knows that double booking is the central risk and proposes a transaction with locking or a conditional update. Separates search (read-heavy, can be slightly stale) from booking (must be correct). Gives rough numbers: bookings per second are small, searches are about a thousand times more frequent. Mentions idempotency for the booking request.
Senior. Models availability carefully: per-night rows or ranges, half-open stays, time zones and stay rules. Designs the hold-then-pay flow with expiry, a sweeper and a status-conditional confirm, and explains why holds and reservations sit in one local transaction while payment is a short saga with compensation. Explains how search filters on availability at scale (a bitmap or interval index updated by events) and why the booking path re-checks the source of truth. Designs pricing as one function with signed quotes, and payments with authorise and capture, a ledger and payouts after check-in. Picks stores per access pattern and justifies sharding by listing.
Staff and above. Frames the business as a two-sided marketplace and the design choices that follow: ranking affects which hosts earn, request-to-book trades conversion for host control, payout timing protects guests. Brings up cross-platform double booking through iCal as a problem no local constraint can solve, and designs detection and recovery for it. Discusses ranking as a learning system with position bias, cold start and multiple objectives, measured by A/B tests on bookings. Covers the hotel side (counts, rate plans, overbooking as a deliberate risk, partner as source of truth), multi-region home regions for listings, and regulation (night caps, tax collection, fee transparency) as requirements that shape the data model. Defines SLOs such as zero double bookings, booking p99 and index freshness.
Deep Dive: sizing every tierShow
The capacity section gave the load. Here we turn it into machines, with the reasoning so you can redo it with other numbers in an interview.
Search tier.
- Peak 5,000 searches per second. Each search does: place resolution (cached), retrieval from the geo and filter index, availability filtering with bitmaps, scoring 1,000-3,000 candidates, and pricing the top results.
- Suppose one search takes about 40 ms of CPU on one core across all of that (index lookups are a few ms; the ranker dominates). Then 5,000 × 0.04 = 200 core-seconds per second: about 200 busy cores. At 50% target utilisation, 400 cores, or about 13 machines with 32 cores. Double it for replicas in a second zone and headroom: about 25-30 search machines per major region.
- Memory per search node: the availability bitmaps for the whole world are about 1 GB; nightly prices 29 GB dense or a few GB sparse; listing documents (filters, geo, scores) 10 M × 1-2 KB = 10-20 GB. Everything fits in a 64-128 GB machine, so each node can hold the full index and no query has to fan out across shards. If the index grows, shard by region.
Availability updates into search.
- 10,000 calendar changes per second at peak. Each updates a few bits and a few price slots in memory: microseconds of work. The challenge is distributing the stream to every search node. With 30 nodes per region and 3 regions, each event is applied about 90 times; 10,000 × 90 = 900,000 tiny updates per second across the fleet, spread over 90 machines, so 10,000 per machine per second. Easy.
Listing page tier.
- 15,000 page views per second at peak. Most data comes from caches (listing details, reviews first page, calendar). At about 5 ms of CPU each, 75 cores. A dozen machines with headroom.
- Redis for listing details and calendars: 10 M listings × 10 KB details = 100 GB, but only the hot fraction needs caching: perhaps 20%, so 20 GB plus calendars. A small Redis cluster (3-6 primaries with replicas) holds it, and 15,000 reads per second (plus misses) is far below what Redis can serve.
Booking tier.
- 200 bookings per second at peak. Each booking transaction touches about 3 night rows, inserts a reservation and an outbox row: perhaps 5-10 ms of database time. 200 × 10 ms = 2 seconds of database time per second across all shards. Even one PostgreSQL primary could handle this; we shard for size and blast radius (8-16 shards), not for throughput.
- Calendar updates (10,000 per second at peak) are the heavier write load: batched and coalesced, they cost perhaps 1-2 ms each, 10-20 seconds of DB time per second, spread over 16 shards: about 1 second per shard per second, which fits with room to spare when spread over cores.
- Storage per shard: 1.5 TB / 16 ≈ 100 GB of calendars plus reservations. Comfortable.
Payments.
- 200 authorisations per second at peak to the PSP, each 300 ms to 2 s. With async I/O this is a few hundred concurrent requests: trivial for the service, but check the PSP's own rate limits and use more than one PSP for resilience.
Event pipeline.
- Kafka carries calendar changes (10,000 per second at peak), reservation events (a few hundred per second), and search impression logs (5,000 searches × 20 impressions = 100,000 events per second at peak, about 400 GB a day). A modest Kafka cluster (6-12 brokers) handles it; impression logs dominate and go to the data lake for ranking training. See Apache Kafka in Practice.
Photos.
- About 1 PB in object storage. Served via CDN; the origin sees only misses. At 15,000 page views per second with about 10 images each, that is 150,000 image requests per second, almost entirely CDN hits. Images are resized at upload into a few standard sizes and served in modern formats. See Content Delivery Networks (CDN).
| Tier | Load at peak | Rough size per region |
|---|---|---|
| Search | 5,000 queries/s | 25-30 machines, full index in memory |
| Listing pages | 15,000 views/s | 10-15 machines plus Redis cluster |
| Booking DB | 200 bookings/s, 10,000 calendar writes/s | 8-16 PostgreSQL shards with replicas (in the home region) |
| Kafka | about 120,000 events/s | 6-12 brokers |
| Photos | 150,000 images/s | CDN; about 1 PB origin storage |
The pattern: search dominates compute, bookings dominate correctness. Spend money on the read side; spend design care on the write side.
Deep Dive: what the public record tells us about AirbnbShow
It helps to know a few public facts, both to calibrate numbers and to show that the design matches reality. Only facts we are confident about are listed here.
The company.
- Airbnb was founded in August 2008 by Brian Chesky, Joe Gebbia and Nathan Blecharczyk. The idea started in October 2007, when two of the founders rented out air mattresses in their apartment.
- It went public on December 10, 2020, raising about 3.5 billion US dollars.
- It acts as a broker: it does not own the homes and earns service fees from bookings. It also owns HotelTonight, a hotel booking app, which shows that homes and hotels on one platform is a real business shape.
Product rules that shape the design.
- Double-blind reviews: reviews are hidden until both sides have submitted or the review window has closed. Our review design implements exactly this rule.
- A ban on parties was made permanent in June 2022. In the design, this becomes rules on maximum guests, extra checks for risky bookings (for example, a one-night local booking on a holiday weekend), and trust and safety workflows.
Regulation.
- Cities regulate short-term rentals. Amsterdam, for example, limits renting out a whole home to 30 nights a year and to groups of at most four people. Barcelona has announced it will end short-term tourist apartment licences by November 2028.
- In 2020 a Dutch court ruling addressed the service fees Airbnb charged on both sides of a booking.
- For the design, regulation means: a per-listing yearly night counter enforced at booking time, maximum-guest rules per jurisdiction, licence numbers on listings, and the ability to delist in bulk by area. These are not afterthoughts; a booking that breaks a city cap can expose the host and the platform to fines.
Engineering publications.
- "Applying Deep Learning to Airbnb Search" (Haldar and colleagues, arXiv 2018): the ranking story told in deep dive 8.
- "Improving Deep Learning for Airbnb Search" (Haldar and colleagues, arXiv 2020): architecture, position bias, cold start.
- "Real-time Personalization using Embeddings for Search Ranking at Airbnb" (Grbovic and Cheng, KDD 2018): listing embeddings from click sessions.
- "Customized Regression Model for Airbnb Dynamic Pricing" (Ye and colleagues, KDD 2018): price suggestions for hosts.
- An engineering blog post titled "Avoiding Double Payments in a Distributed Payments System": idempotency in payments.
We have not verified Airbnb's internal choices for databases or the exact booking architecture, so the design in this page is a reasonable one, not a description of their systems.
Booking volume as a calibration point. Booking Holdings reported roughly 1.1 billion room nights booked in 2024 across its brands. At around 3 nights per booking, that is about 1 million bookings a day, the same order of magnitude as our estimate of 1.5 million. Our numbers are realistic for a top-tier global platform.
Deep Dive: a 45-minute interview plan and follow-up questionsShow
Minutes 0-5: clarify. Homes, hotels, or both? Instant book or host approval? Booking window (two years)? Scale (10 M listings, 1.5 M bookings a day)? What matters most: no double booking, fast search, honest prices.
Minutes 5-10: numbers and entities. Bookings are about 17 per second on average, 200 at peak; searches are about 1,000 times more frequent. Calendar data is under 2 TB; availability bitmaps for all listings fit in 1 GB. Entities: listing, calendar night, price rule, quote, reservation, payment, review.
Minutes 10-15: API. Search with place or bounding box, dates and guests. Listing page with calendar. Quote. Create reservation with an idempotency key. Cancel. Host calendar update.
Minutes 15-25: high-level design. Listing service and database; calendar database as source of truth; search service with geo index, availability bitmaps and ranker, fed by events; pricing service; booking service with local transactions; payment service talking to the PSP; outbox and Kafka; reviews; notifications.
Minutes 25-40: deep dives (let the interviewer pick, but be ready for all):
- No double booking: conditional update per night, row count check, CHECK and exclusion constraints, holds with expiry and a sweeper, idempotency.
- Availability in search: why not query the database per candidate; bitmaps updated by events; stale index is fine because booking re-checks.
- Payments: authorise and capture, payouts after check-in, ledger, reconciliation.
- Pricing consistency: one function, signed quotes.
Minutes 40-45: failures and scale. PSP timeouts, hold expiry races, iCal double bookings, shard by listing, home region per listing.
Follow-up questions and short answers.
- What if two guests click "Book" on the same flat at the same second? Both run the conditional update on the same night rows; row locks serialise them; the second finds the nights taken and gets a 409 with alternatives.
- Why not just use a distributed lock? A lock with a timeout can expire while the holder is still working, and then two writers proceed. The database constraint is the real guard; a lock can only reduce contention.
- How do you show availability for flexible dates ("any weekend in June")? With bitmaps, test each candidate weekend's mask for each listing: a few dozen bit operations per listing. Rank by the best weekend.
- A host changes the price while a guest is checking out. Which price applies? The signed quote's price until it expires. After that, re-quote and show the change before payment.
- How do you stop a guest from being charged twice? Idempotency keys on our API and on PSP calls, unique constraints, and reconciliation.
- How do you handle a host who also lists on another platform? iCal import and export, adaptive polling, push integrations, and a conflict workflow when both sides sell the same night.
- Hotels have 300 identical rooms. Do you store 300 calendars? No: one count per room type per night, decremented atomically; the hotel assigns rooms.
- How would you add "pay part now, part later"? Split the payment into two scheduled charges with a durable timer, authorise or charge the second near the stay, and define what happens if it fails (cancel per policy after a grace period).
- How do you keep search fast when a city has 50,000 listings? Bounded retrieval: viewport, filters and bitmaps prune to a few thousand; a cheap first-stage ranker; the deep ranker only on the top few hundred.
- What is your consistency model? Strong for calendars, reservations and money (single-shard transactions). Eventual (a second or two) for search, caches, guest trip lists and host dashboards.
Deep Dive: one booking end to end, with timingsShow
Follow one guest, Sam, who books a flat in Lisbon for 12-15 June 2027 for two people. Times are realistic targets for a well-run system.
- Search (about 250 ms server time). Sam types "Lisbon". Autocomplete resolves it to a place id with a polygon (10 ms, cached). The Search Service takes the viewport, finds about 9,000 listings inside it from the geo index (5 ms), drops those that do not fit two guests or Sam's filters (5 ms), and tests the 3-night mask on each listing's availability bitmap (well under 1 ms for 9,000 listings). About 2,500 remain. A cheap first-stage model scores all 2,500 (15 ms); the deep ranker re-scores the top 300 (40 ms). Prices for the top 20 cards and 300 map pins come from the in-memory nightly price arrays (5 ms). Results return with a page token.
- Listing page (about 120 ms). Sam opens a flat. Listing details, photos URLs, the first page of reviews and the calendar come from Redis (5-10 ms each, in parallel). The Pricing Service computes a quote: nights 408 EUR, cleaning 40 EUR, guest fee 62.72 EUR, tourist tax 18 EUR, total 528.72 EUR. It signs the quote with a 30-minute expiry.
- Reserve (about 40 ms). Sam clicks "Reserve". The app generates an idempotency key and sends the quote id. The Booking Service verifies the signature, routes to the shard for this listing, and runs the hold transaction: upsert night rows, conditional update on 3 nights (3 rows changed), insert the reservation as held with a 15-minute expiry, insert an outbox event. Commit.
- Pay (about 1-2 s). The Payment Service asks the PSP to authorise 528.72 EUR with an idempotency key derived from the reservation id. The issuer may require 3-D Secure; Sam approves in their banking app. The PSP returns "authorised".
- Confirm (about 20 ms). The Booking Service runs
UPDATE reservations SET status = 'confirmed' WHERE id = ... AND status = 'held'(instant book listing), captures the payment, writes ledger entries and an outbox event. Sam sees the confirmation page. - Fan-out (about 1-2 s, async). The outbox relay publishes
reservation.confirmed. Consumers: the search index updater clears the 3 bits for those nights on every search node; the calendar cache entry is deleted; the guest trips index adds the reservation; notifications send email and push to Sam and the host; the iCal export for this listing changes, so other platforms will see the nights blocked at their next poll. - Before the stay. Reminders are scheduled with durable timers. If Sam cancels within the free cancellation window, the refund is computed from the policy snapshot.
- Check-in + 24 hours. The payout job moves 434.56 EUR from guest payable to host payable and schedules a bank transfer. Ledger entries record platform revenue (76.16 EUR) and tax payable (18 EUR).
- Check-out. The review window opens for both sides. Both submit within the window; both reviews publish together. The listing's rating stats update, and the search document's score changes.
What could go wrong at each step, and the response:
| Step | Failure | Response |
|---|---|---|
| 1 | Bitmap index a second behind | Sam may see a listing that was just booked; step 3 catches it |
| 3 | Another guest's hold took a night | 409; show similar listings for the same dates |
| 4 | PSP times out | Query PSP by idempotency key; never create a second authorisation |
| 5 | Hold expired during 3-D Secure | Re-take nights if free; otherwise void or refund and tell Sam |
| 6 | Search update event delayed | Short window of stale results; no correctness impact |
| 8 | Payout bank rejects details | Payout marked failed; host asked to fix details; money stays in host payable |
Deep Dive: flexible dates and long staysShow
Guests often do not have fixed dates. "Any weekend in June", "a week in August", "a month this autumn". These change the search problem.
Flexible dates with bitmaps.
- For "any weekend in June", the candidate stays are four or five Friday-to-Sunday windows. For each listing, test each window's mask: 5 bit operations. For 10,000 candidates, 50,000 operations: still well under a millisecond.
- For "a week in August", there are about 25 possible 7-night windows. Find any run of 7 free bits in the August slice: a classic bit trick is to AND the bitmap with itself shifted by 1, 2, 4 positions (so each bit means "free for the next k nights"), which needs about log2(7) ≈ 3 shift-and steps.
- Ranking then picks the best window per listing (lowest price or best fit) and shows it on the card: "Fri 11 - Sun 13 June".
// Bit i of `free` = 1 if night i is free. Returns a mask where bit i = 1
// if nights i .. i+len-1 are all free (a run of at least `len` free nights).
function runsOfFree(free: bigint, len: number): bigint {
let acc = free;
let covered = 1;
while (covered * 2 <= len) { // doubling: runs of 2, 4, 8 ...
acc = acc & (acc >> BigInt(covered));
covered *= 2;
}
if (covered < len) acc = acc & (acc >> BigInt(len - covered));
return acc;
}
// Example: does the listing have 7 free nights in a row anywhere in August?
// (runsOfFree(free, 7) & augustStartMask) !== 0nThe trick works because after the doubling steps each bit means "free for covered nights from here"; combining two overlapping windows of length covered covers any length up to 2 × covered.
Stay rules interact with flexible search. A 7-night window must also satisfy the listing's minimum and maximum stay, allowed check-in days and advance notice. These are evaluated only for listings that pass the bitmap test, so their cost is small.
Long stays (28 nights or more).
- Prices are usually monthly with large discounts, so the price array per night is not enough: apply the length-of-stay rule in the pricing function.
- Payments are split: first month at booking, then monthly charges with durable timers. Payouts to the host are monthly too.
- Some jurisdictions treat stays above a threshold as tenancies with different rules (deposits, notice periods). The policy snapshot records which regime applies.
- Search and display must not mix nightly and monthly prices. The ranking paper mentions exactly this kind of bug surfacing through feature distributions: a monthly price for a long stay shown as if it were the nightly price.
Deep Dive: trust and safety in a booking marketplaceShow
Guests sleep in strangers' homes; hosts let strangers in. The platform's job includes making that safe. In system terms, trust and safety is a set of risk checks at key moments, plus investigation tools.
Where checks happen.
- Account creation: email and phone verification, device fingerprint, signals of fake accounts.
- Listing creation: address verification, photo checks (stock photos, photos reused from other listings), price far below the area norm (a classic scam signal).
- Booking: a risk score combining guest history, payment method risk, booking pattern (one night, local guest, large group on a holiday weekend might signal a party), and listing risk. Outcomes: allow, require identity verification, ask the host to approve, or block.
- Messaging: detecting attempts to move payment off the platform ("pay me by bank transfer for a discount") or share contact details before booking.
- After the stay: reviews, complaints and damage claims feed back into both accounts' risk.
Architecture.
- The Booking Service calls a Risk Service synchronously during reservation creation, with a tight timeout (50-100 ms). On timeout, fall back to a conservative default (for example, allow but flag for review, or require host approval for high-risk categories), never to "block everyone".
- The Risk Service reads features from a feature store (precomputed per user, listing, device and payment method) and runs rules plus a model. Rules let analysts react to a new scam pattern within hours; models generalise.
- All decisions are logged with the features used, so investigators can see why a booking was blocked and models can be retrained on outcomes.
Messages.
- Guest and host messaging is a small chat system: conversations keyed by reservation or inquiry, stored by conversation id, with push notifications. Volume is modest compared with a chat app.
- Messages pass through filters before delivery; suspicious ones are held or the sender warned.
- Hosts are measured on response rate and response time, which feed ranking (a host who never answers wastes guests' time).
Fairness.
- Requiring host approval lets hosts choose guests, which also creates room for discrimination. Platforms counter with policies, by hiding some guest details until after acceptance, and by favouring instant book in ranking. For the design, the point is that what the host sees before accepting is a deliberate product decision encoded in the API.
Deep Dive: rules, regulation and taxes in the booking pathShow
Regulation is not only a legal topic; it changes data models and checks.
Night caps. In a city with a 30-night yearly cap for whole-home rentals (Amsterdam has one), the platform must count nights booked per listing per calendar year and refuse bookings that exceed the cap.
- Keep a counter row per (listing, year) on the same shard as the calendar, updated in the booking transaction with a conditional update:
UPDATE listing_year SET nights = nights + 3 WHERE listing_id = 42 AND year = 2027 AND nights + 3 <= cap. A stay crossing New Year updates two rows. - Cancellations decrement it. The counter is part of the same local transaction as the nights, so it cannot drift.
Guest limits. Maximum guests per booking by jurisdiction (four in Amsterdam for whole-home rentals), enforced in the booking validation and the search filter.
Licences. Listings in regulated areas carry a registration number, validated at listing creation (sometimes against a city registry). Bulk delisting by area must be possible when a city changes the law.
Taxes.
- Tourist taxes vary by city: per person per night, a percentage of the price, capped at some number of nights, with exemptions for children. VAT applies to platform fees in many countries.
- A tax rules engine keyed by jurisdiction (resolved from the listing's location) computes tax lines in the quote. Rules are versioned with effective dates, because a booking made in March for a stay in August may fall under a rate that changes in July. The quote records which rule version applied.
- Where the platform collects and remits tax, the ledger has a tax payable account per jurisdiction and a remittance job reports and pays each authority on its schedule.
Fee transparency. Several jurisdictions require that the total price including mandatory fees be shown up front. This pushes the design toward computing totals (not only nightly prices) in search, which the in-memory price arrays plus a cached fee schedule per listing make feasible.
Data residency and privacy. Guest identity documents are sensitive. Store them encrypted, in a separate service with strict access controls and retention limits, and pass only verification outcomes (verified or not) to other services.
Deep Dive: testing and operating the booking pathShow
A design that is correct on paper can still double book in production because of a bug. Some practices that catch problems early:
- Invariant checks. A job runs every few minutes per shard: for each (listing, night), count confirmed and held reservations covering it and compare with
units_reserved. Any mismatch pages the on-call engineer. This catches bugs in release, cancellation or modification paths, the places where counters most often drift. - Concurrency tests. In CI, run hundreds of parallel booking attempts against a single-unit listing for overlapping dates and assert that exactly one wins per night. Run the same test with injected crashes between steps.
- Shadow traffic for ranking. New rankers score real queries in the background, logged but not shown, to check latency and score distributions before an A/B test starts.
- SLOs. Zero double bookings (measured by the invariant job), booking p99 under 2 seconds, search p99 under 500 ms, index freshness under 5 seconds for 99% of updates, payout on time for 99.9% of stays. See Observability: Logs, Metrics and Traces.
- Safe deploys. The booking service and calendar schema change carefully: expand-and-contract migrations, canary releases, and feature flags for new booking flows. See CI/CD and Deployment Strategies.
- Game days. Practise PSP outages (switch to a second PSP or queue bookings in held state with longer expiries), Kafka lag (search goes stale; bookings unaffected), and a shard failover.
Deep Dive: changing a reservation's datesShow
"Can we arrive a day earlier?" sounds simple, but a date change is one of the trickiest operations: it must take new nights and release old ones atomically, re-price, and adjust money, without ever leaving the guest with no booking.
The safe order.
- Compute the difference: nights to add (11 June) and nights to release (none, or 14 June if the guest also leaves earlier).
- In one transaction on the listing's shard: conditional update to take the added nights (row count check), decrement the released nights, update the reservation's
stayrange and version, and write an outbox event. If any added night is taken, roll back: the original reservation stays exactly as it was. - Re-price with a new quote for the new stay, using the same pricing version or current prices according to policy. Compute the difference from what was paid.
- Charge or refund the difference as a separate, idempotent payment step. If the extra charge fails, the reservation must not stay changed for free: either keep the new dates with a payment-due state and a deadline (durable timer), or revert the change in a compensating transaction.
Why not cancel and rebook? Between the cancel and the rebook, another guest could take the nights, and the guest loses their booking. The change must be a single transaction on the nights.
Exclusion constraint subtlety. For single-unit listings, updating the stay range to overlap with itself is fine (the constraint compares against other rows), but extending into another reservation's range fails with a constraint error, which the service maps to "dates not available".
Host approval. On request-to-book listings, a change request may need host acceptance. Then the new nights are held (like a hold for a new booking) while the host decides, and the old reservation stays confirmed. If the host declines or the window passes, the hold is released.
Hotels. Changing dates may also change the rate plan (a non-refundable rate may not allow changes at all). The policy snapshot on the reservation says what is allowed.
Deep Dive: cancellation policies as dataShow
Cancellation policies look like legal text, but they should be modelled as data the system can evaluate, so refunds are computed the same way every time.
A policy as rules. For example:
policy: moderate
version: 7
rules:
- before_checkin: "120h" # 5 days or more before check-in
refund_nights: 1.0
refund_cleaning: 1.0
refund_guest_fee: 1.0
- before_checkin: "0h" # less than 5 days before check-in
refund_nights: 0.5 # half of the nights not yet stayed
refund_cleaning: 1.0
refund_guest_fee: 0.0
- after_checkin: true
refund_nights_unstayed: 0.5
refund_cleaning: 0.0
refund_guest_fee: 0.0
grace_period_after_booking: "48h" # full refund if booked and cancelled quickly, subject to conditionsSnapshot at booking time. The reservation stores the full policy (or its id and version) as it was when booked. If the host switches to a stricter policy later, existing guests keep their terms. This is the policy_snapshot column in the data model.
Evaluation. The refund function takes the snapshot, the reservation's line items, the check-in time in the listing's time zone, and the cancellation time. It returns refund amounts per line item. It is pure (no I/O), so it can be unit-tested exhaustively, including edge cases: cancellation exactly at the boundary, daylight-saving changes, stays that already started.
Exceptions. Extenuating circumstances (natural disasters, serious illness) can override the policy. Model them as an explicit override record with a reason and the approver, so the ledger shows why a refund exceeded the policy.
Hotels. Rate plans carry their own policies (non-refundable, free cancellation until 24 hours before arrival). Partners may define them; the platform maps them into the same rule format.
Key Takeaways#
- Correctness lives in the booking path, speed lives in the search path. Searches are about a thousand times more frequent than bookings. Make search fast and slightly stale; make booking slow enough to be exactly right.
- The database is the guard against double booking. Use an atomic conditional update over every night of the stay in one transaction, check the row count, and back it with a CHECK constraint (and an exclusion constraint for single-unit homes). Locks in other systems only reduce contention.
- Model availability per night, stays as half-open ranges. Nights are the unit you sell;
[check-in, check-out)avoids off-by-one bugs; store calendars sparsely, with stay rules and time zones explicit. - All availability fits in about 1 GB of bitmaps. An in-memory bitmap index updated by events lets search test 25 million availability checks per second at peak and handle flexible dates with a few bit operations.
- Hold, then pay, then confirm. A hold with an expiry, a sweeper, and a status-conditional confirm handle abandoned checkouts and the race between expiry and payment success. Keep nights and reservation in one local transaction; treat the payment as a short saga with refunds as compensation.
- One pricing function and signed quotes. Search shows estimates; the quote is the promise. Integer minor units, a recorded FX rate, versioned tax rules and policy snapshots keep money explainable.
- A marketplace needs a ledger. Authorise and capture, double-entry ledger entries, payouts after check-in, idempotent PSP calls and daily reconciliation.
- Reviews are about trust. Only completed stays review, once per side, double-blind, with Bayesian averages for ranking fairness.
- Ranking is a learning system. Pairwise training on booked versus not-booked listings, careful feature normalisation, and attention to position bias, cold start and the 365-nights-a-year data limit per listing.
- Some double bookings come from outside. iCal polling across platforms leaves a window no local constraint can close; shorten it with adaptive polling and push integrations, and design recovery.
- Shard by listing, home each listing in one region. Every booking stays a single-shard transaction; reads are served from every region; guest and host views are event-fed indexes.
- Hotels sell counts; homes sell a whole unit. Room types, rate plans, deliberate overbooking with a per-night allowance, and partners as the source of truth change the details but not the core guard.