Idempotency and Exactly-Once: What Can You Guarantee?

By Arkaitz

You can guarantee one effect per logical operation. You cannot guarantee one delivery. A network can lose your last message, duplicate your retry, or deliver a request whose acknowledgement never comes back.

Exactly-once delivery is impossible end to end. Exactly-once effect is not. You build it with an idempotency key, a durable record of the result, and a retention window longer than your retry path.

The phrase that brought you here, idempotency exactly once, hides two different promises. One promise is about transmission. The other is about the effect you can actually keep.

That difference decides how you design retries, queues, and payment flows, and whether a vendor's exactly-once claim helps you or gives you false confidence. You are looking at one decision inside the six decisions that make a system distributed: what happens when a write must survive a retry without happening twice.

What does exactly once actually mean?

It means one effect, not one transmission. You have to separate three layers that vendors blur: delivery, processing, and effect.

A broker can deliver a message once, twice, or not at all. Your consumer can run its handler once, twice, or not at all. Your effect — the row, the charge, the email — can land once, twice, or not at all. Only that last layer is a guarantee you can keep.

The HTTP specification gives you the oldest precise definition. RFC 9110 calls a method idempotent when the intended effect on the server of multiple identical requests with that method is the same as the effect for a single such request. It names PUT, DELETE, and the safe methods as idempotent, and it leaves POST out. So your retried POST /charges needs help and your retried PUT /users/42 does not.

Idempotency is not safety. DELETE is idempotent and destructive. You can send it twice without changing the server's state further, and you still cannot undo the first one.

The counter-intuitive part is what your caller sees. Your first call returns 201 Created with a new identifier. Your retry returns 200 OK with the same identifier, or an error if the payload changed. The response differs, but the effect does not.

You design for the effect and let the response describe what your server already did.

Why can't the network deliver a message exactly once?

Because your sender cannot tell a lost message from a lost acknowledgement. You send a request. Your receiver commits the write. The acknowledgement disappears.

Now you face two indistinguishable worlds. Either the write happened and the ack vanished, or the write never happened. You must retry or risk loss, and a retry can duplicate your write. That is the whole problem, and no protocol layer removes it.

Azure's documentation describes the doubt you face. Service Bus duplicate detection says a client can send a message that commits, miss the acknowledgement, and remain in doubt about the outcome of the send operation. Your reasonable next move — resend — creates the duplicate. The page exists because the platform cannot remove that doubt for you.

Kafka's account matches. Confluent's explanation of exactly-once semantics describes a broker that crashes after writing a message but before sending the ack. Your producer cannot know which happened, so it retries and can duplicate the message. Kafka later added sequence numbers and transactions to contain the damage. It did not repeal the network.

Theory sets the floor under your design. Fischer, Lynch, and Paterson proved in 1985 that every protocol for distributed consensus has the possibility of nontermination, even with only one faulty process in an asynchronous system.

You dodge nontermination with timeouts, leases, and leader elections. A timeout is a guess about a failure you cannot observe. Guess wrong and you either retry a committed write or abandon an uncommitted one.

Saltzer, Reed, and Clark gave you the architectural version in 1984: a function can completely and correctly be implemented only with the knowledge and help of the application standing at the end points. The broker does not know whether your database commit succeeded. Your handler does. Any guarantee that claims otherwise has moved the responsibility, not removed it. Retries cross synchronous and asynchronous paths alike, which is why the interaction style changes the timing of your duplicate, never the possibility.

So you choose a failure mode. Stop retrying and you get at-most-once delivery, with loss. Retry and you get at-least-once delivery, with duplicates. There is no third delivery mode, only a handler that makes your duplicates harmless.

What does at-least-once delivery plus idempotent handling give you?

It gives you an effectively-once effect: duplicates arrive, and your effect still happens once. Your broker keeps its contract — deliver at least once — and your handler absorbs the repeats. This is the normal production contract, not a compromise.

SQS standard queues tell you that a stored copy can return and that you should design your applications to be idempotent. RabbitMQ says acknowledgements guarantee at least once delivery, and that without them you get at most once. Both products are telling you where the work moved.

The distinction matters because effectively-once is not a delivery guarantee. Your duplicate still arrives. Your consumer still runs. Your database still receives a second request.

