Why a Committed PostgreSQL Write Can Still Produce a Failed Node.js Response

Why a Committed PostgreSQL Write Can Still Produce a Failed Node.js Response

pr0h0••37 min read•coding
AI Usage (79%)

A local POST /orders handler can return ECONNRESET to the client while its row sits in PostgreSQL — committed and immutable. That gap, between a committed write and a failed Node.js response, is the problem this walkthrough works through end to end: you will build the endpoint, break it on purpose at the commit boundary, and see why the fix is not a try/catch but an idempotency record persisted in the same transaction as the write.

On this page

A successful PostgreSQL COMMIT does not guarantee a successful Node.js HTTP response

Start with the failure the rest of the article hangs on. A client sends POST /orders. The handler validates the body, opens a transaction, inserts an order row, writes a replay record, and calls COMMIT. PostgreSQL acknowledges the commit and fsyncs the WAL. Then the handler tries to write the 201, and the socket is already gone — the client timed out, a load balancer recycled the connection, a mobile radio dropped. The client sees a transport error. The order exists.

My position, up front: retry safety is not something you add at the HTTP layer. It is a durability property of the write path. If the operation and the record needed to replay its result are not committed in the same transaction, then no amount of client-side retry logic can distinguish "the write happened" from "the write did not happen," because the server itself cannot answer that question from its own state. The idempotency record is not a cache and not an optimisation. It is the durable proof of what the operation did, written at the only moment the system can write it atomically.

What the supplied source establishes

The topic comes from a HackerNoon piece, Implementing Transactional API Idempotency With Node.js and PostgreSQL, surfaced through a Google News discovery record dated 2026-11-27. What I was given is a headline, a one-line summary ("the topic centers on coordinating API request handling with database transactions"), and a discovery link — no schema, no code, no measurements, no stated conclusions.

So I will be explicit about attribution, because it matters for a post that contains this much SQL:

  • From the source: the subject — transactional API idempotency with Node.js and PostgreSQL — and the framing that request handling and database transactions must be coordinated. That is all the supplied summary supports, and I am not going to attribute design decisions to an article I have not read.
  • From this article: the schema, the claim protocol, the failure hooks, the test harness, and every code block below. They are my worked example, not a description of that article's implementation.
  • From PostgreSQL and Node.js documentation: the concurrency semantics, which I cite inline where they carry weight and list in Further Reading.

Every command output below is labelled expected and paired with the assertion that either holds or fails when you run it yourself. I did not paste terminal transcripts I cannot produce; where I am reasoning rather than measuring, I say so.

Locate the failure boundary between PostgreSQL and Node.js

The bug is easy to fix once you can name the boundary. The hard part is that both sides of it use the word "failure" for different things.

Trace the request through five separate events

A single logical order creation passes through five events, and only the first four are under your control:

#EventWho decides itReversible?
1Request received and parsedNode.jsyes (reject before writing)
2Transaction executedPostgreSQLyes (ROLLBACK)
3COMMIT acknowledgedPostgreSQLno
4Response bytes emittedNode.jsno (already written)
5Response received by clientnetwork + clientno

Events 1–3 are durability. Events 4–5 are delivery. A connection error is information about event 5, or at best about event 4. It says nothing about event 3, and event 3 is the one that matters. The mistake I see most often in review is a handler that treats "the response did not go out" as though it were "the transaction did not commit," then takes some compensating action — a second DELETE, a status reset, a retry — and creates the duplicate it was trying to prevent.

The mental model that keeps me honest: the commit is the point of no return, and everything after it is a delivery report about a decision that has already been made.

Separate a failed response from an unknown commit outcome

Two different incidents. They deserve different handling.

Case 1 — confirmed commit, failed delivery. COMMIT returned successfully, so the server knows the order exists. The socket write then fails. Nothing about this is ambiguous from the server's perspective; it is ambiguous only from the client's. The correct server behaviour is to do nothing, because there is nothing left to do. The correct client behaviour is to retry with the same key and receive the stored result.

Case 2 — lost connection while COMMIT is in flight. The client sent COMMIT and never got an answer. This one is genuinely unknown. PostgreSQL may have committed and crashed before replying, or it may have aborted the transaction when the backend process noticed the dead socket. From the application's point of view, COMMIT is a one-way message with a possible reply, and you cannot reconstruct the outcome from an exception object.

Case 2 is where "just retry" turns into a duplicate order if you have no idempotency record, and where "just roll back" turns into a lie if you assume the rollback undid something. The design here handles Case 2 by refusing to guess: it returns a retryable 503 telling the client to resend with the same key, and the same-key path resolves the truth on the next attempt. It does not claim the write failed.

⚠️

A client-side query_timeout on COMMIT produces Case 2 even on a perfectly healthy server: node-postgres gives up waiting while PostgreSQL goes on to commit. If you set query_timeout, you have created unknown-outcome commits by configuration.

Why catching an exception and calling ROLLBACK is insufficient

ROLLBACK is not an undo button. It is a request to abort a transaction that is still open. Once COMMIT has been acknowledged, there is no transaction left to abort — PostgreSQL will happily accept the ROLLBACK command and reply WARNING: there is no transaction in progress, and your order row remains.

So this pattern is wrong in a way that stays invisible until it matters:

