BT San Technology

12 February 2026

Online booking for service businesses: designing time slots, capacity and cancellations

29 min read · Websites and web apps

Illustration: a finger tapping a slot on a schedule grid on a tablet, beside a laptop showing time slots with green dots
AI-generated illustration

A calendar that shows green gaps makes people think they can book. But a system that works in practice has to answer several more questions. Is the 09:30 slot still free when the service takes 90 minutes and straddles the lunch break? How many minutes does the person still typing their name hold the spot? What happens if a customer taps confirm twice? If an appointment is moved to a slot that is already full, the original slot must not disappear. And does someone waiting in the queue get a freed seat before a person on the website?

This article builds these mechanisms one piece at a time in TypeScript that Node 24 runs directly, using in-memory SQLite, with nothing to install. All data is for a hypothetical clinic. There is code you can run yourself, real output, and a test suite. Two requests colliding at the same moment is a separate topic, covered in the article on double booking and contention in the database. Here we use only its last line of defense: the constraint in the database.

The real problem: a free slot is a computed result, not data typed into a table

A booking system that starts from one table with one row per appointment often never reaches the finish line. The question the customer asks is whether a slot is free, and that has to be computed from opening hours, breaks, holidays, the length of the service, equipment turnaround time between appointments, the number of chairs or rooms, and the appointments that already exist. If each of these rules is written in a different page, it will not be long before appointments overlap, or a slot that is really free is shown to nobody.

The three hypothetical situations below are not any customer's project. They show what the problem looks like.

  • A hypothetical dental clinic has two chairs. A general check-up takes 30 minutes and a cleaning takes 90 minutes. After someone books a cleaning at 10:00, a system that counts only the start time will still offer 10:30 to someone else on the same chair, because it does not see that the first appointment runs into the afternoon.
  • A hypothetical class studio takes 6 people per session. A customer opens the booking page, spends ten minutes filling in details and then taps pay. Meanwhile someone else takes the last seat. Without a temporary hold that has an expiry time, you get either a person who paid and has no seat, or a seat that stays held so that nobody can use it.
  • A hypothetical machine demo shop has a free cancellation policy up to 24 hours before. Two staff members interpret exactly 24 hours differently. One charges a fee and the other does not. The customer sees this and is unhappy either way. The problem has to end in one line of code that states the boundary clearly and is pinned down by a test.

What the documentation says, before designing

TopicWhat the documentation saysEffect on our code
CHECK and UNIQUEPostgreSQL says that CHECK constrains a column with a Boolean expression and may not reference other rows or tables. UNIQUE prevents duplicate values and creates a B-tree index. The documentation also describes exclusion constraints, which forbid two rows from overlapping under a specified operator.Use CHECK (used <= cap) as the last line of defense for capacity, and UNIQUE with a key to prevent duplicates. If you use PostgreSQL for work where each appointment takes one resource, an exclusion constraint is an alternative.
UPSERTSQLite says ON CONFLICT DO UPDATE applies only when a UNIQUE or PRIMARY KEY constraint conflicts. It does not handle CHECK, and if the DO UPDATE step violates a constraint, the whole INSERT statement is rolled back.If adding to the used counter would exceed capacity, CHECK rejects the whole statement. No half-written value is left behind.
TransactionSQLite says BEGIN IMMEDIATE starts a write transaction immediately and may fail with SQLITE_BUSY if another writer is active. ROLLBACK cancels all changes in the transaction.Every booking, cancellation and move runs in one transaction, and ROLLBACK is the mechanism for moving an appointment atomically.
Time zoneMDN says the timeZone option of Intl.DateTimeFormat accepts IANA names such as Asia/Bangkok.Use Intl to convert UTC time to Bangkok time, with no extra library.
TypeScript in NodeNode.js says type stripping does not support enum, namespaces that contain runtime code, or parameter properties. It requires import type for types, and the .ts extension must be written in import statements.The example code follows all of these limits.
node:sqliteThe current Node.js documentation lists node:sqlite as a release candidate since v25.7.0, and says DatabaseSync is the old name, now deprecated, with Database to be used instead.This example is written and run on Node 24, which uses the name DatabaseSync. If you upgrade Node, change the class name according to the documentation for your version.
Summary from the PostgreSQL, SQLite, MDN and Node.js documentation as read on 2026-11-21. For the real details, read the documentation for the version you use.

The example uses status names, a 24-hour rule, a 50% fee and a 10-minute hold time that we made up. They are not anyone's standard. A real business must have its owner set them. And if you collect deposits or issue refunds, also check the terms with your payment provider and with consumer protection law.

Layout of the example and how to run it

The example folder has no package.json, no external libraries and no network use. You need Node 24 or later. Run the following two commands in that folder.

README.md · lines 21–22
node --no-warnings demo.ts
node --no-warnings --test booking.test.ts
Commands to run the demo and the test suite
FileRole
data/clinic.jsonThe hypothetical business: opening hours, breaks, holidays, chairs, rooms and three services
data/bad-config.jsonA deliberately broken config file, used to test that the system rejects it before bookings open
time.tsConverts between Bangkok local time and UTC
config.tsReads and validates the config file, reporting all problems at once
slots.tsBuilds the time slots that can be offered
policy.tsCancellation policy and fees
db.tsTables, capacity counters and transactions
core.tshold, expiry, passing seats on to the waitlist
booking.tsconfirm, cancel, no-show, reschedule, join the waitlist
demo.tsRuns six sections with the current time pinned, then prints the results
booking.test.tsA node:test suite with eight tests
output.txtThe real output of the demo
Files in the folder examples/service-booking-capacity-cancellation-web

