Video in progress
When should you store consumer offsets in your own DB together with the result instead of in Kafka, and how do you do it?
Where the result is written to a DB and a duplicate is expensive, storing the offset in the same DB transaction makes processing and "where have I read up to" atomic. When a partition is assigned, the consumer reads the offset from the DB and starts from there with seek(); the commit to Kafka remains only for monitoring.
📖 Answer
In plain at-least-once the sequence is: write to the DB → commit to Kafka. If it crashes in between, you get a duplicate. A dedup table keyed by event ID solves this, but it needs an extra row per event. Storing the offset in the DB is a different way: dedup at the partition level, with a single number.
CREATE TABLE kafka_offsets (
group_id text, topic text, partition int, next_offset bigint,
PRIMARY KEY (group_id, topic, partition));
Processing:
@Transactional
public void handle(ConsumerRecord<String, Payment> rec) {
ledger.apply(rec.value());
offsets.upsert("ledger", rec.topic(), rec.partition(), rec.offset() + 1);
}
Jumping to that position when a partition is assigned, in Spring through ConsumerSeekAware:
@Override
public void onPartitionsAssigned(Map<TopicPartition, Long> assignments, ConsumerSeekCallback cb) {
assignments.keySet().forEach(tp ->
offsets.find("ledger", tp).ifPresent(o -> cb.seek(tp.topic(), tp.partition(), o)));
}
Now after a crash the consumer continues exactly from the position confirmed in the DB: no loss, no duplicates, but only for effects written to that DB. An external API or an email isn't covered by this guarantee.
When it isn't worth it: if the result goes to several systems, or the consumer is safe anyway thanks to idempotent writes (upsert, versions). Also, kafka-consumer-groups --reset-offsets no longer works: you have to change the offsets in the DB, so write that into the runbook. I still keep committing to Kafka too, otherwise the lag dashboards show the wrong numbers.
Sign up to mark studied questions and save your progress.