Overview

Every message broker guarantees at-least-once delivery if you configure retries. That guarantee has a corollary: messages will arrive more than once under failure conditions. A network partition clears, a consumer pod restarts mid-commit, a rebalance fires at the worst moment—any of these produces a re-delivered message that your consumer has already processed.

For some data, a duplicate log entry or a replayed analytics event is an irritant. For business transactions it is not. In payment processing, a duplicate execution is a regulatory incident: a double credit to a beneficiary, a double debit from a customer, a duplicate pacs.008 submitted to a clearing system. Clearing and settlement systems run reconciliations that will eventually catch the discrepancy, but not fast enough to prevent the debit going through. The same is true of an order fulfilled twice or a usage record billed twice. Your idempotency layer has to catch it before that.

This article covers the full deduplication stack: the key design problem, three implementation tiers (database, Redis, Kafka EOS), their interaction with ISO 20022 message identifiers, and the monitoring that lets you prove to an auditor that duplicates are being caught. The worked examples use payments, but the same design applies to order numbers, booking references or telecom call-detail records.

Trade-off summary up front

Database deduplication is the simplest and most durable approach; it adds one SQL write per event. Redis deduplication adds 1–3 ms and is appropriate when the database write is not acceptable on the hot path. Kafka EOS is the most complete guarantee, but it constrains your consumer topology and introduces latency that most teams underestimate. You will almost certainly need all three at different points in your pipeline.

At-least-once delivery: what it actually means

At-least-once delivery means the broker ensures the message is delivered to a consumer at least one time. It does not mean once. The two scenarios that produce redelivery in Kafka are:

  • Consumer crash before offset commit. The consumer processes the message and updates its downstream state, but crashes before Kafka records the committed offset. On restart, Kafka redelivers from the last committed offset. The downstream sees the event twice.
  • Producer retry on timeout. The producer sends a message, the broker receives and appends it, but the network drops the acknowledgement. The producer retries. Without idempotent producer configuration, the broker appends a second copy. Two messages, one intent.

At-exactly-once delivery eliminates these scenarios, but it is a property of the full producer–broker–consumer chain, not of any single component. The sections below build up the stack from the most durable layer (database) to the most complete (Kafka EOS).

The deduplication key problem

Before any implementation, you need a stable, globally unique key per business event. This sounds obvious; in practice it is the most common design mistake. Four anti-patterns:

Key choice Problem Use instead
Kafka offset Offset is partition-scoped; the same offset appears in partition 0, 1, 2. Unique only in combination with topic and partition. Composite: topic + partition + offset
Database auto-increment ID Generated at insert time. If the producer crashes between insert and publish, the ID never reaches the consumer. If the message is replayed from an outbox snapshot, the ID is the same but the dedup state may have been cleared. UUID generated before the transaction; use as both PK and event ID in the payload.
Request timestamp Not unique. Two payments from the same account at the same millisecond (concurrent API calls) produce the same key. UUID or ISO 20022 EndToEndId (see §ISO 20022).
Message content hash Semantically identical retries (re-submitted payment for the same amount) have the same hash and are silently dropped. Combine content hash with a nonce or timestamp for idempotency windows, not global dedup.
Carry the key through every hop

The deduplication key generated at the payment entry point must be propagated unchanged through every transformation, enrichment, and routing step. It is a distributed system invariant, not a database concern. If any service in the chain re-generates the key, deduplication breaks silently—the new key has no history and always looks fresh to downstream consumers.

Database-level deduplication

The simplest and most reliable idempotency mechanism is an INSERT ... ON CONFLICT DO NOTHING into a dedicated table. When the same event ID arrives twice, the second insert is a no-op; the application never sees the duplicate.

idempotency-schema.sqlsql
CREATE TABLE processed_events (
  event_id       uuid           PRIMARY KEY,
  event_type     varchar(80)    NOT NULL,
  consumer_group varchar(80)    NOT NULL,
  processed_at   timestamptz    NOT NULL DEFAULT now()
);

-- Optional: partition by month for very high-volume pipelines.
-- Retention: delete rows older than the redelivery window (48h is conservative).
-- Do NOT use TTL deletion based on wallclock age alone—use the Kafka retention
-- window as the authority: if a message can no longer be redelivered, the row
-- can be deleted.

