Offsets and delivery semantics

Mid-level Always asked 7 min

On this page

The question

What are at-most-once, at-least-once and exactly-once delivery in Kafka?

30-second answer

They describe what a crash does to records in flight, and the consumer decides it by when it commits. Commit before processing: at-most-once, a crash can lose records. Commit after processing: at-least-once, a crash repeats them, so processing must be idempotent. Exactly-once means the output records and the input offsets commit in one Kafka transaction, read with read_committed; it covers results written back to Kafka.

Understand it

A crash between processing and commit

Predict

A billing consumer polls offsets 10 to 14 of partition 0 and sends an invoice for each. It commits after the batch, but crashes before that commit.

Another consumer takes over partition 0. What happens to offsets 10 to 14?
View as text

A consumer above a row of offsets 8 to 16 of partition 0, with the batch 10 to 14 marked. Under each record of the batch, how many invoices were sent for it; under the row, a marker at the committed offset. A billing consumer polls offsets 10 to 14 of partition 0 and sends an invoice for each. It commits after the batch, but crashes before that commit. The learner predicts what happens to offsets 10 to 14.

C2 takes over partition 0 and asks for the committed offset. It is still 10, from the batch before, so C2 starts reading at 10.

C2 processes 10 to 14 again and commits 15. Five customers get a second invoice: at-least-once, nothing lost, some things repeated.

Commit right after poll instead, and the offset is 15 before any invoice goes out. A crash at 12 leaves 12 to 14 never invoiced: at-most-once.

The usual fix keeps at-least-once and makes processing idempotent: each invoice is stored under its order ID, and an ID already invoiced is skipped.

A consumer above a row of offsets 8 to 16 of partition 0, with the batch 10 to 14 marked. Under each record of the batch, how many invoices were sent for it; under the row, a marker at the committed offset. A billing consumer polls offsets 10 to 14 of partition 0 and sends an invoice for each. It commits after the batch, but crashes before that commit. The learner predicts what happens to offsets 10 to 14.

C2 takes over partition 0 and asks for the committed offset. It is still 10, from the batch before, so C2 starts reading at 10.

C2 processes 10 to 14 again and commits 15. Five customers get a second invoice: at-least-once, nothing lost, some things repeated.

Commit right after poll instead, and the offset is 15 before any invoice goes out. A crash at 12 leaves 12 to 14 never invoiced: at-most-once.

The usual fix keeps at-least-once and makes processing idempotent: each invoice is stored under its order ID, and an ID already invoiced is skipped.

Takeaway: Kafka resumes from the committed offset, nothing else. Commit after processing and a crash repeats work; commit before and a crash skips it. Most systems pick repeats, and make processing idempotent.

At most, at least and exactly once

Compare

Commit first, then process. The crash comes after 10 and 11; the restart begins at 15, so 12 to 14 are skipped. Nothing repeats, and records can be lost.

View as text

Three steps of a consumer loop in a row, with a crash after the second. Below, offsets 10 to 14, each with how many times its result is seen after the restart.

At most once: steps poll 10-14, commit 15, process. Commit first, then process. The crash comes after 10 and 11; the restart begins at 15, so 12 to 14 are skipped. Nothing repeats, and records can be lost. 12 to 14 never processed.

At least once: steps poll 10-14, process, commit 15. Process first, then commit. The crash comes before the commit; the restart begins at 10, so the whole batch runs again. Nothing is lost, and records can repeat. 10 to 14 processed twice.

Exactly once: steps poll 10-14, write output, commit both. Output records and offset 15 commit in one Kafka transaction. The crash aborts it, so read_committed consumers never see the first output, and the retry commits once. Output seen once per record.

Three steps of a consumer loop in a row, with a crash after the second. Below, offsets 10 to 14, each with how many times its result is seen after the restart.

At most once: steps poll 10-14, commit 15, process. Commit first, then process. The crash comes after 10 and 11; the restart begins at 15, so 12 to 14 are skipped. Nothing repeats, and records can be lost. 12 to 14 never processed.

At least once: steps poll 10-14, process, commit 15. Process first, then commit. The crash comes before the commit; the restart begins at 10, so the whole batch runs again. Nothing is lost, and records can repeat. 10 to 14 processed twice.

Exactly once: steps poll 10-14, write output, commit both. Output records and offset 15 commit in one Kafka transaction. The crash aborts it, so read_committed consumers never see the first output, and the retry commits once. Output seen once per record.

Takeaway: The guarantee depends on when the offset is committed relative to the work. Before it: losses. After it: repeats. In the same Kafka transaction as the output: exactly once, for results written back to Kafka.

