Scrivio Interview library
Kafka21 May 202625 min read

The Gap Between @KafkaListener and Reality

An engineer adds spring-kafka to the pom.xml, drops @KafkaListener(topics = "orders") above a method, points it at a broker, and watches messages flow into the logs within ten minutes. Staging looks clean. The first week in production looks clean. Then a broker restarts during a deploy, or a consumer pod gets OOM-killed mid-batch, or traffic doubles and one partition starts lagging. Suddenly the same order is being processed twice. Or an order vanishes with no exception, no error, no trace. The listener kept running. The metrics looked fine. The message is just gone.

Most Spring Boot engineers hit this wall and discover that @KafkaListener is not really a Kafka client. It is a thin facade over one. Behind the annotation sits a container that polls a KafkaConsumer, a consumer group coordinator on the broker side negotiating partition ownership, an offset commit strategy that decides when a message counts as "done," and a rebalance protocol that can yank partitions away from your pod in the middle of a transaction1. The annotation hides all of it. That is the point of the annotation. It is also the source of nearly every production incident that follows.

The failure modes are predictable once you know where to look. Messages disappear because the consumer auto-committed an offset before the business logic finished. The same message gets processed three times because a rebalance happened between processing and commit. Events arrive out of order because two pods are consuming the same logical stream across different partitions with no awareness of each other. None of these are bugs in the application code. They are bugs in the engineer's mental model of when, exactly, a Kafka message is considered delivered2, 3.

The annotation itself encourages the confusion. You can write @KafkaListener(id = "myListener", topics = "myTopic") and never think about partitions at all4. You can use topicPattern to subscribe to a regex and let Kafka assign whatever partitions it decides4. You can also pin partitions explicitly, set initial offsets, seek to a timestamp on startup, and hook into rebalance callbacks4, 4. The same annotation covers a five-line demo and a twenty-line production-grade consumer. Nothing in the API tells you which one you need, or warns you when the default is wrong for your workload. Newer Kafka versions have added incremental rebalancing through KIP-848, which changes how often onPartitionsAssigned fires and which assignor strategies are even honored5, 5. The defaults shift under you across versions.

Debugging any of this means stepping back from the annotation and looking at what Kafka actually is: a distributed, fault-tolerant commit log where producers append records, brokers replicate and persist them, consumers pull at their own pace, and the whole protocol is deliberately asynchronous so that producers and consumers never have to know about each other6, 6. Every reliability guarantee, and every way that guarantee can break, falls out of that design. Before we can fix a consumer that loses messages, we need to understand what Kafka is doing with those messages in the first place.

Topics, Partitions, and the Commit Log#

Strip away the client libraries and Kafka is a surprisingly small idea: an append-only file, replicated across machines, that many readers can scan independently at their own pace. Every behavior that surprises a Spring Boot engineer later, from rebalance pauses to duplicate deliveries, traces back to that file.

The file is called a partition. A topic is just a name that groups one or more partitions together, and each partition is an ordered, immutable sequence of records written to disk in the order they arrived. Records are never updated in place. New records get appended to the end, each one assigned a monotonically increasing integer called an offset. Offset 0 is the first record ever written to that partition. Offset 1,847,392 is the 1,847,393rd. That number is the only address a consumer ever needs.

Why split a topic into partitions at all? Because one file on one disk caps your throughput at whatever that disk and that network card can do. Partitions are the unit of parallelism. A topic with twelve partitions can be written to and read from twelve places at once, and a consumer group of twelve instances can have each instance own exactly one partition. This is the reason your @KafkaListener scales the way it does, or does not: if the topic has three partitions, you will never get more than three threads doing useful work, no matter how many pods you run.

