Why 80% of Kafka Pitfalls Trace Back to Partitions
This article explains how Kafka's partition model underpins four common issues—consumer parallelism limits, message ordering, rebalance storms, and lag buildup—and provides Spring Boot configuration patterns for reliable production and consumption with manual offset commits, idempotent producers, and dead-letter handling.
Reading font

Mental Model: Kafka Is a Distributed Log, Not a Traditional Queue
Kafka differs fundamentally from RabbitMQ: it is a high-throughput distributed log where messages are appended to disk in order and consumers pull via offsets. Key contrasts:
Throughput : Kafka achieves millions of messages per second per node; RabbitMQ handles tens of thousands per second.
Consumption model : Kafka uses a pull model with offsets; RabbitMQ pushes messages to consumers.
Message retention : Kafka retains messages after consumption (by time or size), enabling replay; RabbitMQ deletes messages on acknowledgment.
Routing : Kafka has weak routing (topic + key partitioning); RabbitMQ offers four exchange types for flexible routing.
Delayed messages : Kafka does not support delayed messages natively; RabbitMQ can simulate them via TTL and dead-letter exchanges.
The "retained after consumption" property enables offset rewinding to replay days-old data—useful for backfills and debugging.
Six Concepts, Three That Matter
Producer → Broker (topic: order-topic)
├── Partition 0: [msg0] [msg1] [msg4]
├── Partition 1: [msg2] [msg5] [msg8]
└── Partition 2: [msg3] [msg6] [msg9]
↑ same group: one partition → one consumer
Consumer Group: order-group
├── Consumer A → Partition 0
├── Consumer B → Partition 1
└── Consumer C → Partition 2Broker, Topic, Offset are straightforward. The critical three:
Partition is the unit of parallelism. A topic with 3 partitions allows at most 3 active consumers in a group; the 4th stays idle. To increase throughput, add partitions—not just machines.
Ordering is guaranteed only within a partition. To keep messages for the same order strictly ordered, send with the same key (order ID). Kafka routes via hash(key) % partitionCount, so identical keys land in the same partition.
Consumer Group is the unit of work distribution. Within a group, partitions are assigned exclusively (each message to one consumer); different groups each consume the full stream independently—this multi-consumer pattern is standard Kafka usage.
Rebalance occurs when group membership or partition count changes. During rebalance, consumption pauses —which explains why adding consumers can temporarily slow things down.
Quick Start with KRaft (No ZooKeeper)
Kafka 3.x uses KRaft mode; a single container suffices:
docker run -d --name kafka -p 9092:9092 apache/kafka:3.7.0Three essential commands:
# Create topic: 3 partitions, 1 replica (local dev)
docker exec -it kafka /opt/kafka/bin/kafka-topics.sh \
--bootstrap-server localhost:9092 --create \
--topic order-topic --partitions 3 --replication-factor 1
# Console consumer—debugging Swiss army knife
docker exec -it kafka /opt/kafka/bin/kafka-console-consumer.sh \
--bootstrap-server localhost:9092 --topic order-topic --from-beginning
# Check lag: LAG column shows unconsumed count
docker exec -it kafka /opt/kafka/bin/kafka-consumer-groups.sh \
--bootstrap-server localhost:9092 --describe --group order-groupJudge consumer health by LAG, not logs. Rising LAG means consumption lags production; stable zero LAG is healthy.
Spring Boot Minimal Setup
Dependency:
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
</dependency>Configuration (every line matters):
spring:
kafka:
bootstrap-servers: localhost:9092
producer:
key-serializer: org.apache.kafka.common.serialization.StringSerializer
value-serializer: org.springframework.kafka.support.serializer.JsonSerializer
acks: all
consumer:
group-id: order-group
auto-offset-reset: earliest
enable-auto-commit: false
key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
value-deserializer: org.springframework.kafka.support.serializer.JsonDeserializer
properties:
spring.json.trusted.packages: com.dev.garden.dto
listener:
ack-mode: manual_immediateProducer:
@Service
public class OrderProducer {
@Autowired
private KafkaTemplate<String, OrderDto> kafkaTemplate;
public void send(OrderDto order) {
// Second arg is key: same orderNo → same partition → local ordering
kafkaTemplate.send("order-topic", order.getOrderNo(), order);
}
}Consumer:
@Component
public class OrderConsumer {
@KafkaListener(topics = "order-topic", groupId = "order-group")
public void handle(OrderDto order,
@Header(KafkaHeaders.RECEIVED_KEY) String key,
Acknowledgment ack) {
try {
// business logic
ack.acknowledge(); // commit offset only on success
} catch (Exception e) {
throw e; // let error handler deal with it
}
}
}The key mindset shift from RabbitMQ: ack.acknowledge() means "I've processed up to here". RabbitMQ acks per message and deletes; Kafka consumers track offsets themselves. Manual commit ≈ RabbitMQ manual ack.
Poison Pills: Don't Let One Bad Message Block a Partition
A message that always fails (deserialization error, missing field, validation failure) will retry indefinitely, blocking the entire partition. Standard pattern: retry N times → dead-letter topic → manual intervention .
@Configuration
public class KafkaErrorConfig {
@Bean
public DefaultErrorHandler errorHandler(KafkaTemplate<String, Object> template) {
// After retries exhausted, publish original message to "order-topic.DLT"
DeadLetterPublishingRecoverer recoverer = new DeadLetterPublishingRecoverer(template);
// 1s interval, 3 retries
return new DefaultErrorHandler(recoverer, new FixedBackOff(1000L, 3));
}
}@KafkaListener(topics = "order-topic.DLT", groupId = "order-dlt-group")
public void handleDead(OrderDto order, Acknowledgment ack) {
log.error("Retried 3 times, dead-letter: {}", order.getOrderNo());
// persist to exception table + alert
ack.acknowledge();
}The dead-letter topic is created automatically as originalTopic.DLT by DeadLetterPublishingRecoverer, but its partition count must match the source topic or publishing may fail.
Reliability Trio
Producer durability
spring:
kafka:
producer:
acks: all
properties:
enable.idempotence: true
retries: 3acks=allwaits for all in-sync replicas; enable.idempotence=true adds broker-side deduplication via producer sequence numbers so retries don't create duplicates.
Consumer durability
enable-auto-commit: false+ ack.acknowledge() after successful processing. Order is critical: process first, then commit. Reversing it (commit then process) loses messages if the process crashes mid-way—the costliest ordering mistake in Kafka.
Consumer exactly-once (business-level)
acks=all+ retries give at-least-once; duplicates will happen . Idempotency must be implemented in business logic (e.g., deduplication keys, upsert semantics).
End-to-end chain: Producer acks=all + idempotence → Broker multi-replica → Consumer manual commit + business idempotence .
Seven Common Pitfalls
Consumers > partitions : Extra consumers idle. Fix: Add partitions, not machines.
Frequent rebalances : Logs show Revoking previously assigned partitions, consumption stalls. Fix: Increase max.poll.interval.ms; avoid long tasks in listener.
Commit before processing : Business fails but offset committed → message lost. Fix: Strict "process then acknowledge".
Auto-commit enabled : Batch lost on shutdown. Fix: enable-auto-commit: false.
Same key not in same partition : Ordering guarantee broken. Fix: Key must be non-null; don't use custom partitioner.
JsonDeserializer trusted packages error : not in the trusted packages. Fix: Configure spring.json.trusted.packages; avoid *.
Topic not pre-created : Auto-created with 1 partition only. Fix: Create topic upfront with desired partition count.
Rebalance trigger #2 deserves emphasis: single-batch processing exceeds max.poll.interval.ms , so the consumer is deemed dead . Don't put minutes-long tasks in the listener; persist to DB and process asynchronously.
Checklist
Kafka = pull model + retained distributed log → replayable consumption
Partition is the sole unit of parallelism and ordering : parallelism ceiling = partition count; ordering only within partition
Ordering scenarios require business key (order ID), never null
Producer acks=all + enable.idempotence; consumer manual commit; business-side idempotence
Poison pills → DefaultErrorHandler + dead-letter topic; no infinite retries
Monitor health via LAG, not logs
No long-running tasks in listeners—they trigger rebalances
Once you internalize partitions, most "mysterious" Kafka problems become self-explanatory.
For questions about attribution, corrections or content rights, please contactand we will review it promptly.