← Back to Backend, page 2

backend-0037 · Hard senior

What happens when two requests with the same idempotency key arrive at the same time, and how do you guarantee that the work runs only once?

A unique constraint on the idempotency key makes the database the referee. Both requests try to insert the key inside their transaction. The first one gets the row. The second one blocks on the unique index until the first commits (then it sees a conflict and returns the stored response) or rolls back (then it can claim the key and do the work). The work and the key are in the same transaction, so a crash leaves nothing behind. Outside a database transaction (for example when the work calls an external API) you need a status column (in progress, done) and a 409 or retry-later answer for requests that arrive while the first is running.

Full answer

Races to cover

  1. Two simultaneous requests, same key: without a unique constraint both pass a "does the key exist?" check and both run. Always claim the key with an atomic INSERT (or SET NX in Redis), never check then insert.
  2. Crash after claiming the key but before finishing: if the claim and the work are in one transaction, the claim vanishes with the rollback, and a retry starts clean. If they are separate (external side effects), store a status and an expiry, and let a janitor or the next retry take over stale in-progress records. Pass the same key to the external system so the external call is idempotent as well.
  3. Failure of the work: store the error response too if it is final (a validation error), but not for transient failures that the client should retry.
  4. Same key, different body: 422.

Choosing the waiting behaviour

  • Block until the first finishes (simple, uses a database lock for the wait, holds a connection).
  • Return 409 with Retry-After so the client retries (cheaper under load).

What exactly-once means here: at-least-once requests plus an idempotent server give exactly one effect for one key within the retention window.

javascript
const { Pool } = require('pg');
const crypto = require('node:crypto');
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

(async () => {
  const pool = new Pool({ max: 8 });
  await pool.query(`DROP TABLE IF EXISTS bk37_idem; DROP TABLE IF EXISTS bk37_orders;
    CREATE TABLE bk37_orders (id serial PRIMARY KEY, item text NOT NULL);
    CREATE TABLE bk37_idem (key text PRIMARY KEY, response jsonb)`);

  async function createOrder(key, item, { crash = false } = {}) {
    const c = await pool.connect();
    try {
      await c.query('BEGIN');
      const claimed = await c.query('INSERT INTO bk37_idem (key) VALUES ($1) ON CONFLICT DO NOTHING RETURNING key', [key]);   // waits if another transaction holds this key
      if (claimed.rowCount === 0) {
        const { rows } = await c.query('SELECT response FROM bk37_idem WHERE key = $1', [key]);
        await c.query('COMMIT');
        return { ...rows[0].response, replay: true };
      }
      await sleep(50);                                              // the work takes a while
      const { rows } = await c.query('INSERT INTO bk37_orders (item) VALUES ($1) RETURNING id', [item]);
      if (crash) throw new Error('process crashed before commit');
      const response = { status: 201, orderId: rows[0].id };
      await c.query('UPDATE bk37_idem SET response = $2 WHERE key = $1', [key, response]);
      await c.query('COMMIT');
      return { ...response, replay: false };
    } catch (err) { await c.query('ROLLBACK'); return { status: 500, error: err.message }; }
    finally { c.release(); }
  }

  // 1. Five identical requests at the same moment.
  const results = await Promise.all(Array.from({ length: 5 }, () => createOrder('key-A', 'book')));
  const orders = (await pool.query('SELECT count(*)::int AS n FROM bk37_orders')).rows[0].n;
  console.log('5 concurrent requests, same key:', results.filter((r) => !r.replay).length, 'did the work,', results.filter((r) => r.replay).length, 'replayed | orders created:', orders);
  console.log('all five got the same order id :', new Set(results.map((r) => r.orderId)).size === 1);

  // 2. The first request crashes. Nothing is left behind, and the retry works.
  const crashed = await createOrder('key-B', 'pen', { crash: true });
  const afterCrash = (await pool.query("SELECT count(*)::int AS n FROM bk37_idem WHERE key = 'key-B'")).rows[0].n;
  const retry = await createOrder('key-B', 'pen');
  console.log('crash, then retry              :', crashed.status, '-> key rows after crash:', afterCrash, '-> retry:', retry.status, 'replay =', retry.replay);

  await pool.query('DROP TABLE bk37_idem; DROP TABLE bk37_orders');
  await pool.end();
})();

Five requests share one key and run on separate pooled connections. The work includes a 50 ms pause so that the requests really overlap, and the crash is simulated with a thrown error before COMMIT. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): 5 concurrent requests, same key: 1 did the work, 4 replayed | orders created: 1 all five got the same order id : true crash, then retry : 500 -> key rows after crash: 0 -> retry: 201 replay = false

Key points

  • Claim the key with one atomic insert, never check then insert.
  • The unique index makes concurrent duplicates wait or conflict.
  • Keep claim and work in one transaction when possible.
  • For external side effects, use an in-progress status and expiry.
  • Pass the key on to downstream systems.

Common mistakes

  • Checking for the key with SELECT and then inserting.
  • Claiming the key in one transaction and doing the work in another, with no status.
  • Waiting forever on an in-flight key (no timeout).
  • Caching transient failures as final results.
  • Forgetting idempotency for the downstream call.

Follow-ups

  • How would you do this with Redis SET NX instead of a database?
  • What do you return to a request that arrives while the first is still running?
  • How do stale in-progress records get cleaned up?

Tips

  • Name the race first.
  • Say 'one atomic claim'.
  • Describe the crash case.