Places where we deliberately simplified have a comment that begins with simplified: stating the limit and the upgrade path right in the code.

Step 1: store time as UTC, display and reckon days in Bangkok time

The rule that avoids the most time bugs is that stored values are UTC, while the meaning of a day, such as what time it opens on Wednesday or whether it is a holiday, follows the branch's local time. The example stores epoch milliseconds and converts back using Intl.DateTimeFormat with timeZone set to Asia/Bangkok. Thailand has no DST, but the conversion code runs two passes so that it also works for zones that do.

time.ts · lines 24–30
export function localToUtc(date: string, hhmm: string): number {
  const [y, m, d] = date.split("-").map(Number);
  const [h, mi] = hhmm.split(":").map(Number);
  const guess = Date.UTC(y, m - 1, d, h, mi);
  const first = guess - offsetMin(guess) * MIN; // เดาด้วย offset ของเวลาที่เดา
  return guess - offsetMin(first) * MIN; // แล้วแก้ด้วย offset ของเวลาจริง (กันกรณีโซนที่มี DST)
}
time.ts converts a date and local time to UTC

You can read more about Buddhist Era dates and calendars in web apps in the article on dates, calendars and time zones. In this part we only pin down one rule: the database holds no local time.

Step 2: build slots from opening hours, breaks and duration

The system does not store free slots as rows. It builds them at query time from the config file. The number of slots a service takes is (service time + equipment turnaround time), rounded up to 15-minute units. Check that the extra ten minutes is counted: for example, a 30-minute general check-up plus 10 minutes of preparation is 40 minutes, which takes three slots.

slots.ts · lines 4–23
// บริการหนึ่งครั้งกินกี่ช่อง: (เวลาทำ + เวลาพักเครื่องมือ) ปัดขึ้นเป็นหน่วย unitMin
export const unitsFor = (cfg: Config, s: Service) => Math.ceil((s.durationMin + s.bufferMin) / cfg.unitMin);

// ช่วงเปิดของวันที่ (UTC ms) หักเวลาพักแล้ว วันหยุดหรือวันที่ไม่มีเวลาเปิดได้ []
export function windows(cfg: Config, date: string): [number, number][] {
  const h = cfg.hours[String(weekday(date))];
  if (!h || cfg.holidays.includes(date)) return [];
  let ws: [number, number][] = [[localToUtc(date, h.open), localToUtc(date, h.close)]];
  for (const b of cfg.breaks) {
    const [bf, bt] = [localToUtc(date, b.from), localToUtc(date, b.to)];
    ws = ws.flatMap(([s, e]): [number, number][] => {
      if (bt <= s || bf >= e) return [[s, e]];
      const out: [number, number][] = [];
      if (bf > s) out.push([s, bf]);
      if (bt < e) out.push([bt, e]);
      return out;
    });
  }
  return ws;
}
slots.ts: the number of slots a service takes, and the open windows after removing break time

The windows function cuts the breaks out of the opening hours. Holidays and days with no opening hours give an empty list. Then startsFor steps through in 30-minute increments and offers only start times where the whole span the service occupies lies inside a single open window. So no appointment straddles the lunch break, and none runs past closing time.

slots.ts · lines 25–37
// เวลาเริ่มที่เสนอได้: ทั้งช่วงที่บริการกินต้องอยู่ในช่วงเปิดช่วงเดียว (ไม่คร่อมพัก ไม่เลยเวลาปิด)
// simplified: ถือว่าช่วงเปิดเริ่มตรงกริด stepMin ถ้าไม่ตรง ต้องจัดกริดจากต้นช่วงเอง
export function startsFor(cfg: Config, s: Service, date: string): number[] {
  const need = unitsFor(cfg, s) * cfg.unitMin * MIN;
  const out: number[] = [];
  for (const [ws, we] of windows(cfg, date)) {
    for (let t = ws; t + need <= we; t += cfg.stepMin * MIN) out.push(t);
  }
  return out;
}

export const isBookableStart = (cfg: Config, s: Service, utc: number) =>
  startsFor(cfg, s, localDate(utc)).includes(utc);
slots.ts: the start times that can be offered, and the check that a requested time is a real slot

The check that the time a customer sends is a real slot must always be done on the server. Do not assume the web page offers only valid slots, because a request can be edited.

Step 3: capacity per slot and per resource

Instead of counting overlapping appointments every time, the example keeps a used counter per resource and per 15-minute slot. The table has a CHECK that used must not exceed cap. A long service therefore reduces the capacity of every slot it occupies, and to ask how much is free, you take the smallest value among those slots. A chair has capacity 1 and a classroom has capacity 6, using the same structure.

