Video in progress
In a doctor appointment booking system, what do you do so two patients can't book the same time at once?
I give the main guarantee to the database: a unique constraint on the slot, or in PostgreSQL an exclusion constraint for time ranges. An application-level "check first, then write" loses under concurrent requests anyway, and locks are only a helper.
📖 Answer
The classic buggy code:
if (!bookingRepo.existsBySlotId(slotId)) { // both requests see it as "free"
bookingRepo.save(new Booking(slotId, patientId));
}
Two requests arrive a millisecond apart, both pass the check, and both records are saved. @Transactional doesn't help here: under READ COMMITTED transactions don't see each other's uncommitted rows.
Solutions, ordered by reliability:
-
Unique constraint. If slots are created in advance, put
unique (slot_id)on the booking table (a partial index to exclude cancelled ones). The second INSERT gets aDataIntegrityViolationException, you catch it and return 409 "This time has just been taken". -
Exclusion constraint, when the time is a free-form range (09:10–09:40):
create extension if not exists btree_gist;
alter table booking add constraint no_overlap
exclude using gist (doctor_id with =, tstzrange(starts_at, ends_at) with &&)
where (status <> 'CANCELLED');
The database itself rejects two overlapping appointments.
-
Atomic conditional UPDATE.
update slot set status='BOOKED', patient_id=? where id=? and status='FREE'— if the number of updated rows is 0, someone got there first. No separate lock needed. -
Optimistic locking (
@Versionon the slot) works too, but takes more code.
I always put in 1 or 2, and 3 on top of it to give the user a fast, clear answer. A distributed lock in Redis is overkill here and gives a weaker guarantee than the database.
There is a UX side too: when booking opens for a popular doctor, hundreds of requests hit one slot. A temporary "hold" (5 minutes, with a TTL) and a final booking after confirmation is the usual approach in booking systems.
Sign up to mark studied questions and save your progress.