When I built an online booking flow for a dental clinic site (Next.js 15, Drizzle ORM, PostgreSQL), the scariest bug wasn't a UI glitch. It was this one: two patients look at the same free 9:00 slot, both click "Book" within the same second, and both get a confirmation email.
The usual first attempt looks fine and is still broken:
// ❌ check, then insert const clash = await db.select().from(appointments).where(overlaps(doctorId, start, end)); if (clash.length) throw new Error("slot_taken"); await db.insert(appointments).values({ doctorId, startsAt: start, endsAt: end, ... }); Between the select and the insert another request can run the same check, see the same empty result, and insert too. Under load (or just two fast clicks from two phones) you get two appointments at 9:00.
Here's what I ended up with, in three small layers.
1. Lock one row per doctor, then re-check inside the transaction
const appt = await db.transaction(async (tx) => { // only one booking per doctor can be in this block at a time await tx.select({ id: doctors.id }).from(doctors) .where(eq(doctors.id, input.doctorId)) .for("update"); // the overlap check now runs while we hold the lock const clash = await tx.select({ id: appointments.id }).from(appointments).where(and( eq(appointments.doctorId, input.doctorId), ne(appointments.status, "canceled"), lt(appointments.startsAt, end), // existing starts before new ends gt(appointments.endsAt, start), // existing ends after new starts )); if (clash.length) throw new BookingError("slot_taken"); const [row] = await tx.insert(appointments).values({ ... }).returning(); return row; }); SELECT ... FOR UPDATE on the doctor's row works like a per-doctor mutex inside Postgres. The second request waits at that line until the first transaction commits, and then its overlap check sees the new appointment and fails cleanly with slot_taken.
Why lock the doctor and not the appointment rows? Because when the slot is free there is no appointment row to lock yet. Locking the parent row avoids that "phantom" problem without switching the whole transaction to SERIALIZABLE and handling retries.
The overlap condition existing.start < new.end AND existing.end > new.start also catches partial overlaps: a 30-minute emergency visit at 9:30 clashes with a 60-minute cleaning that started at 9:00, even though the start times differ.
2. Idempotency key for double clicks and retries
A lock doesn't help if the same patient submits the same form twice (double click, flaky mobile network, the browser retrying a POST). That would be two bookings for one person.
The form generates a random key once, and the table has a unique index on it:
uniqueIndex("appointments_idem_uq").on(t.idempotencyKey) const [dup] = await db.select().from(appointments) .where(eq(appointments.idempotencyKey, input.idempotencyKey)); if (dup) return { appt: dup, created: false }; // same answer as the first time The second submit gets the same appointment back instead of an error or a duplicate.
3. A test that actually races
The part I'd recommend most: write a test that fires parallel requests at the same slot and checks that exactly one wins.
it("three simultaneous bookings for one slot: exactly one succeeds", async () => { const rs = await Promise.allSettled([1, 2, 3].map(() => book(db, input(), NOW))); expect(rs.filter((r) => r.status === "fulfilled")).toHaveLength(1); expect(await db.select().from(appointments)).toHaveLength(1); }); Without the for("update") line this test fails, so it really protects the fix from someone "cleaning up" the code later.
On the UI side, a slot_taken error refreshes the list of free times and says "Sorry, that time was just taken. Please pick another one." It's much friendlier than a generic error.
Small things that also mattered
- Time zones. Slots are generated in the clinic's time zone (an
Intl-based helper), not the server's. Vercel runs in UTC, so a "9:00" built withnew Date()on the server would be wrong for a clinic in New York. - Lead time. Bookings start at least 2 hours ahead, and the server checks it again. The form isn't trusted.
- Public appointment pages use a random 128-bit ID, and they show no phone or email. Patients can cancel up to 24 hours before, and the slot becomes free again.
If you want to see it working, the demo is here: https://brightwell-dental-studio-demo.vercel.app (try booking the same time in two tabs).
I also packaged the full source as a template, with a booking flow, an admin panel with roles, 59 tests and a deploy guide: Dental Clinic Template on Gumroad. The same approach to locking and idempotency is used in my bakery and florist store templates, for stock and delivery slots.
How do you handle this in your apps: row locks, SERIALIZABLE with retries, or an exclusion constraint with tstzrange? I'd like to hear what worked for you.
