Skip to content

Lesson 3 of 13 · 15m

Idempotency Is a Processing Property

Exactly-once delivery does not exist; exactly-once processing is a dedup key committed in the same transaction as the effect.

"Exactly-once delivery" is a phrase marketing uses and protocols cannot honor. The previous lesson established why: after a timeout, the sender cannot know whether the effect landed, so any honest retry mechanism delivers the message at least once. Duplicates are not an edge case in a retried system. They are the guarantee.

What you can build is exactly-once processing — a system where a replayed request is recognized and short-circuited instead of re-executed. Stripe's API is the reference implementation everyone copies, because it is simple enough to be right: the client sends an Idempotency-Key header per logical operation, Stripe stores the first response against that key — including error responses — and replays it verbatim on a retry, for at least 24 hours. Retry with the same key and you do not get a second charge; you get the first answer again.

The mechanism, not the slogan

The naive dedup is a lookup: check the key, run the handler, record the key. It is wrong in exactly the way the last two lessons predict — a crash between "run" and "record," or two concurrent retries racing the check, re-executes the effect. The correct structure is atomic: insert the key and apply the effect in one database transaction, and let a unique constraint be the arbiter.

CREATE TABLE idempotency_keys (
    key        text PRIMARY KEY,
    response   jsonb NOT NULL,
    created_at timestamptz NOT NULL DEFAULT now()
);

-- inside the request transaction:
INSERT INTO idempotency_keys (key, response)
VALUES ($1, $2) ON CONFLICT (key) DO NOTHING;

ON CONFLICT DO NOTHING returning zero rows means "you have been here before": select the stored response and return it. The uniqueness check, the effect, and the response record commit or roll back together — there is no window for a crash to slide into.

Some operations are idempotent by shape, which is better than idempotent by dedup. SET balance = 50 replayed a hundred times yields 50. SET balance = balance + 50 replayed once yields a double-credit. Where you can express state transitions as writes of absolute values or upserts keyed on a natural id, retries become cheap and boring.

Also notice what "a retry" actually is at the boundary: it is any second delivery of the same intent. A client-side timeout retry, a user double-clicking Pay, a load balancer re-issuing the request after a connection reset, and a queue consumer redelivering after a crash are four different mechanisms producing the identical duplicate. The idempotency key is the only thing that treats them uniformly — the dedup happens on intent, not on transport.

Kafka, which is honest about this

Kafka's enable.idempotence=true — default since Apache Kafka 3.0 — makes the producer attach a producer ID and per-partition sequence number; the broker dedups in-flight producer retries inside a session. It does nothing for the consumer, which is still at-least-once: a consumer that processes a record and crashes before committing its offset will see that record again after rebalance. The end-to-end story for read-process-write is transactions: initTransactions, then sendOffsetsToTransaction so the input offset, the produced output, and the commit land atomically or not at all. Even then, the moment your "process" calls an external API or writes to Postgres, the transaction boundary ends and you are back to dedup keys.

What to actually do

Every mutating endpoint that clients can plausibly retry accepts an idempotency key and stores it with the effect, in one transaction. Generate keys client-side per logical operation — a UUID minted when the user clicks "Pay," not per HTTP attempt, so a page refresh or a network flap replays instead of duplicates. Prefer naturally idempotent writes where the data model allows it. Keep responses, including failures, against the key long enough to cover your real retry horizon. And log on dedup hits: a rising replay count is a signal that something upstream is timing out and retrying, which is exactly the kind of thing you want on a dashboard before it becomes an incident.

Was this lesson helpful?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.