db.ts · lines 9–29
const SCHEMA = `
CREATE TABLE resources (id TEXT PRIMARY KEY, capacity INTEGER NOT NULL CHECK (capacity >= 1));
CREATE TABLE load (
  resource_id TEXT NOT NULL REFERENCES resources(id), unit_start INTEGER NOT NULL,
  used INTEGER NOT NULL, cap INTEGER NOT NULL,
  PRIMARY KEY (resource_id, unit_start), CHECK (used >= 0 AND used <= cap)
);
CREATE TABLE bookings (
  id INTEGER PRIMARY KEY, idem_key TEXT NOT NULL UNIQUE, service TEXT NOT NULL,
  resource_id TEXT NOT NULL, start_utc INTEGER NOT NULL, units INTEGER NOT NULL, qty INTEGER NOT NULL,
  customer TEXT NOT NULL, status TEXT NOT NULL CHECK (status IN ('held','confirmed','cancelled','no_show','expired')),
  hold_expires INTEGER, price INTEGER NOT NULL, fee INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE waitlist (
  id INTEGER PRIMARY KEY, customer TEXT NOT NULL, service TEXT NOT NULL, resource TEXT NOT NULL,
  start_utc INTEGER NOT NULL, qty INTEGER NOT NULL, booking_id INTEGER,
  status TEXT NOT NULL CHECK (status IN ('waiting','offered','accepted','expired','declined','lapsed')),
  UNIQUE (customer, service, start_utc)
);
CREATE TABLE outbox (booking_id INTEGER NOT NULL, kind TEXT NOT NULL, UNIQUE (booking_id, kind));
`;
db.ts: all the tables. The CHECK in load is the last line of defense that forbids exceeding capacity
db.ts · lines 57–73
export function remaining(e: Engine, resource: string, start: number, units: number): number {
  const cap = (e.db.prepare("SELECT capacity FROM resources WHERE id = ?").get(resource) as { capacity: number }).capacity;
  const q = e.db.prepare("SELECT used FROM load WHERE resource_id = ? AND unit_start = ?");
  return Math.min(...unitStarts(e, start, units).map((u) => cap - ((q.get(resource, u) as { used: number } | undefined)?.used ?? 0)));
}

export function acquire(e: Engine, resource: string, start: number, units: number, qty: number): void {
  const q = e.db.prepare(`INSERT INTO load (resource_id, unit_start, used, cap)
    VALUES (?, ?, ?, (SELECT capacity FROM resources WHERE id = ?))
    ON CONFLICT (resource_id, unit_start) DO UPDATE SET used = used + excluded.used`);
  for (const u of unitStarts(e, start, units)) q.run(resource, u, qty, resource);
}

export function release(e: Engine, resource: string, start: number, units: number, qty: number): void {
  const q = e.db.prepare("UPDATE load SET used = used - ? WHERE resource_id = ? AND unit_start = ?");
  for (const u of unitStarts(e, start, units)) q.run(qty, resource, u);
}
db.ts: read free space from the fullest slot, book with an UPSERT, and give the space back

If two requests arrive at the same time, logic that checks for free space first and writes afterward can lose the race. In this example every change runs inside BEGIN IMMEDIATE, and if anything slips through, CHECK rejects it. Locking and isolation levels are covered in the article on double booking and are not repeated here.

Step 4: a ten-minute hold and expiry

The customer needs time to fill in details and pay, so the system holds the space first with the status held and an expiry time. If the same request is sent again with the same key, the system returns the original booking and does not hold more space. Expiry is computed as now >= hold_expires, so exactly ten minutes counts as expired. And every function that changes data sweeps expired holds first, so it does not depend on a timer that might stop running.

core.ts · lines 28–44
export function holdInner(e: Engine, r: Req, now: number, ttlMin: number): Res {
  const old = e.db.prepare("SELECT * FROM bookings WHERE idem_key = ?").get(r.key) as Booking | undefined;
  if (old) return { ok: true, replay: true, booking: old }; // กดซ้ำ/ลองใหม่ด้วยคีย์เดิม ได้ใบเดิม
  const svc = e.cfg.services.find((s) => s.id === r.service);
  if (!svc) return { ok: false, reason: "unknown_service" };
  if (!Number.isInteger(r.qty) || r.qty < 1) return { ok: false, reason: "bad_qty" };
  if (r.start < now + e.cfg.leadMin * MIN) return { ok: false, reason: "too_soon" };
  if (!isBookableStart(e.cfg, svc, r.start)) return { ok: false, reason: "not_a_slot" };
  const res = findResource(e, r.service, r.resource, r.start, r.qty);
  if (!res) return { ok: false, reason: "full" };
  const units = unitsFor(e.cfg, svc);
  acquire(e, res, r.start, units, r.qty);
  const info = e.db.prepare(`INSERT INTO bookings (idem_key, service, resource_id, start_utc, units, qty, customer, status, hold_expires, price)
    VALUES (?, ?, ?, ?, ?, ?, ?, 'held', ?, ?)`)
    .run(r.key, r.service, res, r.start, units, r.qty, r.customer, now + ttlMin * MIN, svc.price * r.qty);
  return { ok: true, booking: getBooking(e, Number(info.lastInsertRowid)) };
}
core.ts: holdInner checks the rules one by one, holds the space, then records the held booking
core.ts · lines 47–56
export function sweepInner(e: Engine, now: number): number {
  const rows = e.db.prepare("SELECT * FROM bookings WHERE status = 'held' AND hold_expires <= ?").all(now) as Booking[];
  for (const b of rows) {
    release(e, b.resource_id, b.start_utc, b.units, b.qty);
    e.db.prepare("UPDATE bookings SET status = 'expired' WHERE id = ?").run(b.id);
    e.db.prepare("UPDATE waitlist SET status = 'expired' WHERE booking_id = ? AND status = 'offered'").run(b.id);
  }
  if (rows.length) promote(e, now);
  return rows.length;
}
core.ts: sweepInner gives back the space of expired holds

The order of the rules in holdInner matters. A duplicate key is answered first. Then it checks the service, the quantity, a time that is too close, and whether it is a real slot. Only at the end does it look for a resource. So the reason for a rejection matches what is actually wrong, and is not full in every case.

Step 5: idempotent confirmation