CREATE INDEX processed_events_at_idx ON processed_events (processed_at);

The consumer logic around this table must be atomic with the business write. If you insert into processed_events in one transaction and write the business state in another, a crash between the two leaves you either with a duplicate business write or a ghost idempotency record that permanently blocks the event.

PaymentConsumer.javajava
@KafkaListener(topics = "payment.submitted", groupId = "payments-processor")
@Transactional
public void onPaymentSubmitted(ConsumerRecord<String, PaymentEvent> record,
                                Acknowledgment ack) {

  UUID eventId = UUID.fromString(record.value().getEventId());

  // Atomic guard: insert returns 0 on conflict, skip if duplicate.
  int inserted = jdbc.update(
    """
    INSERT INTO processed_events (event_id, event_type, consumer_group)
    VALUES (?, ?, ?)
    ON CONFLICT (event_id) DO NOTHING
    """,
    eventId, "PaymentSubmitted", "payments-processor");

  if (inserted == 0) {
    // Duplicate detected: ack and discard without side-effects.
    ack.acknowledge();
    metrics.counter("payment.dedup.db.duplicate").increment();
    return;
  }

  // First-time processing: apply business logic in the same transaction.
  paymentService.process(record.value());
  ack.acknowledge();   // offset commit after DB commit confirms durability
}
Manual offset commit matters here

Use enable.auto.commit=false and acknowledge only after the database transaction commits. Auto-commit can advance the offset before the DB write lands, creating a window where a crash produces an undetectable duplicate (the offset is advanced so Kafka will not redeliver, but the DB state was never written).

Redis atomic deduplication

For consumers that do not write to a relational database—notification services, fee calculation engines, routing tables—a Redis SET NX (set-if-not-exists) provides a low-latency idempotency gate. The pattern is a conditional SET with a TTL equal to the maximum redelivery window.

RedisDeduplicator.javajava
private final RedisTemplate<String, String> redis;
private static final Duration DEDUP_WINDOW = Duration.ofHours(48);

public boolean tryAcquire(String eventId, String consumerGroup) {
  String key = "dedup:" + consumerGroup + ":" + eventId;
  // SET key value NX EX seconds — atomic, returns null if key already exists.
  Boolean acquired = redis.opsForValue()
      .setIfAbsent(key, "1", DEDUP_WINDOW);
  return Boolean.TRUE.equals(acquired);
}

// In the consumer:
if (!deduplicator.tryAcquire(eventId, "notifications")) {
  ack.acknowledge();
  return;   // duplicate, discard
}
notificationService.send(record.value());
ack.acknowledge();
Redis replication lag is a real risk

In a Redis Cluster or Sentinel setup, a SET NX succeeds on the primary, and the primary fails before replicating to the secondary. The secondary is promoted; the new primary has no record of the key. The next delivery of the same event passes the gate and is processed a second time. For payments, this is unacceptable. Use Redis Cluster with WAIT 1 0 after the SET to confirm replica acknowledgement, or fall back to the database idempotency table for anything that touches money.

Kafka exactly-once semantics

Kafka 0.11 introduced exactly-once semantics (EOS) as a first-class feature. EOS covers two guarantees: idempotent producers (no broker-side duplicates on retry) and transactional producers (atomic multi-partition writes). Consumer-side exactly-once requires the consume–process–produce loop to use the same transaction.

EOS is the right tool when your pipeline is pure Kafka—you consume from one topic and produce to another, with no external state mutation inside the processing loop. Once you introduce a database write, Redis write, or HTTP call inside the consumer, you are back to needing application-level idempotency, because those side-effects cannot participate in the Kafka transaction.

Idempotent producer configuration

The idempotent producer is the baseline: enable it unconditionally in any production Kafka producer. It adds a producer ID and sequence number to each message batch; the broker rejects any sequence the producer has already seen within its current epoch.