Only your effect does not repeat, and you can measure the duplicates rather than wish them away.

Guarantee Deliveries Effect What it costs you
At-most-once 0 or 1 0 or 1 A lost message is gone
At-least-once 1 or more 1 or more without a guard Duplicates reach your handler
Effectively-once 1 or more Exactly 1 inside a key window Storage, a key, and a dedup boundary
Exactly-once delivery Exactly 1, end to end Exactly 1 Does not exist across an unreliable network

Read the effectively-once row carefully. It is a property of your system, not a setting you buy. It holds only while your key record survives; delete that record too early and the next delivery becomes a new operation.

Idempotency does not fix loss either. Your idempotent handler cannot invent a message the broker never delivered. At-most-once plus idempotency gives you a clean no-op, not a delivered message. Pair your guard with a delivery guarantee that matches the cost of a miss, and remember that every retry you add lowers loss and raises duplicates at the same time.

What makes an operation idempotent in practice?

Three ingredients: a durable uniqueness key, an atomic write that claims it, and a stored response your retry can return. Miss any one and you have a handler that works in the happy path and fails under concurrency.

Your key must describe the logical intent, not the attempt. Generate it when the user clicks Pay, not inside the retry loop. A UUID per attempt defeats the purpose, because every retry looks new.

Stripe's idempotency guide states the contract: A client generates an idempotency key, which is a unique key that the server uses to recognize subsequent retries of the same request. Stripe suggests a v4 UUID or another high-entropy string and caps your key at 255 characters. It also compares your incoming parameters against the original request, so a reused key with different parameters returns an error instead of a second charge.

AWS describes the same contract from your side of the call. The Builders' Library defines an idempotent operation as one where a request can be retransmitted or retried with no additional side effects. It stores the parameters you used for the initial request along with your client request ID, so a later request with the same ID and a different payload returns a validation error indicating a parameter mismatch. Your key is part of the API contract, not a cache hint.

Your atomic write is where a check-then-act handler breaks. The sequence looks safe and is not:

-- Wrong: two concurrent retries can both pass the SELECT.
SELECT id FROM payments WHERE idempotency_key = $1;
-- ... application decides the row is absent ...
INSERT INTO payments (idempotency_key, amount_cents) VALUES ($1, $2);

Two of your requests arrive at the same moment. Both SELECT and find nothing. Both INSERT.

Without a constraint, both succeed and you have two payments. Add a unique index and one insert fails, but your handler must catch that failure and return the winner's result rather than a 500. PostgreSQL's INSERT ... ON CONFLICT gives you the atomic claim in one statement:

INSERT INTO payments (idempotency_key, account_id, amount_cents, status)
VALUES ($1, $2, $3, 'pending')
ON CONFLICT (idempotency_key) DO NOTHING
RETURNING id;

When your insert returns no row, the key already exists. Read the existing row in the same transaction and return its stored response. When it returns a row, you own the operation and can proceed. The unique index is doing concurrency control, not just data hygiene.

Store the response, not only the key. Your retry must receive the first outcome: the same payment identifier, the same status code, the same body. If you store only seen, your retry knows the operation happened but not what to tell the caller. That gap produces a second bug: the client retries again because your response looks like a failure.

How long must you remember an idempotency key?

Longer than the longest path your retry can take, including every queue, dead-letter replay, restore, and manual re-run. There is no universal number. Vendor windows tell you what each system considers normal, not what your incident response needs.

For API v1, Stripe can remove keys once they are at least 24 hours old; a key you reuse after pruning starts a new request. SQS FIFO deduplicates inside a five-minute interval: the documentation says a retried SendMessage within that interval doesn't introduce any duplicates into the queue. Azure Service Bus defaults to ten minutes and allows a maximum of seven days. Birrell and Nelson's 1984 RPC implementation discarded its per-connection call state after an interval, say, after five minutes.

Those windows differ by more than three orders of magnitude because they protect different things. Your five-minute window covers a producer's immediate retry. It does not cover the dead-letter queue you replay after lunch, the database restore from last night, or the operator who re-runs yesterday's batch. If any of those paths can resend your logical operation, your key must outlive it.

