Kafka offsets: where a consumer group resumes
A Kafka consumer group remembers one number per partition, the committed offset, and that number decides which records are lost or repeated after a crash. This page explains the offsets of a partition and runs commit timing, reset policies, seeking by time and resetting a group from outside.
Contents
What an offset is, and which offsets exist
Every record in a Kafka partition has an offset: a 64-bit number, its position in the partition's log. The first record written gets 0, the next 1, and so on. Offsets are never reused, and they belong to one partition: offset 5 in partition 0 and offset 5 in partition 1 are unrelated records.
Kafka keeps no per-message delivery state for consumer groups. Instead, a group remembers one number per partition, the committed offset: the offset of the next record the group should read. Commits are records in the internal, compacted topic __consumer_offsets
| Offset | Meaning | Read with |
|---|---|---|
| Log start offset | The oldest record still stored; it rises as retention deletes data | Admin.listOffsets(OffsetSpec.earliest())consumer.beginningOffsets |
| Committed offset | Where the group resumes after a restart or rebalance | consumer.committedAdmin.listConsumerGroupOffsets |
| Position | The next offset this consumer instance will return from poll() | consumer.position |
| Log end offset (high watermark) | The offset the next written record will get; consumers can read up to here | OffsetSpec.latest()consumer.endOffsets |
Consumer lag is the log end offset minus the committed offset: how many records the group still has to process. The examples use kafka-clientsEmbeddedKafkaKraftBrokerspring-kafka-test
The four offsets of one partition
A shipment-tracking consumer reads part of a topic, commits, and reads on, so that all four offsets differ. The first two records are deleted first, to move the log start offset:
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.kafka.clients.admin.Admin;
import org.apache.kafka.clients.admin.OffsetSpec;
import org.apache.kafka.clients.admin.RecordsToDelete;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.consumer.OffsetAndMetadata;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;
public class OffsetKinds {
static final TopicPartition P0 = new TopicPartition("shipments", 0);
public static void main(String[] args) throws Exception {
EmbeddedKafkaBroker broker = startBroker();
String servers = broker.getBrokersAsString();
try (Admin admin = Admin.create(Map.of("bootstrap.servers", servers))) {
broker.addTopics("shipments");
try (KafkaProducer<String, String> producer = new KafkaProducer<>(Map.of(
"bootstrap.servers", servers,
"key.serializer", StringSerializer.class,
"value.serializer", StringSerializer.class))) {
for (int i = 0; i < 10; i++) {
producer.send(new ProducerRecord<>("shipments", "parcel-" + i));
}
}
admin.deleteRecords(Map.of(P0, RecordsToDelete.beforeOffset(2))).all().get();
try (KafkaConsumer<String, String> consumer = new KafkaConsumer<>(Map.of(
"bootstrap.servers", servers,
"group.id", "tracking",
"enable.auto.commit", false,
"auto.offset.reset", "earliest",
"max.poll.records", 4,
"key.deserializer", StringDeserializer.class,
"value.deserializer", StringDeserializer.class))) {
consumer.subscribe(List.of("shipments"));
int read = 0;
long lastOffset = -1;
while (read < 4) {
for (ConsumerRecord<String, String> r : consumer.poll(Duration.ofSeconds(1))) {
read++;
lastOffset = r.offset();
}
}
System.out.println("read 4 records, the last at offset " + lastOffset);
consumer.commitSync(Map.of(P0, new OffsetAndMetadata(lastOffset + 1)));
consumer.poll(Duration.ofSeconds(1)); // reads ahead without committing
long start = admin.listOffsets(Map.of(P0, OffsetSpec.earliest())).all().get()
.get(P0).offset();
long end = admin.listOffsets(Map.of(P0, OffsetSpec.latest())).all().get()
.get(P0).offset();
OffsetAndMetadata committed = consumer.committed(Set.of(P0)).get(P0);
System.out.println("log start offset : " + start);
System.out.println("committed offset : " + committed.offset());
System.out.println("consumer position : " + consumer.position(P0));
System.out.println("log end offset : " + end);
System.out.println("lag (end - committed): " + (end - committed.offset()));
}
Map<TopicPartition, OffsetAndMetadata> stored = admin
.listConsumerGroupOffsets("tracking").partitionsToOffsetAndMetadata().get();
System.out.println("Admin sees for group tracking: " + stored.get(P0).offset());
} finally {
broker.destroy();
}
}
// Starts a single-node KRaft broker inside this JVM, from spring-kafka-test
static EmbeddedKafkaBroker startBroker() {
// the broker logs at INFO and prints its storage setup, so both are turned off.
// Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
.setLevel(Level.OFF);
PrintStream stdout = System.out;
System.setOut(new PrintStream(OutputStream.nullOutputStream()));
try {
// one broker cannot hold the default 3 copies of the transaction log
EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1).brokerProperties(
Map.of("transaction.state.log.replication.factor", "1",
"transaction.state.log.min.isr", "1"));
broker.afterPropertiesSet();
return broker;
} finally {
System.setOut(stdout);
}
}
}
read 4 records, the last at offset 5
log start offset : 2
committed offset : 6
consumer position : 10
log end offset : 10
lag (end - committed): 4
Admin sees for group tracking: 6
- After
, the log started at offset 2, so a new group withdeleteRecords began there. The fourth record it read was offset 5.earliest - The program committed 6, the offset after the last processed record. The committed offset always names the next record to read, never the last one read.
- The next
fetched the remaining records, so the position moved to 10 while the committed offset stayed at 6. If the consumer crashed now, the next one would start at 6 and see offsets 6 to 9 again.poll() - The log end offset was 10, and the lag was 10 - 6 = 4 records.
- The
client saw the same committed offset, 6. Monitoring tools compute lag this way, from outside the group.Admin
Commits are kept for offsets.retention.minutesauto.offset.reset
When to commit: lost records and duplicates
The moment of the commit decides what a crash costs. Three consumers process invoices, each committing at a different time, and each crashes while processing the fourth invoice. A new instance in the same group then takes over:
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.consumer.OffsetAndMetadata;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;
public class CommitTiming {
static String servers;
public static void main(String[] args) throws Exception {
EmbeddedKafkaBroker broker = startBroker();
servers = broker.getBrokersAsString();
try {
broker.addTopics("invoices");
try (KafkaProducer<String, String> producer = new KafkaProducer<>(Map.of(
"bootstrap.servers", servers,
"key.serializer", StringSerializer.class,
"value.serializer", StringSerializer.class))) {
for (int i = 0; i < 6; i++) {
producer.send(new ProducerRecord<>("invoices", "inv-" + i));
}
}
// each strategy crashes while processing inv-3, then a new instance starts
for (String strategy : List.of("commit-before", "commit-after", "commit-offset")) {
List<String> processed = new ArrayList<>();
try {
run(strategy, processed, true);
} catch (IllegalStateException crash) {
System.out.println(strategy + ": crashed at inv-3, processed " + processed);
}
List<String> again = new ArrayList<>();
run(strategy, again, false);
System.out.println(strategy + ": restart processed " + again);
}
} finally {
broker.destroy();
}
}
static void run(String strategy, List<String> processed, boolean crash) {
Map<String, Object> props = new HashMap<>();
props.put("bootstrap.servers", servers);
props.put("group.id", strategy);
props.put("enable.auto.commit", false);
props.put("auto.offset.reset", "earliest");
props.put("key.deserializer", StringDeserializer.class);
props.put("value.deserializer", StringDeserializer.class);
try (KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props)) {
consumer.subscribe(List.of("invoices"));
long quietSince = System.currentTimeMillis();
while (System.currentTimeMillis() - quietSince < 2000) {
var records = consumer.poll(Duration.ofMillis(200));
if (consumer.assignment().isEmpty() || !records.isEmpty()) {
quietSince = System.currentTimeMillis();
}
if (strategy.equals("commit-before") && !records.isEmpty()) {
consumer.commitSync(); // the position is already past the whole batch
}
for (ConsumerRecord<String, String> r : records) {
if (crash && r.value().equals("inv-3")) {
throw new IllegalStateException("crash"); // no further commits
}
processed.add(r.value());
TopicPartition tp = new TopicPartition(r.topic(), r.partition());
if (strategy.equals("commit-after")) {
consumer.commitSync(Map.of(tp, new OffsetAndMetadata(r.offset() + 1)));
} else if (strategy.equals("commit-offset")) {
// a classic mistake: the committed offset should be the NEXT record
consumer.commitSync(Map.of(tp, new OffsetAndMetadata(r.offset())));
}
}
}
}
}
// Starts a single-node KRaft broker inside this JVM, from spring-kafka-test
static EmbeddedKafkaBroker startBroker() {
// the broker logs at INFO and prints its storage setup, so both are turned off.
// Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
.setLevel(Level.OFF);
PrintStream stdout = System.out;
System.setOut(new PrintStream(OutputStream.nullOutputStream()));
try {
// one broker cannot hold the default 3 copies of the transaction log
EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1).brokerProperties(
Map.of("transaction.state.log.replication.factor", "1",
"transaction.state.log.min.isr", "1"));
broker.afterPropertiesSet();
return broker;
} finally {
System.setOut(stdout);
}
}
}
commit-before: crashed at inv-3, processed [inv-0, inv-1, inv-2]
commit-before: restart processed []
commit-after: crashed at inv-3, processed [inv-0, inv-1, inv-2]
commit-after: restart processed [inv-3, inv-4, inv-5]
commit-offset: crashed at inv-3, processed [inv-0, inv-1, inv-2]
commit-offset: restart processed [inv-2, inv-3, inv-4, inv-5]
- commit-before: committing right after
stored offset 6, the end of the batch, before any invoice was processed. After the crash, the restart processed nothing: inv-3, inv-4 and inv-5 were lost. This is at-most-once delivery.poll() - commit-after: committing
after each invoice stored 3 when inv-2 was done. The restart began at inv-3 and nothing was lost or repeated. With a crash after processing but before the commit, that one record would be processed twice: this is at-least-once delivery.offset + 1 - commit-offset: committing
instead ofr.offset() stored 2 after inv-2. The restart processed inv-2 a second time. This off-by-one mistake repeats one record per partition at every restart.r.offset() + 1
At-least-once is the usual choice, together with processing that tolerates a repeat, for example by writing with the record's key or offset as a unique id. Committing after every record, as here, is clear but slow, because each commitSyncpoll()
commitSynccommitAsynccommitAsynccommitSyncclose()
Where a new group starts: auto.offset.reset
A group with no committed offset, or with one that points to deleted data, starts according to auto.offset.reset
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.time.Duration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.consumer.OffsetAndTimestamp;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;
public class ResetAndSeek {
static final TopicPartition P0 = new TopicPartition("sensor", 0);
static final long HOUR = 3600000L;
static String servers;
public static void main(String[] args) throws Exception {
EmbeddedKafkaBroker broker = startBroker();
servers = broker.getBrokersAsString();
try {
broker.addTopics("sensor");
long now = System.currentTimeMillis();
try (KafkaProducer<String, String> producer = new KafkaProducer<>(Map.of(
"bootstrap.servers", servers,
"key.serializer", StringSerializer.class,
"value.serializer", StringSerializer.class))) {
for (int i = 0; i < 6; i++) { // one reading per hour, the last one now
int hoursAgo = 5 - i;
producer.send(new ProducerRecord<>("sensor", 0, now - hoursAgo * HOUR,
null, hoursAgo + "h ago"));
}
}
for (String reset : List.of("earliest", "latest", "by_duration:PT2H30M", "none")) {
try (KafkaConsumer<String, String> c = consumer("group-" + reset, reset)) {
c.subscribe(List.of("sensor"));
ConsumerRecords<String, String> records = ConsumerRecords.empty();
while (c.assignment().isEmpty()) {
records = c.poll(Duration.ofMillis(200));
}
if (records.isEmpty()) {
records = c.poll(Duration.ofSeconds(1));
}
String first = records.isEmpty()
? "no record yet, position " + c.position(P0)
: "first record at offset " + records.iterator().next().offset()
+ ": \"" + records.iterator().next().value() + "\"";
System.out.printf("%-20s -> %s%n", reset, first);
} catch (RuntimeException e) {
System.out.printf("%-20s -> %s%n", reset, e.getClass().getSimpleName());
}
}
// a seek by time: the first record at or after 3.5 hours ago
try (KafkaConsumer<String, String> c = consumer(null, "earliest")) {
c.assign(List.of(P0));
OffsetAndTimestamp found = c.offsetsForTimes(
Map.of(P0, now - 3 * HOUR - HOUR / 2)).get(P0);
c.seek(P0, found.offset());
String value = c.poll(Duration.ofSeconds(2)).iterator().next().value();
System.out.println("offsetsForTimes(3.5 h ago) -> offset " + found.offset()
+ ", value \"" + value + "\"");
OffsetAndTimestamp future = c.offsetsForTimes(Map.of(P0, now + HOUR)).get(P0);
System.out.println("offsetsForTimes(1 h from now) -> " + future);
}
} finally {
broker.destroy();
}
}
static KafkaConsumer<String, String> consumer(String group, String reset) {
Map<String, Object> props = new HashMap<>();
props.put("bootstrap.servers", servers);
if (group != null) {
props.put("group.id", group);
}
props.put("auto.offset.reset", reset);
props.put("key.deserializer", StringDeserializer.class);
props.put("value.deserializer", StringDeserializer.class);
return new KafkaConsumer<>(props);
}
// Starts a single-node KRaft broker inside this JVM, from spring-kafka-test
static EmbeddedKafkaBroker startBroker() {
// the broker logs at INFO and prints its storage setup, so both are turned off.
// Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
.setLevel(Level.OFF);
PrintStream stdout = System.out;
System.setOut(new PrintStream(OutputStream.nullOutputStream()));
try {
// one broker cannot hold the default 3 copies of the transaction log
EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1).brokerProperties(
Map.of("transaction.state.log.replication.factor", "1",
"transaction.state.log.min.isr", "1"));
broker.afterPropertiesSet();
return broker;
} finally {
System.setOut(stdout);
}
}
}
earliest -> first record at offset 0: "5h ago"
latest -> no record yet, position 6
by_duration:PT2H30M -> first record at offset 3: "2h ago"
none -> NoOffsetForPartitionException
offsetsForTimes(3.5 h ago) -> offset 2, value "3h ago"
offsetsForTimes(1 h from now) -> null
started at offset 0, the oldest reading.earliest , the default, started at position 6, the end of the log, and saw nothing: only records written after the group started would arrive.latest , added by KIP-1106 and supported by the 4.2 client used here, started at the first record no older than two and a half hours: offset 3, the reading from 2 hours ago.by_duration:PT2H30M madenone throwpoll() . This suits applications that must never guess where to start.NoOffsetForPartitionException found offset 2 as the first record at or after 3.5 hours ago, and aoffsetsForTimes to it returned the reading from 3 hours ago. For a time later than the newest record, it returnedseek .null
The reset also applies when a committed offset is out of range, for example after retention deleted the records it pointed to. With latestearliestlatest
Changing a group's offsets from outside
After a bug fix, a team often wants to reprocess some data, which means moving the group's committed offset back. The Adminkafka-consumer-groups.sh --reset-offsets
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import org.apache.kafka.clients.admin.Admin;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.consumer.OffsetAndMetadata;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;
public class AdminOffsets {
static final TopicPartition P0 = new TopicPartition("reports", 0);
static String servers;
public static void main(String[] args) throws Exception {
EmbeddedKafkaBroker broker = startBroker();
servers = broker.getBrokersAsString();
try (Admin admin = Admin.create(Map.of("bootstrap.servers", servers))) {
broker.addTopics("reports");
try (KafkaProducer<String, String> producer = new KafkaProducer<>(Map.of(
"bootstrap.servers", servers,
"key.serializer", StringSerializer.class,
"value.serializer", StringSerializer.class))) {
for (int i = 0; i < 6; i++) {
producer.send(new ProducerRecord<>("reports", "report-" + i));
}
}
System.out.println("first run read : " + readAll());
System.out.println("group offset : " + groupOffset(admin));
// rewind the group, e.g. after fixing a bug in the report code
admin.alterConsumerGroupOffsets("billing",
Map.of(P0, new OffsetAndMetadata(3))).all().get();
System.out.println("after reset : " + groupOffset(admin));
System.out.println("next run read : " + readAll());
// the same change while a member of the group is running
try (KafkaConsumer<String, String> active = consumer()) {
active.subscribe(List.of("reports"));
while (active.assignment().isEmpty()) {
active.poll(Duration.ofMillis(200));
}
try {
admin.alterConsumerGroupOffsets("billing",
Map.of(P0, new OffsetAndMetadata(0))).all().get();
} catch (ExecutionException e) {
System.out.println("reset while active: "
+ e.getCause().getClass().getSimpleName());
}
}
admin.deleteConsumerGroupOffsets("billing", Set.of(P0)).all().get();
System.out.println("after delete : " + groupOffset(admin));
} finally {
broker.destroy();
}
}
static Object groupOffset(Admin admin) throws Exception {
OffsetAndMetadata o = admin.listConsumerGroupOffsets("billing")
.partitionsToOffsetAndMetadata().get().get(P0);
return o == null ? "none" : o.offset();
}
static KafkaConsumer<String, String> consumer() {
return new KafkaConsumer<>(Map.of(
"bootstrap.servers", servers,
"group.id", "billing",
"auto.offset.reset", "earliest",
"key.deserializer", StringDeserializer.class,
"value.deserializer", StringDeserializer.class));
}
// reads until 2 quiet seconds have passed; close() commits the position
static List<String> readAll() {
List<String> seen = new ArrayList<>();
try (KafkaConsumer<String, String> consumer = consumer()) {
consumer.subscribe(List.of("reports"));
long quietSince = System.currentTimeMillis();
while (System.currentTimeMillis() - quietSince < 2000) {
for (ConsumerRecord<String, String> r : consumer.poll(Duration.ofMillis(200))) {
seen.add(r.value());
quietSince = System.currentTimeMillis();
}
if (consumer.assignment().isEmpty()) {
quietSince = System.currentTimeMillis();
}
}
}
return seen;
}
// Starts a single-node KRaft broker inside this JVM, from spring-kafka-test
static EmbeddedKafkaBroker startBroker() {
// the broker logs at INFO and prints its storage setup, so both are turned off.
// Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
.setLevel(Level.OFF);
PrintStream stdout = System.out;
System.setOut(new PrintStream(OutputStream.nullOutputStream()));
try {
// one broker cannot hold the default 3 copies of the transaction log
EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1).brokerProperties(
Map.of("transaction.state.log.replication.factor", "1",
"transaction.state.log.min.isr", "1"));
broker.afterPropertiesSet();
return broker;
} finally {
System.setOut(stdout);
}
}
}
first run read : [report-0, report-1, report-2, report-3, report-4, report-5]
group offset : 6
after reset : 3
next run read : [report-3, report-4, report-5]
reset while active: UnknownMemberIdException
after delete : none
- The first run read all six reports, and closing the consumer committed offset 6.
set it to 3 while no consumer was running. The next run started at report-3, as intended.alterConsumerGroupOffsets- The same call while a member was active failed with
. The broker refuses outside changes to the offsets of a group with active members, because the members would overwrite them with their next commit. Stop all consumers of the group first.UnknownMemberIdException removed the committed offset completely; the next start would followdeleteConsumerGroupOffsets .auto.offset.reset
The command-line tool adds conveniences on top, such as --to-datetime--shift-by--dry-run
Storing offsets with the results
When a consumer writes its results to a database, there is a stronger option than committing to Kafka: store the offset in the same database transaction as the result, and tell the consumer where to start. A ledger adds deposits to a balance, stops after two of four as if it had crashed, and is started again:
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.Duration;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.apache.kafka.clients.consumer.ConsumerRebalanceListener;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;
public class OffsetsInDatabase {
static String servers;
public static void main(String[] args) throws Exception {
EmbeddedKafkaBroker broker = startBroker();
servers = broker.getBrokersAsString();
try (Connection db = DriverManager.getConnection("jdbc:h2:mem:bank")) {
try (Statement s = db.createStatement()) {
s.execute("create table balance (account varchar primary key, cents int)");
s.execute("insert into balance values ('acct-1', 0)");
s.execute("create table kafka_offset (topic varchar, part int, next bigint,"
+ " primary key (topic, part))");
}
db.setAutoCommit(false);
broker.addTopics("deposits");
try (KafkaProducer<String, String> producer = new KafkaProducer<>(Map.of(
"bootstrap.servers", servers,
"key.serializer", StringSerializer.class,
"value.serializer", StringSerializer.class))) {
for (int cents : new int[] {100, 250, 50, 600}) {
producer.send(new ProducerRecord<>("deposits", "acct-1", "" + cents));
}
}
run(db, 2); // processes two deposits, then "crashes"
System.out.println("after the crash: " + state(db));
run(db, Integer.MAX_VALUE);
System.out.println("after a restart: " + state(db));
} finally {
broker.destroy();
}
}
// reads deposits; each one updates the balance AND the offset in one DB transaction
static void run(Connection db, int limit) throws Exception {
try (KafkaConsumer<String, String> consumer = new KafkaConsumer<>(Map.of(
"bootstrap.servers", servers,
"group.id", "ledger",
"enable.auto.commit", false, // Kafka never stores this group's offsets
"key.deserializer", StringDeserializer.class,
"value.deserializer", StringDeserializer.class))) {
consumer.subscribe(List.of("deposits"), new ConsumerRebalanceListener() {
@Override
public void onPartitionsAssigned(Collection<TopicPartition> partitions) {
for (TopicPartition tp : partitions) {
long next = storedOffset(db, tp);
System.out.println("assigned " + tp + ", seeking to stored offset "
+ next);
consumer.seek(tp, next);
}
}
@Override
public void onPartitionsRevoked(Collection<TopicPartition> partitions) {
}
});
int processed = 0;
while (true) {
for (ConsumerRecord<String, String> r : consumer.poll(Duration.ofSeconds(1))) {
if (processed == limit) {
return; // stop without any commit to Kafka
}
try (PreparedStatement add = db.prepareStatement(
"update balance set cents = cents + ? where account = ?");
PreparedStatement offset = db.prepareStatement(
"merge into kafka_offset key (topic, part) values (?, ?, ?)")) {
add.setInt(1, Integer.parseInt(r.value()));
add.setString(2, r.key());
add.executeUpdate();
offset.setString(1, r.topic());
offset.setInt(2, r.partition());
offset.setLong(3, r.offset() + 1);
offset.executeUpdate();
db.commit(); // both changes, or neither
}
processed++;
}
if (!consumer.assignment().isEmpty() && remaining(consumer) == 0) {
return;
}
}
}
}
static int remaining(KafkaConsumer<String, String> consumer) {
TopicPartition tp = new TopicPartition("deposits", 0);
return (int) (consumer.endOffsets(List.of(tp)).get(tp) - consumer.position(tp));
}
static long storedOffset(Connection db, TopicPartition tp) {
try (PreparedStatement q = db.prepareStatement(
"select next from kafka_offset where topic = ? and part = ?")) {
q.setString(1, tp.topic());
q.setInt(2, tp.partition());
try (ResultSet rs = q.executeQuery()) {
return rs.next() ? rs.getLong(1) : 0;
}
} catch (SQLException e) {
throw new IllegalStateException(e);
}
}
static String state(Connection db) throws SQLException {
try (Statement s = db.createStatement();
ResultSet rs = s.executeQuery(
"select b.cents, o.next from balance b, kafka_offset o")) {
rs.next();
return "balance " + rs.getInt(1) + " cents, stored next offset " + rs.getLong(2);
}
}
// Starts a single-node KRaft broker inside this JVM, from spring-kafka-test
static EmbeddedKafkaBroker startBroker() {
// the broker logs at INFO and prints its storage setup, so both are turned off.
// Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
.setLevel(Level.OFF);
PrintStream stdout = System.out;
System.setOut(new PrintStream(OutputStream.nullOutputStream()));
try {
// one broker cannot hold the default 3 copies of the transaction log
EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1).brokerProperties(
Map.of("transaction.state.log.replication.factor", "1",
"transaction.state.log.min.isr", "1"));
broker.afterPropertiesSet();
return broker;
} finally {
System.setOut(stdout);
}
}
}
assigned deposits-0, seeking to stored offset 0
after the crash: balance 350 cents, stored next offset 2
assigned deposits-0, seeking to stored offset 2
after a restart: balance 1000 cents, stored next offset 4
- Each deposit updated the balance and the stored offset in one H2 transaction, so the two can never disagree. After the crash the balance was 350 cents (100 + 250) and the stored next offset was 2.
- The group never committed anything to Kafka (
and no commit calls). On assignment, theenable.auto.commit=false read the offset from the database and calledConsumerRebalanceListener .seek - The restart began at offset 2 and added 50 and 600, for a final balance of 1000 cents: every deposit counted exactly once, even though the consumer stopped in the middle.
This is exactly-once processing into a database without Kafka transactions. It needs a store with transactions, and the seek must happen in onPartitionsAssigned
Choosing a commit strategy
| Requirement | Approach |
|---|---|
| Simple consumers, duplicates acceptable | Auto-commit (the default), processing finished before the next poll() |
| No lost records | enable.auto.commit=falseoffset + 1 |
| No lost records, high throughput | Commit once per batch, commitAsynccommitSync |
| Results written to Kafka exactly once | Transactions with sendOffsetsToTransaction |
| Results written to a database exactly once | Store the offset in the same database transaction, and seek |
| A new group must process history | auto.offset.reset=earliestby_duration |
| Reprocess after a bug fix | Stop the group, reset with Adminkafka-consumer-groups.sh |
Related pages: