Idempotent Consumer in Kafka
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.
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.
| Cause | What happens |
|---|---|
| Crash after processing, before the commit | The database write succeeded, the offset commit never happened, so the record is redelivered after restart. |
| Rebalance | Partitions 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.ms | The consumer is removed from the group; its commit fails with CommitFailedException and the batch is processed again elsewhere. |
| Retries in the listener or error handler | A record that failed half-way, for example after the database write but before a later step, is retried in full. |
| Upstream resends and replays | A 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.
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:
| Key | Example | Assessment |
|---|---|---|
| Event ID created by the producer | A UUID in the payload or in a header such as eventId | Best default. Stays the same across retries, outbox republishing, DLT reprocessing and replays. |
| Business key plus version | paymentId, or orderId + status | Good when the domain already has a unique identifier for the action. |
| Topic, partition and offset | payments-0@42 | Only 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 payload | SHA-256 of the JSON | Risky: two legitimate, identical events (two equal top-ups) would be treated as one. |
5. Implementation Strategies
| Strategy | How it works | Best for |
|---|---|---|
| Naturally idempotent writes | Use 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 key | The 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 table | Insert 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 data | Save 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):
<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
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
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
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
}
}
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:
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”.
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 | |
|---|---|---|
| Covers | Kafka topic → Kafka topic | Any side effect the consumer controls: databases, caches, external APIs with idempotency keys |
| Provided by | Kafka clients and brokers | Your application code and database |
| Cost | Transaction coordination, read_committed consumers | One 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-capturedevent 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=allprevents 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.
13. Related Reading
- Kafka Delivery Semantics: At-Most-Once, At-Least-Once and Exactly-Once
- Idempotent Producer in Kafka
- Transactional Outbox Pattern with Kafka
- How to Replay Messages in Kafka
14. References
Kafka Idempotent Consumer Interview Questions and Answers
Common interview questions on Kafka Idempotent Consumer, from basic to scenario-based, with short answers you can explain in your own words.
Basic questions
Q. What is an idempotent consumer, and why does a Kafka application need one?
Answer: An idempotent consumer gives the same result whether it handles a message once or several times. Kafka consumers are at-least-once by default: processing a record and committing its offset are separate steps, so after a crash or rebalance some records are delivered again. Without idempotent handling, those repeats become double payments, duplicate emails or wrong stock counts. Kafka has no consumer-side setting for this; it is implemented in the application, usually with the database.
Q. In which situations does a consumer receive the same record more than once?
Answer: When it processed records but their offsets were not committed: a crash between processing and commit, a rebalance that moves the partition to another consumer, processing that exceeds max.poll.interval.ms so the commit fails, and error-handler retries of a record that partly succeeded. Duplicates can also come from upstream: a producer or outbox relay that publishes the same event twice, or a deliberate replay from an earlier offset.
Intermediate questions
Q. Why must the processed-message record and the business change be written in the same database transaction?
Answer: Otherwise there is a window where one is saved and the other is not. If the business change commits first and the process dies before the ID is saved, the redelivered event is applied again. If the ID commits first and the business change fails, the event is marked as done but never applied, which loses it. In one transaction both commit or both roll back, and a unique key on the ID makes concurrent duplicates fail safely.
Q. Why is topic-partition-offset a weak idempotency key?
Answer: It identifies a position in one log, not the event. If the same event is published again, for example by an outbox relay after a crash, or reaches the consumer from a retry topic or a DLT, it has a different offset or topic and is not recognised as a duplicate. A unique event ID created by the producer, carried in the payload or a header, stays the same on every path.
Q. Does Kafka’s exactly-once semantics remove the need for an idempotent consumer?
Answer: Only for pipelines that read from Kafka and write only to Kafka. Transactions commit output records and consumer offsets atomically inside Kafka, but a database write, REST call or email made during processing is outside the transaction. If the transaction aborts and the input is reprocessed, that side effect happens again. Services that write to a database still need an idempotent consumer, or must store offsets in the same database transaction.
Tricky and scenario questions
Q. A consumer saves data to the database but crashes before committing the offset. What happens after it restarts, and how do you prevent duplicate processing?
Answer: The group resumes from the last committed offset, so the record is delivered again, either to the restarted consumer or to whichever member received the partition in the rebalance. Kafka cannot know that the database write already happened. To make the repeat harmless, write the event ID into a processed-message table, or rely on a unique business key, in the same database transaction as the data, and skip the event when the ID already exists. Alternatively, store the offset in the same transaction and seek to it on partition assignment.
Q. The handler calls an external payment API, which cannot join your database transaction. How do you make it idempotent?
Answer: Send the event ID as the provider’s idempotency key, so a repeated call returns the original result instead of charging again. If the provider has no such feature, record the attempt as PENDING before the call and COMPLETED with the provider’s reference after it. On redelivery, a COMPLETED row is skipped, and a PENDING row is reconciled by asking the provider for the status of that payment before retrying.
Q. The processed-message table has grown to hundreds of millions of rows. How long must you keep the IDs?
Answer: At least as long as a duplicate can still arrive: the topic’s retention period, plus any replay or DLT reprocessing window you support. After that, a scheduled job can delete old rows in small batches, or the table can be partitioned by date so old partitions are dropped. Removing IDs earlier is the risk to avoid: a replay of older data would then be processed again.