// WRONG — the catch cannot tell "not committed" from "committed, reply lost"
const client = await pool.connect();
try {
  await client.query("BEGIN");
  await client.query("INSERT INTO orders ...");
  await client.query("COMMIT");
  res.writeHead(201); res.end(body);
} catch (err) {
  await client.query("ROLLBACK");   // may be a no-op after a failed COMMIT
  res.writeHead(500); res.end("failed");
}

Two defects. First, the catch covers both INSERT failures and response-write failures, and those require opposite conclusions. Second, the client now has a 500 for an order that exists, which is the exact input that produces duplicate orders in the wild: an honest client retries a 500.

The fix is structural, not defensive. Get the result into a committed, replayable state before touching the socket, and never let a delivery error reach the transactional error path.

Define the retry contract before writing the handler

Most idempotency bugs I have reviewed are contract bugs that no amount of SQL fixes. Before writing a line of the handler, answer four questions.

Scope an idempotency key to an authenticated caller and operation

A client-supplied key is only unique within a scope. If the key space is global, two unrelated accounts can collide, and one account can read another's stored response by guessing a key. That is an information-disclosure bug wearing an idempotency hat.

The composite identity is:

(account_id, operation, key)
  • account_id must come from verified credentials — a session, a validated JWT claim, mTLS, an API key lookup. Never from a request body or a client-settable header. In the lab code below I use a fixed account constant, with a clearly quarantined test-only override.
  • operation is a server-side constant such as orders.create. It stops a key from being reused across endpoints.
  • key is whatever the client sends, bounded in length, and reused for every retry of one logical operation — including retries after a timeout, a 500, a 503, or a dropped connection.

That last clause is the whole contract. A client that generates a fresh key per retry has built a duplicate generator with extra steps.

Reject key reuse with different request semantics

A duplicate request is not automatically a retry. If a key arrives with a different payload, that is a client bug, and the safe answer is 409 Conflict — not "execute it again" and not "return the old response as if it matched."

Getting this right means the fingerprint has to be stable:

  1. Validate explicitly. Don't hash the raw body. Parse it into a known schema with typed fields, so {"quantity": "1"} and {"quantity": 1} are the same order — or are rejected, but decided once.
  2. Normalise. Trim, uppercase currency, reject a field set you did not expect.
  3. Canonicalise. Hash a fixed-order representation, not JSON.stringify(req.body). Object member order is insertion order in V8, so hashing a parsed object makes your fingerprint depend on the client's key ordering.
function fingerprint(order) {
  const canonical = JSON.stringify([
    order.merchantOrderRef,
    order.sku,
    order.quantity,
    order.amountCents,
    order.currency,
  ]);
  return createHash("sha256").update(canonical, "utf8").digest();
}

An array literal makes the field order explicit and immune to future refactors that reorder an object.

Specify what a replay preserves

Replay means: same application status, same serialized response bytes, same selected stable headers. It does not mean reproducing the original request's transport details. Do not store or replay:

  • Date, Server, Connection, Keep-Alive, Transfer-Encoding
  • Set-Cookie (replaying a session cookie days later is a security bug, not a feature)
  • request IDs, trace IDs, or timing headers

Store an allowlist of response headers — for a JSON API, content-type plus content-language and content-location covers most cases. Everything else is transport and gets regenerated.

Note the asymmetry that follows: a replay returns the bytes frozen at commit time. If your serializer changes in a deploy, a key created before the deploy replays the old shape. That is correct — it is what the client was told was true — but it means your response schema is now part of your persistence format, and versioning it is your problem.

State the guarantee narrowly

Write this down, because reviewers will otherwise assume more:

Within the scope (account_id, operation, key), and for as long as the key record is retained, at most one local business operation is committed.

Not exactly-once HTTP delivery — the network can still lose the response. Not protection for a different key representing the same intent. Not atomicity for external side effects like charging a card or publishing to a queue. Not a substitute for a domain uniqueness constraint. Every one of those is a separate mechanism, and two of them get their own section near the end.

Build a reproducible local PostgreSQL and Node.js example

Declare the environment and commands

The versions below are the ones the code targets. Capture resolved versions when you run it, because "pg 8" spans a lot of behaviour.

ComponentVersionWhy it matters
Node.js22.xESM, node:http, global fetch for the harness
PostgreSQL17.xON CONFLICT, gen_random_uuid(), built-in sha256()
node-postgres (pg)8.xPool, client.release(destroy)
docker run --rm -d --name hackyjs-pg \
  -e POSTGRES_USER=lab -e POSTGRES_PASSWORD=lab -e POSTGRES_DB=lab \
  -p 55432:5432 postgres:17

npm init -y
npm pkg set type=module
npm install pg@8
node -e "console.log('node', process.version); console.log('pg', require('pg/package.json').version)"

Expected:

node v22.x.x
pg 8.x.x

Then create the schema and start the server:

psql "postgres://lab:[email protected]:55432/lab" -f schema.sql
DATABASE_URL="postgres://lab:[email protected]:55432/lab" node server.js
## expected: listening on 3100

Keep the example complete and locally scoped

Three files, all runnable:

  • schema.sql — tables and constraints
  • server.js — one node:http server with a pg.Pool
  • test-run.js — the harness that asserts on both HTTP and database state

No framework, deliberately. Express would add nothing here and would hide the one thing that matters: exactly where the socket write happens relative to COMMIT. Identity is a fixed lab account, and the test-only header override is fenced off behind an environment flag with a comment that says exactly where production authentication goes.

Define the order and idempotency tables

