Video in progress
In a hotel booking system, how do you make sure two people can't book the same room for the same day?
"Check first, then write" lets both through when two requests run in parallel. The guarantee has to come from the database itself: a unique constraint on (room, date), an exclusion constraint in PostgreSQL, or updating an inventory row with a lock/optimistic version. While payment is pending, use a temporary hold with a TTL.
📖 Answer
The broken code:
if (!bookingRepo.existsOverlap(roomId, from, to)) { // both requests see "no overlap"
bookingRepo.save(new Booking(roomId, from, to));
}
Two requests check in the same millisecond, both see it as free, and both write. @Transactional doesn't stop this at the default isolation level either.
Option 1 — per-day inventory rows. One row per room-day:
CREATE TABLE room_nights (
room_id BIGINT, night DATE, booking_id BIGINT,
PRIMARY KEY (room_id, night)
);
-- booking 3 nights = 3 INSERTs in one transaction; if one collides, everything rolls back
The unique key settles the race at the DB level.
Option 2 — a PostgreSQL exclusion constraint (for ranges):
ALTER TABLE bookings ADD CONSTRAINT no_overlap
EXCLUDE USING gist (room_id WITH =, daterange(check_in, check_out) WITH &&);
(To use = with room_id you need the btree_gist extension.)
When selling by room type (not a specific room — "20 of the standard rooms"): room_type_inventory(type, night, available) and UPDATE ... SET available = available - 1 WHERE available > 0 — if 0 rows are updated, there's no room left.
You also need a hold. The user sits on the payment page for 10 minutes. The booking is created in HOLD status with an expires_at; if payment goes through it becomes CONFIRMED, otherwise a background job releases it. Without it, of two people sitting on the payment page, one pays and is left without a room.
Syncing with external channels (Booking.com and the like) is a hard part of its own: inventory is exchanged with them asynchronously, so sometimes you need an overbooking policy and a person to resolve it by hand.
Sign up to mark studied questions and save your progress.