Full answer
Tables: rooms(id, hotel_id, type), bookings(id, room_id, guest_id, check_in, check_out, status).
Two reliable ways to stop double booking:
- PostgreSQL exclusion constraint (needs
btree_gist):
text
ALTER TABLE bookings ADD CONSTRAINT no_overlap
EXCLUDE USING gist (room_id WITH =, daterange(check_in, check_out) WITH &&)
WHERE (status <> 'cancelled');- One row per room per night:
room_nights(room_id, night, booking_id, PRIMARY KEY (room_id, night)). Inserting all nights in one transaction fails on any clash. This works on any engine, including SQLite.
Application checks ("is anything overlapping?" then insert) race under concurrency unless the room row is locked first with SELECT ... FOR UPDATE.
Half-open ranges let a guest check out on the same day another checks in. Availability searches then query for rooms with no overlapping booking, using the overlap test check_in < :end AND :start < check_out.
Key points
- Model stays as half-open date ranges
- PostgreSQL exclusion constraints prevent overlaps
- One row per room-night with a unique key works anywhere
- Check-then-insert races without locking
Common mistakes
- Validating availability only in application code
- Using closed ranges that block same-day turnover
Follow-ups
- How would you search available rooms for given dates?
- How would you hold a room for 10 minutes during checkout?
Tips
- Name the concurrency hazard