schema.sql
CREATE TABLE orders (
id                 uuid PRIMARY KEY,
account_id         text NOT NULL,
merchant_order_ref text NOT NULL,
sku                text NOT NULL,
quantity           integer NOT NULL CHECK (quantity BETWEEN 1 AND 100),
amount_cents       integer NOT NULL CHECK (amount_cents > 0),
currency           char(3) NOT NULL CHECK (currency ~ '^[A-Z]{3}$'),
created_at         timestamptz NOT NULL DEFAULT now(),
CONSTRAINT orders_business_unique UNIQUE (account_id, merchant_order_ref)
);

CREATE TABLE idempotency_keys (
id                  bigserial PRIMARY KEY,
account_id          text NOT NULL,
operation           text NOT NULL,
key                 text NOT NULL CHECK (length(key) BETWEEN 8 AND 255),
request_fingerprint bytea NOT NULL,
state               text NOT NULL CHECK (state IN ('in_progress', 'completed')),
response_status     integer,
response_body       bytea CHECK (octet_length(response_body) <= 65536),
response_headers    jsonb NOT NULL DEFAULT '{}'::jsonb,
order_id            uuid REFERENCES orders(id),
created_at          timestamptz NOT NULL DEFAULT now(),
completed_at        timestamptz,
CONSTRAINT idempotency_completion_shape CHECK (
  (state = 'in_progress'
     AND response_status IS NULL AND response_body IS NULL
     AND completed_at IS NULL AND order_id IS NULL)
  OR
  (state = 'completed'
     AND response_status IS NOT NULL AND response_body IS NOT NULL
     AND completed_at IS NOT NULL)
),
CONSTRAINT idempotency_scope_unique UNIQUE (account_id, operation, key)
);

Three details carry weight. idempotency_scope_unique is the concurrency arbiter — not a SELECT then INSERT. response_body is bytea, not jsonb, so a replay returns byte-identical output rather than a re-serialised object. And orders_business_unique is a separate invariant from request deduplication; more on that later.

Explain the temporary claim row and its committed-state invariant

The claim row starts as state = 'in_progress' and is updated to 'completed' before COMMIT, in the same transaction. That produces a useful property:

A committed in_progress row is impossible in correct operation. Uncommitted rows are invisible to every other transaction, and a rollback removes the row entirely. So if your handler ever reads a committed in_progress row, something wrote one outside a transaction — a maintenance script, a manual psql insert, a bug in a migration. That is an invariant violation, not a resumable job.

Which is why the code below throws IDEMPOTENCY_INVARIANT_VIOLATED instead of trying to resume or re-execute over an unfinished row. Resuming would mean guessing whether the interrupted attempt inserted the order, and guessing is what we are eliminating. Detect, alert, investigate by hand.

Note what you cannot do here: PostgreSQL has no deferred CHECK constraint, so you cannot tell the database "this row must be complete by commit time." The row is safe because of the code's structure, not because of a constraint. The idempotency_completion_shape check enforces the weaker, still-useful rule that a completed row always has a replayable payload.

Serialize duplicate requests with PostgreSQL uniqueness

Claim the key with INSERT ON CONFLICT DO NOTHING RETURNING

The claim is a single statement whose row count is the decision:

INSERT INTO idempotency_keys (account_id, operation, key, request_fingerprint, state)
VALUES ($1, $2, $3, $4, 'in_progress')
ON CONFLICT (account_id, operation, key) DO NOTHING
RETURNING id;

One row returned means you own the key and may proceed. Zero rows means someone else owns it or already finished. There is no check-then-act window, and no in-process mutex — which matters because a mutex in one Node process is worthless the moment you run two replicas behind a load balancer.

The cost of ON CONFLICT DO NOTHING is that it tells you that you lost without telling you to whom. It does not return the conflicting row. That is the next problem.

Use a separate SELECT after a losing insert

Run the lookup as a separate statement, not as a CTE in the same statement.

const existing = await client.query(
  `SELECT id, state, request_fingerprint, response_status, response_body, response_headers
     FROM idempotency_keys
    WHERE account_id = $1 AND operation = $2 AND key = $3`,
  [accountId, operation, key]
);

Under READ COMMITTED, each statement takes a fresh snapshot. So the SELECT can see a row that another transaction committed after our INSERT's snapshot was taken. That is exactly what we need when the winner committed while our statement was running.

The tempting single-statement version is a trap:

-- WRONG: the CTE and the outer query share one snapshot
WITH claimed AS (
  INSERT INTO idempotency_keys (...) VALUES (...)
  ON CONFLICT (account_id, operation, key) DO NOTHING
  RETURNING id
)
SELECT * FROM claimed
UNION ALL
SELECT id, state, ... FROM idempotency_keys WHERE account_id = $1 AND operation = $2 AND key = $3;

Per PostgreSQL's documentation on WITH, all sub-statements of a data-modifying CTE are executed with the same snapshot, so the outer SELECT cannot see the winner's row if it committed after that snapshot. You get zero rows, no error, and a handler that has to guess. The two-statement form costs one extra round trip and removes the guess.

📝

If the losing INSERT conflicts with a transaction that is still in flight, PostgreSQL must resolve that conflict before the statement can return, so the duplicate can spend time waiting on the winner. I have not measured the specific wait event in the harness below and would not build logic on it; the bounded retry loop exists precisely so the design does not depend on how long, or whether, a duplicate blocks.

Walk through both competing-transaction outcomes