Choose your window from your worst-case replay, then price the storage. A payments key held for 30 days is cheap next to a duplicate charge and a chargeback. An analytics event key held for 30 days may cost more than the duplicate it prevents. That is a business decision, and it belongs in your design record, not in a library default.

Two rules keep your window honest. First, namespace the key by tenant and operation type, so two teams cannot collide on the same UUID. Second, reject a reused key with a different payload.

Stripe compares parameters and errors on mismatch; AWS returns a validation error. A silent overwrite turns your retry into a data-corruption path.

Your clock matters too. Use one time authority — the database clock — for the write, the TTL, and the expiry sweep. A host clock that drifts, or a monotonic timer that resets on reboot, cannot compare against a stored expiry timestamp. Never let your sweep race a write that is still in flight.

Where do exactly-once claims come from in Kafka, queues, and cloud services?

Each claim names a scope, a window, and a mechanism, and stops at your system boundary. The marketing sentence drops the qualifiers. The documentation keeps them.

Kafka's KIP-98 gives you idempotent producers and transactions. The proposal promises that every message write will be persisted exactly once, without duplicates and without data loss — even in the event of client retries or broker failures. Read the scope: that covers your writes to Kafka partitions.

Your producer gets a producer ID and a sequence number per partition, and the broker deduplicates retries. Transactions extend the unit across partitions. Neither mechanism knows about the remote store your consumer calls.

Confluent says so directly. Its exactly-once article notes that the guarantee is guaranteed within the scope of Kafka Streams' internal processing only, and that an RPC to update a remote store produces side effects not guaranteed exactly once. The same article calls exactly-once processing an end-to-end guarantee and the application has to be designed to not violate the property. Kafka gives you the log half. You supply the other half.

The queue products repeat the pattern, and each one narrows your guarantee. SQS FIFO avoids duplicates inside a five-minute deduplication interval. Pub/Sub supports exactly-once delivery within a cloud region and only for pull subscriptions; push and export subscriptions do not support it. Azure Service Bus deduplicates by MessageId inside a configurable window, ten minutes by default and seven days at most, and the basic tier does not support the feature at all.

You get a window from each product, not a promise that survives your replay. Your stream processor inherits the same boundary. Flink restores from a checkpoint and replays records to keep state consistent, which it calls exactly-once processing semantics. That covers Flink's state.

Your sink still needs a transactional or idempotent writer, or the replay duplicates your output.

Ask three questions of any claim you read. What is your boundary — one partition, one region, one product? How long is the dedup window?

What happens to your side effects outside it? If the answer to the third question is your problem, you have found the work. Queues and streams differ in retention and replay, but neither one moves the boundary past your handler.

What breaks idempotency after the database write?

Side effects outside your transaction: the email, the charge, the webhook, the cache purge, the search index update. A duplicate request that finds your stored result skips the database write, then sends the email again if the send sits after the commit and outside the key's protection.

Consider your order of operations. You commit the payment row and the idempotency key in one transaction, then call the email provider. Your process dies between the commit and the call.

Your retry finds the key, returns the stored response, and never sends the email. Your customer paid and heard nothing. Reverse the order — send first, commit second — and a crash between them sends the email twice. Neither order is safe when two systems must agree.

The transactional outbox fixes the ordering. You write the business row and an outbox row in the same database transaction, and your relay publishes or sends from the outbox. That relay can crash and retry; the outbox row remains until it succeeds.

Your consumer deduplicates by event ID, so a redelivery does not repeat the effect. This is the mechanism behind most reliable event-driven architecture, and it is why the pattern earns its operational cost.

Never dual-write in your request path: a database commit plus a broker publish as two independent operations. The gap between them is a failure domain you cannot close with retries. The outbox turns your two writes into one atomic write plus a replayable read.

You can make the downstream idempotent as well. A payment provider that accepts an idempotency key, an email service that deduplicates by message ID, a search index that treats an update as an upsert — each one removes a duplicate at your edge. If your downstream offers no key, put a dedup table in front of it and accept that the table is now part of your correctness boundary.

Removing retries does not fix this. It converts your duplicate into a loss. Your retry is not the bug. Your non-idempotent handler is.

How do you test idempotency before production?

