A Kafka consumer can process thousands of messages successfully during normal operation and still fail when its partition assignment changes.

Consider an order-processing service running with three consumer instances in the same consumer group. Each instance processes a different set of partitions. Everything works until one instance restarts during a deployment. Kafka detects the membership change and starts a rebalance. Some partitions move to other consumers, and the application must stop processing partitions it no longer owns.

Now imagine that one consumer has already fetched a batch of records but has not completed processing them. Another consumer receives the partition during the rebalance. If the first consumer commits offsets incorrectly, records may be skipped. If it does not commit completed work, records may be processed again.

These problems are difficult to identify with tests that only publish a message and verify that a consumer receives it.

A reliable Kafka consumer test strategy must cover changes in group membership, partition ownership, offset commits, processing failures, and recovery. Developers should also test what happens when a rebalance occurs while the application is handling records.

This article explains how to build meaningful Kafka consumer rebalance tests using MockConsumer, integration tests with a real Kafka broker, and failure-oriented test scenarios.

Why Normal Consumer Tests Are Not Enough

A basic consumer test usually follows a simple sequence:

  1. Publish a message to a Kafka topic.
  2. Start a consumer.
  3. Verify that the consumer receives the message.
  4. Confirm that the expected business operation runs.

This verifies message consumption, but it does not verify how the application behaves when Kafka changes partition ownership.

In production, a consumer group can rebalance for several reasons:

  • A new consumer joins the group.
  • An existing consumer shuts down.
  • A consumer crashes unexpectedly.
  • A consumer stops polling for longer than its configured processing interval.
  • A topic gains additional partitions.
  • A consumer's topic subscription changes.
  • A network interruption causes a consumer to lose group membership.

Each situation can affect partition assignments and processing continuity.

For example, suppose a topic contains six partitions and three consumers. Each consumer initially owns two partitions. When one consumer leaves the group, Kafka must redistribute its partitions among the remaining members.

The application must handle the partitions being revoked and the new partitions being assigned. It must also ensure that work completed before the rebalance is not unnecessarily repeated and that unfinished work is not incorrectly marked as completed.

A normal message-consumption test does not exercise these conditions. That is why rebalance testing should be a separate part of the consumer test suite.

Understand the Different Levels of Rebalance Testing

Not every test needs a running Kafka cluster. Different testing approaches provide different levels of confidence.

Unit testing with MockConsumer

Kafka provides MockConsumer in its Java client library. It implements the Consumer interface and allows developers to simulate consumer behavior without connecting to a real Kafka broker.

It supports operations such as adding records, updating partition metadata, assigning partitions, and simulating rebalance events.

This makes it useful for testing application logic that responds to partition assignment changes.

For example, you can verify that:

  • The application registers a rebalance listener.
  • Revoked partitions trigger the expected cleanup operation.
  • Newly assigned partitions trigger state initialization.
  • Lost partitions do not cause unsafe offset commits.
  • Processing logic handles records from different partitions.

MockConsumer is not a replacement for a real Kafka broker. It does not reproduce the complete group coordination protocol, broker failures, network behavior, or the timing of a distributed rebalance.

Use it to test application behavior, not to prove that Kafka's actual coordination mechanism works correctly.

Integration testing with a real Kafka broker

Integration tests use a running Kafka broker and actual consumer instances.

They allow developers to verify that the consumer group responds correctly when members join, leave, restart, or become unavailable.

These tests are useful for validating:

  • Actual partition assignment.
  • Consumer group membership changes.
  • Offset commits during rebalances.
  • Consumer recovery after a restart.
  • Message processing while ownership changes.
  • Consumer lag during and after reassignment.

An embedded broker or containerized Kafka environment can be used depending on the testing framework and infrastructure.

Failure and resilience testing

Resilience tests intentionally introduce conditions that can interrupt normal processing.

For example, a test may stop a consumer while it is processing a message, delay message handling, interrupt network connectivity, or restart a consumer instance.

The objective is to verify that the application recovers without losing business data or leaving partitions unprocessed.

A strong test suite combines all three approaches. Unit tests provide fast feedback, integration tests validate Kafka behavior, and resilience tests expose problems that appear only under failure conditions.