Two transactions, A and B, same key, overlapping in time.

A commits. B's insert returns zero rows. B's follow-up SELECT — a new statement, new snapshot — sees A's committed completed row, compares fingerprints, and replays. B never touches orders.

A rolls back. B either acquired the key in the first place, or re-attempted and acquired it. A durable claim never existed, so nothing is left behind and B performs the operation normally.

There is a third outcome the two-statement form forces you to handle, and most implementations forget it: zero rows claimed, zero rows found. B's INSERT skipped because of a conflicting row that its subsequent SELECT cannot see — the conflicting transaction had not committed at that snapshot. The correct response is retry, not error and not execute. Re-attempt the whole transaction after a short delay; the next attempt either claims the key or reads the winner's row.

That retry loop is the honest price of ON CONFLICT DO NOTHING. The alternatives:

StrategyBlockingRecovery cost
ON CONFLICT DO NOTHING + SELECT + bounded retrynot guaranteedextra attempt when the conflict is unresolvable in-snapshot
Plain INSERT, catch 23505blocks on the conflicting xid, by definitiontransaction is aborted; must ROLLBACK and open a new transaction to read the winner's row
pg_advisory_xact_lock on a hash of the key, then INSERTserialised per keyextra round trip; lock wait can be unbounded without lock_timeout; hash collisions serialise unrelated keys

I default to the first. It keeps one transaction doing one job and it degrades into a retry rather than an error. I reach for the advisory lock when I need deterministic ordering under heavy duplicate load and can afford the extra lock; I avoid the plain-INSERT form because an aborted transaction cannot continue, which pushes the replay read into a second transaction and doubles the number of failure points.

Compare fingerprints before replaying

Never replay before comparing. The comparison is cheap and the failure mode without it is severe: a client reuses a key with a new payload, receives the previous order's response, and believes its new order was created.

if (!Buffer.from(row.request_fingerprint).equals(fp)) {
  return { kind: "conflict" };   // 409, do not execute, do not replay
}

Buffer.equals needs both sides as buffers — bytea comes back from node-postgres as a Buffer, but be careful with any driver or ORM that coerces it to a hex string; the comparison then silently never matches or, worse, matches the wrong thing.

Also note why ON CONFLICT is not interchangeable with catching a unique violation: a 23505 inside a transaction aborts it. Every subsequent statement fails with 25P02 until you ROLLBACK. ON CONFLICT DO NOTHING keeps the transaction usable, which is what lets the fingerprint check and the replay read happen on the same connection without an extra transaction.

Commit the order and replayable response atomically

Use one checked-out database client for the entire transaction

pool.query() checks out a client, runs one statement, and returns it. Two pool.query() calls can land on two different connections, which means two different sessions, which means the BEGIN applies to a transaction nobody else is in.

Every statement in the unit of work must go through one client:

const client = await pool.connect();
try {
  await client.query("BEGIN ISOLATION LEVEL READ COMMITTED");
  await client.query("SET LOCAL lock_timeout = '2s'");
  await client.query("SET LOCAL statement_timeout = '5s'");
  // claim → lookup → insert order → complete → COMMIT, all on `client`
} finally {
  client.release();
}

SET LOCAL scopes the timeouts to this transaction and they revert on commit or rollback, so a pooled connection never leaks a short lock_timeout into unrelated work.

Serialize the response before COMMIT

This is the step that makes the whole design work, and it is the one people skip. Generate the order ID in Node, insert, read back the authoritative created_at from the database, serialize the response body, and store the bytes — all before COMMIT.

const orderId = randomUUID();

const inserted = await client.query(
  `INSERT INTO orders (id, account_id, merchant_order_ref, sku, quantity, amount_cents, currency)
   VALUES ($1, $2, $3, $4, $5, $6, $7)
   RETURNING created_at`,
  [orderId, accountId, order.merchantOrderRef, order.sku, order.quantity, order.amountCents, order.currency]
);

const payload = Buffer.from(JSON.stringify({
  id: orderId,
  status: "created",
  sku: order.sku,
  quantity: order.quantity,
  amountCents: order.amountCents,
  currency: order.currency,
  createdAt: inserted.rows[0].created_at.toISOString(),
}), "utf8");

await client.query(
  `UPDATE idempotency_keys
      SET state = 'completed',
          response_status = $2,
          response_body = $3,
          response_headers = $4::jsonb,
          order_id = $5,
          completed_at = now()
    WHERE id = $1`,
  [claimId, 201, payload, JSON.stringify({ "content-type": "application/json; charset=utf-8" }), orderId]
);

await client.query("COMMIT");

Two consequences worth stating plainly:

  • If serialization throws — a circular reference, a bad toISOString() on a null — the transaction rolls back and the order does not exist. A committed order without a replayable result is worse than no order, because every subsequent retry either duplicates or lies.
  • The stored bytes are the response. Not a description of it, not a re-derivable projection. A replay does not re-run the serializer.

Separate transactional work from HTTP delivery

The handler's shape is the argument:

const committed = await runIdempotent(accountId, OPERATION, key, fp, order); // may throw
if (committed.kind === "conflict") return send(res, 409, { error: "idempotency_key_reused" });

maybeDropAfterCommit(req);        // test hook only, see below
sendStored(res, committed);       // delivery: best effort, no rollback path