A customer taps confirm twice, a browser retries, or the payment system calls back twice. All of these can happen. So confirm decides from the status. If the booking is already confirmed, it responds with success and says it is a replay, and does not do the work again. The confirmation message to send is recorded in an outbox table with UNIQUE (booking_id, kind), so there is exactly one row per booking, however many times it is tapped.

booking.ts · lines 31–44
// ยืนยันซ้ำได้ผลเดิม: ใบที่ confirmed แล้วตอบ replay และ outbox มีแถวเดียวต่อใบ (UNIQUE)
export function confirm(e: Engine, id: number, now: number): Res {
  sweep(e, now);
  return tx(e, () => {
    const b = getBooking(e, id);
    if (!b) return notFound;
    if (b.status === "confirmed") return { ok: true, replay: true, booking: b };
    if (b.status !== "held") return { ok: false, reason: b.status };
    e.db.prepare("UPDATE bookings SET status = 'confirmed', hold_expires = NULL WHERE id = ?").run(id);
    e.db.prepare("INSERT OR IGNORE INTO outbox (booking_id, kind) VALUES (?, 'confirmation')").run(id);
    e.db.prepare("UPDATE waitlist SET status = 'accepted' WHERE booking_id = ?").run(id);
    return { ok: true, booking: getBooking(e, id) };
  });
}
booking.ts: confirm decides from the status and uses INSERT OR IGNORE with the outbox

Step 6: a cancellation policy with clear boundaries

The example uses a three-tier rule. With 24 hours or more remaining, cancellation is free. With less than that but before the appointment time, the fee is half of the price. Once the appointment time has arrived, cancellation is not possible, and it becomes a no-show charged at the full price. The point to write down clearly is that exactly 24 hours counts as free. The comparison is in milliseconds with the >= operator, with no rounding.

policy.ts
// นโยบายยกเลิก: ขอบเขตชัดเจน เทียบเป็นมิลลิวินาทีของเวลา UTC ไม่ปัดเศษ
export const FREE_HOURS = 24; // ยกเลิกได้ฟรีถ้าเหลือเวลา "อย่างน้อย" 24 ชั่วโมงเต็ม
export const LATE_PCT = 50; // ต่ำกว่านั้นแต่ยังไม่ถึงเวลานัด ปรับ 50% ของราคา
const HOUR = 3_600_000;

export type Tier = "free" | "late" | "started";

export function cancelPolicy(startUtc: number, nowUtc: number, price: number): { tier: Tier; fee: number } {
  const left = startUtc - nowUtc;
  if (left >= FREE_HOURS * HOUR) return { tier: "free", fee: 0 }; // เท่ากับ 24 ชม. พอดี = ฟรี
  if (left > 0) return { tier: "late", fee: Math.round((price * LATE_PCT) / 100) };
  return { tier: "started", fee: price }; // ถึงเวลานัดแล้ว ยกเลิกไม่ได้ เข้าทางไม่มาตามนัด
}
policy.ts: the single function that is the truth about fees
booking.ts · lines 46–61
export function cancel(e: Engine, id: number, now: number): Res {
  sweep(e, now);
  return tx(e, () => {
    const b = getBooking(e, id);
    if (!b) return notFound;
    if (b.status === "cancelled") return { ok: true, replay: true, tier: "replay", fee: b.fee, booking: b };
    if (b.status !== "held" && b.status !== "confirmed") return { ok: false, reason: b.status };
    const p = b.status === "held" ? { tier: "hold", fee: 0 } : cancelPolicy(b.start_utc, now, b.price);
    if (p.tier === "started") return { ok: false, reason: "started" };
    release(e, b.resource_id, b.start_utc, b.units, b.qty);
    e.db.prepare("UPDATE bookings SET status = 'cancelled', fee = ?, hold_expires = NULL WHERE id = ?").run(p.fee, id);
    e.db.prepare("UPDATE waitlist SET status = 'declined' WHERE booking_id = ? AND status = 'offered'").run(id);
    promote(e, now);
    return { ok: true, tier: p.tier, fee: p.fee, booking: getBooking(e, id) };
  });
}
booking.ts: cancel gives back the space, records the fee, then offers the free space to the waitlist

Cancelling a hold that is not yet confirmed carries no fee, because the customer has not yet agreed. Cancelling the same booking again gives the same result.

Step 7: atomic rescheduling

Moving an appointment means giving back the old space and booking the new one. If you do it as two separate statements and the new slot is full, the customer ends up with no place at all. The example does both in one transaction. If the new slot is full, it returns ok as false and lets ROLLBACK undo the release of the old space as well. A nice side effect is that you can move to a slot that overlaps your own previous span, because the old space is released before the check. The business rule in the example is that you can move only while free cancellation still applies.

