Skip to content

    System Design

    Idempotent Consumers and Deduplication

    Make a message consumer safe against repeats: choose the dedupe key, claim it atomically with the effect, use version guards and size retention, with a lab.

    By Published 13 min read

    • system-design
    • idempotent-consumer
    • deduplication
    • messaging
    • spring-jdbc
    Share

    Standard lessonintermediateSpring Boot labBackend System Design

    Before this: Delivery Guarantees: At-Most-Once, At-Least-Once and Exactly-Once, Idempotency Keys and Safe Retries

    What you'll learn: By the end of this lesson you will be able to list where duplicate messages come from, choose a deduplication key that survives a producer retry, pick between a processed-ids table, a naturally idempotent effect and a version guard, explain why the id claim must share one transaction with the effect, size the retention window, and read the output of a Spring and H2 lab.

    A cinema box office sells numbered tickets. When a customer shows up twice with the same booking reference, the clerk looks it up in the booking book, and if it is ticked says "you already have these". Two things make that work: the reference is the same every visit, and the tick is written in the same breath as the tickets are printed. If the clerk ticks the book and then the printer jams, the customer is turned away from tickets that were never printed.

    A message consumer is that clerk. Delivery guarantees shows why at-least-once delivery means repeats, and gives the working definition of an idempotent consumer. This lesson is the dedicated treatment: the key, the store, the transaction, the alternatives and the retention window. The HTTP version is idempotency keys and safe retries; the general laws are in idempotent and commutative operations.

    Verified with Apache Kafka 4.2 documentation, Spring Boot 4.1.2 (spring-jdbc) with H2, and Java 25 as the compile target, on 2026-12-01.

    The core idea

    An idempotent consumer is one whose observable result after handling the same message several times equals the result after handling it once. It achieves that by recording the identity of each message it has handled, in the same atomic step as the effect, and by treating a message whose identity is already recorded as already done.

    microservices.io describes the pattern: "Make a consumer idempotent by having it record the IDs of processed messages in the database", in a separate PROCESSED_MESSAGES table or in the business entities the consumer updates. The reason: with at-least-once delivery, "the consumer can be invoked repeatedly for the same message".

    Three illustrations run through the lesson:

    • Minimal example: a payment event that credits a store balance, handled by five consumers in the Java lab in "Build it".
    • Realistic example: ShopStream's store-payout consumer, in "In practice".
    • Failure example: a consumer that records the id first and applies the effect second, and a table that forgets ids too soon.

    Where duplicates come from

    A duplicate is the same logical event reaching a handler more than once. Four mechanisms produce them.

    Four sources of duplicate deliveriesProducer to Topic (1 two sends); Topic to Consumer (2 redelivery); Consumer to Database (effect); Redrive tool to Topic (4 replay)Producer: retry or republishProducerretry orrepublishTopic: log of recordsTopiclog of recordsConsumer: handlerConsumerhandlerDatabase: effect and idsDatabaseeffect and idsRedrive tool: replay from a DLQRedrive toolreplay from a DLQ1 two sends2 redeliveryeffect4 replay

    Figure 1. Where a repeat can enter. How to read this: arrow 1 is the application sending the same business event twice; arrow 2 is the broker handing a record to a consumer that already handled it; arrow 4 is an operator replaying records. The consumer's own database is the last place a repeat can be stopped.

    1. The application sends twice. The KafkaProducer documentation says "it is imperative to avoid application level re-sends since these cannot be de-duplicated", and that idempotence holds only "for messages sent within a single session". A retry loop around a timeout, or a relay that republishes after a restart, creates two records with two offsets.
    2. The consumer crashes between the effect and the offset commit. The Kafka design documentation: "there is a possibility that the consumer process crashes after processing messages but before saving its position". The restart resumes at the unsaved offset.
    3. A rebalance moves the partition. If poll() is not called within max.poll.interval.ms (default 5 minutes) the consumer "is considered failed" and "the group will rebalance in order to reassign the partitions to another member". A slow handler can have its records handled again by another member while it is still working.
    4. Someone replays. A dead-letter redrive (dead-letter queues and retries), an offset reset or a read-model rebuild reads old records on purpose.

    Mechanism 3 means two copies of one message can run at the same time, not only one after the other.

    Choosing the deduplication key

    The key decides what counts as "the same". It must be stable across every delivery of one logical event, and different for two real events.

    Candidate key Stable when the producer resends? Stable on consumer redelivery? Verdict
    Message id assigned by the producer once per event (a UUID stored with the event) Yes, if the resend reuses the stored event Yes Best default
    Business key (order id plus step, such as ord-1/paid) Yes Yes Good when one event per step exists by design
    Partition and offset No: a resend gets a new offset Yes Protects only against consumer redelivery
    Hash of the payload Yes if bytes are identical Yes Fragile: two real events can carry the same payload

    The id must be written when the event is first created, for example in the transaction that changes the business data (the outbox lesson in this module covers that), so a republish carries the same id. An id generated at send time is new on every send.

    Scope the key by consumer. The lab's primary key is (consumer, message_id): one message may be processed once by the ledger consumer and once by the reports consumer. Without the consumer name the second would skip work it never did.

    Four ways to recognise a repeat

    flowchart TD accTitle: Choosing how a consumer recognises a repeated message accDescr: A decision tree. If the effect is a plain overwrite of the same value, it is naturally idempotent and needs no store. If events carry a per-entity version, a version guard on the row is enough. Otherwise the consumer records message ids in a table with a unique key inside the same transaction as the effect. Q1{"Is the effect a plain overwrite
    of the same value?"} Q2{"Does each event carry a
    per-entity version?"} A["Naturally idempotent:
    no store needed"] B["Version guard:
    apply only if higher"] C["Processed-ids table:
    unique key, same transaction"] Q1 -- yes --> A Q1 -- no --> Q2 Q2 -- yes --> B Q2 -- no --> C

    Figure 2. A decision for the mechanism. How to read this: start at the top and answer in order. The cheapest mechanism that fits is the right one, and the last box is the general fallback.

    • Naturally idempotent effect. "Set the order status to paid" or an upsert of a whole row gives the same result when repeated. The Kafka design documentation gives the case: when messages have a primary key, "the updates are idempotent". It breaks when the effect is relative ("add 1250 to the balance"), sends an email or calls a payment provider.
    • Version guard. The row stores the highest version applied, and an event is applied only if its version is higher. It ignores repeats and late older events, so the end state does not depend on arrival order. It needs a per-entity version the producer increments, and stores one number per entity instead of one row per message.
    • Processed-ids table. The general mechanism for relative effects. Cost: one row per message for as long as repeats can arrive.
    • Make an external effect idempotent too. For a call to another system, pass a key it honours; a local table cannot unsend an email.

    The claim must be atomic with the effect

    "Record the id" and "apply the effect" have the same shape as the commit and the effect in the delivery-guarantees lesson: as two steps, a crash between them fails in one direction or the other.

    sequenceDiagram accTitle: Claiming a message id in the same transaction as the effect accDescr: The consumer opens a transaction, inserts the message id into the processed table, applies the effect, and commits. If the id already exists the insert fails and the transaction rolls back, so the repeat changes nothing. If the process dies after the insert and before the commit, the database rolls the transaction back, so the id is not recorded and a redelivery is processed normally. participant B as Broker participant C as Consumer participant D as Database B->>C: deliver pay-1 C->>D: begin C->>D: insert id pay-1 (unique) C->>D: apply effect C->>D: commit B->>C: redeliver pay-1 C->>D: begin C->>D: insert id pay-1 D-->>C: unique violation C->>D: rollback (nothing changed)

    Figure 3. One transaction, two outcomes. How to read this: the first delivery runs top to bottom and commits. The repeat fails at the insert, and the rollback leaves the effect untouched. A crash anywhere before the commit also rolls everything back, including the id.

    The key is the unique constraint. Reading "have I seen this?" and then writing is a race: two copies that arrive together both read "no". The database's uniqueness check must be part of the insert. In PostgreSQL, INSERT ... ON CONFLICT DO NOTHING "simply avoids inserting a row" instead of raising a unique violation; the lab uses H2 and catches the duplicate-key exception. The offset commit stays a separate step, which is safe because the consumer is idempotent.

    How long to remember

    A table of every id grows forever, so it needs a retention rule, and the rule affects correctness: a repeat that arrives after its id was purged is processed again. The window must exceed the longest time between the first delivery and any possible redelivery: the topic's retention if you ever reset offsets, the delay of a dead-letter redrive, the longest outage of a consumer that resumes from an old offset. If you cannot bound the delay, keep ids as long as the effect matters, or use a version guard that stores one number per entity.

    Build it: payment events against H2

    This is the minimal example. Goal: apply a "payment captured" event that credits a store balance, and see what each design does with a repeat. Not a real system: the data is illustrative, H2 runs in memory, no Kafka broker is involved (the delivery-guarantees lab covers that side), and "a delivery" is one call of the consumer. The code uses Spring JdbcTemplate and TransactionTemplate.

    Setup. From the repository (Docker is not needed):

    cd examples/spring-labs
    ./gradlew :labs:idempotent-consumers:test

    It runs 11 tests, one of which compares the report below with the golden file examples/spring-labs/golden/idempotent-consumers.txt. The core of the idempotent consumer is one transaction (IdempotentPaymentConsumer):

    try {
        return tx.execute(status -> {
            jdbc.update("insert into processed_messages (consumer, message_id, seen_at) values (?, ?, ?)",
                name, payment.id(), clock.getAsLong());
            betweenClaimAndEffect.run(payment.id());
            Db.credit(jdbc, payment);
            return Outcome.APPLIED;
        });
    } catch (DuplicateKeyException repeat) {
        return Outcome.DUPLICATE;
    }

    Hook is a test seam that can throw between the claim and the effect, standing in for a process dying there.

    Runs 1 and 2: a redelivery. A plain consumer credits the store twice; the idempotent consumer once.

    Expected output, captured from a real run (Spring Boot 4.1.2, Java 25, H2 in memory, 2026-12-01):

    Run 1. No deduplication. pay-1 is delivered twice (a redelivery after a crash before the offset commit).
      delivery 1 : APPLIED
      delivery 2 : APPLIED
      balance s-1: 2500 cents (right answer 1250)
    
    Run 2. The idempotent consumer (claim the id and apply the effect in one transaction). Same two deliveries.
      delivery 1 : APPLIED
      delivery 2 : DUPLICATE
      balance s-1: 1250 cents (right answer 1250)
      processed_messages rows: 1

    Runs 3 and 4: two copies at once. CheckThenActPaymentConsumer reads a table with no unique constraint, applies, then writes the mark; a barrier makes both threads read before either writes.

    Expected output, captured from a real run (Spring Boot 4.1.2, Java 25, H2 in memory, 2026-12-01):

    Run 3. Anti-pattern: read the mark, apply, write the mark (no unique constraint). Two copies arrive together.
      outcomes   : APPLIED x2
      balance s-1: 2500 cents (right answer 1250)
    
    Run 4. The idempotent consumer, the same two copies arriving together.
      outcomes   : APPLIED x1, DUPLICATE x1
      balance s-1: 1250 cents (right answer 1250)

    The winning thread in run 4 is not printed, because it varies; the count does not.

    Runs 5 and 6: a death between the mark and the effect. MarkFirstPaymentConsumer commits the id, then applies the effect as a second step. The idempotent consumer fails at the same point, but the transaction rolls the claim back.

    Expected output, captured from a real run (Spring Boot 4.1.2, Java 25, H2 in memory, 2026-12-01):

    Run 5. Anti-pattern: the mark is committed first, the effect is a second step. The process dies between them.
      delivery 1 : FAILED (process died while handling pay-1)
      processed_messages rows after the failure: 1
      delivery 2 (the broker redelivers): DUPLICATE
      balance s-1: 0 cents (right answer 1250) LOST
    
    Run 6. The idempotent consumer, the same death after the claim and before the effect.
      delivery 1 : FAILED (process died while handling pay-1)
      processed_messages rows after the failure: 0
      delivery 2 (the broker redelivers): APPLIED
      balance s-1: 1250 cents (right answer 1250)

    Run 5 is the tick without the tickets: a deduplicating consumer written this way turns a duplicate problem into a lost-effect problem.

    Run 7: a version guard. VersionedStatusConsumer updates the order row only where the stored version is lower than the event's. Order o-2 arrives out of order.

    Expected output, captured from a real run (Spring Boot 4.1.2, Java 25, H2 in memory, 2026-12-01):

    Run 7. No table of ids: the order row keeps the highest version applied.
      order o-1, arrival v1 placed, v2 paid, v2 paid (repeat), v1 placed (late repeat):
        v1 placed -> APPLIED
        v2 paid -> APPLIED
        v2 paid -> STALE
        v1 placed -> STALE
      stored o-1 : v2 paid
      order o-2, arrival v2 paid first, then v1 placed (out of order):
        v2 paid -> APPLIED
        v1 placed -> STALE
      stored o-2 : v2 paid

    Runs 8 and 9: the retention window. A logical clock in minutes: with a 60-minute window a purge at minute 90 removes the id; with 120 it survives.

    Expected output, captured from a real run (Spring Boot 4.1.2, Java 25, H2 in memory, 2026-12-01):

    Run 8. Retention window of 60 minutes (logical clock). pay-1 first arrives at minute 0.
      minute 0   : APPLIED
      minute 30  : DUPLICATE (a repeat inside the window)
      minute 90  : purge removes 1 row(s), 0 left
      minute 90  : APPLIED (a repeat 90 minutes after the first)
      balance s-1: 2500 cents (right answer 1250)
    
    Run 9. Retention window of 120 minutes (logical clock). pay-1 first arrives at minute 0.
      minute 0   : APPLIED
      minute 30  : DUPLICATE (a repeat inside the window)
      minute 90  : purge removes 0 row(s), 1 left
      minute 90  : DUPLICATE (a repeat 90 minutes after the first)
      balance s-1: 1250 cents (right answer 1250)

    What the lab does not show. No broker, no rebalance, no PostgreSQL, no real load. Run 4 shows H2's handling of two inserts of one key; another database enforces the same constraint but its locking and errors differ. The "death" is an exception from a test hook, not a killed process.

    Trade-offs

    Choice Gain Cost Wrong when
    Processed-ids table, same transaction Works for any effect in that database A write and a row per message; a retention rule The effect is outside the database (email, payment call) with no key of its own
    Natural idempotence (upsert, set) No store at all Only for overwrites The effect is relative or has a side effect
    Version guard One number per entity; handles reordering Needs a trusted per-entity version Events carry no version, or versions can be reused
    Dedupe key = partition and offset Free to compute A producer resend is not recognised Producers can send the same event twice
    Short retention Small table A late repeat is applied again Replays can arrive after the window

    In practice: ShopStream's store-payout consumer

    This is the realistic example, an educational scenario on the course's running example ShopStream; nothing in it describes a real company, and every number is illustrative.

    This is a realistic scenario, not a case history.

    The situation

    ShopStream's payments service publishes a PaymentCaptured event for each capture. A payout consumer adds the amount, minus the commission, to the store's payout balance. After a consumer deploy, two stores report payouts too high by exactly one order each.

    Starting architecture

    Store payout consumer, before the fixPayments service to Payments topic (event); Payments topic to Payout consumer (at least once); Payout consumer to Payout database (balance + amount)Payments service: publishes eventsPaymentsservicepublishes eventsPayments topic: payment-capturedPayments topicpayment-capturedPayout consumer: adds to balancePayoutconsumeradds to balancePayout database: store balancesPayoutdatabasestore balanceseventat least oncebalance + amount

    Figure 4. The payout path. How to read this: the consumer commits its offset after updating the balance, so a restart in between delivers the same event again, and the update adds rather than sets.

    Options considered

    Option Behaviour Risk
    A. Commit the offset first No double credit A crash loses a credit: a store is underpaid
    B. Recompute balances nightly from the ledger Repairs drift Wrong numbers all day
    C. Event id in a table with a unique key, in the balance transaction A repeat changes nothing A table to size and purge

    The decision

    Option C, plus a producer rule: the payments service writes the event id when it records the capture, so a republish reuses it. The key is (consumer, event id), kept for the longest plausible delay (illustrative: 14 days).

    Rollout and verification

    Check by counts: duplicates skipped per hour (non-zero after a restart proves the guard works), and each store's balance against the sum of its captured events. A replay in staging with the consumer killed at random points should leave every balance equal to that sum.

    The 2 a.m. failure

    An operator replays a three-week-old dead-letter topic. The table keeps 14 days, so older events are applied a second time and balances jump. The checks are the age of the oldest id in the table against the oldest record in the replay. The mitigation is to stop the consumer and restore balances from the ledger. The lasting fix is to refuse a replay older than the window, or keep ids as long as the topic retains records.

    Architect's notes

    • Put the id in the event at creation, not at send time.
    • Claim and effect share one transaction. If the effect is a remote call, give the remote system a key.
    • Prefer the cheapest mechanism: an overwrite or a version guard before a table.
    • Expect concurrency: a rebalance can run two copies of one message at once.

    Common mistakes

    • Marking first and applying second, in separate transactions: a crash loses the effect.
    • Check, then act, with no unique constraint: two copies pass the check together.
    • Partition and offset as the key when the producer can resend: the resend has a new offset.
    • Purging ids by a convenient age rather than the longest redelivery delay.
    • Treating the idempotent producer as consumer deduplication: it covers one session's retries only.

    Key takeaways

    • At-least-once delivery means every consumer must tolerate a repeat.
    • A dedupe key must be assigned once per event and survive a resend.
    • Record the id and apply the effect in one transaction, with a unique key as the arbiter.
    • An overwrite or a version guard is cheaper than a table when it fits, and a version guard also handles out-of-order arrival.
    • The retention window is a correctness setting, not a housekeeping one.

    Practice exercises

    Exercise 1 (20 min). For a welcome email, a stock decrement, a "set shipping address" event and a refund, name the mechanism from Figure 2.

    Exercise 2 (45 min). Run the lab. Leave the consumer name out of the key of IdempotentPaymentConsumer, add a second consumer that does other work, and explain which messages it skips. Restore the code and re-run the tests.

    Exercise 3 (1 hour). Write the PostgreSQL claim with INSERT ... ON CONFLICT DO NOTHING and say how the consumer knows whether it inserted. Check it against the documentation.

    Exercise 4 (2 hours). Design the retention rule for a ledger consumer that must survive a full topic replay, and say whether a version guard removes the table.

    The other side of this topic

    The front-end view is the client that submits a form twice or replays a queued action after reconnecting: the same event must be recognised by a stable id created when the user acts, which the browser keeps across retries.

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments