BT San Technology

23 March 2026

Two people book the same slot at once: understanding transactions and preventing data conflicts

24 min read · Websites and web apps

Illustration: two people tapping the same time slot on their own tablets while a laptop between them shows one confirmed booking
AI-generated illustration

A clinic opens online booking. Tuesday at 10:00 has one slot left. Two patients tap Book less than a second apart, and both get a confirmation message. On the day, two people stand at the counter with one chair. No line of code is wrong. Two requests ran in parallel, and each one trusted what it had read a moment earlier.

This article reproduces that event with Node 24 and the SQLite that ships with Node, then fixes it three ways and compares which fits which job. The parts that need PostgreSQL- and MySQL-specific features (SELECT ... FOR UPDATE, isolation levels) are written as a separate reference SQL file, and the article says plainly that they were not run in the example.

The real problem: reading and deciding do not happen at the same moment as writing the result

Typical booking code has three steps: ask whether the slot is free, insert a booking row if it is, then reply to the user. There is a gap between step one and step two. Even when it is very short, another request can slip in. Both requests see the slot as free, and both write. Disabling the button on screen after the first tap only stops the same person from tapping twice. It does not stop two people on different devices.

Here are three hypothetical situations. They are not BT San customer projects.

  • An online clinic booking: the 10:00 slot of a single doctor is booked in two rows. Reception has to phone one patient on the day to reschedule.
  • A company meeting room: two departments book the same room at the same time through an internal web page. Nobody finds out until the morning of the meeting.
  • A seminar with one seat left, or the last item in stock: the system sells it twice, yet the remaining count shows 0 as if nothing were wrong.

These three cases belong to the same family of problems, but the best fix differs a little for each. So the article compares three methods on the same data.

What the database documentation says

TopicWhat the documentation saysEffect on the method you choose
UNIQUE in SQLiteEvery row must have a distinct value in a UNIQUE column, and if no conflict clause is given, a violating write is aborted.The database rejects the second person by itself, whether or not the app checks.
BEGIN IMMEDIATE in SQLiteRequests write permission as soon as the transaction starts, and can fail with SQLITE_BUSY if another connection is writing. DEFERRED waits until the first data access.Used in the example instead of row locking, because SQLite locks the whole database, not rows.
PostgreSQL isolation levelsRead Committed is the default. Serializable requires the app to be ready to retry the transaction on a serialization failure, which always returns SQLSTATE 40001.Raising the isolation level is a valid fix, but you pay for it by writing retry code.
FOR UPDATE in PostgreSQLLocks the rows it reads until the transaction ends. Other transactions that try to update, delete or lock those rows are blocked. Deadlocks are detected and one transaction is aborted.There must be a row to lock, and you must allow for being aborted.
Locking reads in MySQL InnoDBSELECT ... FOR UPDATE locks the rows and index entries it reads, as if you had issued an UPDATE, and the locks are released on commit or rollback.Same idea as PostgreSQL, but the details of range (gap) locking differ.
Deadlocks in InnoDBThe app must be ready to resubmit the transaction when it is rolled back because of a deadlock.Every method that locks needs a retry.
Summary of the SQLite, PostgreSQL and MySQL documentation, read on 2026-11-21. References are listed at the end of the article.

Overview of the example

The example is in the article's examples folder. It runs .ts files directly on Node 24 and uses the node:sqlite module that ships with Node, so there is nothing to install and no network is used.

FilePurposeActually run?
db.tsOpens a temporary database file, allows two connections, and creates the tablesRun
booking.tsAll four booking functionsRun
demo.tsPlays four fixed sequences of eventsRun; the result is in output.txt
booking.test.tsnode:test test suiteRun; 4 of 4 passed
postgres-mysql.sqlReference SQL for FOR UPDATE and isolation levelsNot run: the machine that built the example has no PostgreSQL or MySQL
output.txtstdout of node demo.tsCaptured from a real run
Files in the example and whether they were run
db.ts · lines 18–28
// withUnique = true เพิ่ม UNIQUE(slot) ซึ่งเป็นกฎที่ฐานข้อมูลบังคับเอง
export function setup(file: string, withUnique: boolean): void {
  const db = open(file);
  db.exec(`CREATE TABLE bookings (
    id INTEGER PRIMARY KEY,
    slot TEXT NOT NULL,
    patient TEXT NOT NULL${withUnique ? ",\n    UNIQUE (slot)" : ""}
  )`);
  db.exec("CREATE TABLE seats (event TEXT PRIMARY KEY, remaining INTEGER NOT NULL CHECK (remaining >= 0))");
  db.close();
}
db.ts: the bookings table may or may not have UNIQUE(slot), so the two cases can be compared

Step 1: reproduce the collision, two reads then two writes

