00:00

Idempotent Consumer in Kafka

Last updated:

An idempotent consumer in Kafka is a consumer that produces the same result whether it processes a message once or several times. Kafka consumers normally work with at-least-once delivery: after a crash, a rebalance or a slow poll loop, records that were already processed can be delivered again. An idempotent consumer detects or absorbs these repeats, so a payment is booked once, an email is sent once and a stock count is reduced once.

This tutorial explains why duplicates reach consumers, how to choose an idempotency key, the main implementation strategies, and a production-style Spring Boot example that keeps the deduplication record and the business change in one database transaction. Examples use Kafka 4.4, Spring Boot 4 and Spring for Apache Kafka 4.

1. What Is an Idempotent Consumer?

An operation is idempotent when repeating it does not change the result after the first time. Setting an order’s status to SHIPPED is naturally idempotent; adding 100 to an account balance is not. An idempotent consumer makes every message handler behave like the first kind, either because the operation is idempotent by nature or because the consumer remembers which messages it has already handled.

This is an application pattern, not a Kafka setting. Kafka has an idempotent producer (enable.idempotence), but no consumer-side switch: deduplication on the consumer side is always your code, usually backed by your database.

Analogy: A cashier who stamps “PAID” on each invoice. If the same invoice is handed over twice, the stamp shows it was already paid, so no second payment is made.

2. Why Consumers Receive Duplicates

A consumer group stores its progress as a committed offset per partition. Processing a record and committing its offset are two separate steps, and no failure can be ruled out between them. Whenever a consumer stops after processing but before committing, the next owner of the partition starts from the last committed offset and sees those records again.

CauseWhat happens
Crash after processing, before the commitThe database write succeeded, the offset commit never happened, so the record is redelivered after restart.
RebalancePartitions move to another consumer, which resumes from the last committed offset, not from what the old owner actually finished.
Processing longer than max.poll.interval.msThe consumer is removed from the group; its commit fails with CommitFailedException and the batch is processed again elsewhere.
Retries in the listener or error handlerA record that failed half-way, for example after the database write but before a later step, is retried in full.
Upstream resends and replaysA producer that resends after a failure, an outbox relay that republishes after a crash, or a deliberate replay from an earlier offset.

Turning on the idempotent producer does not help here: it prevents duplicate writes to the log, while these duplicates are repeated reads of records that exist only once. The Offset Management tutorial explains commit timing in detail.

3. How an Idempotent Consumer Works

The most common design gives every event a unique ID and records each ID the consumer has processed. The key rule is that the ID record and the business change are written in the same database transaction. Either both exist or neither does, so there is no moment when the business change is saved but the consumer has “forgotten” it.

How an idempotent consumer handles a redelivered messageFirst delivery: the consumer polls offset 42 with event ID e-7f3, then in one database transaction inserts e-7f3 into the processed_message table and writes the ledger entry, then crashes before committing the offset. Redelivery after restart: the consumer polls offset 42 again, the insert of e-7f3 into processed_message finds an existing row and changes nothing, so the business write is skipped and offset 43 is committed. The ledger contains the payment once. First delivery ① poll offset 42payments-0, eventId e-7f3 ② one DB transactioninsert processed_message e-7f3+ insert ledger entry, commit ③ crashoffset 43 never committed restart or rebalance: resume from the last committed offset (42) Redelivery ④ poll offset 42 againsame eventId e-7f3 ⑤ insert e-7f3 againrow exists: 0 rows insertedskip the ledger write ⑥ commit offset 43payment booked once The ID row and the ledger row commit together, so a redelivery always finds the ID
The consumer crashes after its database transaction but before the offset commit. On redelivery, the existing processed_message row tells it the event was already applied.

Committing the offset is still required, but it becomes an optimisation: it only decides how many records are re-read after a failure, not whether the result is correct.

4. Choosing the Idempotency Key

The key must identify the event, not the delivery. Options, from best to weakest:

KeyExampleAssessment
Event ID created by the producerA UUID in the payload or in a header such as eventIdBest default. Stays the same across retries, outbox republishing, DLT reprocessing and replays.
Business key plus versionpaymentId, or orderId + statusGood when the domain already has a unique identifier for the action.
Topic, partition and offsetpayments-0@42Only unique within one topic. The same event republished to another topic, a retry topic or a DLT gets a new offset, so it is not detected.
Hash of the payloadSHA-256 of the JSONRisky: two legitimate, identical events (two equal top-ups) would be treated as one.

