Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 46

Idempotent Consumers for Event Processing

This lesson is built with resources from youtube.com, github.com and 1 more site.

Hello! In our last lesson, we successfully built an event-driven flow where the Auth Service produces a UserRegisteredEvent and a new Notifications Service consumes it. This is a huge step! However, our current consumer is "optimistic"—it assumes everything works perfectly.

Today, we'll make our consumer robust and production-ready by tackling a fundamental challenge in distributed systems: duplicate messages.

Introduction: From "At-Least-Once" to "Effectively-Once"

In our previous lesson, you saw how @KafkaListener makes consuming messages simple. Behind the scenes, the Spring Kafka container polls for messages, passes them to your method, and once your method completes successfully, it commits the offset back to Kafka. This tells Kafka, "I'm done with this message."

But what if your service crashes after processing the message but before committing the offset? Kafka, not having received the acknowledgement, will assume the message was not processed and will redeliver it to another consumer (or the same one when it restarts). This is Kafka's "at-least-once" delivery guarantee in action: it ensures messages aren't lost, but they might be delivered more than once.

In your MERN experience, if you were processing jobs from a queue (like BullMQ), you'd face the same issue. If a worker process fails unexpectedly, the job might be re-processed by another worker, potentially causing duplicate operations.

Our goal today is to implement the Idempotent Consumer pattern. An idempotent operation is one that has the same result whether it's performed once or multiple times. We will make our event processing idempotent, ensuring that even if Kafka sends us the same event 10 times, we only execute our business logic (like sending a welcome email) once. This gives us an "effectively-once" processing guarantee.

To understand the problem more deeply, let's start with a short video.

Handling Duplicate Messages (Idempotent Consumers)

The video 'Handling Duplicate Messages (Idempotent Consumers)' by CodeOpinion clearly explains the common reasons for duplicate messages in systems with an 'at-least-once' delivery guarantee.

Watch the first 3 minutes and 20 seconds of this video (00:00 - 03:20). Focus on the scenarios that lead to message redelivery, such as processing a message but failing to send the acknowledgement.


The Idempotent Consumer Pattern

The core strategy to achieve idempotency is to keep a persistent record of the messages we have already successfully processed.

Here's the flow for every message we receive:

  1. Extract a unique identifier for the event (an "idempotency key").
  2. Start a database transaction.
  3. Within the transaction:
    a. Check a dedicated database table (e.g., processed_events) to see if this event ID already exists.
    b. If it exists, we've seen this event before. We do nothing further and exit gracefully.
    c. If it does not exist, it's a new event. We proceed with our business logic (e.g., simulating the email) AND we insert the event's ID into our processed_events table.
  4. Commit the database transaction.

This entire process must be atomic. By wrapping the business logic and the event tracking in a single database transaction, we guarantee that both steps succeed or neither does. If the application crashes midway, the transaction is rolled back, and no changes are saved. Upon redelivery, the process starts fresh.

This diagram illustrates the pattern perfectly:

Idempotent Kafka Consumer Pattern with Spring Kafka
This diagram shows the flow of an idempotent consumer. A message is received, a database transaction begins, and a filter checks if the event ID exists in the database. If not, the application service performs its logic, and the event ID is saved. The entire operation is then committed atomically.

1. Preparing for Idempotency

1.1. Creating a Unique Event ID

The pattern relies on a unique ID per event. Our current UserRegisteredEvent doesn't have one. We will add this ID as a message header in the producer. Headers are a great place for metadata that isn't part of the core business event payload.

Action (in auth-service):

Modify your UserEventProducer in the auth-service to add a unique ID to each message's headers.

// In auth-service -> src/.../kafka/UserEventProducer.java

// ... imports
import org.springframework.kafka.support.KafkaHeaders;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import java.util.UUID;

// ... class definition

    public void sendMessage(UserRegisteredEvent event) {
        LOGGER.info("Producing UserRegisteredEvent for user: {}", event.getEmail());

        Message<UserRegisteredEvent> message = MessageBuilder
                .withPayload(event)
                .setHeader(KafkaHeaders.TOPIC, "user-registered-events")
                // Add a unique ID for idempotency
                .setHeader("eventId", UUID.randomUUID().toString()) 
                .build();

        kafkaTemplate.send(message);
    }
//...

1.2. Setting up the Database in the Notifications Service

Our notifications-service now needs a database to store the IDs of processed events.