booking.ts · lines 75–95
// ย้ายนัดแบบอะตอมมิก: คืนช่องเก่า หาช่องใหม่ จองช่องใหม่ ใน transaction เดียว
// ถ้าช่องใหม่เต็ม ตัวเลือก ok=false ทำให้ ROLLBACK ช่องเก่ากลับมาเหมือนไม่เคยถูกแตะ
export function reschedule(e: Engine, id: number, newStart: number, now: number): Res {
  sweep(e, now);
  return tx(e, () => {
    const b = getBooking(e, id);
    if (!b) return notFound;
    if (b.status !== "confirmed") return { ok: false, reason: b.status };
    if (cancelPolicy(b.start_utc, now, b.price).tier !== "free") return { ok: false, reason: "too_late" };
    const svc = e.cfg.services.find((s) => s.id === b.service)!;
    if (newStart < now + e.cfg.leadMin * MIN) return { ok: false, reason: "too_soon" };
    if (!isBookableStart(e.cfg, svc, newStart)) return { ok: false, reason: "not_a_slot" };
    release(e, b.resource_id, b.start_utc, b.units, b.qty);
    const res = findResource(e, b.service, "auto", newStart, b.qty);
    if (!res) return { ok: false, reason: "full" };
    acquire(e, res, newStart, b.units, b.qty);
    e.db.prepare("UPDATE bookings SET resource_id = ?, start_utc = ? WHERE id = ?").run(res, newStart, id);
    promote(e, now); // ช่องเก่าที่ว่างลง เสนอให้คิวรอ
    return { ok: true, booking: getBooking(e, id) };
  });
}
booking.ts: reschedule does everything in one transaction

Step 8: a waitlist with its own response window

A person can join the waitlist only for a slot that is really full. If it is still free, they must book directly. When space frees up, whether from a cancellation, an expired hold or a booking moved away, the system calls people in the queue in order, in the same transaction that gives the space back, so no customer on the website can cut in. The offer is a hold with its own 30-minute expiry. If the person does not respond, the offer expires and the space goes to the next person.

core.ts · lines 58–68
// เรียงตามลำดับเข้าคิว (id น้อยก่อน) ใครที่นั่งว่างพอก็ได้ข้อเสนอ ซึ่งเป็น hold ที่มีเวลาหมดอายุของตัวเอง
// ทำใน transaction เดียวกับที่คืนที่ จึงไม่มีลูกค้าหน้าเว็บแทรกก่อนคนในคิว
export function promote(e: Engine, now: number): void {
  const q = e.db.prepare("SELECT * FROM waitlist WHERE status = 'waiting' ORDER BY id").all() as
    { id: number; customer: string; service: string; resource: string; start_utc: number; qty: number }[];
  for (const w of q) {
    if (w.start_utc <= now) { e.db.prepare("UPDATE waitlist SET status = 'lapsed' WHERE id = ?").run(w.id); continue; }
    const r = holdInner(e, { key: `wl-${w.id}`, service: w.service, resource: w.resource, start: w.start_utc, qty: w.qty, customer: w.customer }, now, OFFER_MIN);
    if (r.ok) e.db.prepare("UPDATE waitlist SET status = 'offered', booking_id = ? WHERE id = ?").run(r.booking!.id, w.id);
  }
}
core.ts: promote offers the free space to whoever waited first
booking.ts · lines 97–110
// เข้าคิวรอได้เฉพาะช่องที่เต็มจริง ถ้ายังว่างให้จองตรง ๆ
export function joinWaitlist(e: Engine, r: Omit<Req, "key">, now: number): Res {
  sweep(e, now);
  return tx(e, () => {
    const svc = e.cfg.services.find((s) => s.id === r.service);
    if (!svc || !isBookableStart(e.cfg, svc, r.start) || r.start < now + e.cfg.leadMin * MIN) return { ok: false, reason: "not_a_slot" };
    const dup = e.db.prepare("SELECT id FROM waitlist WHERE customer = ? AND service = ? AND start_utc = ?").get(r.customer, r.service, r.start) as { id: number } | undefined;
    if (dup) return { ok: true, replay: true, id: dup.id };
    if (findResource(e, r.service, r.resource, r.start, r.qty)) return { ok: false, reason: "not_full" };
    const info = e.db.prepare("INSERT INTO waitlist (customer, service, resource, start_utc, qty, status) VALUES (?, ?, ?, ?, ?, 'waiting')")
      .run(r.customer, r.service, r.resource, r.start, r.qty);
    return { ok: true, id: Number(info.lastInsertRowid) };
  });
}
booking.ts: joinWaitlist accepts only full slots and prevents joining twice

Run the demo and read the results

demo.ts pins the current time to 2026-12-01 at 10:00 Bangkok time, so the results are the same every time. In the example for section 4, cancellation is called with times computed backward from the appointment time.

demo.ts · lines 66–73
e = makeEngine(cfg);
const mk = (key: string, hm: string) => { const b = hold(e, req(key, "checkup", S("2026-12-02", hm), key), NOW).booking!; confirm(e, b.id, NOW); return b; };
const [p, q, r] = [mk("p", "09:00"), mk("q", "09:30"), mk("r", "10:00")];
show("ยกเลิกเหลือ 24:00:00 พอดี", cancel(e, p.id, p.start_utc - 24 * 60 * MIN));
show("ยกเลิกเหลือ 23:59:59.999", cancel(e, q.id, q.start_utc - 24 * 60 * MIN + 1));
show("ยกเลิกตอนถึงเวลานัด", cancel(e, r.id, r.start_utc));
show("บันทึกไม่มาตามนัด", markNoShow(e, r.id, r.start_utc));
show("ยกเลิกใบเดิมซ้ำ", cancel(e, p.id, p.start_utc - 24 * 60 * MIN));
demo.ts, section 4: tests the boundaries of the cancellation policy
output.txt
now = 2026-12-01 10:00 (2026-12-01T03:00:00.000Z)

== 1. สร้างช่วงเวลาจากเวลาเปิด พัก วันหยุด ระยะเวลาและเวลาพักเครื่องมือ ==
checkup 30+10 นาที = 3 ช่อง x 15 นาที | พุธ 12-02: 09:00 09:30 10:00 10:30 11:00 13:00 13:30 14:00 14:30 15:00 15:30 16:00
whitening 90+15 นาที = 7 ช่อง x 15 นาที | พุธ 12-02: 09:00 09:30 10:00 13:00 13:30 14:00 14:30 15:00
class 60+0 นาที = 4 ช่อง x 15 นาที | พุธ 12-02: 09:00 09:30 10:00 10:30 11:00 13:00 13:30 14:00 14:30 15:00 15:30 16:00
เสาร์ 12-05 checkup: 09:00 09:30 10:00 10:30 11:00
อาทิตย์ 12-06: 0 ช่วง | วันหยุด 12-10: 0 ช่วง
เก็บในฐานข้อมูลเป็น UTC: 2026-12-02T02:00:00.000Z แสดงเป็น 2026-12-02 09:00 Asia/Bangkok
ไฟล์ตั้งค่าเสีย: hours[1] เปิด/ปิดไม่ถูกต้อง; พักไม่ถูกต้อง 12:00-12:00; วันหยุดไม่ถูกต้อง "2026-02-30"; วันหยุดไม่ถูกต้อง "10/12/2026"; ทรัพยากร chair-1 ความจุต้อง >= 1; บริการ checkup ระยะเวลาต้อง > 0; บริการ checkup อ้างทรัพยากรที่ไม่มี chair-9

== 2. ความจุต่อช่องและต่อทรัพยากร ==
checkup พุธ 09:00 (ก): ok
checkup พุธ 09:00 (ข): ok
checkup พุธ 09:00 (ค): ปฏิเสธ(full)
whitening พุธ 10:00 (ง) กิน 7 ช่อง: ok
checkup พุธ 10:30 (จ): ok
checkup พุธ 11:00 (ฉ): ปฏิเสธ(full)
ที่ว่าง checkup พุธ ช่วงเช้า: 09:00=0 09:30=0 10:00=0 10:30=0 11:00=0 13:00=2 13:30=2
class พุธ 13:00 x4: ok
class พุธ 13:00 x2: ok
class พุธ 13:00 x1: ปฏิเสธ(full)
ขอเวลา 12:30 (ในช่วงพัก): ปฏิเสธ(not_a_slot)
ขอ 09:10 (ไม่ตรงกริด): ปฏิเสธ(not_a_slot)
ขออาทิตย์ 12-06: ปฏิเสธ(not_a_slot)
ขอวันหยุด 12-10: ปฏิเสธ(not_a_slot)
ขอใน 30 นาทีข้างหน้า: ปฏิเสธ(too_soon)

== 3. hold หมดอายุ และคำขอซ้ำ ==
hold #1 หมดอายุ 2026-12-01 10:10
ส่งคำขอ hold คีย์เดิมซ้ำ: ok [replay]
ผ่านไป 9 นาที 59 วินาที: คืนที่ 0 ใบ | ผ่านไป 10 นาที: คืนที่ 1 ใบ
confirm หลังหมดอายุ: ปฏิเสธ(expired)
confirm ครั้งที่ 1: ok
confirm ครั้งที่ 2 (กดซ้ำ): ok [replay]
ข้อความยืนยันที่ถูกจัดคิว: 1 ข้อความ

== 4. นโยบายยกเลิก (ฟรีถ้าเหลือ >= 24 ชม. ปรับ 50% ถ้าน้อยกว่า ไม่มาตามนัดคิดเต็ม) ==
ยกเลิกเหลือ 24:00:00 พอดี: ok tier=free fee=0
ยกเลิกเหลือ 23:59:59.999: ok tier=late fee=400
ยกเลิกตอนถึงเวลานัด: ปฏิเสธ(started)
บันทึกไม่มาตามนัด: ok fee=800
ยกเลิกใบเดิมซ้ำ: ok [replay] tier=replay fee=0

== 5. ย้ายนัดแบบอะตอมมิก ==
ก่อนย้าย พุธ 10:00 ว่าง: 10:00=1
ย้ายไปพฤหัส 09:00 (เต็ม): ปฏิเสธ(full)
หลังย้ายไม่สำเร็จ: นัดยังอยู่ 2026-12-02 10:00 | พุธ 10:00 ว่าง: 10:00=1
ย้ายไปพฤหัส 10:00 (ว่าง): ok
หลังย้ายสำเร็จ: พุธ 10:00 ว่าง: 10:00=2 | พฤหัส 10:00 ว่าง: 10:00=1
ย้ายนัดพฤหัส 10:00 ตอนเหลือ 23 ชม.: ปฏิเสธ(too_late)