Testing Partition Revocation With MockConsumer

The first important scenario is partition revocation.

When Kafka removes a partition from a consumer's assignment, the application may need to commit completed offsets, release resources, or save local processing state.

The ConsumerRebalanceListener interface provides callbacks for handling these events.

Consider a simple component that tracks partition ownership and records when partitions are revoked or assigned.

Java
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import org.apache.kafka.clients.consumer.ConsumerRebalanceListener;
import org.apache.kafka.common.TopicPartition;

public class PartitionTracker
        implements ConsumerRebalanceListener {

    private final Set<TopicPartition> assignedPartitions =
            new HashSet<>();

    @Override
    public void onPartitionsRevoked(
            Collection<TopicPartition> partitions) {

        assignedPartitions.removeAll(partitions);

        System.out.println(
            "Revoked partitions: " + partitions
        );
    }

    @Override
    public void onPartitionsAssigned(
            Collection<TopicPartition> partitions) {

        assignedPartitions.addAll(partitions);

        System.out.println(
            "Assigned partitions: " + partitions
        );
    }

    @Override
    public void onPartitionsLost(
            Collection<TopicPartition> partitions) {

        assignedPartitions.removeAll(partitions);

        System.out.println(
            "Lost partitions: " + partitions
        );
    }

    public Set<TopicPartition> getAssignedPartitions() {
        return Set.copyOf(assignedPartitions);
    }
}

This component maintains a local view of the partitions assigned to the consumer.

The revocation callback removes partitions that are being taken away. The assignment callback adds newly assigned partitions. The lost callback handles partitions for which the consumer no longer has ownership.

In a real application, these callbacks may also coordinate with a state store, stop partition-specific workers, or release resources associated with a partition.

The important point is that the application should respond to the exact partitions supplied by Kafka. Do not assume that every rebalance removes every partition.

Create a unit test for partition reassignment

MockConsumer can simulate a rebalance through its rebalance method. This allows a test to verify how the application reacts when its assignment changes.

Java
import static org.junit.jupiter.api.Assertions.*;

import java.util.List;
import java.util.Set;

import org.apache.kafka.clients.consumer.MockConsumer;
import org.apache.kafka.clients.consumer.OffsetResetStrategy;
import org.apache.kafka.common.TopicPartition;
import org.junit.jupiter.api.Test;

class PartitionTrackerTest {

    @Test
    void shouldUpdatePartitionsAfterRebalance() {

        MockConsumer<String, String> consumer =
            new MockConsumer<>(
                OffsetResetStrategy.EARLIEST
            );

        PartitionTracker tracker =
            new PartitionTracker();

        TopicPartition partition0 =
            new TopicPartition("orders", 0);

        TopicPartition partition1 =
            new TopicPartition("orders", 1);

        TopicPartition partition2 =
            new TopicPartition("orders", 2);

        consumer.subscribe(
            List.of("orders"),
            tracker
        );

        consumer.rebalance(
            List.of(partition0, partition1)
        );

        assertEquals(
            Set.of(partition0, partition1),
            tracker.getAssignedPartitions()
        );

        consumer.rebalance(
            List.of(partition1, partition2)
        );

        assertEquals(
            Set.of(partition1, partition2),
            tracker.getAssignedPartitions()
        );

        consumer.close();
    }
}

The first simulated assignment contains partitions 0 and 1. The second assignment contains partitions 1 and 2.

The test verifies that partition 0 is removed, partition 1 remains assigned, and partition 2 is added.

This is useful for testing assignment-related application logic without waiting for a real consumer group to coordinate a rebalance.

The test does not verify the actual Kafka group protocol or whether a broker would produce this exact assignment. That responsibility belongs to integration testing.

Testing a Consumer Joining an Existing Group

A common production scenario occurs when an application scales horizontally.

Suppose an order-processing service initially runs two consumer instances. The topic has four partitions, so each consumer can receive two partitions.

The operations team then starts a third consumer instance.

Kafka detects the new group member and coordinates a new partition assignment. Depending on the assignment strategy, some partitions may move between existing consumers so that the new consumer can participate.

