A double booking is the worst failure a marketplace like Airbnb can have. Two guests pay for the same home on the same nights, one of them arrives to find someone else in the living room, and the trust that the whole business runs on is damaged in a way no refund fully repairs. Preventing it sounds like a simple database constraint, but at the scale of millions of listings and millions of bookings, it is a distributed systems problem with real tradeoffs. The design has to answer three questions: how to check availability fast enough for search, how to make the booking itself atomic, and what to do when two people try to book the same nights at the same moment.
The first idea is that availability is not a single boolean. A listing has a calendar, and each night has a state: available, booked, blocked by the host, or unavailable because of a minimum stay or a check in rule. Search needs to answer a different question from booking. Search asks which listings are available for a date range, across millions of listings, in well under a second. Booking asks whether this specific listing is still available for these exact nights, right now. Those two questions are served by two different systems, and confusing them is the most common design mistake.
Search reads from an index, not from the transactional database. When a host blocks a date or a booking completes, an event updates the search index, and the listing disappears from results for those nights. The index is eventually consistent, which means a listing can appear available in search for a short time after it has actually been booked. That is acceptable for search, because search results are a suggestion, not a promise. The promise is made at booking time, against the database, where consistency is strict. A system that tried to make search strictly consistent would be slow and fragile, and it would still need the booking time check anyway.
The booking itself is a transaction, and the transaction is the heart of the design. A booking touches several things at once: it must verify the nights are free, mark them as booked, create the reservation record, place a hold on the payment, and notify the host. If any step fails, all of them must be undone, and the nights must become available again. In a relational database, this is a single transaction with a lock on the rows that represent the listing's calendar.
BEGIN;
SELECT night FROM availability
WHERE listing_id = 101
AND night BETWEEN '2026-12-20' AND '2026-12-23'
AND status = 'available'
FOR UPDATE;
-- If the query returns fewer than 4 rows, a night is
-- already booked or blocked, so roll back and tell
-- the guest the dates are no longer available.
INSERT INTO reservations (listing_id, guest_id, check_in, check_out, status)
VALUES (101, 77, '2026-12-20', '2026-12-24', 'pending_payment');
UPDATE availability SET status = 'booked'
WHERE listing_id = 101
AND night BETWEEN '2026-12-20' AND '2026-12-23';
COMMIT;
The SELECT FOR UPDATE is the mechanism that makes the whole thing safe. It takes a row level lock on the availability rows for those nights, and any other transaction trying to book the same nights blocks until the first one commits or rolls back. The second transaction then sees the updated status and fails the availability check. There is no window in which two bookings can both succeed, because the lock serializes them. The lock is held only for the duration of a short transaction, so contention is limited to the rare case where two people book the same listing on the same nights at the same moment, which is exactly the case that needs serializing.
A lock in the database is not the only option, and the alternatives are worth understanding because they show up in other systems. Optimistic locking adds a version number to the listing or the calendar, reads it at the start, and fails the write if the version changed before commit. It performs better under low contention and worse under high contention, because conflicting transactions retry instead of waiting. A distributed lock in Redis or a similar store can serialize bookings across services, but it adds a failure mode: if the lock holder crashes, the lock must expire, and the expiry window has to be handled carefully. The database lock is the simplest correct answer for a single database, and it is usually the right starting point. A service should only move to a more complex mechanism when it can measure a real problem with the simple one.
Payment adds a second phase to the booking, and the design has to handle the gap between reserving the nights and charging the guest. Airbnb does not charge the full amount the instant the guest clicks book. The booking is created in a pending state, the payment is authorized, and the reservation is confirmed once the authorization succeeds. If the authorization fails, the transaction rolls back and the nights are released. If the guest's browser closes or the network drops in the middle, the pending reservation must not hold the nights forever. Pending reservations have a short expiry, often measured in minutes, and a background job releases the nights when the expiry passes. This is the same pattern as a seat hold in ticketing, and the expiry is what keeps a failed payment from blocking a listing for hours.
Idempotency is what makes retries safe, and retries are constant in a system like this. A guest on a slow connection presses the book button twice, a mobile app retries a request that timed out, a load balancer replays a request after a gateway restart. Every one of those retries must produce the same single reservation. The client generates an idempotency key when the booking flow starts, sends it with the request, and the server stores it with the reservation. A second request with the same key returns the original reservation instead of creating a new one. The key is stored in the same transaction as the reservation, so there is no window where the reservation exists but the key does not.
func CreateBooking(ctx context.Context, db *sql.DB, req BookingRequest) (*Reservation, error) {
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return nil, err
}
defer tx.Rollback()
var existingID int64
err = tx.QueryRowContext(ctx,
`SELECT reservation_id FROM idempotency_keys WHERE key = $1`,
req.IdempotencyKey).Scan(&existingID)
if err == nil {
return loadReservation(ctx, tx, existingID)
}
res, err := bookNights(ctx, tx, req)
if err != nil {
return nil, err
}
_, err = tx.ExecContext(ctx,
`INSERT INTO idempotency_keys (key, reservation_id) VALUES ($1, $2)`,
req.IdempotencyKey, res.ID)
if err != nil {
return nil, err
}
if err := tx.Commit(); err != nil {
return nil, err
}
return res, nil
}
The handler above returns the existing reservation when it sees a repeated key, which means the client can retry as aggressively as it wants without creating duplicates. Notice that the idempotency check, the booking, and the key insert all happen inside one transaction. Splitting them across separate calls would open a race where two identical requests both pass the check before either one writes the key.
Calendar sync is the problem that makes this harder than a single database can solve. Hosts list the same property on multiple platforms, and a booking on another platform must block the dates on Airbnb, and vice versa. Airbnb imports and exports iCalendar feeds for this, and it polls those feeds on a schedule. Polling means there is a delay, sometimes minutes, between a booking elsewhere and the calendar updating. During that window, a double booking is possible, and no database lock can prevent it, because the other platform's booking never touches Airbnb's database. The mitigation is operational rather than technical: hosts who sync calendars see a warning about the delay, and the support team handles the rare conflicts with rebooking and compensation. Some problems are not solved by engineering alone, and admitting that is part of good design.
Pricing adds another layer of state that interacts with availability. Nightly prices change with demand, weekends, seasons, and host rules, and the price a guest sees in search must match the price at checkout. The booking flow therefore re-reads the price inside the same transaction that checks availability, and if the price changed since search, the guest sees the new price and confirms again. Showing a stale price and then charging a different one is a trust problem, and it is cheaper to re-confirm than to handle the complaints.
The failure modes worth planning for are specific. A database failover during a booking can leave the client unsure whether the booking succeeded, which is why the client retries with the same idempotency key and the server answers from the stored key. A payment authorization that succeeds but whose response is lost must not create a paid booking without a reservation, which is why the reservation and the payment record are created together and reconciled by a background job. A host who cancels after confirmation triggers a different flow entirely: the guest is rebooked, the host is penalized, and the listing's reputation takes the hit, because the marketplace cannot allow hosts to treat confirmed bookings as optional.
The lesson for a backend engineer is that a booking system is a state machine with a small number of states and strict transitions, and the database is the enforcer. Availability is a set of rows with a status, booking is a locked transaction that flips them, payment is a pending state with an expiry, and retries are safe because of idempotency keys. The search index, the calendar sync, and the notifications are all secondary systems that feed into the transaction but never replace it. Build the transaction first, test it with concurrent bookings for the same nights, and only then build the features around it. A marketplace earns trust by never selling the same night twice, and the way it earns that trust is a lock, a transaction, and a key.
Top comments (0)