Action (in notifications-service):

  1. Add Dependencies: Open the pom.xml for notifications-service and add the dependencies for Spring Data JPA and the PostgreSQL driver.

    <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>
    

    Don't forget to reload your Maven project in your IDE.

  2. Configure Database: In notifications-service/src/main/resources/application.yml, add the database configuration. We'll use the same PostgreSQL container but connect to a different database to maintain service independence.

    
    
    
    # Add this under the 'spring' section
    spring:
    
    
    
      # ... other spring properties
      datasource:
        url: jdbc:postgresql://localhost:5432/notifications_db
        username: user
        password: password
      jpa:
        hibernate:
          ddl-auto: update # For development, this creates/updates the schema automatically
        properties:
          hibernate:
            dialect: org.hibernate.dialect.PostgreSQLDialect
    

    You'll need to manually create the notifications_db database in your PostgreSQL instance. You can do this by connecting to Postgres (e.g., via psql or a GUI tool) and running CREATE DATABASE notifications_db;.

  3. Disable Kafka Auto-Commit: For Spring to manage commit offsets transactionally with the database, we must disable Kafka's own auto-commit mechanism.

    
    
    
    # Add this under spring.kafka.consumer
    spring:
      kafka:
        consumer:
    
    
    
          # ... other consumer properties
          enable-auto-commit: false 
    

2. Implementing the Idempotency Logic

Now for the core implementation. We'll create a JPA entity to store the event IDs and update our consumer.

Action (in notifications-service):

  1. Create the Idempotency Entity: This class represents a record in our tracking table.

    // Create a new package 'com.example.notifications.idempotency'
    // Create IdempotencyRecord.java inside it
    
    package com.example.notifications.idempotency;
    
    import jakarta.persistence.Entity;
    import jakarta.persistence.Id;
    import jakarta.persistence.Table;
    import java.time.Instant;
    
    @Entity
    @Table(name = "processed_events")
    public class IdempotencyRecord {
    
        @Id
        private String eventId;
    
        private Instant processedAt;
        
        // Constructors, getters, setters
        public IdempotencyRecord() {}
    
        public IdempotencyRecord(String eventId) {
            this.eventId = eventId;
            this.processedAt = Instant.now();
        }
    
        // Getters and Setters...
    }
    
  2. Create the Repository: A standard Spring Data JPA interface.

    // In the same 'idempotency' package, create IdempotencyRepository.java
    package com.example.notifications.idempotency;
    
    import org.springframework.data.jpa.repository.JpaRepository;
    import org.springframework.stereotype.Repository;
    
    @Repository
    public interface IdempotencyRepository extends JpaRepository<IdempotencyRecord, String> {
    }
    
  3. Update the Consumer: Now, let's modify UserEventConsumer to use these new components.

    // In src/.../UserEventConsumer.java
    package com.example.notifications;
    
    import com.example.blog.events.UserRegisteredEvent;
    import com.example.notifications.idempotency.IdempotencyRecord;
    import com.example.notifications.idempotency.IdempotencyRepository;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.kafka.annotation.KafkaListener;
    import org.springframework.messaging.handler.annotation.Header;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Transactional;
    
    @Service
    public class UserEventConsumer {
    
        private static final Logger LOGGER = LoggerFactory.getLogger(UserEventConsumer.class);
    
        @Autowired
        private IdempotencyRepository idempotencyRepository;
    
        @KafkaListener(topics = "user-registered-events", groupId = "notifications-group")
        @Transactional // This is the key!
        public void consume(UserRegisteredEvent event, @Header("eventId") String eventId) {
            
            // 1. Check if event has already been processed
            if (idempotencyRepository.existsById(eventId)) {
                LOGGER.warn("Duplicate event received with ID: {}. Skipping.", eventId);
                return;
            }
    
            // 2. Process the event (business logic)
            LOGGER.info("Received UserRegisteredEvent for user email: {} (Event ID: {})", event.getEmail(), eventId);
            LOGGER.info("-> Simulating sending a welcome email to {}", event.getEmail());
    
            // 3. Mark the event as processed
            idempotencyRepository.save(new IdempotencyRecord(eventId));
        }
    }
    

Let's break down the changes:

  • @Autowired private IdempotencyRepository ...: We inject our repository to interact with the database.
  • @Transactional: This is crucial. It tells Spring to wrap the entire consume method in a database transaction. If the method finishes, the transaction commits. If it throws an exception, the transaction rolls back. Spring Kafka's KafkaTransactionManager ensures that the Kafka offset is only committed after the database transaction successfully commits.
  • @Header("eventId") String eventId: We use the @Header annotation to extract our custom eventId header from the Kafka message and bind it to a method parameter.
  • The logic now follows our pattern: check, act, and record, all within one atomic transaction.

