Design the database for a booking site like Airbnb
Listings, search by place and date, and a booking that must never double-book a night. Strong consistency where money moves, geo search where people browse.
More on Database design case studies
- Database Design Interview: A 7-Step Framework
- Design the database for a Q&A site like Quora
- Design the database for a short-video app like TikTok
- Design the database for an ephemeral messaging app like Snapchat
- Who gets the last phone in a flash sale
- Which database for a food delivery app
- The cache expired and the database fell over
- A live final: scale before the toss
- An app like ChatGPT: the answer is written live
- A product Q&A box on sale day
- Tatkal at 10:00: one seat, sold in stretches
- A group chat: one register, many sockets
Keep learning
Overview
Listing text and attributes 7 M listings × 10 KB Relational, plus a copy in the search index 7 M × 25 photos × 4 MB (original + resized copies) 700 TB, growing about 2 TB/day Object storage behind a CDN Calendar (one row per listing per night, 365 days ahead) ≈ 150 GB, ≈ 300 GB with indexes Relational, same shard as the listing Bookings, payments, booked nights 1 M/day × (1 KB + 0.5 KB + 4 × 50 B) 1.7 GB/day ≈ 620 GB/year Relational, ACID 0.7 M/day × 1 KB 0.7 GB/day ≈ 255 GB/year Relational (or wide-column keyed by listing) Listing page views 1 M/day Rows written per booking ≈ 70 rows/s ≈ 210 rows/s Search: area + dates + guests + price, sorted by relevance very high (≈ 5,600/s peak) Seconds stale is fine Search index: geo field, guests, price, available-dates field Open a listing page very high (≈ 16,700/s peak) Seconds stale is fine, except the price shown at checkout Cache by listing_id, filled from the listings shard Show a listing calendar for 3 months PK (listing_id, night) range scan Book: hold nights, create booking low (≈ 35/s peak) Strict: never two guests per night Primary of the listing shard, one transaction Pay for a booking a few seconds Exactly once per intent UNIQUE (idempotency_key) Guest: my trips Own new booking must appear Index on (guest_id, check_in) Host: upcoming bookings of my listings Index on (listing_id, check_in) Reviews of a listing, newest first Stale is fine Index on (listing_id, created_at DESC) Bookings, booked nights, payments, calendar Relational database (PostgreSQL or MySQL) Users, listings, reviews Same relational database Structured, related by foreign keys, modest size. Keeping them next to bookings allows joins for host and guest pages. Discovery (search) Search engine with a geo index (Elasticsearch, OpenSearch, Solr) Geo, ranges, text and ranking in one query, scaled out with replicas. Not the source of truth: rebuilt from the database. Object storage + CDN Large immutable blobs. The database stores only the object key and the order. Listing page, search results Cache (Redis or Memcached) with short TTL and invalidation events Absorbs the read rate. Never used to decide whether a night is free. Change events Outbox table + log (Kafka) via change data capture Moves every committed change to search, cache and analytics without a dual write. 1. Check, then insert Application code only ✕ Double books under concurrency Never on its own. 2. SELECT … FOR UPDATE on calendar rows Row locks on pre-created listing-night rows The second booking of the same nights waits ✓ if every writer locks, in night order 3. UNIQUE (listing_id, night) in booking_nights A unique index The second insert of the same night waits, then fails ✓ for every code path One row per night: a 30-night stay writes 30 rows. Portable to MySQL and PostgreSQL. 4. Optimistic version on calendar rows Conditional UPDATE + affected-row count ✓ if the row count is checked Good when conflicts are rare and the guest spends minutes on the form. Must retry or report. 5. Exclusion constraint on a date range A GiST index on (listing_id, stay) The overlapping insert waits, then fails with 23P01 PostgreSQL only. One row per booking. Cannot depend on now(), so expired holds need a sweeper. Shard by user_id (separate from listings). Generated id, never reused UNIQUE, NOT NULL Stored lower-cased NOT NULL ISO 3166 code Instant in UTC Shard by listing_id. A host is any user who owns a listing: no role column needed. NOT NULL, FK users.id (logical across shards) lat, lng NOT NULL, CHECK ranges About 10 cm precision IANA name, e.g. 'Europe/Lisbon' CHECK (max_guests > 0) CHECK (> 0) ISO 4217 CHECK IN ('draft','active','paused') Drives cache invalidation INDEX (host_id) for the host dashboard PK part 1, FK listings.id PK part 2 Display order NOT NULL, UNIQUE width, height Host-controlled price and rules per night, pre-created for 365 days. status and version are needed only for approaches 2 and 4. Local date of the listing, no time, no zone Overrides the base price DEFAULT 1 CHECK IN ('open','blocked','booked') NOT NULL DEFAULT 0 For approach 4 PK range scan serves "3 months of calendar" Shard by listing_id: the same shard as the calendar. NOT NULL, FK listings.id A host block has no guest check_in, check_out CHECK (check_out > check_in) Half-open: nights are check_in … check_out − 1 CHECK (guests > 0) CHECK IN ('pending','confirmed','blocked','cancelled','expired') total_minor, currency BIGINT, CHAR(3) Price quoted at booking time, copied in NULL when confirmed Pending holds expire INDEX (listing_id, check_in) for the host view INDEX (guest_id, check_in) — or a guest_trips table on the guest shard PostgreSQL option: EXCLUDE USING gist (listing_id WITH =, daterange(check_in, check_out) WITH &&) WHERE (status IN ('pending','confirmed','blocked')) The rule "one guest per night" as a key. PK part 1 NOT NULL, FK bookings.id ON DELETE CASCADE The PK (listing_id, night) is the unique constraint that stops double booking Co-located with the booking. NOT NULL, FK bookings.id Created by the client per payment intent CHECK IN ('charge','refund','payout') amount_minor, currency CHECK (amount_minor > 0) CHECK IN ('pending','authorized','captured','failed') UNIQUE, NULL until known Provider charge id created_at, updated_at INDEX (status, created_at) for the reconciliation job Only a real stay can be reviewed, once per side. Copied from the booking for the listing page CHECK (rating BETWEEN 1 AND 5) INDEX (listing_id, created_at DESC) Check for overlap, then insert, with no constraint Two guests booked for the same night Locking nights in different orders Deadlock between two bookings Calling the payment provider inside the booking transaction Hold the nights as pending, commit, then call the provider Pending holds that never expire Listing looks booked forever after an abandoned checkout hold_expires_at + a job that marks old holds expired and frees the nights Writing to the database and then to the search index from the app A crash between the two leaves search out of date for good Outbox row in the same transaction, then change data capture Trusting search results for availability A guest clicks a listing that was booked two seconds ago Reading availability from a replica before booking Replica lag makes a booked night look free The check that decides is the constraint on the primary Storing check-in as a UTC timestamp In Tokyo, midnight 10 June is 15:00 on 9 June UTC: the night shifts by a day DATE for nights, plus the listing time_zone for times like check-in at 15:00 Inclusive end date Back-to-back stays rejected, or one night too many charged Half-open ranges: [check_in, check_out) Reading the price from listings at payment time Copy the quoted total into the booking Retrying a payment without an idempotency key Guest charged twice UNIQUE idempotency_key in payments, and the same key sent to the provider Money in FLOAT Integer minor units + currency code Sharding bookings by guest_id The overlap check needs all bookings of a listing: a cross-shard query Reviews with no link to a stay booking_id NOT NULL, UNIQUE (booking_id, author_role), allowed only after check_out chapters · database design case studies Design the database for a booking site like Airbnb Hosts list homes, guests search a map for free dates, and one night can be sold to one guest only. This chapter applies the seven steps from the design framework to that site. Most of the traffic is browsing, which is easy to scale with copies. The hard part is a few dozen bookings per second that must never collide, and payments that must never run twice. reads per booking bookings at peak 1 shard per booking transaction (listing_id) strict rules: one guest per night, one charge “Check the calendar, then insert the booking” in application code, or deciding availability from the search index. Two guests press Book for the same nights within the same millisecond. Who wins, and how does the loser find out?
Brochure versus ledger
search, view, book Search index geo cells + availability copy Booking service hold → pay → confirm Relational DB UNIQUE (listing_id, night) Payment provider idempotency key one transaction charge once Search, cache and analytics are copies, rebuilt from the outbox. Only the ledger decides whether a night is free.
1. Requirements: what the system must do, and how well
Start with the actions people take, then the qualities each action needs. They differ a lot from one action to the next.
What users do
Host: create a listing (text, location, photos, capacity, price), set price and blocked nights per date, see upcoming bookings. Both: after the stay, review each other once.
How well
No double booking, ever. This is the one hard rule. Exactly-once payment per booking intent, even with retries. Available for browsing even when booking is degraded.
Left out on purpose
Messaging, ranking models, fraud scoring, tax rules, currency exchange. Each is its own system that reads from the core described here. Writing the two hard rules down first matters: they decide the store for bookings and payments before any number is computed. Everything else can be eventually consistent.
2. Estimation: a read-skewed system with a small, strict write path
Assumptions, all round numbers for a large marketplace: 7 million active listings, 20 million daily active users, 8 searches per user per day, 3 listing pages opened per search, 1 million bookings per day averaging 4 nights, and a peak hour 3× the daily average. A day has 86,400 seconds. Per day Photos are over 99% of the bytes and none of the hard problems. The transactional data (bookings, payments, nights, reviews) grows by about 2.4 GB a day, under 1 TB a year: a size a sharded relational cluster handles comfortably. ! Check the units before the conclusion
3. Entities: the nouns, and the one that is easy to miss
The obvious entities are users, listings, listing_photos, bookings, payments and reviews. The one that carries the hard rule is the listing-night: a single night of a single listing. A guest books a range of dates, but what can be sold only once is each night inside it. A user can be a guest, a host or both. Being a host is a fact derived from owning a listing, so no role column is needed. A listing has one host, many photos, one calendar row per future night, many bookings and many reviews. A calendar night holds what the host controls: the price for that date and a minimum stay. (Blocked dates are stored like bookings, see section 7.) A booking covers the nights from check-in up to, not including, check-out. It copies the quoted price in, because the listing price can change later. A booked night (listing_id, night, booking_id) is the row that can exist once per night. Section 7 shows why it earns its own table. A payment belongs to a booking. Charges, refunds and payouts are separate rows, never an updated amount. A review belongs to a finished booking, one per side. Tying it to a stay is what makes it trustworthy.
4. Access patterns: write every query down with its rate and its tolerance
A schema is only good relative to the queries it serves. List them with how often they run, how fast they must answer and how stale they may be. The last column is the key or index that makes each one cheap. Access patterns Staleness allowed Served by
Search by place: why a B-tree on (lat, lng) is not enough
A composite index on (lat, lng) can narrow the latitude to a band, but inside that band the longitudes are spread over the whole planet, so the second column barely helps (the same limit as any range on a leading column, see range scan). Geo indexes solve this by cutting the map into cells and giving each cell a key. A geohash interleaves the bits of latitude and longitude into one string, so nearby points share a prefix: precision 5 is a cell of about 4.9 × 4.9 km, precision 6 about 1.2 × 0.6 km. A quadtree splits a square into four only where it is crowded, so a dense old town gets small cells and the countryside large ones. A search then becomes: find the cells that touch the search circle, read the listings in them (candidates), check the exact distance, apply the other filters. Try the cell size, and put the search centre on a cell corner. The date filter is the part most designs forget. Checking availability in the booking database for every candidate would put the search load on the one store that must stay calm. Instead, each listing's search document carries its free nights (a list of open date ranges, or a 365-bit map), updated from change events after every booking and every host edit. The result can be seconds stale. That is acceptable because the booking transaction checks again, for real.
Keeping the copies in step: the outbox
If the booking service commits a booking and then updates the search index in a second call, a crash between the two leaves search wrong until someone notices. Instead, the booking transaction also inserts a row into an outbox table. Both commit or neither does. A relay (or change data capture reading the binlog or WAL) publishes outbox rows to a log, and the search indexer and cache invalidator consume them, each at least once, so they must apply each event idempotently, using the listing's updated_at or a version number to skip events older than what they already have.
6. Partition key: listing_id, and keep a listing's bookings with its calendar
Section 2 showed that write throughput does not force sharding: 35 bookings per second fits one primary. What does push towards it, after a few years, is size and operations: about 3 TB of bookings, nights, payments and reviews make backups, restores, index builds and failovers slow, and one primary is one blast radius. Splitting into, say, 16 shards gives about 190 GB each. The shard key follows from the hard rule. The double-booking check compares a new booking with every other booking of the same listing. If all of a listing's rows (listing, calendar_nights, bookings, booking_nights, payments, reviews) carry listing_id and are sharded by it, that check is a local transaction on one shard. Shard bookings by guest_id instead and the check becomes a cross-shard read plus a distributed lock or a two-phase commit (see two-phase commit), for no gain.
Recommended
Even spread, since no single listing gets much traffic. Every booking is single-shard. New shards are added by splitting hash ranges. Cost: queries by guest or by host fan out, so they get their own index (below).
When law or latency asks for it
Data residency rules or a far-away data centre can justify placing listings by country first. A listing never moves, so the region is stable. Cost: regions are uneven (Paris against a rural area), so hash by listing_id inside each region anyway.
Tempting, then painful
Keeps a host's dashboard on one shard. But a property manager with 5,000 listings makes one shard much hotter than the rest.
7. Consistency: the booking must not double-sell a night
Five ways to stop double booking Where the rule lives What the second guest sees The race in approach 1 is the same pattern as the lost update: a decision made on a read that is stale by the time of the write. Raising the isolation level is not the general fix: REPEATABLE READ keeps each snapshot stable, which is what lets both checks pass, and MySQL's gap locks only help if the check is a locking read on an index that covers the range (see gap locks and locks…
More courses
- Jobs, linked to lessons — Browse jobs where every requirement links to the chapter that teaches it. See how ready you are, how long the gap takes to close, and which listings look stale.
- Match a job post to courses — Paste a job post. Each skill is matched to a track here and put in learning order, foundations first.
- React patterns from open source — Patterns extracted from Material UI, Radix, React Aria, React Hook Form, Redux Toolkit, TanStack, and Next.js — not slides about hooks.
- System Design — Core concepts first (SQL vs NoSQL, CAP, indexing, replication, sharding), then designs grouped by what carries them: the database, Redis, Kafka, or many services.
- NestJS: build a real API — One ticket-booking API, built in order: a plain Node server first, then NestJS modules, validation, a real database, and the features real clients lean on.
- Microservices — Microservice patterns one diagram at a time: how to split a monolith, how services talk, and how data stays consistent without distributed transactions.
- Kafka — A beginner-to-senior path through event logs, reliable delivery, production operations, and disaster recovery.
- AI engineering for software engineers — Eight free reads, in order, for software engineers moving into AI: when to build an agent, how to build one, how to test it, and how the model works underneath.
- Frontend system design — How a UI is sliced when it is a product, not a page: ownership of state, cache, routes, and what happens when the network lies.
- TypeScript in depth — The type system as a design tool. Inference, narrowing, generics, and the errors that mean the model is wrong — not a catalog of utility types.
- CSS in depth — See the box, then the page. Visual chapters from the box model through Flexbox surprises, Grid, selectors, and units, then backgrounds, shapes, and visual effects, each with a playground.
- Accessibility — Foundations first (WCAG in plain words, semantic HTML, lists, alt text), then hands-on HTML labs, a full pass of WAI-ARIA 1.3, and a final fix-the-page challenge.
- Docker — What an image is, why layers cache, and how containers find each other on a network.
- Redis — Fifteen Redis patterns, one picture each: cache, session, lock, counter, rate limiter, queue, and when Redis is the wrong tool.
- Kubernetes — Kubernetes from zero to operators: why it exists, Pods, Deployments and Services, then configuration, networking, storage, scheduling, scaling and security.
- AWS — AWS networking in plain English. A VPC is a gated housing society: streets are subnets, the Internet Gateway is the main gate, and a route table is the signboard.
- Networking: the NetRoute game — NetRoute is a packet logistics game. You wire up computers, switches, routers, firewalls and gateways, set each device, and watch glowing packets travel. If a packet gets dropped, the game shows you which header field was wrong.