A Kafka consumer application may work reliably for months without requiring any changes to its topic configuration. Then, as message volume increases, the development team decides to add more partitions to improve parallel processing.
The change appears straightforward. An administrator increases the partition count, Kafka makes the additional partitions available, and consumers should continue processing messages.
However, changing partition counts can affect how messages are distributed across consumers. It can also introduce ordering problems, unexpected workload distribution, and processing delays if the application assumes that partition ownership remains unchanged.
Consider an order-processing application that consumes messages from a topic named orders. Initially, the topic has three partitions and three consumer instances. Each consumer processes one partition.
As the application grows, the team increases the partition count from three to six. Kafka can now distribute the six partitions across the available consumers, but the ownership assignments must be updated. Existing consumers may receive additional partitions, and a new consumer joining the group can trigger another rebalance.
This is where consumer group coordination becomes important.
Kafka provides partition assignment strategies and rebalance callbacks that allow applications to manage ownership changes safely. Developers can also use cooperative rebalancing and static membership to reduce unnecessary interruptions.
This article explains what happens when Kafka partition counts change, how consumer groups respond, how to handle reassignment correctly, and what developers should consider before increasing partitions in a production environment.
Understanding the Relationship Between Topics, Partitions, and Consumers
A Kafka topic is divided into partitions. Each partition is an ordered sequence of records, and Kafka maintains offsets to identify the position of records within that partition.
Consumers normally process records as members of a consumer group.
Within a consumer group, a partition is assigned to only one consumer at a time. This allows multiple consumers to process different partitions in parallel without competing for the same partition assignment.
Consider a topic named orders with three partitions:
<CodeBlock language="mermaid" id="68430"> flowchart TB T["orders topic"] T --> P0["Partition 0"] T --> P1["Partition 1"] T --> P2["Partition 2"] P0 --> C1["Consumer 1"] P1 --> C2["Consumer 2"] P2 --> C3["Consumer 3"] </CodeBlock>
Each consumer receives one partition.
Now increase the topic to six partitions:
<CodeBlock language="mermaid" id="68431"> flowchart TB T["orders topic"] T --> P0["Partition 0"] T --> P1["Partition 1"] T --> P2["Partition 2"] T --> P3["Partition 3"] T --> P4["Partition 4"] T --> P5["Partition 5"] P0 --> C1["Consumer 1"] P1 --> C2["Consumer 2"] P2 --> C3["Consumer 3"] P3 --> C1 P4 --> C2 P5 --> C3 </CodeBlock>
The consumer group now has six partitions to process. If the assignment strategy distributes them evenly, each of the three consumers can receive two partitions.
The actual assignment depends on the configured partition assignor and the topics subscribed to by the group.
An important rule is that a consumer group cannot process more partitions in parallel than the number of partitions available. If a topic has three partitions and the group has five consumers, at least two consumers will have no partition assigned for that topic.
Increasing the partition count creates more opportunities for parallel processing, but it does not automatically guarantee higher throughput. Consumers, brokers, downstream databases, and external services must also have enough capacity to handle the additional workload.
What Happens When the Partition Count Changes?
When a topic's partition count increases, Kafka updates the topic metadata. Consumers need to discover the new metadata and determine whether their current assignments are still valid.
The consumer group coordinator manages membership and partition assignment coordination. Depending on the configured protocol and assignor, a rebalance may occur to distribute the partitions.
For example, suppose the orders topic originally has three partitions:
Consumer | Existing assignment |
|---|
Consumer 1 | Partition 0 |
Consumer 2 | Partition 1 |
Consumer 3 | Partition 2 |
After increasing the topic to six partitions, the group needs to incorporate partitions 3, 4, and 5.
A possible new assignment is:
Consumer | New assignment |
|---|
Consumer 1 | Partitions 0 and 3 |
Consumer 2 | Partitions 1 and 4 |
Consumer 3 | Partitions 2 and 5 |
The assignment above is illustrative. Kafka does not guarantee that every partition will remain with its previous consumer. The result depends on the assignment strategy and the group membership.
During a rebalance, consumers may temporarily stop processing partitions while ownership changes. This can increase processing latency, particularly when the application has long-running message handlers or performs expensive initialization whenever partitions are assigned.
Developers should therefore treat a partition-count change as an operational event that requires monitoring and application-level preparation.
Understanding Kafka Partition Assignment Strategies
Kafka provides multiple partition assignment strategies. Choosing the appropriate strategy affects how partitions are distributed and how much reassignment happens when the consumer group changes.
RangeAssignor
RangeAssignor assigns partitions to consumers based on partition ranges, generally considering each topic separately.
For example, if a topic has six partitions and three consumers, the assignment may look like this:
Consumer | Assignment |
|---|
Consumer 1 | Partitions 0 and 1 |
Consumer 2 | Partitions 2 and 3 |
Consumer 3 | Partitions 4 and 5 |
This strategy is straightforward, but when a group subscribes to multiple topics, the per-topic assignment can produce uneven overall distributions.
RoundRobinAssignor
RoundRobinAssignor distributes partitions across consumers in a round-robin pattern.
For example, if there are two topics, each with three partitions, and three consumers, a possible assignment is:
Consumer | Assignment |
|---|
Consumer 1 | Topic A partition 0, Topic B partition 0 |
Consumer 2 | Topic A partition 1, Topic B partition 1 |
Consumer 3 | Topic A partition 2, Topic B partition 2 |
This can produce a more balanced distribution across multiple topics when consumers subscribe to the same set of topics.
However, the assignment may change more than necessary during membership changes.
StickyAssignor
StickyAssignor attempts to maintain a balanced assignment while preserving as many existing partition assignments as possible.
This reduces unnecessary partition movement when consumers join or leave the group.
For example, if one consumer leaves, Kafka can redistribute its partitions while retaining the assignments of other consumers whenever possible.
Sticky assignment is useful when moving a partition requires expensive initialization, local state loading, or other application work.
CooperativeStickyAssignor
CooperativeStickyAssignor combines sticky assignment behavior with cooperative rebalancing.
Instead of requiring every consumer to give up all its partitions during a rebalance, it allows consumers to retain partitions that do not need to move.
This can significantly reduce processing interruptions during membership changes.
For newer consumer deployments, CooperativeStickyAssignor is generally preferable when supported by the entire group and configured with a compatible upgrade strategy.
Configuring Cooperative Rebalancing
In Java applications using the Kafka consumer client, you can configure the CooperativeStickyAssignor through the partition.assignment.strategy property.
For example:
Properties properties = new Properties();
properties.put(
ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,
"localhost:9092"
);
properties.put(
ConsumerConfig.GROUP_ID_CONFIG,
"order-processing-group"
);
properties.put(
ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG,
StringDeserializer.class.getName()
);
properties.put(
ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,
StringDeserializer.class.getName()
);
properties.put(
ConsumerConfig.PARTITION_ASSIGNMENT_STRATEGY_CONFIG,
CooperativeStickyAssignor.class.getName()
);
This configuration tells the consumer to use CooperativeStickyAssignor.
All consumers participating in the group must support a compatible cooperative assignment strategy. A mixed configuration can prevent the group from using cooperative rebalancing as intended.
Also, do not change assignment strategies across a production consumer group without considering the migration path. Older Kafka clients may require a staged upgrade rather than switching every consumer simultaneously.
The important benefit is that cooperative rebalancing reduces the number of partitions that must stop processing during reassignment. It does not eliminate every rebalance or guarantee uninterrupted processing.
Handling Partition Revocation and Assignment Callbacks
When partitions move between consumers, the application may need to save processing state, commit offsets, release resources, or initialize new partition-specific state.
Kafka provides the ConsumerRebalanceListener interface for this purpose.
The interface includes callbacks such as:
onPartitionsRevoked: Called when partitions are being removed from the consumer.
onPartitionsAssigned: Called after partitions have been assigned.
onPartitionsLost: Called when the consumer has lost ownership of partitions, which is supported by current Kafka consumer APIs.
The callback behavior depends on the rebalance protocol.
With eager rebalancing, consumers typically revoke all their assigned partitions before the new assignment is applied. With cooperative rebalancing, only the partitions that must move are revoked.
This distinction is important. Application code should process the exact partition collection supplied by the callback rather than assuming that every partition will always be revoked.
The following example shows how a Java consumer can register a rebalance listener:
KafkaConsumer<String, String> consumer =
new KafkaConsumer<>(properties);
consumer.subscribe(
Collections.singletonList("orders"),
new ConsumerRebalanceListener() {
@Override
public void onPartitionsRevoked(
Collection<TopicPartition> partitions) {
System.out.println(
"Partitions revoked: " + partitions
);
try {
consumer.commitSync();
} catch (CommitFailedException ex) {
System.err.println(
"Offset commit failed: " + ex.getMessage()
);
}
}
@Override
public void onPartitionsAssigned(
Collection<TopicPartition> partitions) {
System.out.println(
"Partitions assigned: " + partitions
);
}
@Override
public void onPartitionsLost(
Collection<TopicPartition> partitions) {
System.out.println(
"Partitions lost: " + partitions
);
}
}
);
The revocation callback commits offsets before the consumer gives up ownership. This can reduce unnecessary reprocessing when the next consumer takes over.
However, committing the consumer's current position is safe only if the application has completed processing all records covered by that position.
For applications that process records asynchronously, maintain an explicit record of completed offsets for each partition. Do not commit an offset simply because the consumer has fetched the record.
The lost callback should not be treated like normal revocation. If ownership has already been lost, another consumer may be processing the same partition. Attempting to commit offsets or perform partition cleanup as though ownership were still guaranteed can introduce incorrect behavior.
Managing Offsets Correctly During Rebalances
Offset management is one of the most important parts of a reliable Kafka consumer.
Suppose a consumer reads records from partition 2 and processes them using an external database.
If the consumer commits offset 150 before the corresponding database operation completes, and the application crashes, Kafka may consider the record processed even though the business operation was not completed.
On the other hand, if the consumer completes processing but fails to commit the offset, the next consumer may process the same record again.
This is why applications should distinguish between fetched offsets and successfully processed offsets.
For example, consider the following consumer loop:
while (true) {
ConsumerRecords<String, String> records =
consumer.poll(Duration.ofMillis(500));
for (ConsumerRecord<String, String> record : records) {
processOrder(record.value());
System.out.println(
"Processed partition: " + record.partition()
+ ", offset: " + record.offset()
);
}
consumer.commitSync();
}
In this simple example, the consumer processes the records synchronously and commits after the batch has completed.
For production systems, processOrder should complete its required business operation before the offset is committed.
If the application uses asynchronous processing, a more careful design is required. Track completion independently for each partition and commit only the highest contiguous offset whose preceding records have all completed successfully.
For example, if offsets 100, 101, and 102 are fetched, but processing completes in the order 100, 102, and 101, the consumer must not commit beyond 100 until 101 has completed.
This avoids skipping records after a failure.
For applications that need stronger guarantees between Kafka and an external database, consider an idempotent processing design or an appropriate transactional pattern. Kafka offset commits and database transactions are not automatically one atomic operation.
Understanding Static Membership
Another technique for reducing unnecessary rebalances is static membership.
Normally, a consumer joining a group receives a dynamic member identity. If the consumer restarts, it may temporarily leave the group and rejoin with a new identity, triggering reassignment.
Static membership allows an application instance to use a stable group identity through group.instance.id.
For example:
properties.put(
ConsumerConfig.GROUP_INSTANCE_ID_CONFIG,
"order-consumer-instance-01"
);
Each consumer instance must have a unique and stable group.instance.id within the group.
When a statically configured consumer restarts with the same identity within the relevant session timeout, Kafka can recognize it as the same member rather than immediately treating it as a completely new consumer.
This can reduce unnecessary rebalances during controlled restarts and temporary outages.
However, static membership does not eliminate rebalances caused by genuine assignment changes, including partition-count changes.
It also requires careful identity management. If two running consumers use the same group.instance.id, Kafka can reject the duplicate member and force one of the consumers out of the group.
Use stable identities based on deployment instance identity rather than generating a new random value every time the application starts.
Understanding the Impact of Increasing Partition Counts
Adding partitions provides more parallelism, but it also changes the behavior of the topic.
One important consideration is message-key partitioning.
Kafka commonly uses the message key to determine which partition receives a record. If a producer uses the default key-based partitioning strategy, changing the number of partitions can change the partition selected for a given key.
For example, suppose an application sends all messages for customer 101 using the same key.
Before increasing the partition count, those messages may be assigned to partition 1. After increasing the partition count, the same key may map to another partition.
This can affect ordering across the historical and newly produced records for that customer.
Kafka preserves record order within an individual partition. It does not provide a general ordering guarantee across multiple partitions.
Therefore, if an application relies on key-based ordering, increasing the partition count requires additional planning.
For example, consider a customer account application where deposit and withdrawal events must be processed in order. If older events for a customer remain in one partition while newer events are routed to another after a partition-count change, two consumers could process those records concurrently.
Possible strategies include:
Pause production during a controlled migration.
Drain existing records before changing partition counts.
Use a versioned topic with a carefully planned migration.
Implement application-level sequencing or state validation.
Use a stable custom partitioning strategy when the partitioning requirements justify it.
Do not assume that adding partitions is always a transparent scaling operation. For key-sensitive applications, it can change message distribution and business processing order.
Monitoring Consumer Group Rebalances
A production consumer should expose enough information to identify frequent rebalances and their impact.
Useful metrics and operational signals include:
Consumer group rebalance count.
Rebalance duration.
Partition assignment changes.
Consumer lag by partition.
Time spent processing records.
Offset commit failures.
Poll interval and heartbeat activity.
Consumer membership changes.
Kafka consumer logs can also help identify why a rebalance occurred.
Common causes include:
A new consumer joining the group.
An existing consumer leaving or crashing.
A consumer failing to poll within max.poll.interval.ms.
A session timeout caused by missed heartbeats.
Topic partition changes.
Subscription changes.
Consumer deployment or configuration changes.
For example, a consumer may continue fetching records but spend too long processing a batch before calling poll again. If the processing time exceeds max.poll.interval.ms, Kafka can consider the consumer unresponsive and trigger a rebalance.
Increasing max.poll.interval.ms may be appropriate for a workload with legitimately long processing times, but it should not be used to hide a consumer that is blocked or unable to keep up.
Review the processing architecture, batch size, and poll frequency before changing timeout settings.
A Safe Procedure for Increasing Partition Counts
Increasing partitions in production should be treated as a planned operational change.
A practical procedure looks like this:
Review the current topic partition count and the expected workload.
Confirm that the application can handle the new partition distribution.
Check whether message ordering depends on keys.
Review the consumer group's assignment strategy.
Confirm that all consumers use compatible rebalance protocols.
Test the partition increase in a non-production environment.
Verify that revocation and assignment callbacks handle partial partition changes.
Confirm that offsets are committed only after successful processing.
Increase the partition count during an appropriate operational window.
Monitor consumer lag, rebalance duration, processing errors, and application throughput.
For example, the partition count can be increased with Kafka's topic administration command:
kafka-topics.sh \
--bootstrap-server localhost:9092 \
--alter \
--topic orders \
--partitions 6
This command increases the partition count to six. Kafka does not support reducing a topic's partition count through this operation.
After the change, verify the topic configuration:
kafka-topics.sh \
--bootstrap-server localhost:9092 \
--describe \
--topic orders
Then monitor the consumer group to confirm that partitions have been assigned as expected.
Do not immediately assume that the consumer group is balanced simply because the topic reports the new partition count. Confirm the actual assignments and observe whether consumers are keeping up with the incoming workload.
Conclusion
Increasing Kafka partition counts can improve processing parallelism, but it also changes how partitions are distributed across consumer group members. Applications must be prepared for reassignment, offset management, and potential changes in message ordering.
CooperativeStickyAssignor can reduce unnecessary partition movement, while ConsumerRebalanceListener provides a way to save state, commit completed offsets, and initialize newly assigned partitions. Static membership can also reduce some rebalances caused by temporary consumer restarts.
The most important consideration is that partition-count changes are not purely an infrastructure operation. They can affect application-level processing guarantees, especially when messages are partitioned by key.
Before increasing partitions in production, test the assignment strategy, validate offset handling, review ordering requirements, and monitor consumer behavior after the change. This helps scale Kafka consumers without introducing duplicate processing, skipped records, or unexpected interruptions.
Join the conversation! Your thoughts help the community grow.