Everything above the sendStored line either produced a committed, replayable result or threw before committing. Everything below it is delivery. There is no code path from a socket error back into the transaction, because the transaction is over and the variables holding it are out of scope.

Attach an error listener to the response so a late EPIPE cannot take down the process:

res.on("error", (err) => {
  console.error(JSON.stringify({ event: "response_write_failed", code: err.code }));
  // The database outcome is already decided. Nothing to roll back.
});

Handle database connection loss without inventing certainty

The transaction wrapper tracks where the failure happened, because that determines whether the outcome is knowable:

let phase = "before_commit";
try {
  // ...
  phase = "commit_in_flight";
  await client.query("COMMIT");
  phase = "committed";
  return { kind: "new", status: 201, body: payload, headers };
} catch (err) {
  if (phase === "commit_in_flight") {
    // Unknown: the server may or may not have committed.
    throw Object.assign(err, { outcome: "unknown" });
  }
  if (phase !== "committed") {
    try { await client.query("ROLLBACK"); } catch { /* socket may be gone */ }
  }
  throw Object.assign(err, { outcome: phase === "committed" ? "committed" : "aborted" });
} finally {
  client.release(phase === "committed" ? undefined : true);
}

Three rules encoded there:

  1. A COMMIT that was sent and not acknowledged is unknown. Not failed. The handler maps it to 503 with an instruction to retry with the same key.
  2. A connection lost before COMMIT was sent is aborted. PostgreSQL ends the transaction when the backend notices the dead client, so no commit can happen afterwards.
  3. Discard the client. client.release(true) destroys it rather than returning it to the pool. A connection whose transaction state is unknown must never be handed to the next request; you would be handing on a session that might still hold locks or an open transaction.

The 503 body matters as an API contract:

{ "error": "outcome_unknown_retry_same_key", "retryWith": "same-idempotency-key" }

A client that reads that and generates a new key has ignored the instruction. A client that follows it gets the stored result if the commit landed, or a fresh execution if it did not. That is the whole recovery mechanism, and it is one sentence of contract plus one database row.

Define which failures consume a key

Be explicit, because "every error is cached" is a claim that quietly breaks clients:

FailureKey consumed?Why
Malformed JSON / invalid key headerno — rejected before BEGINnothing was attempted; the request never entered the idempotent path
Schema validation failure (422)nodeterministic; retrying the same body fails identically
Unexpected transactional errorno — rolled back, claim gonenothing durable happened; a retry should be able to execute
23505 on orders_business_uniquenothe transaction aborts, so the completion UPDATE cannot run; the rejection is deterministic and re-derives on retry
Success (201)yes — row completedthe replay record is the point
COMMIT unacknowledgedunknown — resolve on retrythe key is the only way to find out

The fourth row is the one that surprises people. Persisting a deterministic business rejection as a stored response requires writing the rejection record after rolling back the failed attempt, in a separate transaction — which reintroduces exactly the non-atomic window this article is about. For deterministic rejections that re-derive identically from the same input, not caching them is the right trade, and it is why the worked example does not store 409s or 422s.

Demonstrate the committed-write, failed Node.js response case

Every output in this section is labelled expected. The harness asserts each one; the numbers are what the assertions require, not a pasted transcript.

Establish the baseline request and persisted state

curl -sS -D headers.txt -o body.json -X POST http://127.0.0.1:3100/orders \
  -H 'content-type: application/json' \
  -H 'idempotency-key: 0b1f2c3d-4e5f-4a6b-8c9d-0e1f2a3b4c5d' \
  -d '{"merchantOrderRef":"lab-order-001","sku":"SKU-RED-42","quantity":1,"amountCents":2599,"currency":"USD"}'

cat body.json

Expected:

{"id":"<uuid>","status":"created","sku":"SKU-RED-42","quantity":1,"amountCents":2599,"currency":"USD","createdAt":"<iso8601>"}
SELECT count(*) FROM orders WHERE account_id = 'acct_lab_0001';            -- expected: 1
SELECT state, response_status, octet_length(response_body) AS bytes
  FROM idempotency_keys WHERE key = '0b1f2c3d-4e5f-4a6b-8c9d-0e1f2a3b4c5d';
-- expected: completed | 201 | <n>

Drop the HTTP connection immediately after COMMIT

The hook is deliberately narrow: it fires only when an environment flag is set and the peer is loopback, so it cannot be repurposed against real traffic.

function maybeDropAfterCommit(req) {
  if (process.env.LAB_DROP_AFTER_COMMIT !== "1") return false;
  const peer = req.socket.remoteAddress ?? "";
  const loopback = peer === "127.0.0.1" || peer === "::1" || peer === "::ffff:127.0.0.1";
  if (!loopback) return false;
  req.socket.destroy();     // no response bytes are written
  return true;
}

It runs after runIdempotent returns, so the transaction has committed and no response has been emitted. Restart with LAB_DROP_AFTER_COMMIT=1 and resend with a fresh key:

LAB_DROP_AFTER_COMMIT=1 node server.js
curl -sS -X POST http://127.0.0.1:3100/orders \
  -H 'content-type: application/json' \
  -H 'idempotency-key: 7c9e6679-7425-40de-944b-e07fc1f90ae7' \
  -d '{"merchantOrderRef":"lab-order-002","sku":"SKU-RED-42","quantity":1,"amountCents":2599,"currency":"USD"}'

Expected on the client:

curl: (52) Empty reply from server