5. Implementation Strategies

StrategyHow it worksBest for
Naturally idempotent writesUse upserts and absolute values: status = 'SHIPPED', INSERT ... ON CONFLICT (order_id) DO UPDATE.State-transfer events that carry the full new state.
Unique constraint on a business keyThe target table has a unique column, for example payment_id; a duplicate insert fails or does nothing.Events that create exactly one row.
Processed-message tableInsert the event ID into a dedicated table in the same transaction as the business change.General purpose: increments, several tables per event.
Offsets stored with the dataSave the partition offset in the same database transaction and seek to it on assignment.Single-sink pipelines that want exactly-once into one database.

Calls to systems you do not control, such as a payment provider or an email service, cannot join your database transaction. For those, pass the event ID as the provider’s idempotency key if it supports one, or record a PENDING status before the call and DONE after it, so a redelivery can check what already happened.

6. Spring Boot Example

A ledger service consumes payment-captured events and books each payment once. It uses PostgreSQL, Spring JDBC and Spring for Apache Kafka. Dependencies (Spring Boot 4.2 parent):

pom.xml (dependencies)
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-kafka</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <scope>runtime</scope>
</dependency>

6.1 Tables

schema.sql
CREATE TABLE processed_message (
    consumer_group VARCHAR(100) NOT NULL,
    message_id     VARCHAR(100) NOT NULL,
    processed_at   TIMESTAMPTZ  NOT NULL DEFAULT now(),
    PRIMARY KEY (consumer_group, message_id)
);

CREATE TABLE ledger_entry (
    id         BIGSERIAL PRIMARY KEY,
    account_id VARCHAR(50)    NOT NULL,
    amount     NUMERIC(19, 2) NOT NULL,
    event_id   VARCHAR(100)   NOT NULL
);

The primary key includes the consumer group, so two different services can process the same event independently while each processes it only once.

6.2 Event and transactional service

LedgerService.java
package com.javabytechie.ledger;

import java.math.BigDecimal;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

record PaymentCaptured(String eventId, String accountId, BigDecimal amount) {}

@Service
public class LedgerService {

    private static final Logger log = LoggerFactory.getLogger(LedgerService.class);
    private static final String GROUP = "ledger-service";

    private final JdbcTemplate jdbc;

    public LedgerService(JdbcTemplate jdbc) {
        this.jdbc = jdbc;
    }

    @Transactional  // one database transaction for the ID row and the business change
    public void book(PaymentCaptured event) {
        int inserted = jdbc.update("""
                INSERT INTO processed_message (consumer_group, message_id)
                VALUES (?, ?)
                ON CONFLICT DO NOTHING
                """, GROUP, event.eventId());

        if (inserted == 0) {
            log.info("Duplicate event {} skipped", event.eventId());
            return;
        }

        jdbc.update("INSERT INTO ledger_entry (account_id, amount, event_id) VALUES (?, ?, ?)",
                event.accountId(), event.amount(), event.eventId());
        log.info("Booked {} for account {} (event {})", event.amount(), event.accountId(), event.eventId());
    }
}
  • ON CONFLICT DO NOTHING (PostgreSQL) returns 0 updated rows for a known ID instead of throwing, so no exception handling is needed and concurrent duplicates are handled by the primary key.
  • The ID is inserted first. If the ledger write then fails, the whole transaction rolls back, including the ID row, so the retry is processed normally.

6.3 Listener and configuration

PaymentCapturedListener.java
package com.javabytechie.ledger;

import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

@Component
public class PaymentCapturedListener {

    private final LedgerService ledgerService;

    public PaymentCapturedListener(LedgerService ledgerService) {
        this.ledgerService = ledgerService;
    }

    @KafkaListener(topics = "payment-captured", groupId = "ledger-service")
    public void onPaymentCaptured(PaymentCaptured event) {
        ledgerService.book(event);
        // Default ack mode BATCH: the container commits offsets after all records of the poll are processed
    }
}
application.yml
spring:
  datasource:
    url: jdbc:postgresql://localhost:5432/ledger
    username: ledger
    password: ${LEDGER_DB_PASSWORD}
  kafka:
    bootstrap-servers: localhost:9092
    consumer:
      auto-offset-reset: earliest
      value-deserializer: org.springframework.kafka.support.serializer.JacksonJsonDeserializer
      properties:
        spring.json.trusted.packages: com.javabytechie.ledger
        spring.json.value.default.type: com.javabytechie.ledger.PaymentCaptured