SQLite in Node is synchronous, so two requests never truly run in parallel inside one process. The example sets the order itself: connections A and B both read first, then both write. This is the same order that happens when two real requests interleave. The upside is that the result repeats every time. The downside is that it proves this order causes the problem, but it does not measure how often it happens in a real system.

demo.ts · lines 11–28
// ลำดับเหตุการณ์ถูกกำหนดตายตัว เพื่อให้ผลซ้ำได้ทุกครั้ง: A อ่าน, B อ่าน, A เขียน, B เขียน
function raceCheckThenInsert(withUnique: boolean) {
  const t = tempDb();
  setup(t.file, withUnique);
  const a = open(t.file), b = open(t.file);
  console.log("A ตรวจ ว่างหรือไม่:", isFree(a, SLOT));
  console.log("B ตรวจ ว่างหรือไม่:", isFree(b, SLOT));
  insertBooking(a, SLOT, "คุณสมชาย");
  console.log("A จองสำเร็จ");
  try {
    insertBooking(b, SLOT, "คุณสมหญิง");
    console.log("B จองสำเร็จ");
  } catch (e) {
    console.log("B ถูกปฏิเสธ:", isUniqueViolation(e) ? "UNIQUE constraint" : String(e));
  }
  console.log("จำนวนแถวของช่อง", SLOT, "=", countRows(a, SLOT));
  a.close(); b.close(); t.cleanup();
}
demo.ts: the fixed order A reads, B reads, A writes, B writes, reused for both the no-UNIQUE and UNIQUE cases

The result for the case with no rule in the database is in the output section below. One slot has two rows.

Step 2, first method: let the database enforce it with UNIQUE

Add one line, UNIQUE(slot), to the table and use exactly the same sequence of events. A writes, and B is rejected by the database. The app needs no protection logic at all. What you do need is to catch this error and turn it into a message a person can understand, such as: this slot was just booked, please choose another time.

booking.ts · lines 51–53
export function isUniqueViolation(e: unknown): boolean {
  return (e as { errcode?: number }).errcode === 2067; // SQLITE_CONSTRAINT_UNIQUE
}
booking.ts: check the SQLite error code instead of comparing message text

This is the cheapest method and should always be the last line of defense. The limit is that it only works for rules that can be written as uniqueness of columns, for example one doctor, one slot (UNIQUE on the pair doctor_id and slot). If the rule is more complex, such as meeting rooms with overlapping times, plain UNIQUE is not enough.

Step 3, second method: a transaction that takes write permission before checking

The idea is to put the check and the write in one transaction and ask for write permission at the start, so nobody can slip in between. In the example, SQLite uses BEGIN IMMEDIATE, which locks the whole database for writing. The second person hits SQLITE_BUSY at BEGIN and has to retry. On the retry, they see that the slot is already booked.

booking.ts · lines 12–33
export type TxStep = { ok: true } | { ok: false; reason: "busy" | "taken" };

export function beginImmediate(db: DatabaseSync): TxStep {
  try {
    db.exec("BEGIN IMMEDIATE"); // ขอสิทธิ์เขียนทันที ใครมาทีหลังต้องรอหรือล้ม
    return { ok: true };
  } catch (e) {
    if ((e as { errcode?: number }).errcode === 5) return { ok: false, reason: "busy" }; // SQLITE_BUSY
    throw e;
  }
}

export function checkAndInsert(db: DatabaseSync, slot: string, patient: string): TxStep {
  if (!isFree(db, slot)) {
    db.exec("ROLLBACK");
    return { ok: false, reason: "taken" };
  }
  insertBooking(db, slot, patient);
  db.exec("COMMIT");
  return { ok: true };
}
booking.ts: beginImmediate and checkAndInsert
  • PostgreSQL and MySQL have no whole-database lock like this. The usual tool is SELECT ... FOR UPDATE, which locks only the rows involved. The SQL example is in postgres-mysql.sql, which was not run in this example.
  • FOR UPDATE can only lock rows that exist. If a time slot has no row yet, there is nothing to lock. Create the slot rows in advance, or rely on UNIQUE as the last line of defense.
  • The PostgreSQL default is Read Committed, where a plain check-then-write can still collide. Raising it to Serializable prevents that, but the app must retry when it gets SQLSTATE 40001.

Step 4, third method: a conditional UPDATE for seats or stock

If what you count is the quantity remaining, not a specific time slot, the wrong pattern is this: read the remaining number, subtract one in the app, and write the new value over the old one. Two requests that both read 1 will both write 0, and two items are sold. The right pattern is to put the condition inside a single UPDATE. The database checks and decrements in one step, and you look at the number of rows changed to see whether it succeeded or is sold out.