Depending on how the socket is torn down this can surface as (56) Recv failure: Connection reset by peer. Both are transport errors and both mean the same thing to your client code: unknown outcome.

Expected in the database — the point of the exercise:

SELECT count(*) FROM orders WHERE merchant_order_ref = 'lab-order-002';     -- expected: 1
SELECT state, response_status FROM idempotency_keys
 WHERE key = '7c9e6679-7425-40de-944b-e07fc1f90ae7';                        -- expected: completed | 201

The client saw an error. The order exists. A handler without the replay record would now be one retry away from a duplicate.

Retry the same key and recover the stored response

Restart without the hook and resend the identical request with the identical key.

curl -sS -D headers2.txt -o body2.json -X POST http://127.0.0.1:3100/orders \
  -H 'content-type: application/json' \
  -H 'idempotency-key: 7c9e6679-7425-40de-944b-e07fc1f90ae7' \
  -d '{"merchantOrderRef":"lab-order-002","sku":"SKU-RED-42","quantity":1,"amountCents":2599,"currency":"USD"}'

grep -i '^x-idempotent-replay' headers2.txt    # expected: x-idempotent-replay: true
sha256sum body2.json
psql "$DATABASE_URL" -At -c \
  "SELECT encode(sha256(response_body), 'hex') FROM idempotency_keys
    WHERE key = '7c9e6679-7425-40de-944b-e07fc1f90ae7'"

Expected: both hashes are identical, and

SELECT count(*) FROM orders WHERE merchant_order_ref = 'lab-order-002';    -- expected: 1

Byte equality is the assertion that matters. Any re-serialisation — a different date format, a re-ordered field — would show up here as two hashes.

Demonstrate what a new key changes

Same payload, different key:

curl -sS -o /dev/null -w '%{http_code}\n' -X POST http://127.0.0.1:3100/orders \
  -H 'content-type: application/json' \
  -H 'idempotency-key: 5d41402a-bc4b-4a1e-9f2c-1f0e2d3c4b5a' \
  -d '{"merchantOrderRef":"lab-order-002","sku":"SKU-RED-42","quantity":1,"amountCents":2599,"currency":"USD"}'

Expected: 409 — not a duplicate order, because orders_business_unique catches the repeated merchantOrderRef. Remove that constraint and the same command returns 201 with a second order row.

That is the clearest possible demonstration of why the key is a request-deduplication primitive and not a business rule. orders_business_unique is what stops the second logical order; the idempotency key is what stops the second retry of the first one. Change the key on every network retry and you have disabled the second mechanism entirely.

Keep the experiment's conclusion precise

What this experiment demonstrates is a lost response after a known commit. The commit succeeded, the handler knew it, and the socket write never happened. That is Case 1 from earlier.

What it does not demonstrate is a lost COMMIT acknowledgement. To test Case 2 you must break the connection during the COMMIT round trip — via a proxy that blackholes the response, or iptables/tc on loopback, or by killing the backend mid-commit. I have not run that experiment, and I am not going to describe its output. If you build it, the assertion is not "the client got an error" but "a SELECT on a fresh connection resolves whether the order exists, and a same-key retry converges to exactly one order either way." That convergence is the property under test.

Test concurrency and rollback instead of stopping at the happy path

Launch simultaneous duplicates from a JavaScript test harness

node test-run.js with a batch of identical in-flight requests. Node 22's global fetch keeps connections alive, so these genuinely overlap.

const N = 20;
const key = "b1946ac9-2d8f-4c1a-9e77-3f0c2a6b8d41";
const payload = JSON.stringify({
  merchantOrderRef: "lab-order-101", sku: "SKU-RED-42",
  quantity: 1, amountCents: 2599, currency: "USD",
});

const responses = await Promise.all(Array.from({ length: N }, () =>
  fetch("http://127.0.0.1:3100/orders", {
    method: "POST",
    headers: { "content-type": "application/json", "idempotency-key": key },
    body: payload,
  })));

const statuses = responses.map((r) => r.status);
const bodies = await Promise.all(responses.map((r) => r.text()));
const replays = responses.map((r) => r.headers.get("x-idempotent-replay"));

console.log({ statuses: [...new Set(statuses)], distinctBodies: new Set(bodies).size,
              newCount: replays.filter((v) => v === "false").length });

Expected:

{ statuses: [ 201 ], distinctBodies: 1, newCount: 1 }

Then assert on the database, not on the HTTP surface:

SELECT count(*) FROM orders WHERE merchant_order_ref = 'lab-order-101';   -- expected: 1
SELECT count(*) FROM idempotency_keys WHERE key = 'b1946ac9-...';         -- expected: 1
SELECT state FROM idempotency_keys WHERE key = 'b1946ac9-...';            -- expected: completed

newCount: 1 is the interesting number. It says exactly one of the twenty requests performed the operation and nineteen replayed. If you see newCount greater than one, the claim is broken; if you see fewer 201s than requests, the retry loop is too short for the contention you are generating.

Race different payloads under the same key

Two valid bodies, one key, submitted concurrently:

const a = JSON.stringify({ merchantOrderRef: "lab-order-201", sku: "SKU-RED-42", quantity: 1, amountCents: 2599, currency: "USD" });
const b = JSON.stringify({ merchantOrderRef: "lab-order-202", sku: "SKU-BLU-42", quantity: 2, amountCents: 5198, currency: "USD" });

Expected: one 201 and one 409, and exactly one matching order row.