The servers that hold these partition files are called brokers. A broker is a JVM process responsible for storing partition data and serving it to clients. A Kafka cluster is a handful of brokers that know about each other. Partitions are distributed across them, and each partition is replicated to several brokers for durability, but only one of those replicas is the leader at any given moment. All reads and writes for a partition go through its leader. The followers exist to take over if the leader dies. When you read about "rebalances" and "leader elections," this is what is moving: the assignment of which broker leads which partition.

Now the part that trips people up. Kafka consumers do not receive messages. They fetch them. A consumer opens a connection to the broker leading a partition, sends a request that says "give me records starting at offset N," and receives a chunk of the log back. Then it asks again. Then again. What looks like a push from inside your @KafkaListener method is, underneath, a polling loop the Spring container runs on your behalf.

This pull model is deliberate. In a push system the broker decides how fast to send, and a slow consumer either falls over or forces the broker to buffer indefinitely. With pull, the consumer regulates its own ingestion rate and the broker stays simple. It also gives the consumer something powerful: because the consumer specifies the offset on every fetch, it can rewind. Set the offset back to yesterday morning and you re-read yesterday morning's events. The log is still there. Kafka did not delete it when you read it the first time. This is the single biggest mental shift coming from RabbitMQ or ActiveMQ: consumption does not destroy the message. Reading is a cursor, not a queue pop.

Hold onto that picture. A topic is N append-only files spread across brokers. A producer picks one of those files and appends to its leader. A consumer holds a cursor (an offset) into each file it has been assigned, and advances that cursor by asking for more. Everything else, acknowledgments, consumer groups, commits, rebalances, is machinery built around protecting and coordinating those cursors. Once the storage model is clear, the next question writes itself: how does a record actually get into the log in the first place, and when is the producer allowed to believe the write succeeded?

Producer Event Flow: From send() to Broker Acknowledgment#

producer.send(record) returns a Future almost instantly. That speed is a half-truth. The message has not touched a broker. It has barely left your JVM.