The following resources provide excellent code examples and explanations that mirror our implementation. While they use C#/.NET, the architectural pattern is identical.

Kafka Exactly-Once Delivery in Spring Boot

The article 'Kafka Exactly-Once Delivery in Spring Boot' provides a concise, Spring Boot-specific example of this pattern. It reinforces the code we've just written.

Read the sections 'Step 4 — The Consumer: The Hardest Part Done Right' and 'Step 5 — Commit Offsets After DB Commit'. Notice how their consumer logic and entity are almost identical to what we've implemented. This confirms we are following a standard, robust pattern.

Fix Duplicate Messages with the Idempotent Consumer Pattern

For a visual walkthrough of the transactional logic, watch this segment from Milan Jovanović's video. It clearly explains how the database transaction ensures atomicity.

Watch from 05:59 to 08:35. Pay close attention to how he wraps the business logic and the idempotency record insertion within a using (var transaction = ...) block. Our @Transactional annotation achieves the same result declaratively.


3. Your Task: Verifying Idempotency

It's time to see our robust consumer in action.

  1. Run the Stack: Make sure your Docker services (kafka, postgres, etc.) are running.
  2. Start Services: Run both the auth-service and the notifications-service.
  3. First Event: Send a POST request to http://localhost:8080/api/auth/register with a new user.
    • Observe: Look at the notifications-service logs. You should see the "Simulating sending a welcome email..." message. Check your notifications_db in Postgres; the processed_events table should now contain one record with the eventId.
  4. Simulate a Duplicate: We will manually send a message with the same eventId to simulate a redelivery.
    • Find the eventId from the notifications-service log of the first event.

    • Open a terminal and execute the following command, replacing <YOUR_EVENT_ID> and <YOUR_EVENT_PAYLOAD> accordingly. The payload is the binary Avro data, which is hard to construct manually.

    • A simpler approach: Let's simulate the duplicate at the source. Temporarily modify the UserEventProducer in auth-service to send a hardcoded eventId.

      // In auth-service -> UserEventProducer.java ... temporarily change this line
      .setHeader("eventId", "STATIC-TEST-ID-12345") // Hardcode a static ID
      
    • Restart the auth-service.

    • Register a new, different user. The event will be sent with the static ID. The first time, it will be processed.

    • Register another new user. The event will be sent with the same static ID again.

    • Observe: In the notifications-service logs, you should see the message: Duplicate event received with ID: STATIC-TEST-ID-12345. Skipping. This proves your consumer is now idempotent!

    • Remember to remove the hardcoded ID from your producer afterward!


Debugging-First: What Happens on Concurrent Processing?

Imagine a scenario where two consumer instances receive the exact same message at nearly the same time (e.g., during a partition rebalance). Both might pass the idempotencyRepository.existsById(eventId) check. What happens then?

  • Both consumers proceed to execute the business logic and try to save the IdempotencyRecord.
  • The first consumer's transaction will commit successfully, inserting the record into the processed_events table.
  • When the second consumer's transaction tries to commit, the database will throw a DataIntegrityViolationException because the eventId is a primary key and must be unique.
  • This exception causes the second consumer's @Transactional method to fail and roll back.
  • Spring Kafka's error handling will then kick in. By default, it will retry processing the message.
  • On the retry attempt, the existsById(eventId) check will now return true, and the message will be correctly identified as a duplicate and skipped.

This is the power of using a database unique constraint as a final line of defense against race conditions.


Conclusion

Fantastic work! You have elevated our simple consumer into a robust, production-grade component. By implementing the Idempotent Consumer pattern, you've ensured data integrity even in the face of message redeliveries, which are a fact of life in distributed systems.

Key Takeaways:

  • "At-least-once" delivery requires consumers to be idempotent to prevent duplicate processing.
  • The Idempotent Consumer pattern uses a persistent store (like a DB) and a unique event ID to track processed messages.
  • Using a single database transaction (@Transactional) to wrap the business logic and the event tracking is critical for atomicity.
  • Disabling Kafka's auto-commit (enable-auto-commit: false) allows the Spring transaction manager to control offsets, committing them only after the DB transaction succeeds.

Preview of the Next Lesson:
Our consumer is now safe from duplicates. But what if a message is fundamentally broken or causes an unrecoverable error (a "poison pill")? Our current setup would retry it indefinitely, blocking the processing of all subsequent messages in that partition. In the next lesson, we will implement a Dead Letter Queue (DLQ) to automatically sideline these toxic messages for later inspection, ensuring our consumer never gets stuck.