When the offset is committed decides the guaranteeAfter polling, a consumer either commits before processing, which gives at-most-once because a crash loses records, or after processing, which gives at-least-once because a crash repeats them. Committing the offsets in the same Kafka transaction as the output gives exactly-once for results written to Kafka.before processingafter processingin the output'stransactionpollWhen is theoffset committed?At most once:a crash losesrecordsAt least once:a crash repeats themExactly once,Kafka to Kafka
When the offset is committed decides the guaranteeAfter polling, a consumer either commits before processing, which gives at-most-once because a crash loses records, or after processing, which gives at-least-once because a crash repeats them. Committing the offsets in the same Kafka transaction as the output gives exactly-once for results written to Kafka.before processingafter processingin the output'stransactionpollWhen is theoffset committed?At most once:a crash losesrecordsAt least once:a crash repeats themExactly once,Kafka to Kafka
When the offset is committed decides the guarantee

In code

// spring.kafka.listener.ack-mode=manual
@KafkaListener(topics = "orders", groupId = "billing")
void on(OrderPlaced e, Acknowledgment ack) {
    invoices.createOnce(e.orderId(), e);   // idempotent: a repeat finds the invoice and skips
    ack.acknowledge();                     // only now may the offset be committed
}
Spring Kafka: acknowledge after the work is done
producer.initTransactions();                          // transactional.id set; fences older instances
while (running) {
    ConsumerRecords<String, Payment> records = consumer.poll(Duration.ofMillis(500));
    if (records.isEmpty()) continue;
    producer.beginTransaction();
    try {
        for (var r : records)
            producer.send(new ProducerRecord<>("payments-eur", r.key(), toEur(r.value())));
        producer.sendOffsetsToTransaction(nextOffsets(records), consumer.groupMetadata());
        producer.commitTransaction();                 // output and offsets visible together
    } catch (ProducerFencedException fatal) {
        throw fatal;                                  // a newer instance took over: stop
    } catch (KafkaException e) {
        producer.abortTransaction();                  // read_committed readers never see it
        seekToCommitted(consumer, records.partitions()); // and read the batch again
    }
}
Read, process, write: output and offsets in one transaction
spring.kafka.producer.transaction-id-prefix=converter-tx-
spring.kafka.consumer.enable-auto-commit=false
# Every consumer of payments-eur, not only this service
spring.kafka.consumer.isolation-level=read_committed
Spring Boot: transactions on, and downstream readers skip aborted output
// enable.auto.commit=true: the next poll commits these offsets, finished or not. A crash loses them
 Wrong for (var r : consumer.poll(timeout)) executor.submit(() -> handle(r));

// Handle the batch before polling again, so every commit covers finished work
 Right for (var r : consumer.poll(timeout)) handle(r);
Auto commit plus a thread pool commits records nobody processed yet
A transaction commits the output and the offsets togetherThe application sends converted records to payments-eur, which stay invisible to read_committed consumers. It adds its group's offsets to the transaction and writes offset 15 of the input partition as pending, then commits. The transaction coordinator writes commit markers to the output partition and to the offsets topic, and the output becomes visible.__consumer_offsetspayments-eurTransaction coordinatorAppread_committed consumers now see the recordsconverted records, not yet visibleadd the group's offsetspayments P0 at 15, pendingcommitTransactioncommit markercommit marker
A transaction commits the output and the offsets togetherThe application sends converted records to payments-eur, which stay invisible to read_committed consumers. It adds its group's offsets to the transaction and writes offset 15 of the input partition as pending, then commits. The transaction coordinator writes commit markers to the output partition and to the offsets topic, and the output becomes visible.__consumer_offsetspayments-eurTransaction coordinatorAppread_committed consumers now see the recordsconverted records, not yet visibleadd the group's offsetspayments P0 at 15, pendingcommitTransactioncommit markercommit marker
A transaction commits the output and the offsets together

Solve it

A currency converter double-counts payments after every restart

A service reads payments, converts each amount to euros and writes the result to payments-eur. A reporting job sums payments-eur. After each deploy the euro total is slightly higher than the source total. The service uses auto commit. Find why, and make the totals match.

  1. Find the window. Auto commit runs every 5 seconds inside poll. Records converted and sent after the last commit are converted again by the next owner after a restart, so payments-eur holds duplicates.
  2. Notice everything stays in Kafka. Input and output are both topics, so a Kafka transaction can cover the output records and the input offsets together: exactly-once processing.
  3. Turn transactions on. Set a transaction ID prefix, disable auto commit, and let the Spring listener container run each batch in a transaction. A crash aborts the open one; the retry commits once.
  4. Fix the readers too. Aborted records stay in the log. The reporting job must read with read_committed, or it still counts them. A side effect outside Kafka, such as an email, would need idempotency instead.
  5. Check. Kill the service in the middle of a batch in a test, restart it, and compare counts and sums of input and output: equal.
// spring.kafka.producer.transaction-id-prefix=converter-tx-
// spring.kafka.consumer.isolation-level=read_committed   (and in the reporting job)
@KafkaListener(topics = "payments", groupId = "converter")
void convert(Payment p) {
    kafka.send("payments-eur", p.id(), rates.toEur(p));   // part of the running transaction
}   // returns: commit output and consumed offsets; throws: abort both, record redelivered
The listener joins the container's transaction; output and offsets commit together

