Idempotency and deduplication

At-least-once is the only delivery you get: check-then-process caught 3 duplicate charges of 300, an atomic claim caught all, and a claim never released lost 40 payments.

11 min read🌐 Distributed Systems

Every message system you will use in production delivers at least once. Kafka does, SQS does, RabbitMQ does, and so does a plain HTTP client with a retry. "At least once" means exactly what it says: sometimes twice.

So "exactly once" is not something the infrastructure gives you. It is a property you build into the thing that receives the message, by making the second delivery do nothing. That property is idempotency, and the way you implement it decides whether it actually holds.

Why duplicates are normal

A consumer takes a message, does the work, and then acknowledges it — commits the offset, deletes it from the queue, returns 200. Any failure between the work and the acknowledgement produces a duplicate:

  • The consumer crashes after charging the card and before committing the offset. On restart, the message is delivered again.
  • A consumer group rebalances while a message is being processed. Another consumer is given the partition and starts from the last committed offset.
  • The acknowledgement is sent and lost on the network, and the broker redelivers after a timeout.
  • A producer retries a send whose acknowledgement it never saw, and the broker already had it.

None of those is a bug. They are the price of never losing a message, and every "we never get duplicates" is a sentence about a system that has not yet had a bad day. The Kafka course's lesson on offsets shows the crash case in detail.

Three handlers, one race

Here is a payment consumer. It receives 2,000 payment messages on 8 threads. One message in twenty is redelivered, and — the realistic part — the copy arrives while the first is still being processed, as it does after a rebalance. Charging takes a millisecond, standing in for a call to the provider.

Dedupe.javajava
static void charge(String paymentId) throws InterruptedException {
    Thread.sleep(1);                       // the call to the payment provider
    charges.incrementAndGet();
}

No deduplication does what you expect:

plaintext
no deduplication                 deliveries 2100   payments 2000   charges 2100

A hundred customers charged twice.

Check, charge, then remember is what most people write first. Look up whether the payment was processed; if not, charge and record it:

Dedupe.java — check firstjava
if (seen.contains(id)) return;       // SELECT ... WHERE payment_id = ?
charge(id);
seen.add(id);                        // INSERT processed(payment_id)

Three runs:

plaintext
check, charge, then remember     deliveries 2100   payments 2000   charges 2097
check, charge, then remember     deliveries 2100   payments 2000   charges 2100
check, charge, then remember     deliveries 2100   payments 2000   charges 2100

It caught three duplicates out of three hundred. The check is correct and useless: both copies check at the same moment, both see "not processed", and both charge. The window between the check and the insert is the length of the charge, and the duplicate arrives inside it. This is check-then-act — the compound operation the concurrency course shows is not atomic even on a concurrent map — moved into a database.

Claim first, atomically inverts the order. Record the payment id first, in an operation that only one caller can win, and charge only if you won:

Dedupe.java — claim firstjava
if (!claimed.add(id)) return;        // INSERT ... ; unique violation means someone else has it
charge(id);
plaintext
claim first, atomically          deliveries 2100   payments 2000   charges 2000

Exactly 2,000, in all three runs. In the demo the atomic claim is ConcurrentHashMap.newKeySet().add, which returns false if the element was already there. In a real service it is an INSERT into a table with a unique constraint on the message or payment id — the database decides who won, and the loser gets a constraint violation instead of a charge.

The claim that is never released

Claim-first has its own failure, and it is the opposite one. What if the charge fails after the claim succeeded?

A second experiment: 2,000 payments, the provider fails on the first attempt for 1 in 50, and the broker redelivers those once.

plaintext
claim, then charge                 payments 2000   first attempts failed 40   charges 1960
claim, charge, release on failure  payments 2000   first attempts failed 40   charges 2000

Forty payments were never taken. Each redelivery found the claim already present and skipped — deduplication working perfectly, against a message that was never processed. Releasing the claim when the work fails (deleting the row, or marking it FAILED so a retry may proceed) brings it back to 2,000.

That fix covers an exception. It does not cover a crash between claim and charge, where no code runs to release anything. That is why real claim rows carry a state and a lease:

statemeansa redelivery should
IN_PROGRESS, lease validsomeone is working on itskip, or wait
IN_PROGRESS, lease expiredthe worker probably diedtake over the claim
DONEfinished, with its result storedreturn the stored result
FAILEDfinished, unsuccessfullyallow a retry

"Probably died" is doing real work in that table. The worker may be alive and merely slow, which is the leader-election problem in miniature — and the reason fencing tokens exist.

The side effect you cannot put in your transaction

The deduplication row and the database work can commit together. The payment provider cannot join that transaction. So there is always a window where the charge happened and your record of it did not:

  1. Claim the payment id.
  2. Call the provider. The provider charges the card, and the response times out.
  3. You mark the claim FAILED and a retry runs — and charges again.

Your deduplication cannot fix this, because your system genuinely does not know whether the charge happened. Only the provider knows. The answer is to pass the idempotency key downstream: payment providers accept a key per request and return the original result for a repeated key, which is the same protocol the REST course's idempotency lesson builds on the server side. Idempotency is only a system property if every hop with a side effect honours the same key.

Natural idempotency, when you can get it