A useful integration test should verify the following:

  • Both original consumers initially receive partitions.
  • The third consumer joins using the same group ID.
  • The consumer group completes its rebalance.
  • All expected partitions are assigned.
  • No partition is assigned to two active members at the same time.
  • The application continues processing records after reassignment.

The test should use actual consumer instances rather than manually assigning partitions.

For example, the test can start two consumers, wait until the initial assignments are established, and then start the third consumer. Each consumer should record the partitions reported by its assignment callback.

Use a bounded wait with a clear timeout rather than assuming that the rebalance completes immediately.

A useful assertion is that the union of all active consumers' assignments contains every expected partition. Also verify that the intersection between any two consumers' active assignments is empty.

This confirms that the group has reached the expected assignment state.

Testing Consumer Failure During Message Processing

One of the most important scenarios is a consumer failure while processing a record.

Consider an application that reads an order event and updates a database.

The following sequence can cause a duplicate operation:

  1. Consumer 1 reads an order event.
  2. The application successfully updates the database.
  3. Consumer 1 crashes before committing the Kafka offset.
  4. Kafka assigns the partition to Consumer 2.
  5. Consumer 2 reads the same event again.

This is an expected possibility when an application performs an external operation and commits its offset separately.

Kafka cannot automatically make an arbitrary database operation and an offset commit one atomic transaction.

A test should verify that repeating the same event does not create duplicate business records or duplicate financial operations.

One common approach is to use an idempotency key.

For example:

Java
public void processOrder(
        String eventId,
        String orderData) {

    if (orderRepository.existsByEventId(eventId)) {
        return;
    }

    orderRepository.save(
        new OrderEntity(eventId, orderData)
    );
}

The eventId identifies the business operation. If the same Kafka record is delivered again, the application can recognize that it has already been processed.

For production systems, the database should enforce uniqueness for the event identifier. Checking for an existing record and inserting a new one without a database constraint can still create duplicates when two processing attempts run concurrently.

The integration test should simulate the failure boundary: allow the business operation to complete, prevent the offset from being committed, restart or replace the consumer, and verify that processing the same event does not create a second business operation.

This test checks application recovery behavior rather than assuming that Kafka guarantees exactly-once execution for external systems.

Testing Slow Consumers and Poll Interval Problems

Another realistic failure occurs when message processing takes longer than expected.

Kafka consumers must continue polling to remain active members of the group. If application processing blocks the consumer thread for too long, the consumer can exceed max.poll.interval.ms and lose its group membership.

For example, suppose a consumer fetches a batch of 100 records. Processing each record requires a slow external API call. If the entire batch takes longer than the configured maximum poll interval, Kafka may consider the consumer unresponsive and trigger a rebalance.

A useful test should deliberately introduce processing delays.

The test can:

  • Publish a batch of records.
  • Configure a short max.poll.interval.ms for the test.
  • Make the message handler wait longer than the configured interval.
  • Observe whether the consumer loses its assignment.
  • Verify that another consumer can take over the partition.
  • Confirm that records are eventually processed.

Do not rely on arbitrary Thread.sleep calls as the only synchronization mechanism. Use latches, bounded polling, and explicit test conditions wherever possible.

For example, a CountDownLatch can signal when the test handler begins processing. The test can then control when processing is released, making the failure scenario more predictable.

Also remember that max.poll.interval.ms and session.timeout.ms serve different purposes. The former limits the time between poll calls for a consumer in the group, while the latter relates to detecting a member that stops sending heartbeats under the applicable group protocol.

Testing both conditions helps identify whether failures come from slow application processing or loss of consumer connectivity.

Testing Cooperative Rebalancing

Cooperative rebalancing is designed to reduce unnecessary partition movement.

Unlike eager rebalancing, where consumers typically give up all their partitions before receiving a new assignment, cooperative rebalancing allows partitions that do not need to move to remain with their existing owners.

This behavior is particularly useful for applications that maintain local state or perform expensive initialization when partitions are assigned.

A realistic test should start multiple consumers using a compatible cooperative assignment configuration.