Spring for Apache Kafka sets enable.auto.commit to false unless you set it yourself, and the listener container commits offsets after the records from each poll have been processed (ack mode BATCH). If the application stops between the database commit and the offset commit, the next delivery of the event is detected as a duplicate:

Log after a restart (excerpt)
INFO  LedgerService : Booked 49.90 for account ACC-1001 (event e-7f3)
      ... application killed before the offset commit, then restarted ...
INFO  LedgerService : Duplicate event e-7f3 skipped
INFO  LedgerService : Booked 15.00 for account ACC-2002 (event a-91c)

7. Alternative: Storing Offsets in the Database

When a consumer writes to one database only, it can store the Kafka offset in that database, in the same transaction as the data. On startup or after a rebalance it reads the stored offsets and seeks to them, so Kafka’s committed offsets are no longer the source of truth. The KafkaConsumer Javadoc describes this pattern under “Storing offsets outside Kafka”.

SeekToStoredOffsets.java
consumer.subscribe(List.of("payment-captured"), new ConsumerRebalanceListener() {
    @Override
    public void onPartitionsAssigned(Collection<TopicPartition> partitions) {
        for (TopicPartition tp : partitions) {
            // offsetStore reads the last offset saved together with the business data
            offsetStore.find(tp).ifPresent(offset -> consumer.seek(tp, offset + 1));
        }
    }

    @Override
    public void onPartitionsRevoked(Collection<TopicPartition> partitions) {
        // nothing to do: every processed record already saved its offset in the same transaction
    }
});

This gives exactly-once results into that database without a deduplication table, but it ties the offset to one sink. As soon as a handler writes to two systems, go back to event IDs.

8. Idempotent Consumer vs Kafka Exactly-Once

Kafka’s exactly-once semantics (a transactional producer plus isolation.level=read_committed) make a consume–transform–produce step atomic: output records and consumer offsets are committed in one Kafka transaction. They do not cover side effects outside Kafka. A database insert, a REST call or an email made inside that step can still be repeated when the Kafka transaction aborts and the input is reprocessed.

Kafka exactly-once (transactions)Idempotent consumer
CoversKafka topic → Kafka topicAny side effect the consumer controls: databases, caches, external APIs with idempotency keys
Provided byKafka clients and brokersYour application code and database
CostTransaction coordination, read_committed consumersOne extra insert per message and a table to clean up

Most real services need the idempotent consumer even when they also use Kafka transactions.

9. Real-World Use Cases

  • Payments and ledgers: a redelivered payment-captured event must not create a second ledger entry.
  • Notifications: mark an email as sent per event ID, so a rebalance does not send the customer two confirmations.
  • Inventory: stock decrements are not idempotent by nature, so they need an event-ID check.
  • Search and cache updates: writing the full document by ID is naturally idempotent and needs no extra table.
  • Saga participants: each step of a saga may receive its command twice and must answer the same way both times.

10. Common Mistakes

  • Checking and writing the ID in separate transactions, which leaves a gap where the business change is saved but the ID is not.
  • Using “select, then insert” without a unique constraint. Two consumers processing the same event during a rebalance can both see “not processed”.
  • Keying on the offset and missing duplicates that arrive through a retry topic, a DLT or another topic.
  • Deleting processed IDs too early. A replay or a late redelivery after cleanup is processed again.
  • Assuming the idempotent producer or acks=all prevents consumer duplicates. They protect the write path, not redelivery.

11. Best Practices

  • Give every event a unique ID at the source and keep it unchanged through retries, outbox republishing and replays.
  • Prefer naturally idempotent operations (upserts, absolute state) and use a processed-message table only where needed.
  • Enforce uniqueness in the database with a primary key or unique index, never only in application code.
  • Keep processed IDs longer than any possible redelivery or replay window, at least as long as the topic’s retention, and delete older rows with a scheduled job.
  • Pass the event ID to external APIs as their idempotency key.
  • Test it: kill the consumer between the database commit and the offset commit and check that nothing is applied twice.

12. Summary

Kafka consumers are at-least-once by default, so crashes, rebalances, retries and replays deliver some records more than once. An idempotent consumer makes that harmless: give each event a stable ID, record the ID in the same database transaction as the business change, and enforce uniqueness with a database constraint. Use naturally idempotent writes where possible, store offsets with the data when there is only one sink, and remember that Kafka’s exactly-once transactions do not cover side effects outside Kafka.

14. References