kafka-producer.yamlyaml
# Spring Boot application.yml — Kafka producer section
spring:
  kafka:
    producer:
      # Idempotent producer: prevent broker-side duplicates on retry.
      properties:
        enable.idempotence: "true"          # requires acks=all, retries>0
        acks: "all"
        retries: 2147483647               # Integer.MAX_VALUE: retry until success
        max.in.flight.requests.per.connection: 5  # safe with idempotence enabled
        delivery.timeout.ms: 120000       # 2 min total; adjust to payment SLA

      # Transactional producer (EOS): enable when consume-process-produce loop needed.
      transaction-id-prefix: "payment-processor-"  # unique per application instance

    consumer:
      properties:
        # Read only committed messages when consuming from a transactional topic.
        isolation.level: "read_committed"
        enable.auto.commit: "false"
        auto.offset.reset: "earliest"
        max.poll.records: 100
        max.poll.interval.ms: 300000    # 5 min; sized to max batch processing time
transaction-id-prefix must be unique per service instance

If two pods share the same transaction-id-prefix, the broker assigns the same producer ID to both. A producer with a higher epoch fences a lower-epoch producer—the lower-epoch pod’s in-flight transactions abort. In Kubernetes, append the pod hostname or a deterministic shard ID to the prefix. Randomizing the suffix defeats the fencing guarantee, because the broker has no history to fence against.

Consumer isolation levels

The isolation.level consumer config controls which messages are visible to the consumer. Its interaction with transactional producers is subtle:

  1. read_committed (recommended for payment pipelines)

    Only messages from committed transactions are visible. Aborted transaction messages are filtered by the broker. Uncommitted messages from an in-flight transaction are withheld until the transaction commits or aborts. This introduces a small amount of end-to-end latency but guarantees that aborted messages never reach the consumer.

  2. read_uncommitted (default)

    All messages, including those from in-flight and subsequently aborted transactions, are visible. The consumer sees the abort marker after the fact but has already processed the message. For a payment pipeline, this means consumers must handle abort markers explicitly—which most Spring Kafka setups do not do by default.

  3. LSO lag implications

    The Last Stable Offset (LSO) is the highest offset below any open transaction. Consumer lag metrics that use the log end offset minus the committed offset will be inflated by open transactions. Wire your consumer lag alerting to the LSO, not the LEO, to avoid false alerts during long-running transactions.

  4. Partition assignment and EOS

    A transactional producer is bound to specific partitions at send time. On consumer group rebalance, a new consumer instance inherits the partition—but the transaction manager on the old instance may still have an open transaction. The transaction coordinator will time out the open transaction and abort it, ensuring the new consumer does not see an orphaned partial write.

  5. Non-transactional topics alongside transactional ones

    If the pipeline mixes transactional and non-transactional topics in the same consumer group, read_committed applies only to the transactional topics. Non-transactional topics are read with no isolation. This is safe but must be explicitly understood by the engineering team maintaining the consumer group configuration.

ISO 20022 EndToEndId as the idempotency key

ISO 20022 payment messages carry a mandatory EndToEndIdentification field in the CdtTrfTxInf block. This identifier is assigned by the originating party and must remain unchanged across every step of the payment chain: pacs.008 origination, pacs.002 confirmation, pacs.004 return, and camt.056 cancellation request. It is, by the ISO 20022 specification, an idempotency key.

pacs008-fragment.xmlxml
<CdtTrfTxInf>
  <PmtId>
    <!-- EndToEndId: originator-assigned; MUST be preserved end-to-end -->
    <EndToEndId>E2E-20261024-000123</EndToEndId>
    <!-- TxId: set by the first instructing agent; passed on unchanged along the interbank chain -->
    <TxId>TX-20261024-0001</TxId>
    <!-- UETR: UUIDv4 generated once at origination; universally unique end-to-end -->
    <UETR>a23cc4f5-7e8b-4c12-a9d1-3f4e5b6c7d8e</UETR>
  </PmtId>
  <IntrBkSttlmAmt Ccy="EUR">5000.00</IntrBkSttlmAmt>
  <!-- ... -->
</CdtTrfTxInf>

