Dev.to WebDev 🛠 Dev 👁 2 📖 4 min read

How I made double booking impossible in a Next.js + Postgres booking app

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" wi

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

A repeated submit gets the same appointment back instead of an error or a duplicate. If two identical submits arrive at exactly the same moment, the unique index stops the second one, so there's still never a second booking.

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("one time slot cannot go to two patients, even concurrently", 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);
});

One honest caveat I found later: my test suite runs on PGlite (Postgres in-process), which executes one transaction at a time. So this test checks the outcome, but it passes even without the for("update") line, because there's no real race inside PGlite. To catch someone "cleaning up" the lock later, run the same test against a real Postgres with a connection pool, where the requests really do run in parallel.

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 with new 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. My bakery and florist store templates use a similar approach: atomic conditional stock updates, a lock per delivery window, and the same idempotency key on orders.

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.

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.