research/idempotency-keys-for-a-booking-form

Idempotency Keys for a Booking Form: Stopping Double Clicks and Retries From Creating Two Bookings

Engineering Note · November 23, 2026 · 8 minute read · Node.js · SQLite · Forms · Reliability

Give each form submission a unique ID, created in the browser and sent with every try, and have the server record that ID in a table with a primary key before it does any work. A repeat with the same ID then gets the first answer instead of a second booking. We built a small booking endpoint both ways and hit it with a double click, a client that timed out and retried, a reused key with different details, and a failure halfway through. Without a key, the double click made two bookings and the timed-out client made four. With a key, every case ended with exactly one.

Everything below was run on Linux with Node.js 22.23.5, using node:http, node:crypto and the built-in node:sqlite module, which reports SQLite 3.54.1. node:sqlite is still marked experimental in this version and prints a warning when loaded. No packages were installed. The outputs are the real ones from these runs. This note goes with today’s Retrying a Flaky HTTP Call With Backoff and a Deadline, which retries only requests that are safe to repeat; a key is what makes a POST safe to repeat.

Why isn’t a disabled button enough?

Disabling the submit button after the first click is worth doing. It stops the most common duplicate. But a booking can be sent twice in other ways: a slow network that makes the visitor press again after the page reloads, a second open tab, a script or a mobile app that retries on its own after a timeout. The server is the only place that sees every try, so the server has to decide whether a request is new.

How does the endpoint work?

Two tables: the bookings, and a table of keys. The key is the primary key, so SQLite itself guarantees each one can be stored once.

const db = new DatabaseSync(":memory:");
db.exec(`
  CREATE TABLE bookings (id INTEGER PRIMARY KEY, name TEXT, slot TEXT);
  CREATE TABLE idempotency (
    key        TEXT PRIMARY KEY,
    body_hash  TEXT NOT NULL,
    state      TEXT NOT NULL,          -- 'pending' or 'done'
    status     INTEGER,
    response   TEXT,
    created_at TEXT NOT NULL DEFAULT (datetime('now'))
  );
`);

Creating a booking takes a while, because it first waits on an outside call (here a sleep, standing in for checking a calendar or taking a deposit). That wait is where duplicates sneak in.

let workMs = 50;          // how long the outside call takes
let failNext = false;     // make the next outside call fail once

async function createBooking(body) {
  await sleep(workMs);                      // e.g. check the calendar or take a deposit
  if (failNext) { failNext = false; throw new Error("calendar service timed out"); }
  const { lastInsertRowid } = db
    .prepare("INSERT INTO bookings (name, slot) VALUES (?, ?)")
    .run(body.name, body.slot);
  return { id: Number(lastInsertRowid), slot: body.slot };
}

The keyed handler does four things, in this order:

  1. Claim the key. Insert it as pending with ON CONFLICT(key) DO NOTHING. If one row changed, this request is the first and does the work.
  2. If the key was already there, compare the body. A different SHA-256 hash of the body means the key was reused for a different request: refuse with 422.
  3. If the first request is still running, say so. Answer 409 with Retry-After: 1 rather than doing the work again.
  4. If it finished, replay the stored answer, with a header so we can see it was a replay.

When the work fails, the key is deleted, so the client can try again with the same key.

const claim = db.prepare(
  "INSERT INTO idempotency (key, body_hash, state) VALUES (?, ?, 'pending') ON CONFLICT(key) DO NOTHING"
);
const lookup = db.prepare("SELECT body_hash, state, status, response FROM idempotency WHERE key = ?");
const finish = db.prepare("UPDATE idempotency SET state = 'done', status = ?, response = ? WHERE key = ?");
const release = db.prepare("DELETE FROM idempotency WHERE key = ?");

// inside the request handler, for /keyed
  const key = req.headers["idempotency-key"];
  if (!key) return send(res, 400, { error: "Idempotency-Key header required" });
  const hash = createHash("sha256").update(raw).digest("hex");

  const claimed = claim.run(key, hash).changes === 1;
  if (!claimed) {
    const row = lookup.get(key);
    if (row.body_hash !== hash) return send(res, 422, { error: "key reused with a different body" });
    if (row.state === "pending") return send(res, 409, { error: "same request still in progress" }, { "retry-after": "1" });
    return send(res, row.status, JSON.parse(row.response), { "idempotent-replayed": "true" });
  }
  try {
    const result = await createBooking(body);
    finish.run(201, JSON.stringify(result), key);
    return send(res, 201, result);
  } catch (e) {
    release.run(key);                       // let the client try again
    return send(res, 500, { error: e.message });
  }

The /naive route on the same server calls createBooking directly, with no key.

The test client posts JSON with fetch, a timeout per request, and the key in an Idempotency-Key header. Each key is a fresh crypto.randomUUID() per test:

async function post(path, body, key, timeoutMs = 5000) {
  const headers = { "content-type": "application/json" };
  if (key) headers["idempotency-key"] = key;
  try {
    const r = await fetch(base + path, { method: "POST", headers, body: JSON.stringify(body), signal: AbortSignal.timeout(timeoutMs) });
    const replay = r.headers.get("idempotent-replayed") ? " (replayed)" : "";
    return `${r.status}${replay} ${await r.text()}`;
  } catch (e) { return `client gave up: ${e.name}`; }
}

What happened in each case?

The full output, with the experimental warning removed:

1. double click, no key
   [
  '201 {"id":1,"slot":"2026-11-24T10:00"}',
  '201 {"id":2,"slot":"2026-11-24T10:00"}'
]
   bookings: 2
