Building an Idempotent Kafka Consumer with Spring Boot 3: Preventing Duplicate Event Processing in Distributed Systems
Kafka makes communication between microservices reliable and scalable, but handling messages correctly when failures occur is a different challenge. A consumer can receive the same event more than once, even when the producer publishes it only once. This behaviour is expected in systems that use at-least-once message delivery.
Consider an order-processing service that receives an event indicating that a payment has been completed. The consumer updates the order status and records the payment. If the application crashes after committing the database transaction but before committing the Kafka offset, Kafka can deliver the event again. Without an idempotency mechanism, the application may execute the same business operation twice.
In this article, we will build a database-backed idempotent Kafka consumer using Java 21, Spring Boot 3, Spring Kafka, PostgreSQL and Spring Data JPA. We will also examine how Redis can improve duplicate detection, and why it should not replace durable transaction management.
1. Why Kafka Consumers Receive Duplicate Events
Kafka consumers maintain offsets to track which records have been processed. A consumer normally commits an offset after processing a record. However, database transactions and Kafka offset commits are separate operations unless an appropriate transactional design is implemented.
Imagine the following sequence:
- A consumer receives an event with ID
evt_9981274. - The application processes the order and updates PostgreSQL.
- The database transaction commits successfully.
- The consumer crashes before committing its Kafka offset.
- Kafka assigns the partition to another consumer.
- The new consumer receives the same event again.
The database update has already happened, but Kafka has no confirmation that the application completed processing. Consequently, the event is delivered again.
This is one reason application-level idempotency is important in distributed systems.
2. What Is Idempotency?
An operation is idempotent when executing it multiple times produces the same final result as executing it once.
For example, setting an order status to PAID is naturally idempotent if the operation only updates the status. However, adding the payment amount to an account balance is not naturally idempotent because repeated execution can credit the account multiple times.
We can prevent this by assigning every event a unique identifier and recording which events have already been processed.
Our design uses an inbox table in PostgreSQL. The event identifier is protected by a unique constraint. The event record and the corresponding business update are committed within the same database transaction.
3. Architecture and Processing Flow
The processing flow is straightforward:
Kafka Topic
|
v
Spring Kafka Consumer
|
v
Extract Event ID
|
v
Insert into Processed Events Table
|
+---- Event already exists
| |
| v
| Skip duplicate
|
+---- New event
|
v
Execute business logic
|
v
Commit database transaction
|
v
Listener returns successfully
|
v
Kafka offset is committed
The important design decision is that the idempotency record and business update must participate in the same database transaction.
4. Database Design
First, create a table to track processed Kafka events.
CREATE TABLE processed_events (
id BIGSERIAL PRIMARY KEY,
event_id VARCHAR(150) NOT NULL UNIQUE,
event_type VARCHAR(100) NOT NULL,
processed_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
The unique constraint on event_id ensures that two concurrent consumers cannot successfully register the same event identifier.
For a production system, the event identifier should be generated by the producer and remain unchanged across retries and redeliveries. Do not generate a new identifier every time a consumer receives the event.
5. Spring Boot Implementation
Add the required dependencies to your Spring Boot 3 application:
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
Step 1: Create the event entity
@Entity
@Table(name = "processed_events")
public class ProcessedEvent {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "event_id", nullable = false, unique = true)
private String eventId;
@Column(name = "event_type", nullable = false)
private String eventType;
@Column(name = "processed_at", nullable = false)
private LocalDateTime processedAt;
protected ProcessedEvent() {}
public ProcessedEvent(String eventId, String eventType) {
this.eventId = eventId;
this.eventType = eventType;
this.processedAt = LocalDateTime.now();
}
}
Step 2: Implement atomic event registration
For PostgreSQL, we can use INSERT ... ON CONFLICT DO NOTHING. This avoids relying on an exception to detect duplicate events.
@Repository
public class IdempotencyRepository {
private final JdbcTemplate jdbcTemplate;
public IdempotencyRepository(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public boolean registerEvent(String eventId, String eventType) {
String sql = """
INSERT INTO processed_events
(event_id, event_type, processed_at)
VALUES (?, ?, CURRENT_TIMESTAMP)
ON CONFLICT (event_id) DO NOTHING
""";
int inserted = jdbcTemplate.update(
sql, eventId, eventType
);
return inserted == 1;
}
}
The method returns true when a new event is registered and false when the event identifier already exists.
Step 3: Implement the transactional service
This is the most important part of the implementation. Both event registration and the business update must execute within the same database transaction.
@Service
public class OrderEventService {
private final IdempotencyRepository idempotencyRepository;
private final OrderRepository orderRepository;
public OrderEventService(
IdempotencyRepository idempotencyRepository,
OrderRepository orderRepository) {
this.idempotencyRepository = idempotencyRepository;
this.orderRepository = orderRepository;
}
@Transactional
public void process(OrderCreatedEvent event) {
boolean newEvent = idempotencyRepository.registerEvent(
event.getEventId(),
"ORDER_CREATED"
);
if (!newEvent) {
return;
}
Order order = new Order();
order.setOrderId(event.getOrderId());
order.setStatus("CREATED");
orderRepository.save(order);
}
}
If the business operation fails and the exception causes the transaction to roll back, the idempotency record is rolled back as well. Kafka can then redeliver the event and the application can retry processing it.
If the database transaction commits successfully but the consumer crashes before the offset commit, the event is delivered again. This time, the unique event identifier already exists, so the business operation is skipped.
Step 4: Create the Kafka listener
@Component
public class OrderEventConsumer {
private final OrderEventService orderEventService;
public OrderEventConsumer(OrderEventService orderEventService) {
this.orderEventService = orderEventService;
}
@KafkaListener(
topics = "order-events",
groupId = "order-service-group"
)
public void consume(OrderCreatedEvent event) {
orderEventService.process(event);
}
}
The listener returns normally after successful processing or when a duplicate is detected. If processing fails, the exception should propagate to the Kafka listener container so that its configured error-handling mechanism can take action.
6. Handling Retries and Dead Letter Topics
Not every failure should be retried indefinitely. Temporary database connectivity issues may recover after a short delay, while invalid event payloads may require manual investigation.
Spring Kafka provides DefaultErrorHandler and DeadLetterPublishingRecoverer for retry and recovery handling.
@Configuration
public class KafkaErrorConfiguration {
@Bean
public DefaultErrorHandler errorHandler(
KafkaTemplate<Object, Object> kafkaTemplate) {
DeadLetterPublishingRecoverer recoverer =
new DeadLetterPublishingRecoverer(
kafkaTemplate,
(record, exception) ->
new TopicPartition(
record.topic() + ".DLQ",
record.partition()
)
);
ExponentialBackOff backOff =
new ExponentialBackOff(1000L, 2.0);
backOff.setMaxElapsedTime(10000L);
return new DefaultErrorHandler(recoverer, backOff);
}
}
This configuration retries failed records using exponential backoff and publishes records that cannot be recovered to a dead-letter topic. Production systems should also define which exception types are retryable and which should go directly to the DLQ.
Offset acknowledgement and recovery behaviour depend on the listener container configuration. Therefore, test the complete processing and recovery flow rather than assuming that returning from a method always means an offset has been committed.
7. Where Does Redis Fit?
Redis can be useful when duplicate events arrive frequently and the application needs a fast preliminary check. An atomic Redis operation such as SET NX can prevent multiple consumers from acquiring the same temporary key.
However, Redis introduces another failure boundary. Consider a consumer that records a Redis key and then crashes before updating PostgreSQL. A redelivered event may be rejected because the Redis key still exists. This can prevent valid processing.
For this reason, a Redis key should not be treated as proof that a business transaction has completed. If Redis is used, the design needs explicit states, recovery rules, key expiry handling and reconciliation with the durable database record.
For critical operations, the database-backed inbox pattern should remain the source of truth.
8. Production Considerations
- Stable event IDs: Every event must have a unique identifier that remains consistent across retries.
- Atomic database operations: Store the idempotency record and update business data in the same transaction.
- External API calls: A database transaction cannot roll back an external HTTP request. Use an outbox, an idempotent downstream API or a separate workflow for external side effects.
- Retention policy: Decide how long processed event records must be retained. Deleting them too early can allow old events to be processed again.
- Monitoring: Track duplicate counts, retry attempts, processing latency, consumer lag and DLQ volume.
- Failure testing: Simulate consumer crashes, database failures, rebalances and repeated event delivery.
Conclusion
Duplicate Kafka delivery is not necessarily a broker defect. It is a normal condition that applications must handle when they rely on at-least-once delivery.
A reliable consumer should not assume that every event arrives exactly once. By using stable event identifiers, database uniqueness constraints and transactional business processing, we can make repeated delivery safe for database-backed operations.
Redis can provide an additional performance optimisation, while Spring Kafka error handlers and dead-letter topics help manage failures that cannot be resolved immediately.
The key engineering principle is simple: design your consumers to tolerate duplicate delivery instead of assuming duplicates will never happen.
Frequently Asked Questions
1. Does Kafka guarantee exactly-once message delivery?
Kafka supports several delivery semantics, including transactions for Kafka-to-Kafka processing. Exactly-once effects in an external database require additional application-level transaction design.
2. Is Redis SETNX enough for Kafka idempotency?
No. Redis can provide atomic key creation, but it does not automatically coordinate with a database transaction or Kafka offset commit.
3. What is an idempotent Kafka consumer?
It is a consumer designed so that processing the same event multiple times does not repeat the intended business effect.
4. What is the inbox pattern?
The inbox pattern stores incoming event identifiers in a durable database table and uses them to prevent duplicate business processing.
Keywords: Kafka Idempotency, Spring Boot 3, Apache Kafka Consumer, Duplicate Message Processing, Kafka At Least Once Delivery, Spring Kafka, PostgreSQL, Redis, Database Transactions, Inbox Pattern, Dead Letter Queue, Event Driven Microservices, Distributed Systems, Java 21.
Comments
Post a Comment