booking.ts · lines 39–49
// แบบผิด: อ่านค่าไปคำนวณในแอปแล้วเขียนทับ (lost update)
export const readRemaining = seatsLeft;
export function writeRemaining(db: DatabaseSync, event: string, value: number): void {
  db.prepare("UPDATE seats SET remaining = ? WHERE event = ?").run(value, event);
}

// แบบถูก: เงื่อนไขอยู่ใน UPDATE เดียว ฐานข้อมูลตัดสินให้ ดูจาก changes
export function takeSeat(db: DatabaseSync, event: string): boolean {
  const r = db.prepare("UPDATE seats SET remaining = remaining - 1 WHERE event = ? AND remaining > 0").run(event);
  return Number(r.changes) === 1;
}
booking.ts: the wrong way (read then overwrite) and the right way (conditional UPDATE)

This method needs no locking of your own, works in the same form on PostgreSQL and MySQL, and is the one to choose first when the rule is: count, and never go below zero. The example also adds CHECK (remaining >= 0) to the table, a last line of defense just like UNIQUE.

Real run: four sequences of events

output.txt

== 1) ไม่มีกฎในฐานข้อมูล: ตรวจแล้วค่อยจอง ==
A ตรวจ ว่างหรือไม่: true
B ตรวจ ว่างหรือไม่: true
A จองสำเร็จ
B จองสำเร็จ
จำนวนแถวของช่อง 2026-12-01 10:00 = 2

== 2) แก้ด้วย UNIQUE(slot): ลำดับเดิมทุกอย่าง ==
A ตรวจ ว่างหรือไม่: true
B ตรวจ ว่างหรือไม่: true
A จองสำเร็จ
B ถูกปฏิเสธ: UNIQUE constraint
จำนวนแถวของช่อง 2026-12-01 10:00 = 1

== 3) แก้ด้วย transaction ที่ขอสิทธิ์เขียนก่อน (BEGIN IMMEDIATE), ไม่มี UNIQUE ==
A เริ่ม transaction: {"ok":true}
A ตรวจ ว่าง: true
B เริ่ม transaction: {"ok":false,"reason":"busy"}
A จองและ commit: {"ok":true}
B ลองใหม่: {"ok":true}
B ตรวจแล้วจอง: {"ok":false,"reason":"taken"}
จำนวนแถวของช่อง 2026-12-01 10:00 = 1

== 4) ที่นั่งสุดท้าย: อ่านแล้วเขียนทับ กับ UPDATE มีเงื่อนไข ==
A เห็นเหลือ 1 B เห็นเหลือ 1
แบบอ่านแล้วเขียนทับ: ขายไป 2 คน ทั้งที่มี 1 ที่ แต่ตัวเลขบอกเหลือ 0 (ไม่มีใครรู้ว่าขายเกิน)
แบบ UPDATE มีเงื่อนไข: A = true B = false เหลือ 0
Output of a real run on 2026-11-21 with node demo.ts (Node 24.21)
  1. Sequence 1, no rule in the database: A and B both see the slot as free and both bookings succeed. One slot has two rows. This is the bug.
  2. Sequence 2, with UNIQUE: the same order of events, but B is rejected. One row remains.
  3. Sequence 3, BEGIN IMMEDIATE transaction: B cannot start (busy) until A commits. When B retries, it sees the slot is already booked, and there is no duplicate row, even though this table has no UNIQUE at all.
  4. Sequence 4, the last seat: with read-then-overwrite, two people are sold a seat although there is only one, and the remaining number shows 0, which looks normal. With the conditional UPDATE, A succeeds and B is rejected.

Test suite

booking.test.ts has four tests. The first confirms the bug is real when there is no rule. (If this one fails, the simulated order no longer reproduces a collision, and the results of the other tests mean nothing.) The other three test each fix. The last one fires 10 orders at 3 items in stock and must sell exactly 3, no more and no fewer. If someone removes UNIQUE or drops the remaining > 0 condition, the tests fail.

booking.test.ts · lines 25–31
test("UNIQUE(slot): คนที่สองถูกปฏิเสธ เหลือหนึ่งแถว", () => {
  const { a, b, done } = twoConnections(true);
  insertBooking(a, SLOT, "A");
  assert.throws(() => insertBooking(b, SLOT, "B"), (e) => isUniqueViolation(e));
  assert.equal(countRows(a, SLOT), 1);
  done();
});
booking.test.ts: the UNIQUE test

