In your consumer loop, where do you commit the offset, and what changes if you move it?
Sketch your own answer first, then compare it with the one below.
A strong answer
After the work, for most consumers. Read a batch, apply its effects, then commit the offset of the next message to read. A crash before the commit makes the next owner re-read the batch, so effects repeat but nothing is lost. That is at-least-once, and it pairs with idempotent effects.
Commit before the work and a crash loses the batch, which is at-most-once. That is acceptable for data like metrics, where a gap is cheaper than a repeat.
Auto-commit is the one to be careful with. The Java client commits on a timer (5 seconds by default) inside poll, so a batch can be committed while it is still being processed, or after it failed.
Batch size is the dial. Committing every message sends many commits, while committing every 500 repeats up to 500 messages after a crash. Pick by the cost of a repeat. Also commit one past the last message you finished, or that message replays on each restart.
Sources
- Apache Kafka project (2024). Apache Kafka documentation: consumer configs.
- Apache Kafka project (2024). Apache Kafka documentation: message delivery semantics.