Scrivio Interview library
ConceptFoundations6 min read · updated 12 November 2026

A Kafka consumer in a Spring Boot service uses the default at-least-once delivery. Explain why messages can be processed twice and how an idempotent consumer prevents duplicate side effects.

With at-least-once delivery, the consumer commits its offset only after processing, so a crash or rebalance after processing but before the commit makes Kafka deliver the same records again; producer retries can add duplicates too unless the idempotent producer is enabled, and that only covers producer to broker. An idempotent consumer prevents duplicate side effects by recording each processed message id in a table in the same database transaction as the side effect and skipping known ids, or by making the operation naturally idempotent, such as a versioned upsert. Kafka's exactly-once covers read-process-write inside Kafka, not external side effects.

Why this question is asked

Every Kafka consumer that changes a database, sends an email or calls an API will one day process the same message twice. Teams discover it as a duplicated email or a double ledger entry, often months after launch. Interviewers ask about it because it tests whether we know exactly when offsets are committed, where duplicates come from, and why exactly-once is narrower than its name suggests. In this answer, we will recap offsets and at-least-once delivery, reproduce a redelivery, look at producer-side duplicates, build an idempotent consumer in Spring Boot, and finish with what Kafka's exactly-once really covers.

1A Quick Recap of Offsets and At-Least-Once

A Kafka consumer reads records from a partition in order, and each record has an offset, its position in the partition. The consumer group stores a committed offset per partition, which says where to resume after a restart. At-least-once delivery means the offset is committed only after the record is processed. Spring Kafka's listener container does this by default: it calls our @KafkaListener method and commits the offsets afterwards, in batches or per record depending on the acknowledgement mode.

The ordering is deliberate. If we committed before processing and then crashed, the record would be skipped forever, which is at-most-once. Committing after means nothing is lost, but there is a window where the work is done and the commit is not.

2Why the Same Message Comes Back

Suppose the consumer processes records 100 to 104 and has committed up to 99. Before the next commit, the pod is killed during a deployment, or the group rebalances because a new consumer joined or one took too long between polls and was considered dead. The partition is assigned to another consumer, which starts from the committed offset 100 and processes 100 to 104 again.

Step throughRedelivery after a rebalance
Consumer AKafkaConsumer BDatabase
records 100-104
apply 100-104 (side effects done)
killed before commit
rebalance: partition to B, resume at 100
apply 100-104 again
commit offset 105

6 messages in order. Play them, or step through them one at a time.

The side effects of 100 to 104 happen twice; Kafka did nothing wrong.

3Duplicates From the Producer Side

Duplicates can also be written into the topic. If a producer sends a record, the broker stores it, but the acknowledgement is lost, the producer retries and the broker stores it again. The idempotent producer fixes that: with enable.idempotence=true, the default in recent Kafka clients, the producer attaches a producer id and sequence number to each batch, and the broker drops a batch it has already written.

But notice how narrow that guarantee is. It covers one producer session sending to the broker. If the application itself calls send() twice, for example because an HTTP request was retried, or an outbox relay resent a row after a crash, Kafka sees two different records with the same content. Those duplicates reach the consumer, and only the consumer can recognise them.

4Building an Idempotent Consumer

An idempotent consumer is one where processing a message twice has the same effect as processing it once. The usual way is an inbox, a processed-messages table keyed by a unique message id that the producer puts in the event or in a header. In the same database transaction as the side effect, the consumer inserts the id; if it already exists, the message is a duplicate and we skip it.

Java
CREATE TABLE processed_message (
consumer text NOT NULL,
message_id uuid NOT NULL,
processed_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (consumer, message_id)
);
@KafkaListener(topics = "payments", groupId = "ledger")
@Transactional
public void on(PaymentCompleted e) {
int inserted = jdbc.update("""
INSERT INTO processed_message (consumer, message_id) VALUES ('ledger', ?)
ON CONFLICT DO NOTHING""", e.eventId());
if (inserted == 0) return; // seen before: skip
ledger.credit(e.accountId(), e.amount()); // same transaction as the insert
}
// first delivery -> inserted = 1, ledger credited
// redelivery -> inserted = 0, nothing happens

