Video in progress
How do you prevent the same room from being booked twice for an overlapping time range in a hotel booking system?
The most reliable way is an exclusion constraint in the database itself: EXCLUDE USING gist (room_id WITH =, stay WITH &&). It rejects overlapping ranges at any isolation level and on any code path. A check in the application is only for a friendly error message.
📖 Answer
The usual wrong solution is "check first, then write":
if (repo.existsOverlap(roomId, from, to)) throw new BusyException();
repo.save(new Booking(roomId, from, to));
Under READ COMMITTED, two parallel requests both see it free and both write. A unique index doesn't help: the ranges aren't equal, they overlap.
PostgreSQL has a dedicated tool for this:
CREATE EXTENSION IF NOT EXISTS btree_gist;
CREATE TABLE bookings (
id bigserial PRIMARY KEY,
room_id bigint NOT NULL,
stay daterange NOT NULL,
status text NOT NULL,
EXCLUDE USING gist (room_id WITH =, stay WITH &&)
WHERE (status <> 'CANCELLED')
);
daterange('2026-11-10', '2026-11-12') is [) by default, so the checkout day doesn't collide with the next guest's check-in day. The second write is rejected with 23P01 (exclusion_violation), and the application turns that into a "room is taken" message.
The other options and why I choose them less:
SELECT ... FOR UPDATEon the room row works, but every code path has to remember to do it, and all bookings for one room become sequential.SERIALIZABLEworks, but it brings retries and an effect on other transactions.- A daily slot table (
room_id, dayunique) works with a plain unique index and moves to other DBs; with hourly bookings the rows multiply.
In a distributed system (bookings through another service, with external channel managers) this constraint still remains the final truth; with the external side you need a temporary "hold" and a mechanism to release it when it expires.
Sign up to mark studied questions and save your progress.