Video in progress
Why are messages processed twice in a Kafka consumer during a rebalance, and how do you reduce it?
If the consumer processed a message but the partition moved to another consumer before it could commit the offset, the new owner starts from the last committed offset and receives those messages again. Idempotent processing is the main defense, and settings only reduce the probability.
📖 Answer
In Spring Kafka the default is AckMode.BATCH: the offset is committed after the whole batch returned by poll() is processed. If a batch has 500 messages and a rebalance starts at the 300th, those 300 messages are processed again.
Typical causes of a rebalance:
- processing took longer than
max.poll.interval.ms(default 5 minutes), so the consumer was kicked out of the group; - pods restarted one by one during a deploy;
- a heartbeat didn't arrive within
session.timeout.ms(a long GC pause).
Ways to reduce it:
spring.kafka.consumer:
max-poll-records: 50
properties:
partition.assignment.strategy: org.apache.kafka.clients.consumer.CooperativeStickyAssignor
group.instance.id: ${HOSTNAME} # static membership
- Lower
max-poll-records: the batch is smaller, so there are fewer repeats too. - Cooperative sticky assignor: during a rebalance only the partitions that move are paused, not all of them.
- Static membership: a pod that comes back quickly after a restart doesn't trigger a rebalance.
AckMode.RECORD: a commit after every message, but throughput drops.
Even so, duplicates never drop to zero. The consumer must still be written to be idempotent. That is a design requirement, not a configuration one.
Sign up to mark studied questions and save your progress.