Skip to main content

Chapter 25 — Idempotency, Delivery Semantics & the Exactly-Once Myth

Part V · Distributed Systems, Messaging & Scale | Prerequisites: Ch 23–Ch 24 | Builds: idempotent claim-submission and clearinghouse-webhook handlers for Pulsely

Earlier we waved a hand at it — "make your POST idempotent with an idempotency key, we'll explain later." We said it again about webhooks: "the clearinghouse retries, so dedup on the event id, more on that later." This is later.

When you call a normal function, it either runs or it doesn't. Over a network there's a third possibility: it might have run, and you may never find out. The network can lose your request, lose the reply, delay either, or send either twice — and a timeout looks identical in every case, so you can't tell which one happened. That is the hard truth the theory chapters earned, and from that single fact everything in this chapter falls out by force.

Here is the chain of reasoning the whole chapter defends, stated up front so you can hold it: reliable systems retry (a request with no answer must be resent, or you lose work). Retrying means at-least-once delivery (the original might have landed; now you've sent it twice). At-least-once means duplicates are an ambient condition, not a bug — they will arrive, forever, no matter how good your code is. So correctness cannot come from preventing duplicates. It has to come from making the duplicate do nothing. That property is idempotency, and this chapter derives it from first principles, builds it into Pulsely's two most expensive endpoints — claim submission and the clearinghouse webhook — and then dismantles the most expensive myth in the field: that a message broker can hand you exactly-once delivery. It can't. Nobody can. What you can have is something humbler and entirely sufficient, and learning the difference is the difference between a senior engineer and someone repeating a vendor's slide.


1. The problem: the duplicate you cannot prevent​

It's 2 a.m. and the pager goes off. A patient is furious: they were billed twice for a single office visit. Two claims, C-88412 and C-88419, same patient, same encounter, ninety seconds apart, two claim rows, two 837 transmissions to the clearinghouse, two patient-responsibility balances. Support escalates because the patient is threatening to report a double-billing to the state and leave a one-star review. You pull the logs expecting to find a bug — a loop, a retry gone wrong in your code — and instead you find something worse, because it isn't a bug at all: both submissions succeeded. Two clean POST /claims, two 201s, two valid claims. The server did exactly what it was told, twice.

Here's what actually happened, reconstructed from the client's logs. The biller tapped Submit claim. The tablet opened a connection, sent POST /claims, and the server processed it: created the claim, generated the 837, handed it off to the clearinghouse, started writing the 201 response. But the biller was walking the claim through the clinic on a tablet, and the wifi dropped in the back hallway — the kind of dead zone every hospital and clinic has. The response packet — the only evidence that the submission succeeded — never made it back to the tablet. The HTTP client has an 8-second timeout. At 8.0 seconds, having heard nothing, it did the only sane thing a reliable client can do: it retried. Same request, fresh connection. The second one sailed through cleanly and got its 201. The screen showed success. The biller, who'd watched a spinner for eight seconds and assumed the first tap "didn't take," had also tapped again. Now there are two claims and the biller remembers tapping twice, so they don't even believe you when you say the software submitted once.

Stare at the failure, because it is the whole chapter. The client could not distinguish "my request was lost" from "the response was lost." In both cases the symptom is identical: silence past the deadline. In the first case retrying is correct and necessary — without it the claim is silently never submitted and the practice never gets paid. In the second case retrying is a disaster. The client has no way to tell them apart, so a client that wants to never-lose-a-claim must retry, which means it must sometimes double-submit. You cannot fix this on the client. You cannot fix it with a better timeout. You cannot fix it with a more reliable network, because "more reliable" is not "perfectly reliable," and the gap between those two is exactly where this lives. (The very same read-check-write race shows up wherever a finite resource meets concurrency: two front-desk staff grabbing the same 9:00 slot, a duplicate e-Rx, a double-submitted claim — all one shape.)

Now the second variant, because money has more than one door. Pulsely gets paid through a clearinghouse — the intermediary that routes your claims to payers and routes the payers' responses back to you. It tells you about accepted claims, denials, and remittances (the 835, the electronic "explanation of payment") via webhooks — it POSTs an event to your /webhooks/clearinghouse endpoint. Read any clearinghouse's integration docs and you'll find this sentence, verbatim in spirit across every real one: "We may send the same event more than once. Your endpoint must be idempotent." They are not apologizing for a flaw; they are describing physics. Their webhook sender has the exact same problem your tablet client has — it POSTs remittance.posted, your server processes it and starts to return 200, the 200 is lost, and their sender, having heard nothing, retries. Your handler ran twice. The first time it posted the remittance, inserted a ledger row, reduced the claim's outstanding balance, and notified the billing team "Claim paid." The second time it did all of that again: a duplicate ledger row that makes the RCM books not balance, a double balance reduction, and a second confusing notification. The remittance itself was idempotent at the clearinghouse (they dedup the payload on their side), but your side effects weren't, and that's where the damage landed.

🧭 Mental model. You are not trying to prevent the duplicate from arriving. That fight is unwinnable; the duplicate is built into the medium. You are trying to make the duplicate boring — to design the handler so that the second, third, and fiftieth copy of a request leave the system in exactly the same state as the first, with no extra claims, no extra ledger rows, no extra notifications. The duplicate still arrives. It just doesn't do anything.

Why this chapter lands now, right after the theory chapters, is not an accident of ordering. Everything you added for reliability earlier — retries with backoff, read-after-write routing, and the queues and async handlers coming soon — is also a duplicate-generation machine. Every retry you add to survive a lost message is a machine for occasionally delivering that message twice. And in a clinical system the stakes run past accounting: the same retry that duplicates a claim can duplicate an e-Rx sent to a pharmacy or a medication order on the floor, where a second copy is a patient-safety event, not an accounting one. Idempotency is not an optional polish layer. It is the tax you pay for having a reliable system at all. Skip it and your "reliability" features are quietly corrupting your data — and occasionally your patients' charts — every time the network hiccups.


2. The mental model: converge, don't accumulate​

Reframe every state-changing handler you will ever write with one question: if this runs twice, does the system converge or does it accumulate?

A handler converges when running it again lands you on the same final state. set claim #C-4471 status to SUBMITTED converges — run it once, it's submitted; run it again, it's still submitted, no change. A handler accumulates when each run adds something. insert a new claim row, transmit an 837 to the clearinghouse, post a $180 charge to the ledger, balance = balance + 10 — every one of these piles up under repetition. Two runs, two claims; fifty runs, fifty rows. The single most useful instinct this chapter can give you is to feel the difference between a converging operation and an accumulating one the moment you write it, because the accumulating ones are precisely the operations that retries turn into bugs.

The formal version is one line, and it's worth memorizing because it's the definition interviewers want: an operation f is idempotent if f(f(x)) = f(x) — applying it any number of times (N ≥ 1) leaves the system in the same state as applying it once. SUBMITTED is idempotent. += 1 is not. Most of the work in this chapter is converting the accumulating operations you actually need (you genuinely must create a claim and transmit an 837) into a shape that behaves idempotently from the outside, even though the underlying write is destructive.

The second model you must hold is a clean split that careless writing constantly blurs. There are two layers, and conflating them is the root of most confusion in this whole field:

DELIVERY layer │ EFFECT (processing) layer
"how many times does the message │ "how many times does the SIDE EFFECT
arrive at my process?" │ actually land in my state?"
│
- controlled by the network/broker │ - controlled by YOUR handler
- you almost NEVER control it │ - you ALWAYS control it
- duplicates here are unavoidable │ - duplicates here are a choice you made

Delivery is how many times the bytes show up at your door — set by the network, the client's retry policy, the broker. You have almost no control over it; the duplicate claim submission arrived, twice, and nothing you do at the handler changes that. Effect is how many times the consequence lands — a row written, a claim transmitted, a notification sent. That you control completely. The entire discipline of this chapter is: stop fighting the delivery layer; win at the effect layer. Let duplicates arrive freely; ensure exactly one of them has an effect.

The machinery that does this has a simple shape — a memory gate in front of the side effect:

request ──▶ ┌────────────────────────┐
│ "have I seen this │── yes, already done ──▶ replay the stored result
│ key before?" │
│ (a dedup memory, │── no, first time ─────▶ do the work, REMEMBER the
│ keyed by something │ key + the outcome, respond
│ stable across retries)│
└────────────────────────┘

The gate is keyed by something that stays the same across retries of the same logical request (a UUID the client minted once, the clearinghouse's event.id) and different across genuinely-different requests. On a miss, do the work and record both the key and what happened. On a hit, don't do the work again — replay what you recorded. That's it. Everything else in this chapter is making that gate atomic, durable, and correct under concurrency, because the naive version of it is a race condition wearing a helpful disguise.

🔑 The single-effect invariant. For a given idempotency key, at most one committed side effect may exist. That sentence is the load-bearing beam of the entire chapter. Every table, transaction, fencing token, and TTL we build exists to uphold it. When you're lost in the mechanics later, come back and ask: does this design still guarantee at most one committed effect per key? If you can't answer yes, the design is wrong.

One more distinction, because three different ideas get jammed under the word "idempotent" and senior engineers keep them separate. Deduplication drops the second copy before it runs (the gate above). An idempotent effect lets the second copy run because running it is a harmless no-op (UPDATE ... SET status='paid' WHERE status='pending' updates zero rows the second time). Commutativity means order doesn't matter (add problem X then add problem Y = add Y then add X). They overlap but they are not the same, and a design that needs commutativity but only has dedup will still corrupt under reordering. We'll hit all three; just don't let the vocabulary fool you into thinking one technique covers all three problems.


3. Theory & invariants​

Idempotency is a property of semantics, not of HTTP​

You've read that GET, PUT, and DELETE are "idempotent" and POST is not. That is a statement about what those verbs are supposed to mean, and it is a contract you are obligated to honor — not a guarantee the framework enforces for you. PUT /claims/C-4471 {status: "submitted"} is idempotent if you implement it as a set-to-value; nothing stops you from writing a PUT handler that appends a row every call, and then your "idempotent" verb accumulates. DELETE /claims/C-88412 is idempotent if deleting an already-deleted claim is a no-op 204 rather than a 404-then-error. The verb tells callers what to expect; honoring it is on you. POST is labeled non-idempotent precisely because "create a new thing" naturally accumulates — which is exactly why POST /claims is the dangerous one and why it's the endpoint we'll spend the most ink making safe.

The delivery-semantics vocabulary, stated precisely​

Three terms, and you must be able to define each crisply because interviews probe exactly here:

  • At-most-once. Send and forget; if the message is lost, it's gone, and you never retry. Zero duplicates, possible loss. Acceptable for things where a miss is cheap: a "dashboard widget rendered" UI-telemetry ping, a best-effort cache invalidation. (The healthcare exception worth flagging: a chart view looks like a fire-and-forget analytics event, but HIPAA makes every view an auditable record — that one you must not drop, which is why the audit log runs at-least-once, never at-most-once.)
  • At-least-once. Send, wait for an ack, and retry until you get one. Never lose a message, but you may deliver it more than once (every lost-ack becomes a duplicate). This is the default posture of every reliable system, and therefore the world you must design your handlers to survive.
  • "Exactly-once." The message arrives precisely once — no loss, no duplication. It is in scare-quotes everywhere in this chapter because, at the delivery layer, it does not exist. It is a marketing term for a combination of weaker things, and the next section is its eulogy.

The exactly-once-delivery myth​

Here is the central thesis, and you should be able to defend it cold:

Exactly-once delivery is impossible across an unreliable network. Effectively-once processing is achievable, and it's all you ever needed.

The impossibility has a one-line intuition that you can reconstruct in an interview without invoking any heavy theorem. Suppose the sender wants to deliver a message exactly once. It sends the message and waits for an ack — because without an ack it can't know whether to retry. But the ack can be lost just as easily as the message. So now: if the sender gets no ack, did the receiver get the message (and the ack was lost) or not (and the message was lost)? It cannot tell. If it retries, it risks a duplicate. If it doesn't, it risks a loss. No finite exchange of messages closes this gap — every protocol bottoms out in "someone sent the last message and doesn't know if it arrived." This is the Two Generals problem, and it is not an engineering limitation that better hardware fixes; it is a property of communicating over a channel that can drop messages. (It's a close relative of another famous result, FLP: if a network can drop or delay messages, no protocol can guarantee that two parties reliably agree on anything — the same wall, seen from a different angle.)

So if delivery can't be exactly-once, what can be? Effectively-once processing, defined precisely as:

effectively-once processing = at-least-once delivery + idempotent / dedup'd effect
(let duplicates arrive) (make duplicates do nothing)

You give up on the impossible goal (one delivery) and combine two achievable things: a delivery layer that never loses (retry until acked, accepting duplicates) and an effect layer that converges (the second delivery commits nothing new). The observable result is identical to exactly-once — one claim, one remittance, one notification — even though the message was delivered twice. The myth dies not because exactly-once outcomes are impossible, but because you achieve them at the effect layer, never the delivery layer.

Natural vs synthetic keys​

The dedup gate needs a key that's stable across retries. Two sources:

  • Natural key — a domain value that's already unique and already in the request. The clearinghouse's event.id on a webhook. A claim control number the payer echoes back. A device reading's device_id + timestamp on an RPM stream. It's free (you didn't have to invent a carrying mechanism) but it only exists when the domain happens to provide one, and keying on it couples your dedup to schema assumptions.
  • Synthetic key — a token generated solely to deduplicate, carried in an Idempotency-Key header (a UUID the client mints once per logical request and reuses across that request's retries). Works for any endpoint, decoupled from your schema — but it's only as good as the client's discipline in minting it once and reusing it.

You'll use both in Pulsely: synthetic (Idempotency-Key) for POST /claims because we control the client and claim submission has no pre-existing unique key, and natural (event.id) for the clearinghouse webhook because the clearinghouse hands us a perfectly good one.

The atomicity invariant — the one most designs get wrong​

The dedup gate from §2 has a fatal naive implementation: SELECT to check if the key exists; if not, do the work; then INSERT the key. Walk two concurrent retries through that and watch it die. Request A SELECTs — key absent. Request B SELECTs — key still absent (A hasn't inserted yet). Both proceed to "do the work." Two claims, two 837s. The check-then-act has a window between the check and the act where a second request slips through — it's a classic time-of-check-to-time-of-use race, and your dedup just created the exact duplicate it was meant to stop.

🔑 The atomicity invariant. The dedup-check and the side-effect commit must live inside the same atomic boundary — one transaction. If "have I seen this key?" and "do the work" can be observed in separate steps, two concurrent duplicates each see "no" and each do the work. The fix is to stop asking and start asserting: make the database's own concurrency control decide the winner. Insert the key first under a unique constraint; the loser of the race gets a duplicate-key error instead of a green light. The DB serializes the contenders; your if statement never could.

This builds directly on what you already know about transactions and isolation — the dedup record and the business write commit together or not at all — and it's why we'll prefer a SQL dedup table co-located with the claim write over a separate dedup store whenever the side effect is itself a database write.

Dedup windows: exactly-once within a window​

Dedup memory is finite. You cannot remember every key forever — the table would grow without bound and every lookup would slow down. So you expire keys after some window W. Which means the honest statement of the guarantee is not "exactly-once" but "exactly-once within window W." A duplicate that arrives after its key has expired sails through as if new. This is not a flaw to fix; it's a knob to set deliberately. You size W to exceed the maximum retry horizon of the caller — if a clearinghouse retries a webhook for up to three days, your webhook dedup window must be ≥ three days, or a legitimate late retry gets double-processed. The window is a probabilistic cost knob, not a correctness switch, and a senior engineer states the number and why in the design doc.

📎 Borrowed on credit: queue and broker mechanics. This chapter assumes messages get retried and redelivered, but it does not explain how a queue stores them, how visibility timeouts and acknowledgements work, how a dead-letter queue catches poison messages, or how the transactional outbox atomically bridges your database write to the queue publish. Those are the substance of Chapter 26. Here we only need the fact of at-least-once redelivery to motivate idempotency; the plumbing that produces it is the next chapter's job. Wherever you see "a retry arrives," mentally substitute "Chapter 26 will explain why it arrives."


4. Under the hood: building the idempotent handler​

Enough theory. Let's build the gate for real, in TypeScript against Postgres, the way it ships.

The dedup table​

CREATE TABLE idempotency_keys (
user_id BIGINT NOT NULL, -- the authenticated actor (biller/clinician)
idem_key TEXT NOT NULL, -- the synthetic Idempotency-Key
request_hash TEXT NOT NULL, -- hash of the request body, to catch key reuse
status TEXT NOT NULL, -- 'in_flight' | 'completed'
response_code INT, -- stored to replay the exact result
response_body JSONB,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (user_id, idem_key) -- scope per user; see §8 for why not global
);

The primary key on (user_id, idem_key) is the whole engine. It is a unique constraint, and that constraint — not any code we write — is what serializes concurrent duplicates. Note request_hash: we store a fingerprint of the original request so that if a client reuses a key for a genuinely different body (a client bug), we can detect it and refuse loudly rather than silently returning the wrong cached answer.

Insert-first, not check-first​

Here is the correct claim-creation handler. Read the comments — the ordering of operations is the entire point.

async function createClaim(req: Request, res: Response) {
const userId = req.user.id; // identity from the trust boundary
const idemKey = req.header('Idempotency-Key'); // synthetic key, minted once by the client
if (!idemKey) return res.status(400).json({ error: 'Idempotency-Key required' });

const reqHash = sha256(canonicalJSON(req.body)); // fingerprint to catch key reuse

// ONE transaction wraps BOTH the dedup gate AND the business write — the atomicity invariant.
const result = await db.tx(async (t) => {
// 1) Assert the key, don't ask about it. The unique constraint is the race referee.
try {
await t.none(
`INSERT INTO idempotency_keys (user_id, idem_key, request_hash, status)
VALUES ($1, $2, $3, 'in_flight')`,
[userId, idemKey, reqHash]
);
} catch (e) {
if (isUniqueViolation(e)) {
// We LOST the race (or this is a retry). Look at the existing record and decide.
const row = await t.one(
`SELECT * FROM idempotency_keys WHERE user_id=$1 AND idem_key=$2`,
[userId, idemKey]
);
if (row.request_hash !== reqHash) {
return { code: 422, body: { error: 'Idempotency-Key reused with a different body' } };
}
if (row.status === 'completed') {
return { code: row.response_code, body: row.response_body }; // REPLAY, do no work
}
return { code: 409, body: { error: 'request already in progress' } }; // in-flight duplicate
}
throw e;
}

// 2) We WON the race. Do the real, accumulating work — exactly once, inside this tx.
const claim = await createClaimForEncounter(t, userId, req.body);

// 3) Remember the outcome so future retries replay instead of re-executing.
await t.none(
`UPDATE idempotency_keys
SET status='completed', response_code=201, response_body=$3
WHERE user_id=$1 AND idem_key=$2`,
[userId, idemKey, claim]
);

return { code: 201, body: claim };
});

res.status(result.code).json(result.body);
}

The crucial move is step 1. We do not SELECT WHERE idem_key = ... and branch. We insert, and let the unique constraint reject the loser. Under fifty concurrent retries, exactly one INSERT succeeds; the other forty-nine catch the unique violation and fall into the replay/in-flight path. The database's row-level locking does the serialization that an application if could never do correctly. This is the single most important pattern in the chapter: insert-on-conflict beats check-then-act, always.

Idempotent effects via the database​

Inside createClaimForEncounter, the business writes themselves should be idempotent where they can be, as defense in depth. Two database primitives carry most of the load:

-- "create if absent" — the second run conflicts and does nothing, no error, no duplicate row.
INSERT INTO claims (id, provider_id, encounter_id, status)
VALUES ($1, $2, $3, 'submitted')
ON CONFLICT (id) DO NOTHING;

-- conditional write — a replay updates ZERO rows because the guard no longer matches.
UPDATE encounters
SET status = 'billed', claim_id = $1
WHERE id = $2 AND status = 'signed';
-- check the affected-row count: 1 = we did it; 0 = someone (maybe a replay) already billed it.

The pattern to internalize: use the affected-row count as the "did I actually do it?" signal. A conditional UPDATE ... WHERE status='signed' that touches zero rows is telling you "the encounter was already billed" — which is exactly what you want a replay to discover. (Notice the guard does double duty: it also refuses to bill an encounter that isn't signed yet, so the state machine and the idempotency come from the same clause.)

Never write balance = balance + 10 for an effect that might run twice; that's the accumulating shape. Write an absolute set guarded by a version — SET balance = :absoluteValue WHERE version = :expected — so the second run either no-ops or is rejected. If "guarded by a version" feels like new vocabulary, it isn't: this is optimistic concurrency, the same idea as an HTTP ETag / If-Match, or React Query refusing to write data that's gone stale under it. The row carries a version number, you only write if the version is what you last saw, and a retry that carries an old version updates zero rows instead of clobbering the fresher state that got there first.

Fencing tokens: defeating out-of-order replays​

Dedup handles the "same effect twice" case. It does not handle a subtler one: a stale effect arriving after a newer one. Picture a claim that was paid, then the payer issued a recoupment (a takeback — they reverse a payment they already sent). The clearinghouse sends remittance.posted (v1, paid) and later remittance.recouped (v2). The network delays the first retry of posted so badly that it arrives after recouped has already been applied. Naive dedup might let that late posted re-flip the claim to paid — overwriting the recoupment with stale truth, and now your AR says you were paid for money the payer already clawed back.

The fix is a fencing token: a monotonically increasing version attached to each state transition, with a write guard that rejects anything older than what's already applied.

UPDATE claims
SET status = $newStatus, applied_version = $incomingVersion
WHERE claim_id = $id
AND applied_version < $incomingVersion; -- reject any token <= the last applied

The late posted carries applied_version = 1; the row already shows applied_version = 2 from the recoupment; the WHERE matches zero rows; the stale write is silently and correctly dropped. This is the same fencing-token idea you met earlier for stopping a paused leader from clobbering state after a failover — here it stops a slow retry from clobbering newer state. Same primitive, different villain.

The webhook handler​

The clearinghouse webhook has its own shape because the key is natural (the provider's event.id) and there's a security step that must come first:

async function clearinghouseWebhook(req: Request, res: Response) {
// 1) VERIFY THE SIGNATURE BEFORE TRUSTING ANYTHING — incl. before trusting event.id.
if (!verifyClearinghouseSignature(req.rawBody, req.header('X-Clearinghouse-Signature'), WEBHOOK_SECRET)) {
return res.status(400).send('bad signature'); // an unsigned event.id is attacker-controlled
}
const event = req.body; // { id: 'evt_123', type: 'remittance.posted', ... }

await db.tx(async (t) => {
// 2) Dedup on the NATURAL key inside the SAME tx as the ledger write (atomicity invariant).
try {
await t.none(`INSERT INTO processed_events (event_id) VALUES ($1)`, [event.id]);
} catch (e) {
if (isUniqueViolation(e)) return; // already processed — replay is a no-op
throw e;
}
// 3) The effect, idempotent and fenced, committed atomically with the dedup record.
await applyRemittance(t, event); // ledger insert, AR reduction, notify billing — all once
});

// 4) Return 2xx FAST so the clearinghouse stops retrying. Heavy/slow work is already idempotent,
// so it's safe to do it inline or hand it to a background worker.
res.status(200).send('ok');
}

Note the ordering of defenses: signature first, dedup second, effect third, fast 2xx last. Verifying the signature before trusting event.id matters because event.id is the dedup key — if an attacker can forge events, they can poison your dedup table or replay captured events (more in §8). And the 200 must come back fast: the clearinghouse treats a slow or failed response as "delivery failed" and retries, manufacturing the very duplicates you're guarding against. Fast-ack, then let the (already-idempotent) work happen.

🏭 In production the dedup record and the business write being in one transaction is what makes a crash mid-handler safe. If the process dies after the claim is created but before the 201 is sent, the whole transaction — dedup row included — either committed (so the client's retry replays the stored result) or rolled back (so the retry does the work fresh). There is no in-between where the effect happened but the key is missing, because Chapter 17's atomicity guarantees they share a fate. The moment you split them across two transactions — or worse, across a database and a separate Redis — you reopen exactly the crash gap the design was built to close.

🛑 What we deliberately did not explain. How the queue that redelivers these messages actually stores and leases them, how acknowledgements and visibility timeouts work, and how the outbox pattern atomically gets an event from your claim transaction into that queue — all Chapter 26. How Kafka's transactional producer and consumer offsets compose into its own "exactly-once" story — Chapter 27. We used the redelivered message; we didn't build the thing that redelivers it.

The Java/JVM contrast that teaches the myth​

(Skip this aside if you never touch Kafka — the transferable payoff is the last paragraph, not the config.)

Spring gives you no built-in idempotency — you build the same idempotency_keys table and the same insert-on-conflict, just in Java. But the teaching example lives in Kafka, and it's the best one in the field. Kafka advertises "exactly-once semantics" (EOS), and it genuinely works — but before the config scares you, here's the whole trick in plain terms: Kafka is just doing the two moves you already know — a dedup gate plus one atomic commit — wired into the broker. Each message gets stamped with an id and a counter (that's the dedup key from §2), and the consumer records "I've processed up to here" — its offset, a bookmark of how far it has read — in the same commit as its output (that's the atomicity invariant from §3). With that picture, the config reads as an implementation of familiar ideas, not new magic:

  • enable.idempotence=true on the producer → the broker dedups producer retries (via a producer id + sequence number — the dedup gate).
  • a transactional producer + consumers set to read_committed → the consumer's offset commit and its output land atomically (the atomicity invariant).

It genuinely works, and it is still effectively-once, not exactly-once delivery: the dedup is by producer-id+sequence, and the atomic offset commit is the shared transaction. Kafka didn't repeal the Two Generals problem; it implemented effectively-once within its own boundary and gave it a punchier name.

Here is the line that separates senior from junior: Kafka's "exactly-once" guarantee ends the instant you write to a system Kafka doesn't control. Your consumer reads a message exactly-once from Kafka's perspective and then writes to Postgres — and that write is a fresh at-least-once hop with its own lost-ack risk, outside the transaction. If the consumer crashes after the Postgres write but before committing its Kafka offset, Kafka redelivers, and your Postgres write happens again. The EOS guarantee stopped at the broker edge. So even with Kafka EOS on, your database sink must be idempotent. "Kafka has exactly-once, so I'm safe" is the most expensive sentence in this chapter, and now you can explain precisely why it's false.


5. In production: lifecycle, windows, and the whole pipeline​

Tutorials stop at the happy path. Production is the lifecycle and the edges.

The key record is a state machine, and crashes happen mid-state. A record goes in_flight → completed → expired. The dangerous state is in_flight: a request inserted its key, started the work, and then the process died before reaching completed. Now a retry arrives, sees in_flight, and... what? You have two honest choices. Treat a fresh in_flight as a genuine concurrent duplicate and return 409 (the original is still running). Treat a stale in_flight — older than some reaping threshold, say 60 seconds past the maximum request duration — as abandoned, and let the retry take over (because the transaction that owned it rolled back on the crash, so no effect actually committed; it's safe to redo). Run a periodic reaper that deletes or resets in_flight rows older than the threshold. Skip this and a single mid-request crash leaves a key permanently stuck, silently rejecting every retry of a request that never actually completed.

new ──insert──▶ in_flight ──work done──▶ completed ──TTL──▶ expired (pruned)
│
└──process crashed, row stale──▶ reaped → retry may proceed

Replay the exact result, and police key reuse. Store the response code and body so a replay returns the identical answer the original produced — a retry of "submit claim" should get back the same claim id and 201, not a fresh attempt. And bind the key to the request: if a client sends the same Idempotency-Key with a different body (we caught this via request_hash in §4), that's a client bug, and you should reject it with 422 loudly rather than silently serving the cached response for a request that no longer matches. Surfacing it loudly is a kindness — it turns an invisible data-correctness bug into a visible 422 the client team fixes in an afternoon.

Size the dedup window to the caller's retry horizon, and write down the number. A client that retries for seconds-to-minutes needs a short window; a clearinghouse that retries webhooks for ~3 days needs a webhook dedup window of at least 3 days. Pick the number from the caller's actual behavior, document why in the ADR, and prune past it. A window shorter than the retry horizon means a legitimate late retry double-processes; a window absurdly longer just costs storage.

Scope keys per (user, endpoint), never globally. A global key namespace means user A's Idempotency-Key: "abc" collides with user B's "abc" — B's request gets A's cached response, which is both a correctness bug and, in a system carrying PHI, an information leak (more in §8). The same UUID on POST /claims and POST /appeals should be treated as two independent requests. Scope it into the key's primary key, as we did with (user_id, idem_key).

Operational hygiene. Index the dedup table for its exact lookup (the primary key already does this). TTL-prune it so it doesn't grow unbounded and slow every write. Monitor the age of the oldest in_flight row — a rising number means crashes are leaking stuck keys. And emit a "duplicate suppressed" metric: a healthy low rate is normal (the network hiccups); a sudden spike tells you a client's retry logic went haywire, an RPM device is re-POSTing in a loop, or a deploy is double-firing — it's signal, not noise, and one of the most useful early-warning gauges you'll have.

Making the whole pipeline effectively-once. Idempotency at one handler isn't enough if the message that triggered it was itself produced by a non-idempotent step. The end-to-end recipe is: an idempotent producer (publishing the same logical event twice is harmless) feeds an idempotent consumer (the handler we built), and the dangerous "did I write the business row and publish the event?" step is made atomic by the outbox pattern — write the business row and an outbox event in one transaction, then a separate relay publishes outbox rows (and a duplicate publish is fine because the consumer is idempotent). That's the glue that makes the guarantee hold from POST /claims all the way to the "claim paid" notification. We're naming it here; Chapter 26 builds it.

The client contract is part of the design. None of this works if the client doesn't reuse the same key across retries of the same logical request and mint a fresh key for a genuinely new request. Document this contract explicitly for every client team and partner. The guarantee is only ever as strong as the caller's key discipline — a client that generates a new UUID on every retry has effectively disabled your dedup while believing it's enabled.


6. Common pitfalls​

Check-then-act race. Signature: dedup uses SELECT WHERE key=...; under concurrent retries two requests both find "no key," both proceed, double effect — and it only shows up under load, never in your single-threaded test. Fix: insert-with-unique-constraint first; let the database serialize the contenders and catch the conflict. Stop asking whether the key exists; assert it and handle the rejection.

Dedup store and side effect in different transactions. Signature: the key is recorded in Redis but the claim is written to Postgres in a separate step; a crash between them leaves a key with no claim (future retries wrongly skip) or a claim with no key (future retries duplicate). Fix: put the dedup record and the business write in one atomic boundary — same database, same transaction — or bridge them with the outbox. Never two uncoordinated writes.

Non-idempotent effect hiding behind an idempotent-looking key. Signature: dedup passes, but the handler still does balance = balance + 10 (read-modify-write), and two requests that both slipped the gate under a rare race each increment. Fix: make the effect itself idempotent — absolute conditional writes (SET balance = :x WHERE version = :v), ON CONFLICT DO NOTHING, set-to-value — never relative accumulations.

Key derived from volatile data. Signature: the key is built from a timestamp or from the per-attempt request id that the HTTP client regenerates on retry — so every retry looks brand new and dedup never fires. Fix: the key must be minted once per logical request (synthetic UUID generated before the first attempt and reused) or be a stable natural key; it must be identical across all retries of the same intent.

Replaying a stale write out of order. Signature: an old remittance.posted retry overtakes a newer recouped and re-marks the claim paid. Fix: fencing token / version guard — WHERE applied_version < :incoming — so any write older than what's applied is rejected.

Trusting the webhook payload before verifying its signature. Signature: you dedup on event.id and act on the event before checking the provider's signature, so a forged event.id poisons your dedup table or a replayed captured event is accepted. Fix: verify the signature first; only then is event.id trustworthy enough to be a dedup key.

Unbounded dedup table. Signature: no TTL, the table grows forever, lookups slow down, and one day an index no longer fits in memory and writes stall. Fix: TTL + periodic pruning, with the window sized to the retry horizon, not "keep everything forever."

Assuming a broker gives you exactly-once end-to-end. Signature: "Kafka EOS is enabled, so I don't need idempotent writes" — while the consumer writes to an external Postgres that gets a duplicate every time the consumer crashes before committing its offset. Fix: the broker's guarantee stops at its boundary; the external sink must be independently idempotent.


7. Tradeoffs​

Synthetic (header) key ↔ natural (domain) key. Synthetic (Idempotency-Key) works on any endpoint and stays decoupled from your schema, but it requires a dedup store and depends on client discipline to mint-once-reuse. Natural (event.id, claim control number) is free when a domain-unique value already exists and needs no client cooperation, but it isn't always available and it couples dedup to your data model. You lean natural when the domain hands you a stable unique id and you can't trust the client to mint keys (third-party callers like a clearinghouse); you lean synthetic when no natural key exists or you control the client and want one uniform mechanism across endpoints.

SQL dedup table ↔ Redis SET key NX EX. A SQL table is transactional with the business write — dedup and effect commit or roll back together, upholding the atomicity invariant for free — but it's slower and adds a row to your hottest path. Redis SET key val NX EX ttl is fast and self-expiring, but it's a separate atomic boundary from your Postgres write, which reopens the crash gap unless the downstream effect is itself idempotent. Reverse toward Redis only when the effect is already idempotent on its own and dedup latency genuinely dominates; default to the SQL table whenever the side effect is a database write, because co-locating them is what makes the guarantee airtight. (This is the same Redis-vs-durable-store tension you met earlier around dedup and rate-limit state.)

Block the in-flight duplicate (409) ↔ wait for it ↔ return cached. On a concurrent duplicate of a still-running request you can return 409 immediately (simplest, but pushes the retry decision back to the client), wait for the original to finish and return its result (best UX, but ties up a connection and risks cascading holds), or replay the cached response (only possible once the original has completed). For most APIs, 409 for true in-flight collisions plus cached-replay for completed ones is the pragmatic default.

Dedup window length. Longer windows give a stronger guarantee (later duplicates still caught) at the cost of storage and slower pruning; shorter windows are cheap but let late duplicates slip through as "new." Remember this is a cost knob on a probabilistic guarantee, not a correctness switch — you're buying down the probability of a late-duplicate, not eliminating it.

Idempotency everywhere ↔ only at the money / clinical-safety boundaries. Making every endpoint idempotent has real cost — a dedup row and a constraint check on every write, plus the storage and pruning. Targeting only the operations where a duplicate is genuinely expensive (claims, payments, medication and lab orders, anything that moves money or touches patient safety) concentrates the effort where it pays. A duplicate "mark task as read" is harmless; a duplicate claim is a compliance flag and a duplicate e-Rx is a patient-safety event. Spend the complexity where a duplicate actually hurts.

🚫 A framing this book rejects. "We'll just turn on exactly-once delivery in the broker and not worry about idempotency." Teams burn entire quarters chasing this, configuring transactional everything, and still ship double-billed claims — because the guarantee they bought stops at the broker's edge and every external write is a fresh at-least-once hop. The correct architecture is the humble one: at-least-once delivery plus an idempotent effect. Stop trying to make duplicates impossible; make them boring. The engineer who internalizes that ships correct systems; the one chasing exactly-once delivery ships incidents with confident-sounding config.


8. Security & scale notes​

Idempotency keys are a side channel if you let them be. A guessable or globally-scoped key is an attack surface. If keys are global, attacker A can submit a request with key "k", and when victim B later (or concurrently) uses "k", B might receive A's cached response — and in a system carrying PHI, serving one user's stored response to a different user isn't merely an information leak, it's an unauthorized disclosure of protected health information, i.e. a reportable HIPAA breach. (Or A's request blocks B's by claiming the key — a targeted denial of service.) The defenses are the same three moves: scope keys per authenticated user (so A's keyspace never touches B's), require unguessable keys (UUIDv4, not sequential integers), and bind the key to the request body (so a reused key with a different body is rejected, not silently served). The per-user scoping we baked into (user_id, idem_key) isn't just for collision-avoidance; it's a security boundary.

Webhook replay attacks. An attacker who captures one validly-signed webhook can re-POST it. Dedup on event.id stops a replay of an already-processed event — but only if the signature is verified first (an attacker who can forge event.id can manufacture fresh ids that dodge your dedup). The full defense is signature verification + dedup on the natural id + a timestamp-tolerance window (reject events whose signed timestamp is too old, so a captured event can't be replayed days later). Dedup alone is necessary but not sufficient.

The dedup table as a write amplifier. Because creating a key writes a row, an attacker who floods your endpoint with unique keys can bloat the table and slow every legitimate lookup — an unauthenticated (or thinly-authenticated) write amplification. Rate-limit key creation per user, and keep the TTL aggressive so abuse is self-cleaning.

The dedup lookup is now on the hot path of every write — make it one round trip. Every mutating request pays the dedup cost, so it must be a single indexed operation. This is another reason insert-on-conflict beats select-then-insert: it's one round trip and one lock acquisition, not two. Under a retry storm for the same request — a flapping RPM device re-POSTing the same reading fifty times, or a hammering client — all fifty contend on the same row and serialize through one lock. Bound that contention with fast in-flight rejection (409 immediately rather than waiting), so a hot key doesn't pin a connection-pool slot per duplicate and starve unrelated traffic.

Multi-primary is the hard edge. Everything here assumes the key-check and the effect hit the same authority — one writer per key. Under multi-primary or eventually-replicated topologies (multi-leader), a duplicate can land in two regions before they sync, each sees "no key," each does the effect — and your single-effect invariant is broken across the partition. The mitigation is to ensure single-writer-per-key: route all requests for a given idempotency key (or a given claim, patient, or account) to the same primary, so the dedup gate always meets the same authority. If you can't guarantee that, your "exactly-once within the window" degrades to "exactly-once within the window and within one region," and you must say so.

Cached-response storage is a capacity line item. Storing response bodies for replay isn't free at scale — a high-volume endpoint with large responses can balloon the dedup table. Treat pruning and TTL as a first-class capacity concern, store only what a replay actually needs (status + a compact body, not the whole request), and budget the storage like any other hot table.


9. Interview lens & exercises​

Interview questions​

"Design an idempotent POST /claims."

  • Junior answer: "I'd SELECT to check if a claim with that key already exists, and if not, create it." (The check-then-act race; doubles under concurrency.)
  • Senior answer: names the key source (synthetic Idempotency-Key or natural claim control number), the atomic insert-on-conflict that lets the unique constraint referee the race, response replay for completed keys and 409 for in-flight ones, a dedup window sized to the caller's retry horizon, and a fencing/version guard so a stale retry can't overwrite newer state — all inside one transaction with the ledger write.

"Is exactly-once delivery possible? Defend your answer."

  • Junior: "Yes, Kafka has exactly-once."
  • Senior: "No for delivery — the Two Generals intuition: message and ack can both be lost, so no finite protocol guarantees a single delivery. Yes for effectively-once processing = at-least-once delivery + idempotent effect. Kafka's EOS is effectively-once within its boundary (producer-id+sequence dedup, atomic offset commit), and the guarantee ends the moment you write to an external system — that sink must be independently idempotent."

"Your webhook handler ran twice and double-posted a remittance. Walk me through the fix."

  • Junior: "Add a check at the top of the function to see if we've handled it."
  • Senior: "Verify the clearinghouse signature first, then dedup on the provider's event.id via insert-on-conflict inside the same transaction as the ledger write, return 2xx fast so the provider stops retrying, and make the effect idempotent and fenced so a late replay after a recoupment is rejected."

"Natural vs synthetic idempotency keys — when each?"

  • Junior: picks one unconditionally.
  • Senior: "Natural when a domain-unique id already exists and I can't trust the caller to mint keys (third parties like a clearinghouse); synthetic when none exists or I control the client and want one uniform mechanism — and either way scope it per-user and make it unguessable for the security reasons."

"Where does your dedup guarantee break?"

  • Junior: "It doesn't."
  • Senior: "Four places: after the window expires (a late duplicate looks new); across two transactions (a crash in the gap leaves key-without-effect or effect-without-key); under multi-primary (a duplicate lands in two regions before sync); and on out-of-order replay without a fencing token (stale state overwrites newer)."

Exercises & the Pulsely increment​

  1. Idempotent POST /claims (the increment). Add an Idempotency-Key header to Pulsely's claim endpoint. Build the idempotency_keys table with a (user_id, idem_key) unique constraint, the insert-on-conflict path, response replay for completed keys, and 409 for in-flight ones. Prove it: fire the same request 50× concurrently and assert exactly one claim row and exactly one 837 transmission to the clearinghouse. If you see two, your dedup is check-then-act somewhere — find it.

  2. Idempotent clearinghouse webhook (the increment). Dedup the remittance webhook on the provider's event.id inside the ledger transaction. Verify the signature before trusting the id. Add a version/fencing guard so a replayed remittance.posted arriving after a recouped is rejected. Prove it: replay a captured event and assert no second ledger row and no second "claim paid" notification.

  3. Break it on purpose. Implement the naive check-then-act version first. Drive concurrent retries until you observe the double effect (you will). Then convert to insert-on-conflict and watch it vanish. Feeling the bug appear and disappear under your own hands is worth more than any diagram.

  4. Window experiment. Set a 10-second dedup TTL. Send a duplicate at t=9s (suppressed) and another at t=11s (slips through). Write up, in one paragraph, what correctness degrades to once the window expires — proving to yourself that the window is a probabilistic cost knob, not a correctness switch.

  5. Write the ADR. Decide and record Pulsely's idempotency-key design: key source (synthetic Idempotency-Key for POST /claims, natural event.id for webhooks), scope ((user, endpoint)), storage (dedicated idempotency_keys SQL table, co-located with the claim write — not Redis, because the effect is a DB write and we want one atomic boundary), record lifecycle (in_flight → completed → expired, with a stale-in_flight reaper), retention window (claims: minutes, aligned to client retry; webhooks: ≥ 3 days, aligned to the clearinghouse's retry horizon), and response-replay semantics (store code + body, reject reused-key-with-different-body as 422). Record the rejected options — Redis-only dedup, global key scope, chasing broker exactly-once — each with the reason it loses.

Diagrams to draw​

  • The lost-ack sequence. client → server (commit) → response dropped → client times out → retry → second commit. Draw the request-lost path beside it and show both produce the identical retry — the picture that proves the duplicate is unpreventable.
  • The key-record state machine. new → in_flight → completed → expired, with the crash edge from in_flight to "reaped → retry may proceed."
  • The three delivery lanes. at-most-once vs at-least-once vs "exactly-once," with a box overlaid on at-least-once labeled "+ idempotent effect = effectively-once processing" — showing where the real guarantee lives.
  • The atomic-boundary contrast. dedup-check + side-effect inside one transaction (correct) beside two separate writes with the crash gap shaded red (broken). Draw it once and you'll never split them again.

Key takeaways​

  • Reliable systems retry; retrying means at-least-once delivery; at-least-once means duplicates are an ambient condition. Correctness comes from making the duplicate do nothing, not from preventing it.
  • Idempotency = f(f(x)) = f(x): running an operation N times lands the same state as running it once. Reframe every handler as "does this converge, or does it accumulate?"
  • Separate the two layers: delivery (how many times the message arrives — you don't control it) vs effect (how many times the side effect lands — you always control it). Win at the effect layer.
  • Exactly-once delivery is impossible (Two Generals); effectively-once processing is achievable = at-least-once delivery + idempotent effect. Brokers' "exactly-once" is this, renamed, and it stops at the broker's boundary.
  • The single-effect invariant: at most one committed side effect per key. The atomicity invariant: the dedup-check and the effect must share one transaction — insert-on-conflict, never check-then-act.
  • Natural keys (domain-unique, e.g. event.id) vs synthetic keys (Idempotency-Key UUID); make effects idempotent with ON CONFLICT DO NOTHING, conditional writes, and the affected-row count; defeat out-of-order replays with fencing tokens.
  • "Exactly-once within window W" is the honest guarantee — the window is a probabilistic cost knob. Scope keys per-user (a leaked cached response is a HIPAA breach), verify webhook signatures before dedup, and remember multi-primary breaks single-writer-per-key.

← Previous: Ch 24 — Distributed Systems Theory II · Up: Part V overview · Master TOC · Next: Ch 26 — Queues & Background Processing →