What actually happens is a handoff between two threads with a queue in the middle2. Your application thread serializes the record, picks a partition (via the configured partitioner or the key's hash), and drops it into an in-memory structure called the record accumulator. The accumulator groups records into per-partition batches. A separate background sender thread (the I/O thread) drains those batches and pushes them to the broker over the Kafka wire protocol6. The Future you got back resolves only when the broker responds, or when the client gives up.

Text
send() drain
App ─────► [Record Accumulator] ─────► Sender Thread ─────► Broker
thread partition0: [batch] (I/O) (leader)
partition1: [batch] │
partition2: [batch] ▼
waits for ack

This is why Kafka producers feel fast: the application thread's job ends at the queue. Throughput comes from the sender thread batching many records into one network request. The knobs that govern this batching (batch.size, linger.ms, buffer.memory) are not just performance tuning. They define how much data lives in your process memory with no broker copy yet, which is exactly the data you lose if the JVM dies.

The acknowledgment the sender thread waits for is controlled by the acks setting, and this is where most silent message loss originates2. There are three values:

acksWho must confirmFailure mode
0Nobody. Fire-and-forget.Any network blip or broker restart loses the record.
1The partition leader only.Leader crashes after acking but before replicating: record gone.
allLeader plus all in-sync replicas.Slowest, but survives single-broker loss.

Starting with Kafka client 3.0 (bundled with Spring Boot 2.7+ via spring-kafka 2.8+), the default for acks is all. On older clients the default was 1, and code written against those versions kept that default when libraries were upgraded if the property was never set explicitly. Do not rely on the version-dependent default. Set spring.kafka.producer.acks=all in application.yml so the behavior travels with your code instead of with whichever client version happens to be on the classpath.

For producers that must not lose or duplicate records, pair acks=all with idempotence:

YAML
spring:
kafka:
producer:
acks: all
retries: 2147483647 # retry indefinitely up to delivery.timeout.ms;
# this is the pairing the docs recommend with idempotence
properties:
enable.idempotence: true
max.in.flight.requests.per.connection: 5
delivery.timeout.ms: 120000

Idempotence makes the broker deduplicate retries using a producer ID and a per-partition sequence number, so a retried batch after a transient network error does not become a duplicate. Without it, retries > 0 plus acks=all can produce duplicates on the broker even though the producer thought it sent once.

One subtlety the two-thread model creates: send() can block. If the accumulator fills up because the sender thread cannot keep pace with the broker (or the broker is down), the application thread blocks inside send() until max.block.ms expires, then throws. Engineers who assume send() is purely asynchronous discover this the first time a broker goes slow and their HTTP request threads start piling up on what looked like fire-and-forget calls.

So the producer-side lifecycle, end to end: serialize on the app thread, enqueue into the accumulator, batch by partition, drain on the sender thread, transmit to the leader, wait for the configured replicas to acknowledge, resolve the Future. Only after that last step is the record durable in a partition's commit log, sitting there until a consumer group claims the partition and starts reading.

Consumer Groups, Partition Assignment, and the Rebalance Protocol#

A single Spring Boot instance running @KafkaListener(topics = "orders") works. Scale it to three pods behind a Kubernetes deployment and something less obvious happens: the three pods do not each receive every message. They split the topic's partitions between them, coordinated by a Kafka broker that none of your application code explicitly references. That coordination is the consumer group protocol, and it is the single largest source of duplicate or dropped messages in production Spring Boot consumers.

How an instance joins. A consumer group is a set of consumer instances that collaborate to consume one or more topics, with each partition assigned to exactly one consumer in the group at any moment7. The group identity comes from a single string: spring.kafka.consumer.group-id. Every Spring Boot pod that boots with the same group-id becomes a member of the same group, regardless of which host it runs on or when it started.

When a Spring Boot application starts its listener container, the underlying Kafka client picks one broker as the group coordinator for that group. The coordinator is chosen deterministically by hashing the group ID against the __consumer_offsets topic's partitions; whichever broker leads the resulting partition becomes the coordinator. The new consumer then sends a JoinGroup request to that coordinator. The coordinator collects join requests within a short window, elects one consumer as the group leader, and sends the leader the full member list. The leader runs the partition assignment strategy locally and returns the result to the coordinator, which distributes each consumer's slice via a SyncGroup response.

This matters because your Spring Boot app does not decide which partitions it reads. The group leader does. And the group leader is whichever consumer happened to join first, which on a rolling deploy is essentially random.

Assignment strategies. Kafka supports configurable partition assignment strategies that determine how partitions are distributed among consumers during a rebalance7. The three you will encounter in practice:

  • RangeAssignor (the historical default): assigns contiguous ranges of partitions per topic. Skews badly when partition counts do not divide evenly across consumers.
  • RoundRobinAssignor: distributes partitions one at a time across all consumers. Better balance, but every rebalance reshuffles everything.
  • CooperativeStickyAssignor: tries to preserve existing assignments and only moves the partitions that must move. This is the modern default in newer clients and the one you almost always want.

Set it explicitly: spring.kafka.consumer.properties.partition.assignment.strategy=org.apache.kafka.clients.consumer.CooperativeStickyAssignor.

What triggers a rebalance. A rebalance happens whenever the group's membership or the topic's partition count changes. The full list: a new consumer joins, an existing consumer leaves or crashes, a consumer's session timeout expires without heartbeats, or new partitions are added to a topic8, 8. One more trigger bites Spring Boot apps specifically: exceeding max.poll.interval.ms between calls to poll(). If your @KafkaListener method takes longer than five minutes to process a batch (the default), the broker assumes your consumer is wedged and kicks it out of the group.

Heartbeats and processing are decoupled. A background thread sends heartbeats every heartbeat.interval.ms (default 3 seconds), and if the broker does not see one for session.timeout.ms (default 45 seconds), it considers the consumer dead, removes it from the group, and triggers a rebalance to redistribute its partitions8. The poll-interval check is separate: it fires when the main thread is alive enough to heartbeat but too slow to call poll() again.

Java
┌─────────────────────────────────────────────────────────┐
│ REBALANCE TRIGGERS │
├─────────────────────────────────────────────────────────┤
│ • New consumer joins (pod scale-up, rolling deploy) │
│ • Consumer leaves cleanly (graceful shutdown) │
│ • Session timeout (no heartbeat in 45s) │
│ • max.poll.interval exceeded (slow processing) │
│ • Topic partition count increased │
└────────────────────────┬────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────┐
│ 1. Coordinator marks group as rebalancing │
│ 2. All consumers receive REBALANCE_IN_PROGRESS │
│ 3. Consumers stop polling, revoke current partitions │
│ 4. Each consumer sends JoinGroup │
│ 5. Leader computes assignment │
│ 6. SyncGroup distributes new partitions │
│ 7. Consumers resume polling on new assignments │
└─────────────────────────────────────────────────────────┘

During steps 3 through 7, all consumers in the group pause consumption. Rebalances directly cause processing stalls and can result in duplicate message delivery if offsets were not committed before the rebalance began7. A consumer halfway through processing a batch when revocation hit will have those same messages delivered to whichever consumer ends up with that partition next. The cooperative protocol shortens the stall window but does not eliminate the duplicate-delivery problem; that one belongs to offset management.

What Spring Boot hides from you. The rebalance mechanics above happen at the Kafka client layer, but your Spring Boot code never calls subscribe(), never handles JoinGroup responses, and never sees a ConsumerRebalanceListener unless you explicitly install one. Spring's KafkaMessageListenerContainer wraps all of this, and the defaults it picks are quiet about failure.

Three Spring Boot-specific behaviors are worth knowing. First, the listener container runs the poll loop on a dedicated thread per consumer instance, and your @KafkaListener method executes on that same thread by default. If your method blocks on a slow downstream call, you are blocking the poll loop, and max.poll.interval.ms is counting down. Second, on a clean shutdown (a SIGTERM that triggers Spring's context close), the container calls consumer.close(), which sends a LeaveGroup request and triggers an immediate rebalance instead of waiting for the session timeout. This is good for liveness but means rolling deploys cause N rebalances for N pods unless you tune group.instance.id for static membership. Third, you can hook the rebalance itself by providing a ConsumerAwareRebalanceListener on the container's ContainerProperties. Inside onPartitionsRevokedBeforeCommit, you get one last chance to commit offsets for work you actually completed:

Java
@Bean
public ConcurrentKafkaListenerContainerFactory<String, String> kafkaListenerContainerFactory(
ConsumerFactory<String, String> consumerFactory) {
var factory = new ConcurrentKafkaListenerContainerFactory<String, String>();
factory.setConsumerFactory(consumerFactory);
factory.getContainerProperties().setConsumerRebalanceListener(
new ConsumerAwareRebalanceListener() {
@Override
public void onPartitionsRevokedBeforeCommit(
Consumer<?,?> consumer, Collection<TopicPartition> partitions) {
log.warn("Revoking partitions: {}", partitions);
}
});
return factory;
}

Without that listener, a rebalance during processing is silent. You will see the duplicates downstream and have no log line pointing back at the cause.

Knowing which partitions a consumer owns and when it loses them is only half the picture. The other half is what the consumer remembers about where it stopped reading, which is tracked through offsets and the commit protocol.

Offset Management: The Mechanism Behind At-Least-Once and At-Most-Once Delivery#

An offset is just an integer. That is the entire trick. For each partition a consumer reads from, Kafka stores a single number per consumer group representing the position of the last record that group has acknowledged as consumed. That number lives in an internal compacted topic called __consumer_offsets, keyed by the tuple (group.id, topic, partition). When a consumer in the group disconnects, crashes, or is rebalanced off a partition, the next consumer to take ownership reads that number and starts fetching from the record immediately after it9.

Everything reliability-related about consuming flows from one question: when does that number get written?

The default answer is on a timer. With enable.auto.commit=true and auto.commit.interval.ms=5000, the consumer client periodically writes whatever offset it has most recently fetched, regardless of whether your code has finished doing anything with those records2. This is fast, it is convenient, and it is the source of most "we lost messages" incident reports. Picture the sequence: poll returns 100 records, the auto-commit timer fires and writes offset 100, your handler is partway through record 47 when the pod is killed. The replacement consumer reads offset 100 from __consumer_offsets and starts at record 101. Records 47 through 100 are gone from this consumer group's perspective. They were never processed, but Kafka believes they were. That is at-most-once delivery, and you usually did not mean to opt into it2.

Flip the order and you get the opposite failure mode. Process first, commit second. Now if the consumer crashes between processing record 47 and committing offset 47, the next consumer reads the old offset and replays record 47. The message is not lost. It is delivered again. This is at-least-once delivery, and it is what almost every production Kafka consumer actually wants10. The cost is that your downstream logic has to tolerate duplicates: insert with an idempotency key, upsert instead of insert, check-then-write. Whatever the strategy, the consumer side cannot eliminate the duplicate by itself.

People reach for exactly-once next, and this is where the lifecycle bites back. There is always a window, however small, between "I finished processing this record" and "the broker has durably recorded my new offset." A crash inside that window produces a duplicate on restart. You can shrink the window by moving the offset commit into the same database transaction as the processing side-effect, which is the pattern Spring Kafka exposes via KafkaTransactionManager and chained transaction managers. You can use Kafka's transactional producer to make read-process-write loops atomic within Kafka itself. What you cannot do is make the window zero across arbitrary external systems10. Exactly-once end-to-end is a property of the entire pipeline, not a checkbox on the consumer10.

For most Spring Boot services, the right default is manual acknowledgment with at-least-once semantics and idempotent handlers. That maps onto three concrete configuration choices:

YAML
spring:
kafka:
consumer:
enable-auto-commit: false
auto-offset-reset: earliest
listener:
ack-mode: MANUAL_IMMEDIATE

MANUAL_IMMEDIATE tells the Spring container to commit the offset synchronously the moment your listener method calls ack.acknowledge(). Other modes change the timing: RECORD commits after each record returns successfully, BATCH commits once per poll after all records in the batch are processed, TIME and COUNT commit on intervals or thresholds. Each mode is a different bet about where you want the crash window to fall.

With offsets understood as the pivot point, the whole lifecycle has a single thread running through it. The producer's acks setting decides when a record is durably written. The partition assignment protocol decides which consumer instance owns which slice of the log. The offset commit strategy decides what happens when that consumer dies mid-record. The next section maps these three control points back onto the Spring Boot abstractions you actually configure.

Wiring It All Together: @KafkaListener and Spring Kafka's Lifecycle#

Every mechanism covered so far, producer acks, partition assignment, rebalance callbacks, offset commits, exists in the Kafka client. Spring Kafka does not replace any of it. It wraps it. When you write @KafkaListener(topics = "orders"), Spring builds a KafkaMessageListenerContainer that owns a consumer instance, runs the poll() loop on a dedicated thread, dispatches each record to your method, and decides when to commit offsets1, 11. Understanding which knob on the annotation corresponds to which stage of the lifecycle is the difference between a listener that works in dev and one that survives a deploy at 2am.

The container is the lifecycle. When the Spring context starts, the KafkaListenerEndpointRegistry creates one ConcurrentMessageListenerContainer per @KafkaListener method. That concurrent container starts N KafkaMessageListenerContainer instances, one per thread, each with its own KafkaConsumer. Each child container runs the same loop forever: poll, dispatch, (maybe) commit, repeat.

Text
Spring context start
│
▼
KafkaListenerEndpointRegistry
│
▼
ConcurrentMessageListenerContainer (concurrency = N)
│
├── KafkaMessageListenerContainer #1 ── KafkaConsumer ── poll loop
├── KafkaMessageListenerContainer #2 ── KafkaConsumer ── poll loop
└── KafkaMessageListenerContainer #N ── KafkaConsumer ── poll loop
│
├─ subscribe() → triggers rebalance
├─ poll() → fetches records
├─ dispatch → your @KafkaListener method
└─ commit (sync or async, per AckMode)

Each child container is the unit that joins the consumer group, gets partitions assigned, and commits offsets. Stop the container and you leave the group cleanly. Crash it and you wait for the session timeout before the group rebalances.

Concurrency must match partitions. The concurrency attribute on @KafkaListener sets how many child containers (and therefore how many threads and how many KafkaConsumer instances) the concurrent container spawns3. The rule is simple and unforgiving: if your topic has P partitions and you set concurrency to C, then min(C, P) threads do work and max(0, C - P) threads sit idle forever12. Set C below P and each thread serially processes records from multiple partitions, capping your throughput at single-thread speed per partition12.

Java
@KafkaListener(
id = "orders",
topics = "orders",
groupId = "order-service",
concurrency = "6" // match this to the topic's partition count
)
public void onOrder(Order order,
@Header(KafkaHeaders.RECEIVED_PARTITION) int partition,
@Header(KafkaHeaders.OFFSET) long offset) {
// one thread per partition processes records here
}

If you scale this service to three instances with concurrency=6 against a 6-partition topic, you now have 18 consumers competing for 6 partitions. Twelve of them will sit idle. This is the same arithmetic as the rebalance section, applied to Spring's threading model.

AckMode is where at-least-once lives or dies. By default since Spring Kafka 2.3, the container sets enable.auto.commit=false and takes over commits itself11, 11. The container's behavior is controlled by AckMode, which defaults to BATCH: after every poll() returns and your listener has been invoked for every record in that batch, the container commits the offsets11, 12. This is fine until processing throws halfway through the batch, in which case the records you already processed will be redelivered after restart.

The available modes map directly onto the offset semantics discussed earlier:

AckModeCommit happens when...
RECORDlistener returns successfully for each record11
BATCH (default)all records from a poll() are processed11
TIMEbatch processed and ackTime has elapsed since last commit11
COUNTbatch processed and ackCount records since last commit11
MANUALyou call acknowledgment.acknowledge(); commit deferred to next poll11
MANUAL_IMMEDIATEyou call acknowledgment.acknowledge(); commit fires now11

For at-least-once with side effects you cannot undo (database writes, HTTP calls to a payment processor), MANUAL_IMMEDIATE is usually what you want. The listener accepts an Acknowledgment parameter, you call acknowledge() only after the work is durably done, and the offset commit happens before the next poll11, 11:

Java
@KafkaListener(
topics = "payments",
groupId = "payment-processor",
containerFactory = "manualAckContainerFactory"
)
public void onPayment(Payment payment, Acknowledgment ack) {
paymentService.charge(payment); // do the work first
ack.acknowledge(); // then commit the offset
}

The container factory needs AckMode.MANUAL_IMMEDIATE:

Java
@Bean
public ConcurrentKafkaListenerContainerFactory<String, Payment> manualAckContainerFactory(
ConsumerFactory<String, Payment> cf) {
var factory = new ConcurrentKafkaListenerContainerFactory<String, Payment>();
factory.setConsumerFactory(cf);
factory.getContainerProperties().setAckMode(AckMode.MANUAL_IMMEDIATE);
return factory;
}

Get this wrong in the other direction, handing the message off to an ExecutorService and returning immediately under the default BATCH mode, and the container commits offsets while your worker pool still has records in flight. A shutdown at that moment loses them, with no error, no retry, no trace12, 12. Async dispatch and auto-commit do not mix.

Failure handling: nack and redelivery. Acknowledgment also exposes nack(Duration sleep) and nack(int index, Duration sleep)11. Calling nack() commits any pending offsets, discards the rest of the current poll's records, and seeks back to the failed record so it gets redelivered on the next poll11. The sleep argument pauses the entire listener (all assigned partitions) for that duration, which is useful for backing off on a transient downstream failure11. Throwing an exception from the listener method gives you similar behavior via DefaultErrorHandler, which by default retries with backoff and then sends to a dead-letter topic if configured.

Seeking: ConsumerSeekAware for replay and recovery. If your committed offset is wrong, or your application's view of "processed" drifted from Kafka's, Spring Kafka's answer is ConsumerSeekAware. Implement it on your listener class and you get callbacks at three lifecycle moments: when partitions are assigned at startup, when they are revoked during rebalance, and when you want to seek mid-flight13.

Java
@Service
public class OrderListener implements ConsumerSeekAware {
private final OffsetService offsetService;
@Override
public void onPartitionsAssigned(Map<TopicPartition, Long> assignments,
ConsumerSeekCallback callback) {
// pull the last application-confirmed offset from your own DB
assignments.forEach((tp, kafkaOffset) -> {
Long appOffset = offsetService.getOffset(tp.topic(), tp.partition());
if (appOffset!= null) {
callback.seek(tp.topic(), tp.partition(), appOffset);
}
});
}
@KafkaListener(topics = "orders", groupId = "order-service")
public void onOrder(ConsumerRecord<String, Order> record, Acknowledgment ack) {
//...
}
}

The callback fires once per partition assignment. To re-seek without restarting the container, keep a reference to the ConsumerSeekCallback from registerSeekCallback and invoke it from inside the listener thread13. Seeks must happen on the consumer thread; calling them from a worker pool will not work.

Out-of-order acks with async processing. If you need to process records from the same partition in parallel and acknowledge them out of order, Spring 2.8+ supports asyncAcks=true on the container properties14. The container defers out-of-order commits until the gaps are filled and pauses the consumer to prevent new records from arriving while there are outstanding acks. This is a sharp tool. It bends the per-partition ordering guarantee Kafka is built on, and it only works with MANUAL or MANUAL_IMMEDIATE. Reach for it when you have measured that a single-threaded partition consumer cannot keep up and you have verified that your downstream logic is genuinely order-independent.

Every @KafkaListener you write is doing all of this whether you configured it or not: choosing an AckMode, sizing a thread pool against partitions, handling rebalances, deciding when to commit. The defaults are reasonable for a demo. They are dangerous for a payment system.

Configuring for Correctness: Avoiding Silent Message Loss and Duplicates#

The mechanisms are now visible. What remains is the choice of which knobs to turn, and the honest answer is that the correct settings depend on a question only you can answer: what does your business actually require when a message is in flight and something fails?

Start there. Three delivery postures cover almost every real system, and each maps to a small, specific set of configuration decisions.

If losing a message is worse than processing it twice (payments, order placement, audit logs), you want at-least-once with idempotent processing. On the producer, set acks=all and enable.idempotence=true, and ensure the broker side has min.insync.replicas=2 so a write is not acknowledged until a second replica has it on disk2. On the consumer, set enable.auto.commit=false and use AckMode.MANUAL_IMMEDIATE, calling acknowledgment.acknowledge() only after your processing and any downstream writes have succeeded2. Then accept that duplicates will happen during rebalances and crashes, and make your handler idempotent: dedupe on the message key, check a processed-IDs table, or use an upsert with a natural unique constraint10. There is no clever configuration that removes this requirement.

If duplicate processing is worse than loss (fire-and-forget metrics, best-effort notifications), you can leave auto-commit on with a short auto.commit.interval.ms and use acks=1 on the producer. You are explicitly trading durability for simplicity. Be honest with yourself that you are doing that.

If you genuinely need exactly-once across a read-process-write loop within Kafka, use the transactional producer with transactional.id set, and on the consumer side isolation.level=read_committed. This works when your sink is another Kafka topic. The moment a database or external API enters the loop, you are back to at-least-once plus idempotent writes.

One setting cuts across all three postures: max.poll.interval.ms. It must exceed the worst-case time your handler takes to process a single poll's worth of records, or the broker will evict your consumer mid-work and trigger a rebalance that hands the same records to someone else8. Measure your p99 processing time per batch, multiply by your safety factor, and set it explicitly. The default of five minutes is a guess, not an answer.

Before your next deploy, walk through this:

  1. **What is the producer's acks setting, and does the broker's min.insync.replicas back it up?** If acks=all hits a topic with only one in-sync replica, you have the latency cost without the durability benefit.
  2. **Is enable.auto.commit false, with offsets committed after processing succeeds?** If not, you have a message-loss window every five seconds by default.
  3. Can your handler be invoked twice with the same record without corrupting state? If you cannot say yes with confidence, you do not have at-least-once. You have at-least-once-and-occasionally-broken.
  4. **Is max.poll.interval.ms larger than your measured worst-case batch processing time?** If you have not measured, the answer is no.

Wiring up @KafkaListener is the easy part. The lifecycle underneath is where systems quietly fail. You now have that lifecycle in your head: producer batching and acknowledgment, partition assignment and rebalance, poll loops and offset commits, and the Spring container that orchestrates them. The shift that matters is no longer treating Kafka as a queue you read from, but as a log you hold a cursor into, where every guarantee is something you opt into by configuration and code. Pick one consumer in your codebase today, the one that processes something you would be embarrassed to lose, and audit it against the four questions above. Whatever you find first is the bug that was always going to bite you in production.

Sources

  1. Kafka Consumers: Under the Hood of Message Processingarchitecture-weekly.com
  2. Understanding and Mitigating Message Loss in Apache Kafka - DEV Communitydev.to
  3. Using Kafka Producers and Consumers properlymedium.com
  4. @KafkaListener Annotation :: Spring Kafkadocs.spring.io
  5. Rebalancing Listeners :: Spring Kafkadocs.spring.io
  6. Kafka Producers and Consumers | Conduktorconduktor.io
  7. Kafka Rebalancing: Triggers, Effects, and Mitigationredpanda.com
  8. Kafka Rebalancing Explained: How It Works & Why It Mattersconfluent.io
  9. Kafka Consumer Design: Consumers, Consumer Groups, and Offsets | Confluent Documentationdocs.confluent.io
  10. java - Effective strategy to avoid duplicate messages in apache kafka consumer - Stack Overflowstackoverflow.com
  11. Message Listener Containers :: Spring Kafkadocs.spring.io
  12. Deep Dive into Kafka Offset Commit with Spring Bootpiotrminkowski.com
  13. spring boot - How to seek a particular offset in kafka listener method? - Stack Overflowstackoverflow.com
  14. Manually Committing Offsets :: Spring Kafkadocs.spring.io

Keep reading

Kafka13 August 2026

How Kafka Rebalances a Consumer Group, Step by Step

The orders topic has six partitions. Consumer A owns 0 through 2, consumer B owns 3 through 5, and both are keeping pace with the write rate. Ahead of a traffic spike you start a...

13 min readRead the article
Kafka12 August 2026

How Kafka Handles Backpressure: Durable Log, Pull Consumers, Blocking Producers

send() is asynchronous in a specific and limited sense: it hands a record to an in-memory buffer and returns. When that buffer has no room, it does not return. A payments service...

14 min readRead the article
Kafka6 August 2026

Debugging Kafka in Production: Four Failure Modes and Their Parameters

The orders-events topic has 12 partitions, consumed by six instances of a payments-enrichment service. Roughly every five minutes, the group logs a rebalance, all 12 partitions...

15 min readRead the article