== 6. คิวรอ: ที่นั่งที่ว่างถูกเสนอให้คนถัดไป ==
เข้าคิวช่องที่ยังว่าง (11:00): ปฏิเสธ(not_full)
เข้าคิว: แคท #1 แดน #2
แคท=waiting แดน=waiting
w1 ยกเลิก (ฟรี): ok tier=free fee=0
หลัง w1 ยกเลิก: แคท=offered แดน=waiting | ข้อเสนอของแคทหมดเวลา 2026-12-01 10:30
ผ่าน 29 นาที: แคท=offered แดน=waiting
ผ่าน 30 นาที: แคท=expired แดน=offered
แดนกดยืนยันที่ 35 นาที: ok
สุดท้าย: แคท=expired แดน=accepted
Output from a real run on 2026-11-21 with node --no-warnings demo.ts (Node 24), the whole file
  1. Section 1: a general check-up takes 3 slots and a cleaning takes 7 slots. A cleaning is offered at 09:00 to 10:00 and 13:00 to 15:00. There is no 10:30, because it would straddle the lunch break. Saturday has five slots, and Sunday and holidays have none. And 09:00 Bangkok time is stored as 02:00 UTC.
  2. The broken config file is rejected with every problem listed in a single message, including the date 2026-02-30, which does not exist, and a resource that is referenced but missing.
  3. Section 2: a general check-up at 09:00 can be booked twice because there are two chairs. The third is full. A cleaning at 10:00 takes one chair for all 7 slots, so 11:00 is full. The class accepts 4 and then 2 people. The 7th person gets full.
  4. Invalid requests are rejected with different reasons. 12:30, 09:10, a Sunday and a holiday are not_a_slot, and a slot 30 minutes away is too_soon.
  5. Section 3: at 9 minutes 59 seconds, no hold is released. At exactly 10 minutes, one is released. Confirming after expiry gives expired. Confirming twice gives replay, and there is one confirmation message.
  6. Section 4: exactly 24:00:00 remaining is free. One millisecond short is late, with a fee of 400 baht. Once the appointment time has arrived, cancellation is not possible, and recording a no-show charges the full price of 800 baht.
  7. Section 5: moving to a full slot is rejected and the original slot stays as free as before. Moving to a free slot succeeds and the free-space figures for both days change accordingly. Moving with 23 hours remaining is rejected.
  8. Section 6: the waitlist. Kat is ahead of Dan. When someone cancels, Kat gets the offer. At 29 minutes nothing has changed. At 30 minutes Kat's offer expires, Dan gets the offer, and Dan confirms in time.

The test suite: the fragile points are pinned down

booking.test.ts has eight tests and uses only node:test. Each test creates a fresh in-memory database and does not depend on the others. The important one is capacity. It books repeatedly across both services, checks that no row has used above cap, and also proves that writing beyond capacity directly through the database is rejected by CHECK.

booking.test.ts · lines 32–44
test("ความจุไม่เกินไม่ว่าจะลองจองกี่ครั้ง และบริการยาวกินหลายช่อง", () => {
  const e = makeEngine(cfg);
  const starts = startsFor(cfg, cfg.services[0], "2026-12-02");
  let n = 0;
  for (let round = 0; round < 4; round++) for (const s of starts) hold(e, req(`h${n++}`, round % 2 ? "whitening" : "checkup", s), NOW);
  const rows = e.db.prepare("SELECT used, cap FROM load").all() as { used: number; cap: number }[];
  assert.ok(rows.length > 0 && rows.every((r) => r.used >= 0 && r.used <= r.cap));
  assert.throws(() => acquire(e, "chair-1", starts[0], 1, 2), /CHECK/); // ด่านฐานข้อมูล
  const e2 = makeEngine(cfg);
  assert.equal(hold(e2, req("w", "whitening", S("2026-12-02", "10:00")), NOW).booking!.units, 7);
  assert.equal(hold(e2, req("c1", "checkup", S("2026-12-02", "11:00")), NOW).ok, true); // เก้าอี้อีกตัว
  assert.equal(hold(e2, req("c2", "checkup", S("2026-12-02", "11:00")), NOW).reason, "full");
});
booking.test.ts: capacity is never exceeded, and a long service takes several slots

The next test covers the cancellation fee boundaries: exactly 24 hours, one millisecond short, and at the appointment time. If someone changes >= to >, this test fails immediately.

booking.test.ts · lines 64–70
test("ขอบเขตค่ายกเลิก: เหลือ 24 ชม. พอดีฟรี ขาดไป 1 ms ปรับ 50% ถึงเวลานัดคือไม่มา", () => {
  const start = S("2026-12-02", "09:00"), H24 = 24 * 60 * MIN;
  assert.deepEqual(cancelPolicy(start, start - H24, 800), { tier: "free", fee: 0 });
  assert.deepEqual(cancelPolicy(start, start - H24 + 1, 800), { tier: "late", fee: 400 });
  assert.deepEqual(cancelPolicy(start, start - 1, 800), { tier: "late", fee: 400 });
  assert.deepEqual(cancelPolicy(start, start, 800), { tier: "started", fee: 800 });
});
booking.test.ts: the 24-hour boundary in milliseconds
booking.test.ts · lines 72–81
test("ย้ายนัด: ปลายทางเต็มต้องไม่เสียช่องเดิม ย้ายทับช่องตัวเองได้ และเลย 24 ชม. แล้วย้ายไม่ได้", () => {
  const e = makeEngine(cfg);
  const x = hold(e, req("x", "checkup", S("2026-12-02", "10:00")), NOW).booking!; confirm(e, x.id, NOW);
  for (const k of ["f1", "f2"]) confirm(e, hold(e, req(k, "checkup", S("2026-12-03", "09:00")), NOW).booking!.id, NOW);
  const before = loads(e);
  assert.equal(reschedule(e, x.id, S("2026-12-03", "09:00"), NOW).reason, "full");
  assert.equal(loads(e), before); // ฐานข้อมูลเหมือนเดิมทุกแถว
  assert.equal(reschedule(e, x.id, S("2026-12-02", "10:30"), NOW).ok, true); // ซ้อนกับช่วงเดิมของตัวเอง
  assert.equal(reschedule(e, x.id, S("2026-12-03", "10:00"), S("2026-12-02", "10:30") - 23 * 60 * MIN).reason, "too_late");
});
booking.test.ts: a reschedule to a full destination must not change even one row in the database
booking.test.ts · lines 83–97
test("คิวรอ: เสนอคนแรก ที่ถูกเสนอไว้คนอื่นแทรกไม่ได้ หมดเวลาแล้วไปคนถัดไป", () => {
  const e = makeEngine(cfg);
  const slot = S("2026-12-04", "09:00");
  const [a] = ["a", "b"].map((k) => { const b = hold(e, req(k, "checkup", slot), NOW).booking!; confirm(e, b.id, NOW); return b; });
  const c = joinWaitlist(e, req("c", "checkup", slot), NOW), d = joinWaitlist(e, req("d", "checkup", slot), NOW);
  assert.equal(joinWaitlist(e, req("z", "checkup", S("2026-12-04", "11:00")), NOW).reason, "not_full");
  cancel(e, a.id, NOW);
  assert.equal(waitlistStatus(e, c.id!).status, "offered");
  assert.equal(hold(e, req("walkin", "checkup", slot), NOW + MIN).reason, "full");
  sweep(e, NOW + 30 * MIN);
  assert.equal(waitlistStatus(e, c.id!).status, "expired");
  assert.equal(waitlistStatus(e, d.id!).status, "offered");
  assert.equal(confirm(e, waitlistStatus(e, d.id!).booking_id!, NOW + 31 * MIN).ok, true);
  assert.equal(waitlistStatus(e, d.id!).status, "accepted");
});
booking.test.ts: the waitlist. A person who has been offered a seat is not cut in front of, and when the offer times out it goes to the next person