Using this in a real system: PostgreSQL and MySQL

  • Always use UNIQUE (or an exclusion constraint in PostgreSQL for overlapping time ranges) as the last line of defense, even when locking is in place. It protects you even if the app code has a bug or someone writes data through another route.
  • If you use FOR UPDATE, lock rows in the same order everywhere (for example sorted by id) to reduce the chance of deadlock. When one happens, retry the whole transaction. Both the PostgreSQL and MySQL documentation say deadlocks can happen and the app must be ready to handle them.
  • If you use Serializable in PostgreSQL, catch code 40001 and retry, with a limit on attempts (for example 3) and a small random backoff. Otherwise users will see random errors.
  • Set a short timeout for waiting on locks (one second, not minutes). Long waits let requests pile up until the whole server responds slowly.
  • Keep transactions short. Do not call external APIs, send email or wait for the user inside a transaction that holds a lock.
  • MySQL InnoDB and PostgreSQL differ in the default isolation level and in the details of range locking. Do not assume the behavior of one database holds for the other, and test on the real database version you use.
  • A repeated request from a single user (tapping twice, or retrying after the connection drops) is a different problem. Fix it with an idempotency key. This article covers different people competing for the same thing.

Hypothetical examples: applying this to three kinds of business

Clinics and beauty salons

One stylist, one time: UNIQUE on the pair staff_id and start_time handles it directly. If services take different lengths of time (30 minutes and 90 minutes), split the day into 30-minute slots and book several slots in one transaction. If any one slot collides, cancel the whole set.

Meeting rooms and training rooms

Overlapping time ranges make plain UNIQUE insufficient. In PostgreSQL you can use an exclusion constraint on the time range. In MySQL you must break the time into smaller slots or lock the room's row before checking. This is an example to test on the real database before you trust it.

Seminars, courses and limited-stock items

A conditional UPDATE fits best, but a business decision must go with it, for example when a seat that is held but not yet paid for returns to the pool. That is a business rule, not a database matter.

Comparing the three methods

MethodBest forStrengthsLimits
UNIQUE in the databaseOne slot, one personOne line, covers every way into the dataCan only express uniqueness rules, and the error must be translated for the user
Transaction that locks first (SQLite: BEGIN IMMEDIATE, PostgreSQL/MySQL: FOR UPDATE)Complex rules, checking several tables before writingAny condition can be written in the appThere must be a row to lock, you must write retry code and watch for deadlocks. The example that was actually run uses SQLite only
UPDATE ... WHERE remaining > 0Seats, stock, quotasNo locking of your own, works on any databaseCounting only. It does not record who got which seat, so add a buyer row in the same transaction
The best setup is UNIQUE or CHECK as the last line of defense, then one more method chosen by the type of rule

Common mistakes and a checklist

  • Disabling the button on screen and assuming that is enough.
  • Checking with a SELECT and writing in another statement, with no transaction or any rule in the database.
  • Reading the remaining count, subtracting in the app and writing it back.
  • Catching the UNIQUE error and telling the user "system error" instead of saying the slot has just been booked.
  • Holding a transaction open while calling an external service.
  • Testing with one request at a time and concluding there is no problem.
  1. Write the rule that must never be broken as one clear sentence, for example: one stylist can have only one booking per time period.
  2. Decide whether the rule can be written as UNIQUE, CHECK, an exclusion constraint or a conditional UPDATE. If it can, put it in the database first.
  3. If you need locking, define the lock order, the timeout and the number of retries.
  4. Translate database errors into a message and options for the user.
  5. Write a test that interleaves reads and writes like this example, and also test with truly parallel requests against a real database in a test environment.
  6. Watch how many times a constraint rejects a request and how many real deadlocks occur, so you know which slots are contested most.

Caveats of the example: it uses SQLite, which locks the whole database, so BEGIN IMMEDIATE does not behave like FOR UPDATE in PostgreSQL or MySQL. The two connections are in one process and are interleaved by hand, so this is not a real parallel workload. The file postgres-mysql.sql was not run, so test it on a real database before use. The current node:sqlite documentation says DatabaseSync is an older name replaced by Database. The example runs on Node 24.21, but if you update Node, check the class name again. All data is hypothetical.

References

  1. PostgreSQL — Transaction isolation (Read Committed default, serialization failures and retry) (accessed 2026-11-21)
  2. PostgreSQL — Explicit locking (row-level locks, FOR UPDATE, deadlocks) (accessed 2026-11-21)
  3. MySQL 8.4 — InnoDB locking reads (SELECT ... FOR UPDATE) (accessed 2026-11-21)
  4. MySQL 8.4 — How to minimize and handle deadlocks (accessed 2026-11-21)
  5. SQLite — BEGIN TRANSACTION (DEFERRED, IMMEDIATE, SQLITE_BUSY) (accessed 2026-11-21)
  6. SQLite — CREATE TABLE (UNIQUE constraints, conflict resolution) (accessed 2026-11-21)
  7. Node.js — SQLite (node:sqlite) (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