2. same key sent twice, one after the other
   201 {"id":1,"slot":"2026-11-24T10:00"}
   201 (replayed) {"id":1,"slot":"2026-11-24T10:00"}
   bookings: 1
3. double click with the same key
   [
  '201 {"id":1,"slot":"2026-11-24T10:00"}',
  '409 {"error":"same request still in progress"}'
]
   bookings: 1
4. same key, different body
   201 {"id":1,"slot":"2026-11-24T10:00"}
   422 {"error":"key reused with a different body"}
   bookings: 1
5. slow server: client times out after 1 s, retries every 600 ms
   /naive: [
  'client gave up: TimeoutError',
  'client gave up: TimeoutError',
  'client gave up: TimeoutError',
  'client gave up: TimeoutError'
] bookings: 4
   /keyed: [
  'client gave up: TimeoutError',
  '201 (replayed) {"id":1,"slot":"2026-11-24T10:00"}'
] bookings: 1
6. side effect fails once, client retries with the same key
   500 {"error":"calendar service timed out"}
   201 {"id":1,"slot":"2026-11-24T10:00"}
   bookings: 1  keys: [ 'done' ]

Case by case:

  1. Two requests at once, no key: two bookings. Both passed through the slow step before either was saved. Nothing on the server connected them.
  2. The same key twice: one booking. The second request got the first answer back, the same booking ID, marked as a replay.
  3. Two requests at once with the same key: one booking. The second request found the key pending and got a 409. A real client would wait a second and ask again, and get the replay.
  4. The same key with a different time slot: refused. Without the hash check, the second request would have been told “201, booked” for a slot that was never booked.
  5. A slow server and an impatient client. The outside call took 1.5 seconds; the client gave up after 1 second and tried again 600 ms later. Without a key, the visitor saw four timeouts, and the business got four bookings for one person. With a key, the second try arrived after the first had finished and got the stored booking back. Note that the client never saw the first try succeed: a timeout on the client says nothing about what happened on the server.
  6. The first try failed: the retry worked. Because the key was deleted after the failure, the retry with the same key did the work and stored the result. Had we stored the 500 as the answer, every retry would have replayed the failure.

What does the browser side need?

Very little. Create the key once per submission and reuse it for every try of that submission:

  • Put a UUID in a hidden field when the form is rendered, or create it with crypto.randomUUID() on the first submit and keep it in memory.
  • Send it in a header (Idempotency-Key) or as a form field. The server reads the same value either way.
  • Reuse the same key when retrying after a timeout or a 409. Make a new key only when the visitor changes the details and submits again on purpose.
  • Keep disabling the button after the first click. It is cheap, and it cuts the number of repeats the server has to answer.

A checklist for adding keys to an existing form

  • A table with the key as its primary key, a body hash, a state, the stored answer and a created_at time.
  • Claim the key before any outside call or database write.
  • Refuse a known key with a different body.
  • Answer “still in progress” for a pending key rather than doing the work again.
  • Store the answer only on success. Delete the key on failure so a retry can try again.
  • Delete old keys on a schedule; for a form, a day is plenty.
  • Make the client reuse the key on every retry, including retries made by your own code.

Limitations

  • The endpoint ran in one Node.js process with an in-memory SQLite database. A real site with several servers needs the key table in a shared database; the primary key still guarantees one claim per key, but we did not test that across processes or on a hosted database.
  • If the process crashes after the booking is saved but before the key is marked done, the key stays pending forever and the booking exists. A production version should save the booking and mark the key in one transaction where it can, and treat a pending key older than a few minutes as failed. We did not test crashes.
  • Outside calls that cannot be undone, such as charging a card, need their own idempotency support from the provider. A key in our own table stops us from calling twice, but not from a provider’s side effect if our call timed out after it succeeded. We could not test a real payment provider here.
  • node:sqlite is experimental in Node.js 22.23.5 and may change.
  • We did not test key expiry, which the checklist recommends.

Frequently asked questions

What is an idempotency key?

It is a unique ID, usually a random UUID, that the client creates once per action and sends with every try of that action. The server stores the key with the result of the first try. A later request with the same key gets the stored result instead of doing the work again, so a double click or a retry cannot create a second booking or charge.

Does disabling the submit button stop duplicate submissions?

It stops the most common double click, but not a retry after a timeout, a second tab, a browser that resends the form or a script that retries on its own. In our test, a client that timed out and retried created four bookings against an endpoint without a key. The server has to recognize repeats; the button only reduces them.

Where should the idempotency key be created?

On the client, once per action, before the first try: for a form, when the page loads or when the visitor first presses submit, kept in a hidden field or in memory. Every retry of that same submission must reuse it. A new key per try defeats the purpose, because the server sees each try as a new request.

What should the server do when the same key arrives while the first request is still running?

Do not run the work a second time. Our endpoint answers 409 with a Retry-After header, and the client tries again shortly after, when the stored result is ready. In our double-click test, the second click got that 409 and only one booking was created.

What if the same key is sent with different form data?

Refuse it. Store a hash of the request body with the key, and if a later request with that key has a different hash, answer with an error instead of replaying the old result. Our endpoint answered 422, which kept a changed time slot from being silently confirmed as the original one.

How long should idempotency keys be kept?

Long enough to cover every retry a client might make, which for a form is minutes to hours. A day is a comfortable margin. Delete older rows on a schedule using a created_at column. We did not test expiry in this note.

More from Research

← All research