Then introduce a membership change by starting another consumer or stopping an existing one.

Verify that:

  • The group reaches a valid final assignment.
  • Partitions that do not need to move remain assigned where possible.
  • Revocation callbacks handle only the partitions being transferred.
  • Assignment callbacks initialize newly received partitions.
  • Processing resumes correctly after the rebalance.

Do not write a test that assumes the exact same partition assignment for every run unless the test controls all relevant assignment inputs.

Instead, validate the properties that matter: complete coverage, no simultaneous ownership of a partition within the group, correct cleanup, and successful processing after reassignment.

Testing Offset Commit Failures

Offset commits can fail during a rebalance or when a consumer loses ownership of a partition.

An application must not assume that every commit request succeeds.

A useful test should simulate a commit failure and verify that the application does not mark unfinished records as completed.

For example, a consumer might process a batch of records and attempt to commit synchronously. If the commit fails, the application should log the failure and allow Kafka's normal recovery behavior to determine which records may be delivered again.

The application should also avoid swallowing commit exceptions and continuing as though the offset was successfully saved.

With MockConsumer, developers can simulate several consumer operations and exceptions. However, a real broker integration test is needed to validate actual commit behavior during group membership changes.

For asynchronous processing, offset tracking must be partition-specific. A failure in one partition should not cause the application to commit past unfinished records in that partition simply because another partition has completed its work.

Building a Rebalance Integration Test Suite

A practical integration test environment should use a real Kafka broker and multiple consumer instances.

Each consumer should use the same group ID and subscribe to the same topic. The test should observe assignments through ConsumerRebalanceListener callbacks.

A useful test suite can include these scenarios:

Test scenario Expected behavior
Second consumer joins Partitions are redistributed
Consumer shuts down normally Its partitions move to active members
Consumer crashes Remaining members recover its partitions
Consumer processing is delayed Poll timeout behavior is detected
Topic gains partitions New partitions become available to the group
Offset commit fails Uncommitted work can be processed again
Consumer restarts It resumes from the committed position
Cooperative rebalance occurs Unaffected partitions remain assigned where possible

Avoid making these tests depend on exact timing. Kafka group coordination is asynchronous, and a test that expects a rebalance to complete within a fixed number of milliseconds can become unreliable across different machines and environments.

Instead, wait for observable conditions, such as a specific assignment being reached or a record being processed. Always use a maximum timeout so that a failed test does not hang indefinitely.

Practical Recommendations for Reliable Rebalance Tests

A good rebalance test suite should validate business behavior, not just Kafka callbacks.

For example, checking that onPartitionsRevoked was called is useful, but it does not prove that the application committed offsets safely or stopped processing records it no longer owns.

Keep the following considerations in mind:

  • Test partition revocation, assignment, and loss separately.
  • Verify that offset commits reflect completed processing.
  • Simulate consumer restarts and unexpected failures.
  • Test duplicate delivery when processing succeeds but offset commits fail.
  • Use real brokers to validate consumer group coordination.
  • Test slow processing and poll interval violations.
  • Validate cooperative assignment without assuming a fixed assignment layout.
  • Monitor consumer lag and rebalance duration in integration environments.
  • Use bounded waits and deterministic synchronization instead of relying on arbitrary delays.

Most importantly, make the tests repeatable. A rebalance test that passes only occasionally is difficult to trust and can hide the very production problems it is intended to detect.

Conclusion

Kafka consumer rebalances are normal events in a distributed application, but they create important failure boundaries that developers must test.

MockConsumer is useful for verifying application-level assignment and revocation logic. Integration tests with real Kafka brokers validate group coordination, while resilience tests help identify problems caused by consumer crashes, slow processing, and offset commit failures.

A reliable test suite should go beyond checking whether a consumer receives messages. It should verify that partitions are handled safely when ownership changes, completed work is committed correctly, unfinished work can be recovered, and duplicate deliveries do not create duplicate business operations.

Treat rebalancing as a normal part of the consumer lifecycle, not as an exceptional condition. Testing these scenarios before deployment makes Kafka applications more predictable and helps prevent message-processing failures when the consumer group changes.