Dev.to WebDev 🛠 Dev 👁 0 📖 5 min read

How to stop double bookings on Cloudflare D1 (no transactions, no exclusion constraints)

If you build a booking page, two customers will eventually click the same 10:30 slot within the same second. On Postgres you would reach for an exclusion constraint or SELECT ... FOR UPDATE. On Cloudflare D1 (SQLite at t

If you build a booking page, two customers will eventually click the same 10:30 slot within the same second. On Postgres you would reach for an exclusion constraint or SELECT ... FOR UPDATE. On Cloudflare D1 (SQLite at the edge) you have neither, and a Worker can't hold an interactive transaction across awaits.

This post shows the pattern we use in production: a pure slot engine that decides what is free, plus an insert-then-recheck step that makes the race harmless. About 60 lines of TypeScript, no locks, no extra services.

1. The table

CREATE TABLE bookings (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  shop_id INTEGER NOT NULL,
  staff_id INTEGER,              -- NULL = no staff, one "chair"
  date TEXT NOT NULL,            -- '2026-12-01'
  time TEXT NOT NULL,            -- '10:30'
  duration_min INTEGER NOT NULL,
  status TEXT NOT NULL DEFAULT 'confirmed'
);
CREATE INDEX bookings_shop_date ON bookings(shop_id, date);

Why not a UNIQUE(shop_id, date, time)? Because services have different lengths. A 60-minute haircut at 10:00 and a 30-minute beard trim at 10:30 never share a start time, yet they overlap. A unique index can't see that.

2. Work in minutes

Every comparison gets easier if times are integers:

export const toMin = (t: string) => {
  const [h, m] = t.split(":").map(Number);
  return h * 60 + m;
};
export const toHHMM = (min: number) =>
  `${String(Math.floor(min / 60)).padStart(2, "0")}:${String(min % 60).padStart(2, "0")}`;

And the one rule everything rests on, two ranges [s, e) and [x.start, x.end) overlap when:

const overlaps = (s: number, e: number, x: { start: number; end: number }) =>
  s < x.end && x.start < e;

Half-open ranges mean a booking ending at 10:30 does not clash with one starting at 10:30. That's what customers expect.

3. A pure slot engine

Keep the "what is free?" logic free of I/O so you can unit test it with plain arrays:

type Busy = { start: number; end: number; staff_id: number | null };

export function availableSlots(opts: {
  open: string; close: string; step: number; duration: number;
  breakStart?: string; breakEnd?: string;
  bookings: { time: string; duration_min: number; staff_id: number | null }[];
  staffIds: (number | null)[];   // [null] when the shop has no staff
}): Map<string, number | null> {
  const out = new Map<string, number | null>();
  const busyAll: Busy[] = [];
  if (opts.breakStart && opts.breakEnd)
    busyAll.push({ start: toMin(opts.breakStart), end: toMin(opts.breakEnd), staff_id: null });

  const bookingBusy: Busy[] = opts.bookings.map((b) => ({
    start: toMin(b.time), end: toMin(b.time) + b.duration_min, staff_id: b.staff_id,
  }));

  for (let t = toMin(opts.open); t + opts.duration <= toMin(opts.close); t += opts.step) {
    const end = t + opts.duration;
    if (busyAll.some((x) => overlaps(t, end, x))) continue;
    for (const sid of opts.staffIds) {
      const clash = bookingBusy.some(
        (x) => (sid === null || x.staff_id === sid || x.staff_id === null) && overlaps(t, end, x),
      );
      if (!clash) { out.set(toHHMM(t), sid); break; } // first free staff wins
    }
  }
  return out;
}

It returns "HH:MM" -> staff id, so the same call both lists free times for the calendar and picks who gets the booking.

A quick test with Node's built-in runner:

import { test } from "node:test";
import assert from "node:assert/strict";

test("a 60 min booking at 10:00 hides 10:00 and 10:30", () => {
  const slots = availableSlots({
    open: "09:00", close: "12:00", step: 30, duration: 30,
    bookings: [{ time: "10:00", duration_min: 60, staff_id: null }],
    staffIds: [null],
  });
  assert.deepEqual([...slots.keys()], ["09:00", "09:30", "11:00", "11:30"]);
});

4. The race

The naive flow is: load bookings → run availableSlots → insert. Two requests can both pass the check before either inserts. D1 gives you batch() (atomic, but you can't branch on a read inside it), so instead of preventing the race we make it detectable and self-healing:

  1. Check with the slot engine (fast path, rejects 99% of conflicts).
  2. Insert the booking and get its id back.
  3. Re-check: is there an older confirmed booking (smaller id) that overlaps mine?
  4. If yes, I lost the race. Cancel my own row and tell the customer.

AUTOINCREMENT ids are assigned in commit order on D1's single writer, so "smaller id" is a fair tie-breaker: the first insert always wins and exactly one of the two survives.

const booking = await db.prepare(
  `INSERT INTO bookings (shop_id, staff_id, date, time, duration_min)
   VALUES (?, ?, ?, ?, ?) RETURNING id`,
).bind(shopId, staffId, date, time, duration).first<{ id: number }>();

const start = toMin(time), end = start + duration;
const clash = await db.prepare(
  `SELECT id FROM bookings
    WHERE shop_id = ? AND date = ? AND status = 'confirmed' AND id < ?
      AND (? IS NULL OR staff_id IS NULL OR staff_id = ?)
      AND ? < (CAST(substr(time,1,2) AS INTEGER) * 60 + CAST(substr(time,4,2) AS INTEGER) + duration_min)
      AND (CAST(substr(time,1,2) AS INTEGER) * 60 + CAST(substr(time,4,2) AS INTEGER)) < ?
    LIMIT 1`,
).bind(shopId, date, booking!.id, staffId, staffId, start, end).first();

if (clash) {
  await db.prepare("UPDATE bookings SET status = 'cancelled' WHERE id = ?").bind(booking!.id).run();
  return error("Sorry, someone just took that time. Please choose another.");
}

The SQL is the same overlaps() rule, just written with SQLite string functions so it runs on the stored HH:MM.

Two details that matter:

  • Send emails only after the re-check. Otherwise the loser gets a confirmation for a booking that no longer exists.
  • Cancel, don't delete. The cancelled row is a free audit trail of how often the race actually happens.

5. Small extras that save support tickets

  • Per-phone limit. Count upcoming confirmed bookings for the same phone number and cap it (we use 3), so one person can't hold every slot.
  • "Same time" guard. Reject a second booking from the same phone at the same date and time before you even run the engine.
  • Blocks never cancel bookings. When the owner blocks an afternoon, keep existing bookings and warn the owner about overlaps instead of silently cancelling customers.

Wrap-up

On D1 you don't need locks to avoid double bookings. Make the availability logic pure, insert first, then let the database tell you who came first. The loser gets a friendly message and the calendar stays correct.

The code above is lifted from SlotDesk, a booking app we built on Cloudflare Workers + D1 + Hono. If you'd rather start from the full thing (staff calendars, reminders, Stripe subscriptions, reviews), the source kit is here: https://rasareka.gumroad.com/l/slotdesk?utm_source=devto&utm_campaign=m6 and there's a live demo at https://slotdesk-demo.rasareka.com

Questions about the pattern are welcome in the comments.

This article was drafted with AI assistance.

📰 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.