Hold expiry at 9 minutes 59 seconds versus 10 minutes, and repeated confirmation producing only one message, have their own tests in the same file.

What to add for real use

  • A database shared by several machines, such as PostgreSQL. The same UNIQUE and CHECK constraints keep working, and you add row locking on the counter at booking time. See the article on double booking for details.
  • A background hold sweeper that runs periodically, in addition to sweeping when a request arrives, so the waitlist gets offers on time even when nobody visits the website.
  • Real notifications from the outbox table by email, LINE or SMS, with retries and a log of what has been sent.
  • Collecting deposits or fees through a payment provider, where the webhook must be idempotent on the same principle.
  • Opening hours that do not fit the grid, resource-specific holidays, staff on sick leave, and retroactive schedule edits that must not make existing appointments disappear.
  • User permissions, customers' personal data, and an audit log of who changed an appointment and when.

Adapting it to other businesses

  • Repair shop or car service center: the resource is the service bay. Durations vary a lot and there is waiting time for parts. Separate the appointment status from the repair job status, and set an equipment turnaround time longer than at a clinic.
  • Beauty salon or spa: the resource is a stylist or a room, and the customer can choose the stylist. Use the resource slot the customer specifies instead of auto, and you may need to book several services back to back in one go.
  • Workshop or course: capacity is a number of people. The waitlist matters a great deal because people cancel often. Shorten the offer time as the class date approaches.

Common mistakes

  • Storing local time in the database mixed with UTC, then computing the wrong day when the server or zone changes.
  • Counting capacity only at the start time and not reducing every slot the service occupies, so long services overlap.
  • Forgetting equipment turnaround or tidy-up time between appointments, so the technician has no time to prepare.
  • Not checking the requested time on the server, and accepting a time that is not a real slot.
  • A hold with no expiry, or relying only on a timer, so that when it stops the space stays held forever.
  • Confirming twice and sending the message or charging the money twice.
  • Moving an appointment by cancelling and then booking again as two steps, so the customer loses the slot if the new one is full.
  • Writing the 24-hour rule only as text, with no boundary test, so people interpret it differently.
  • A waitlist that releases free space to the website first, so people who have waited longest never get a seat.

Checklist before opening a booking system

  1. Write the services, durations, equipment turnaround times and usable resources into a config file, and have the system validate the file before it starts.
  2. Confirm with the business owner that the holidays, breaks and opening hours for each day are correct.
  3. Have the business owner sign off on the cancellation policy as numbers, including the exactly-24-hours case and the no-show case.
  4. Set the hold time and the waitlist offer time according to real customer behavior.
  5. Check that CHECK and UNIQUE exist in the real database, not just in the code.
  6. Test simultaneous bookings from several machines, and test repeated confirmation.
  7. Test a reschedule whose destination is full, and check that the original slot does not disappear.
  8. Set up notifications and check the outbox table for leftover messages.
  9. Rehearse a server crash during a hold, and check that the system sweeps and gives the space back by itself after it comes back.

Cautions about the example: it uses in-memory SQLite in a single process. It has no users or permissions, no real notifications, no real money, no opening hours that do not fit the grid, no support for staff as resources, and it has not been tested with concurrent requests from several processes. Use it as a learning model, not as a production system.

References

  1. PostgreSQL — Constraints (CHECK, UNIQUE, exclusion) (accessed 2026-11-21)
  2. SQLite — UPSERT (ON CONFLICT DO UPDATE) (accessed 2026-11-21)
  3. SQLite — Transactions (BEGIN IMMEDIATE, ROLLBACK) (accessed 2026-11-21)
  4. Node.js — SQLite (node:sqlite, in-memory databases) (accessed 2026-11-21)
  5. Node.js — Running TypeScript natively (type stripping) (accessed 2026-11-21)
  6. Node.js — Test runner (node:test) (accessed 2026-11-21)
  7. MDN — Intl.DateTimeFormat constructor (timeZone option) (accessed 2026-11-21)

Add us on LINE

Scan with the LINE app on your phone

QR code to add LINE @Bankoos

LINE ID: @Bankoos

Open LINE on this computer