Do not assume which one wins — it is a race, and a test that hardcodes the winner is flaky. Assert on the set: {201, 409}, plus SELECT count(*) FROM orders WHERE merchant_order_ref IN ('lab-order-201','lab-order-202') equals 1, plus the stored request_fingerprint matches whichever payload was accepted.

Inject a failure before COMMIT

if (process.env.LAB_FAIL_BEFORE_COMMIT === "1") {
  throw new Error("LAB_FAIL_BEFORE_COMMIT injected");   // after the orders INSERT, before completion
}

Because the throw happens inside the open transaction, PostgreSQL aborts it and the claim row disappears with everything else.

SELECT count(*) FROM orders WHERE merchant_order_ref = 'lab-order-301';    -- expected: 0
SELECT count(*) FROM idempotency_keys WHERE key = 'lab-key-301';           -- expected: 0

Restart without the flag and resend with the same key: expected 201, one order, one completed row. This is the other half of the argument — a key must not be consumed by a failure that left nothing durable behind. If the claim row survived the rollback, the client would be permanently locked out of an operation that never happened.

Test independent scopes and unrelated keys

Two claims to verify:

  1. Scopes are isolated. With LAB_ALLOW_ACCOUNT_HEADER=1 (test-only; the header is never trusted otherwise), create under acct_lab_0001, then replay the same key under acct_lab_0002. Expected: 201 or 202 from a fresh execution for the second account — never a copy of the first account's response.
  2. Keys are independent. Two different keys, same account, same payload: expected both 201, two order rows — unless orders_business_unique rejects the second, in which case one 201 and one 409 from the business constraint. Check which constraint fired; 23505 on orders_business_unique is not the same event as a fingerprint conflict.

That second case deserves attention: idempotency made it harder to see that a client was creating duplicate logical orders, because both requests were "legitimate" under their own keys.

Present a failure matrix with database assertions

ScenarioHTTP resultOrdersKey rowEvidence type
Normal create2011completedautomated assertion
20 concurrent duplicates201 × 20, one x-idempotent-replay: false11, completedautomated assertion
Same key, different payload201 + 40911, fingerprint of winnerautomated assertion
Failure before COMMIT50300automated assertion
Response dropped after COMMITclient transport error11, completedautomated assertion via hook
Retry after dropped response201, byte-identical body11, completedautomated assertion (hash comparison)
New key, same business ref40912automated assertion
COMMIT acknowledgement lost503 outcome_unknown_retry_same_key0 or 10 or 1not exercised — requires connection fault injection mid-commit
Committed in_progress row observed500 invariant violation—1, in_progressnot exercised — requires a deliberate out-of-band insert

The last two rows are the ones I would want in CI before shipping, and they are the two this walkthrough does not demonstrate. Say so in your own design doc rather than letting the green test suite imply coverage it does not have.

Bound the operational cost of retry safety

A correct design that nobody sizes is an outage waiting for a traffic spike. Retry safety has real costs, and they belong in the design rather than in the incident review.

Put limits on lock waits and transaction duration

Duplicate requests hold connections while they wait for the winner. With a pool of 10 and a client retry storm, you can consume the whole pool on requests that are all waiting for one transaction to finish — a self-inflicted stampede.

SET LOCAL lock_timeout = '2s';
SET LOCAL statement_timeout = '5s';

Set lock_timeout deliberately below your client's own timeout so PostgreSQL gives up first and you get a clean, retryable error instead of a client that gives up while the server keeps working. When a duplicate times out on the lock, return 503 with the same instruction: retry with the original key. Do not return 409 — nothing conflicted, you just refused to wait.

Also set idle_in_transaction_session_timeout on the role. A handler that opens a transaction and then awaits an unrelated HTTP call will otherwise hold the claim row — and its locks — for the duration of that call.

Define retention as part of the API contract

DELETE FROM idempotency_keys
 WHERE state = 'completed' AND completed_at < now() - interval '24 hours';

That statement is a contract change, not housekeeping. Deleting a record makes its key executable again: a client that retries after the window elapses performs the operation a second time. So:

  • Pick the window from your supported retry behaviour, not from disk pressure. If clients retry over 72 hours, a 24-hour window is a bug.
  • Only delete completed rows. An in_progress row is either invisible (uncommitted) or an invariant violation; deleting the violation hides the evidence.
  • Never delete a row whose transaction is still open. Uncommitted rows are invisible to the cleanup query anyway, so a plain DELETE cannot race an active claim — but a cleanup job that uses SELECT then DELETE across statements can.
  • Document it. "Keys are honoured for 24 hours" belongs in the API docs next to the retry guidance.
💪

If you cannot state your retention window in the API documentation, you do not have an idempotency contract — you have a best-effort cache that happens to sit in a database.

Limit and protect stored responses

You are storing a copy of every response body. That is a new data store with new obligations.

  • Bound everything. Key length (255 in the schema), request body size (64 KB in readJson), response size (octet_length(response_body) <= 65536). An unbounded body column is how a single client with a large response turns into a disk incident.
  • Allowlist headers on the way out. content-type, content-language, content-location. Never set-cookie, never authorization echoes, never location with a signed URL inside it.
  • Minimise the payload. Store what the client was told, not the full internal representation. If the response includes a customer email, that email now lives in your idempotency table with your idempotency table's retention policy.
  • Apply the same access controls. Row-level security, encryption at rest, and audit logging where your business data requires them — because this table is business data.