For SWIFT cross-border payments, and for the market infrastructures that have adopted it, the UETR is the authoritative end-to-end reference at the network level. Within an institution’s internal Kafka pipeline, use the UETR as the primary idempotency key and the EndToEndId as a secondary key for customer-facing tracing. Do not use the InstrId: it is a point-to-point reference between two agents and changes at each interbank leg, so as an idempotency key it fails for any multi-hop payment. The TxId is assigned by the first instructing agent and, under the ISO 20022 definition, passed on unchanged along the interbank chain — but it is not set by the debtor, so it cannot catch a customer’s resubmission.

UETR format and generation

A UETR is a UUIDv4 in lowercase hyphenated form (8-4-4-4-12). Generate it once, at the originating system, and treat it as immutable. The SWIFT gpi tracker uses it as the primary key across all correspondent banks in the payment chain. Domestic schemes and market infrastructures publish their own rules on UETR usage and uniqueness; check the rulebook for each scheme you connect to and enforce the stricter rule in your dedup store. Include it in every event envelope your Kafka topics carry for ISO 20022 payment flows.

Monitoring deduplication

A deduplication layer you cannot observe is a deduplication layer that fails silently. Four metrics to wire before going live:

dedup-metrics.yamlyaml
# Prometheus recording rules for deduplication health

groups:
  - name: dedup
    rules:

    - record: payment_dedup_duplicate_rate
      expr: |
        rate(payment_dedup_db_duplicate_total[5m])
        / rate(payment_events_received_total[5m])
      # Alert if >0.1% of messages are duplicates over a sustained 15m window.
      # A sudden spike usually means a consumer rebalance storm or a bad deployment.

    - record: payment_dedup_miss_rate
      expr: |
        rate(payment_dedup_redis_miss_total[5m])
        / rate(payment_events_received_total[5m])
      # A Redis miss followed by no DB duplicate = first delivery: OK.
      # A Redis miss followed by a DB conflict = Redis TTL too short or cluster failover.

    - alert: DedupDatabaseLag
      expr: |
        pg_table_bloat_bytes{table="processed_events"} > 10e9
      annotations:
        summary: "processed_events table bloat > 10 GB — cleanup job may be stuck"
      # processed_events must be pruned on schedule; bloat prevents index scan efficiency.

    - alert: KafkaTransactionAbortRate
      expr: |
        rate(kafka_producer_transaction_abort_total[5m]) > 0.05
      annotations:
        summary: "Kafka transaction abort rate >5% — check max.poll.interval.ms"

The most useful operational signal is the deduplication ratio over time. In a healthy pipeline, it stays below 0.1%. A ratio above 1% consistently indicates either a consumer rebalance storm (too-short max.poll.interval.ms), a Kafka offset replay triggered by a reset, or a producer misconfiguration that is re-sending batches.

When idempotency is not enough

Idempotency does not solve ordering

An idempotent consumer correctly discards duplicate events, but it does not guarantee that events arrive in the order they were produced. A payment amendment that arrives before the original payment passes the deduplication check (it has a different event ID) but is applied to state that does not yet exist. Ordering is a partition-key problem: co-locate all events for the same payment on the same partition using the payment ID as the message key. Idempotency and ordering are independent guarantees—you need both.

Three additional scenarios where application-level idempotency alone is insufficient:

  • Long-running sagas. A multi-step payment saga (authorise → reserve funds → execute → confirm) involves events across multiple topics. Deduplication on each topic independently does not prevent a saga that completed step 3 from being replayed from step 1 if the saga coordinator crashes. Use a saga state machine with its own idempotency table keyed on the saga ID.
  • External system calls inside the consumer. An HTTP call to a legacy system of record, an SMS notification, a SWIFT message dispatch—none of these can participate in a Kafka transaction or a database transaction. For these side-effects, use a dedicated outbox table to track whether the external call was made, and call the external system only once per idempotency key, checking the outbox before each call.
  • Consumer group topic resets. An operations team manually resets the consumer group offset to replay a production incident. Without an idempotency layer, every downstream system re-receives every event from the reset point. With a database idempotency table and a sufficiently long retention window, the replayed events are silently discarded. If the retention window has elapsed, the table has been pruned and the events will be reprocessed. Size your retention window to the maximum credible reset window: for a production payment pipeline, 7 days is a reasonable minimum.