Some operations need no deduplication table, because running them twice is harmless:

  • Setting a value: UPDATE orders SET status = 'SHIPPED' WHERE id = ? is idempotent. Incrementing one — SET shipped_count = shipped_count + 1 — is not.
  • Conditional updates that encode the expected state: SET status = 'SHIPPED' WHERE id = ? AND status = 'PACKED' does the transition once, and the duplicate affects zero rows.
  • Upserts keyed by a business id rather than inserts with a generated one.

Designing messages as "the new state is X" rather than "add one" makes most consumers idempotent without any bookkeeping. It is not always possible — a payment is inherently "move this money" — but it is worth asking for every message type.

How long to remember

A deduplication table grows forever unless you decide otherwise. Retention must be longer than the longest possible redelivery delay: the broker's retention, plus the time a message can sit in a retry topic, plus how long a consumer can be down before someone replays from an old offset. Keep ids for less than that, and a late duplicate is processed as new.

Under the hood: why exactly-once is unreachable in general, and the one narrow place a broker gets it anyway

Everything above builds exactly-once processing out of at-least-once delivery plus a receiver that remembers. It is worth being honest about why that construction is necessary rather than a workaround for something a smarter protocol could fix outright.

No finite exchange of messages over an unreliable channel lets two parties both become certain of a shared outcome. This is the informal shape of the Two Generals Problem: general A sends "attack at dawn," and wants confirmation the message arrived before committing; general B receives it and sends an acknowledgement, but now B cannot be sure the acknowledgement arrived either, so B would want an acknowledgement of the acknowledgement — and the regress never terminates, because every message that would settle the uncertainty is itself a message that can be lost. A producer and a consumer talking over a network are in exactly this position: the producer cannot, from the outside, distinguish "the consumer never got the message" from "the consumer got it, processed it, and the acknowledgement was lost," and no amount of extra round-tripping removes that specific ambiguity — it only shrinks the probability of hitting it, never to zero. This is why "exactly once, end to end, between two independently-failing systems" is not a feature some vendor forgot to build; it is not on the menu. Every "exactly-once" claim in a broker's documentation is scoped to a boundary the vendor controls end to end, and it is worth reading exactly which boundary.

Kafka's idempotent producer is the narrow case where a form of exactly-once genuinely holds — because it shrinks the problem to one the broker can fully see. The scope is deliberately small: not "this event is processed exactly once by my consumer" (still the application's job, via the deduplication table above), but "this producer's retried send is written into the log at most once." The mechanism: when idempotence is enabled, the broker assigns the producer a producer id (PID) for its session, and the producer attaches a per-partition sequence number to every batch it sends, starting at zero and incrementing by one for each batch. The broker tracks, per (PID, partition), the highest sequence number it has durably appended. A retried send — the producer resent a batch because it never saw the broker's acknowledgement — arrives with the same sequence number as a batch already appended, and the broker recognises the duplicate and does not append it again, while still returning success to the producer. A batch that arrives out of the expected sequence (a gap, or a number already superseded) is rejected, because it signals the producer's session state and the broker's have diverged. This works because, unlike the payment-to-database-to-customer chain earlier in this lesson, both ends of this specific exchange — producer and broker — are systems Kafka's own protocol controls completely, so there is no third silent party (a card network, a person) whose state can drift out of view.

The boundary matters in practice: idempotent production stops a flaky network from writing a message into the log twice. It says nothing about whether your consumer's processing of that one guaranteed-singular message is itself idempotent — that is still this lesson's claim-first table, applied at the consumer.

Try it yourself

Trace a sequence-number dedup window, the way a broker deduplicates a retried batch

A broker deduplicating an idempotent producer's retries does not need a full key-value table — it only needs the highest sequence number seen per producer, because sequence numbers are assigned in order. Trace what a small dedup window accepts and rejects.

java
int highestSeen = -1;
int[] incoming = {0, 1, 1, 2};   // batch 1 resent after a lost acknowledgement
 
for (int seq : incoming) {
    if (seq <= highestSeen) {
        System.out.println("batch " + seq + " -> duplicate, not appended");
    } else {
        highestSeen = seq;
        System.out.println("batch " + seq + " -> appended (highest now " + highestSeen + ")");
    }
}

Before running it: which batch is the retry, and how does the broker tell it apart from a brand-new one using only a single integer per producer?

Misconceptions

  • "Kafka's idempotent producer gives you exactly-once processing." It gives exactly-once appending to the log for one producer's retried sends — a narrower, fully-controlled boundary. Your consumer's side effects (a charge, an email) are outside that boundary and need the claim-first deduplication this lesson builds, exactly as if the producer were not idempotent at all.
  • "With enough retries and acknowledgements, exactly-once delivery is achievable — it's just hard to implement." It is not a matter of trying harder. The Two Generals argument shows the ambiguity (did it arrive, or did the acknowledgement get lost?) cannot be resolved by any finite exchange over a channel that can lose messages, only worked around — which is exactly what an idempotency key does: it does not prevent the duplicate, it makes the duplicate harmless.

Sources

  • Attributed informally to E. A. Akkoyunlu, K. Ekanadham and R. V. Huber (1975), and popularized as "the Two Generals Problem" — the impossibility argument behind why acknowledged delivery over an unreliable channel cannot be made certain.
  • Apache Kafka documentation and KIP-98 ("Exactly Once Delivery and Transactional Messaging") — the idempotent producer's producer id and per-partition sequence number.
  • Martin Kleppmann, Designing Data-Intensive Applications — chapter 11 discusses exactly-once semantics and their real scope in stream processing systems.
Progress is saved on this device and to your account when signed in.