Replay the same request sequentially, concurrently, and across a crash, then assert one effect. A happy-path test proves nothing. The bug appears only when two attempts overlap or when your process dies between the effect and the acknowledgement.

Five tests cover most of your risk:

  1. Sequential duplicate. Send the same key and payload twice from your client. Assert one row, one charge, and an identical response body.
  2. Concurrent duplicate. Fire both requests at the same instant from two of your threads. Assert one effect and no 500. The loser must return the winner's result, not a unique-violation stack trace.
  3. Crash after commit, before ack. Kill your handler after the database commit and before the broker acknowledgement, then let the broker redeliver. Assert one effect. A proxy that drops the ack, or a fault-injection hook in your handler, makes this reproducible.
  4. Same key, different payload. Assert a validation error, not a silent second operation. Compare a hash of your canonical payload.
  5. Late duplicate after expiry. Wait past your retention window, resend, and document what happens. The test should confirm the known risk, not pretend it away.

Run these against your real database. A mock cannot reproduce the unique-index race, and the unique index is the component you are testing. Assert row counts directly, not through an ORM that might hide your duplicate. Keep the test in the suite that runs on every schema change, because a dropped constraint silently removes your guarantee.

Add three metrics: duplicate-request rate, key-conflict rate, and the age of the oldest key still in use. The first tells you how often the network repeats itself. The second tells you whether your clients reuse keys correctly. The third tells you when your retention window is about to expire under load.

Your dedup store can fail too. If it is unavailable, you choose between failing closed (reject the request, preserve correctness) and failing open (accept it, risk a duplicate).

You are making the per-operation availability trade-off behind consistency versus availability. Fail your payment path closed. You can fail a page-view counter open. Write the choice down before your incident.

Should you ever choose at-most-once or at-least-once?

Yes. Match your guarantee to the cost of a duplicate against the cost of a loss. Exactly-once is not the universal target. It is one point on a trade-off curve, and sometimes the wrong one for your workload.

Workload Delivery choice Why
Page-view analytics At-least-once, dedup optional A duplicate is cheap to filter; a loss barely moves the trend
Audit log At-least-once, dedup by event ID A missing entry is worse than a repeated one
Payment capture At-least-once plus provider idempotency key A duplicate charge costs money and trust; a loss costs a sale
Inventory decrement At-least-once plus reservation ID Two decrements oversell; a lost decrement undersells
Email notification At-least-once plus outbox A missing email breaks the flow; a duplicate annoys
Cache invalidation At-least-once The operation is naturally idempotent; replay is harmless

You choose at-most-once when a duplicate is worse than a miss and you cannot make the effect idempotent. A legacy side effect with no key, a non-reversible external action, a one-shot command — in those cases, refusing to retry is the honest choice. You accept the loss and you monitor it.

You choose at-least-once almost everywhere else, because duplicates are usually cheaper than holes. Your handler carries the cost: one key, one unique index, one stored response.

You choose exactly-once effect when you control the whole boundary: one database, one transaction, one log. The moment a side effect crosses into a system you do not control, your guarantee becomes a negotiation with that system's idempotency support.

What can you actually guarantee?

Three things, and you can write all three in your design document. Your broker delivers at least once. Your handler produces at most one effect per key inside a retention window. Your outbox carries side effects across the boundary without a dual write.

You cannot get the fourth guarantee: exactly-once delivery across an unreliable network. The proof is older than your framework. Your sender cannot distinguish a lost message from a lost acknowledgement, and no amount of retrying turns that doubt into knowledge. Helland and Campbell put the asynchronous version bluntly: nothing is guaranteed! Helland's earlier paper calls exactly-once in-order messaging a facility that needs a long-lived connection, and says scalable applications rarely have one.

So write the honest sentence in your design doc: the broker delivers at least once; the handler makes the effect idempotent; the key outlives the retry path; side effects leave through the outbox. Then test that sentence with a duplicate, a concurrent retry, and a crash.

That is the guarantee you can keep, and it is where idempotency does its work. The vendor's sentence is shorter because it stops at the boundary of the product. Your sentence has to cover the boundary of your system, where the duplicate lives and the exactly-once effect is either designed or lost.

Related Reading