The key point is that the id and the side effect commit together. If the transaction fails, neither is saved, and the redelivery processes the message properly. If it succeeds and the offset commit is lost, the redelivery finds the id and skips. A dedup check stored somewhere else, such as Redis, cannot give that guarantee, because the two writes can diverge.

Where the side effect is not in our database, an email or an external API call, the inbox alone cannot be atomic with it. Then we pass a deterministic idempotency key to the external system, or accept and limit the rare duplicate.

5Naturally Idempotent Operations

Sometimes we do not need a table at all, because the operation is idempotent by nature. Setting a value is idempotent, adding to it is not. A projection that stores a customer's status can be written as an upsert guarded by the source version, so applying the same event twice, or an older event late, changes nothing.

Java
INSERT INTO customer_view (id, status, version) VALUES (:id, :status, :v)
ON CONFLICT (id) DO UPDATE SET status = EXCLUDED.status, version = EXCLUDED.version
WHERE customer_view.version < EXCLUDED.version;
-- apply v7 -> 1 row; apply v7 again -> 0 rows

This is often the cleanest design for projections. Counters, balances and anything that sends something out still need an explicit dedup.

6What Kafka's Exactly-Once Does Not Cover

Kafka offers exactly-once semantics through transactions: a consumer can read records, produce output records and commit its input offsets in one Kafka transaction, so the output and the progress are atomic. In Spring Kafka this is a transactional KafkaTemplate with a listener container that uses it. Consumers of the output, reading with isolation.level=read_committed, never see aborted results.

But this covers read-process-write inside Kafka only. A database update, an email or an HTTP call made during processing is not part of the Kafka transaction. If the transaction aborts and the record is processed again, those side effects happen again. So even with exactly-once enabled, any consumer with external side effects must still be idempotent.

7Follow-up questions

Which message id should the producer use?

A unique id per event, generated once when the event is created and kept on every resend, such as a UUID stored in the outbox row. It must not be derived from the content alone if two genuinely different events could look identical, and it must not be regenerated on retry, or every resend looks new.

Can we avoid redeliveries by committing offsets more often?

Committing after every record shrinks the window but does not remove it, since a crash can still happen between processing and committing, and it costs throughput. Redeliveries are part of at-least-once; we design for them rather than try to eliminate them.

How long do we keep processed ids?

Longer than the longest time a duplicate can arrive, which depends on how far back a consumer might rewind and how long producers retry. Days to weeks is common, with a scheduled job deleting older rows, or partitioning the table by day so old partitions can be dropped.

8Conclusion

In this answer, we saw that at-least-once delivery commits offsets after processing, so a crash or rebalance in between causes redelivery, and that producer retries cause duplicates unless the idempotent producer is enabled, which still only covers producer to broker. An idempotent consumer records processed message ids in the same database transaction as its side effect and skips ids it has seen, or uses a naturally idempotent operation such as a versioned upsert. Kafka's exactly-once covers read-process-write inside Kafka, not database writes, emails or API calls.

What to say in the interviewAbout 90 seconds aloud

Open with

With at-least-once delivery, the listener container commits the offset after my method has processed the record. So there is always a window where the work is done but the commit has not happened.

Then, if they want more

If the pod crashes, is redeployed, or the group rebalances in that window, the partition moves to another consumer that resumes from the last committed offset and processes the same records again. Duplicates can also come from the producer: if an acknowledgement is lost and the producer retries, the broker can store the record twice.

The idempotent producer, which is on by default in recent clients, prevents that, but only for the producer to broker path; an application that sends the same event twice still creates two records. So the consumer has to protect itself.

I would give every event a unique id, and in the same database transaction as the side effect, insert that id into a processed-messages table with a primary key, using insert on conflict do nothing. If nothing was inserted, it is a duplicate and I skip it.

Because the id and the side effect commit together, a redelivery is always harmless. For projections, a versioned upsert can be naturally idempotent instead. And I would point out that Kafka's exactly-once transactions only cover consume, produce and offset commits inside Kafka, not database writes or external calls.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A Kafka consumer in a Spring Boot service uses the default at-least-once delivery....": https://scrivio-interview-library.netlify.app/spring-boot/distributed-data/6ac02bb8d9/