How to answer

  • At-least-once with idempotent processing is the usual choice.
  • The producer side needs acks=all and idempotence not to lose or duplicate on retries.
  • Exactly-once does not cover side effects outside Kafka, such as a database or an email.
  • Kafka Streams turns it on with processing.guarantee=exactly_once_v2.

Common mistakes

  • Claiming Kafka guarantees exactly-once to any external system out of the box.
  • Saying at-least-once is a bug to fix rather than a choice to design for with idempotency.

Follow-up questions

What is the difference between auto commit and manual commit, and which do you choose?

With enable.auto.commit=true, the client commits the offsets returned by the previous poll every 5 seconds, during poll. That is at-least-once only if you finish each batch before polling again; with asynchronous processing it commits work not done, and loses it on a crash. Manual commit, with commitSync, commitAsync or a Spring acknowledgment, commits exactly when the work is done. Spring Kafka disables auto commit and commits for you after each batch.

  • Auto commit also commits on close, and can repeat up to 5 seconds of work after a crash.
  • Commit the next offset to read, last processed plus one.
  • Committing per record is safe but slow; per batch is the usual middle.

See it in the infographic: A crash between processing and commit

How do Kafka transactions work?

A producer with a transactional.id registers with a transaction coordinator, a broker. Between beginTransaction and commitTransaction, its records to any partitions, plus the consumer offsets it adds with sendOffsetsToTransaction, form one unit. On commit or abort the coordinator writes markers into every partition involved. Consumers with isolation.level=read_committed only see committed records. A restarted producer with the same transactional.id fences the old one off.

  • Aborted records stay in the log; read_uncommitted consumers, the default, still see them.
  • read_committed consumers wait for open transactions, so long ones add latency.
  • The transactional.id must be stable per producer instance and unique across instances.

See it in the infographic: At most, at least and exactly once

A consumer processed offsets 10 to 14. Which offset does it commit, and why does it matter?

It commits 15: the committed offset is the position of the next record to read, not the last one processed. A restarted or new owner of the partition starts exactly there. Committing 14 by mistake makes record 14 run again after every restart; committing too far ahead skips records. With commitSync and no arguments, the consumer commits the positions returned by the last poll, which already follow this rule.

  • The position is per partition.
  • The offset map passed to commitSync must hold record.offset() + 1.
  • Committed offsets live in the internal topic __consumer_offsets.

See it in the infographic: A crash between processing and commit

What acknowledgment modes does a Spring Kafka listener container offer?

The container commits for you according to its AckMode. BATCH, the default, commits after all records of a poll are processed. RECORD commits after each record. TIME and COUNT commit after an interval or a number of records. MANUAL and MANUAL_IMMEDIATE let the listener call Acknowledgment.acknowledge; the first queues the commit until the batch ends, the second commits at once.

  • All of them commit after processing, so the result is at-least-once.
  • With a transaction manager, offsets commit with the transaction instead.
  • An error handler decides whether a failed record is retried, skipped or sent to a Dead Letter Topic.

See it in the infographic: At most, at least and exactly once

Does Kafka exactly-once cover a service that reads from Kafka and calls a payment API?

No. Kafka transactions cover records written to Kafka and offsets committed to Kafka, nothing else. If the payment API is called and the transaction then aborts, the call already happened, and the retry calls it again. For external effects, design for at-least-once: send an idempotency key the API recognizes, or record the processed event ID in your own database with the change, and skip repeats.

  • Exactly-once is a property of a read-process-write loop inside Kafka.
  • The outbox pattern covers the opposite direction, from a database to Kafka.
  • Idempotency keys make repeated external calls harmless.

See it in the infographic: At most, at least and exactly once

How do you get effectively-once processing when the output is a database?

Make the write idempotent: an upsert keyed by the event or entity ID, or a processed-events table with a unique key, written in the same database transaction as the change. You can also store the consumed offset in the database in that transaction, and seek to it on startup, so database and position never disagree.

Check yourself

1. A consumer commits right after each poll, then processes the records. It crashes halfway through a batch. What does that give?
Show answers
  • At most once: Correct. The offsets moved past records never processed, so they are skipped.
  • At least once: Incorrect. That needs the commit after processing.
  • Exactly once: Incorrect. That needs a transaction around output and offsets.
2. A consumer has processed offsets 10 to 14 of a partition. Which offset should it commit?
Show answers
  • 15: Correct. The committed offset is the next record to read.
  • 14: Incorrect. Then record 14 is processed again after a restart.
  • 10: Incorrect. Then the whole batch is processed again after a restart.
3. A transactional producer writes 3 records and then aborts the transaction. Which consumers can see the 3 records?
Show answers
  • Consumers with isolation.level=read_uncommitted, the default: Correct. Aborted records stay in the log, and only read_committed filters them out.
  • Only consumers with isolation.level=read_committed: Incorrect. Those are exactly the consumers that skip aborted records.
  • No consumer, because the records are deleted: Incorrect. Kafka never deletes from the middle of a log; it writes an abort marker.