Note 002 · Data1 min read
No double bookings, enforced by the database
Holds, transactions and a PostgreSQL exclusion constraint in a multi-tenant booking system.
In a salon booking system the worst bug isn't a crash. It's two customers booked with the same stylist at the same time, both holding a confirmation.
In Bokyi, availability depends on a lot: the staff member's working hours, the branch's hours and exceptions, existing bookings and active holds. Checking all of that in application code is necessary, but not enough. Two requests can run the same check at the same moment, both see a free slot, and both write.
Let the database say no
Bookings live in PostgreSQL, and the bookings table has an exclusion constraint on each staff member's time. However the race goes, the second overlapping booking fails in the database, and the API turns that into an ordinary conflict response. Roughly this shape:
-- a sketch of the idea, not the production schema
EXCLUDE USING gist (
staff_id WITH =,
tstzrange(starts_at, ends_at) WITH &&
) WHERE (status <> 'cancelled')Holds before bookings
A customer doesn't book directly. They get a short hold on a slot, then confirm. Confirmation locks the hold, checks it hasn't expired, re-checks the staff member's bookings and creates the booking, all in one transaction.
The hold token also makes confirmation idempotent. On a weak mobile connection the app may send it twice; the second request gets back the booking the first one created instead of a new one.
Expired holds
A scheduled job clears expired holds every five minutes, but nothing waits for it. Every availability query ignores a hold the moment it expires, so the slot frees up on time even when the job runs late.
- Laravel
- PostgreSQL