Video in progress

Strong Junior 📨 Kafka and messaging

What's the difference between `commitSync()` and `commitAsync()`, and when do you use each?

commitSync() waits for the broker's response and retries on its own after a transient error, but it blocks the thread. commitAsync() doesn't wait and doesn't retry. The usual pattern: commitAsync() in the loop, commitSync() on shutdown and on rebalance.

📖 Answer

Until commitSync() returns, the consumer thread does nothing. If you call it after every poll, throughput drops noticeably. What you get in return is certainty that the commit was actually written.

commitAsync() sends the request and returns right away. It deliberately doesn't retry: otherwise an old commit (offset 100) could arrive late and overwrite a newer commit (offset 200). You see the failure in the callback:

try {
    while (running) {
        var records = consumer.poll(Duration.ofMillis(500));
        process(records);
        consumer.commitAsync((offsets, ex) -> {
            if (ex != null) log.warn("Commit o'tmadi: {}", offsets, ex);
        });
    }
} finally {
    try {
        consumer.commitSync();   // make sure the final state is written
    } finally {
        consumer.close();
    }
}

If one async commit fails, the next one writes a newer offset anyway, so in a loop this is safe. On shutdown there is no "next one", so you need commitSync() there.

In Spring Kafka you don't write this by hand: the container commits for you. It's synchronous by default, and you can switch to async with ContainerProperties.setSyncCommits(false), but you rarely need to.