Instrument outcomes without logging secrets

Six counters, one structured log line per attempt:

console.log(JSON.stringify({
  event: "idempotency_attempt",
  request_id: reqId,
  key_digest: createHash("sha256").update(`${accountId}:${key}`).digest("hex").slice(0, 16),
  outcome: "new" | "replay" | "fingerprint_conflict" | "retry_contention" | "rollback" | "commit_unknown",
  attempt,
  duration_ms: Date.now() - startedAt,
}));

Track, as counters or metrics:

  • new operations vs replays — the replay ratio tells you whether clients are retrying too aggressively
  • fingerprint conflicts — a spike means a client is generating keys incorrectly
  • lock waits and contention retries — pool pressure before it becomes saturation
  • rollbacks and unknown commit outcomes — unknown outcomes should be rare and alertable

Log a key digest, never the raw key: the key is a bearer-ish credential for reading a stored response if anything upstream trusts it. Never log the response body. Correlate by request_id, and keep key_digest stable enough to count distinct keys without being reversible.

Extend the design carefully beyond one PostgreSQL transaction

The local guarantee is real and narrow. Two extensions break it if you assume it carries over.

Use an outbox for work that cannot join the transaction

Charging a payment provider inside the handler is not made atomic by the idempotency table. The charge either succeeds or fails outside your database, and no COMMIT in your process can include it. Wrapping the call in the same transaction gives you the illusion of atomicity with none of the guarantees — the local transaction can roll back after the card was charged.

The workable pattern is an outbox row written in the same transaction as the order:

CREATE TABLE outbox (
  id           bigserial PRIMARY KEY,
  topic        text NOT NULL,
  payload      jsonb NOT NULL,
  created_at   timestamptz NOT NULL DEFAULT now(),
  dispatched_at timestamptz
);

Order and outbox event commit together or not at all. A separate dispatcher reads undispatched rows, calls the payment provider, and marks them dispatched. That dispatcher must still be idempotent at the downstream boundary — a provider-side idempotency key, a deduplication table on the consumer — because the dispatcher can crash after charging and before marking the row. Your local idempotency table cannot deduplicate a charge made by a retrying dispatcher; only the downstream system can.

So the guarantee becomes: at most one order per key, at least one dispatch attempt per outbox row, and the downstream system is responsible for collapsing those attempts.

Keep business uniqueness separate from request deduplication

Two different keys can describe the same prohibited action. A client that crashes before persisting its key, then generates a new one, produces two keys for one intent — and the idempotency table will faithfully execute both.

That is why orders_business_unique exists. Request deduplication protects against retries; a domain constraint protects against intent. Conflating them produces one of two failures:

  • Only idempotency keys: a key-regenerating client creates duplicate orders, and nothing stops it.
  • Only a domain constraint: a legitimate retry hits 23505 and the client has no way to tell "you already did this" from "someone else took this reference."

You probably need both. And when the domain constraint fires inside the transaction, the conflicting insert aborts it — so the rejection cannot be stored as a replay record in that same transaction. The 409 for a duplicate business reference is therefore not cached under the key, which means a retry re-executes and re-derives the same rejection. That is acceptable for a deterministic constraint, and it is worth writing down as policy rather than discovering it under load.

Conclusion — A failed response is not evidence of a failed write

A COMMIT that succeeded and a response that never arrived are two facts about two different systems, and only one of them is durable. Everything in this article follows from refusing to collapse them into a single "it failed" boolean.

The position: if your handler can return an error for an operation that committed, the client cannot retry safely, and no amount of client-side sophistication fixes it. The server has to be able to answer "what did this request do?" from its own committed state, which means the answer must be written in the same transaction as the doing.

Close with the implementation checklist

  • Identity from verified credentials; key scoped to (account_id, operation, key).
  • Validate and canonicalise before hashing; fixed field order, no raw-body hashing.
  • Claim with INSERT ... ON CONFLICT DO NOTHING RETURNING against a unique constraint, not a SELECT-then-INSERT.
  • Follow-up SELECT as a separate statement under READ COMMITTED; never a data-modifying CTE with a fallback read.
  • Handle the third outcome: zero claimed, zero found → bounded retry.
  • Compare fingerprints before replaying; mismatch is 409, never a replay.
  • One checked-out client for BEGIN, claim, insert, completion, COMMIT.
  • Serialize the response before COMMIT and store the bytes.
  • Send only after commit; no code path from a socket error back into the transaction.
  • Treat an unacknowledged COMMIT as unknown; 503 with "retry same key"; destroy the client.
  • lock_timeout, statement_timeout, idle_in_transaction_session_timeout set deliberately.
  • Retention window documented in the API contract.
  • Assert on database state in tests, not just HTTP status.

The last item is the one that separates a working implementation from a plausible one. A test that only checks 201 passes against a handler that creates three orders. SELECT count(*) FROM orders does not.

Further Reading

Cite PostgreSQL's primary documentation for concurrency and transactions

Cite the client and HTTP behavior used by the example

  • node-postgres: Transactions — the pool.connect() / client.release() model, and why every statement in a transaction must use the same client.
  • Node.js 22 http module — server request and response lifecycle, socket errors, and writableEnded/destroyed semantics used in the delivery helpers.

These are API references. They document the behaviour the walkthrough relies on; they are not evidence that the experiments above were executed on your machine. Run node test-run.js and check the assertions.

Share this post

More posts

Loading comments…