Video in progress
How do you write a consumer so that the result isn't corrupted if a message arrives twice?
Make the consumer idempotent: store each event's unique ID and recognize a repeat, or make the operation naturally repeatable (upsert, "set the state"). At-least-once is the norm in Kafka, so a duplicate is an expected case.
📖 Answer
The most reliable way is to write the processing and the "processed" mark in a single DB transaction:
@KafkaListener(topics = "payments", groupId = "ledger")
@Transactional
public void onPayment(PaymentEvent e) {
int inserted = jdbc.update("""
insert into processed_events(event_id, processed_at)
values (?, now()) on conflict (event_id) do nothing
""", e.eventId());
if (inserted == 0) {
log.info("Dublikat o'tkazib yuborildi: {}", e.eventId());
return;
}
ledger.credit(e.accountId(), e.amount());
}
event_id is generated on the producer side and travels inside the message. Don't use the Kafka offset as the ID: if the message is resent, the offset will be different.
Alternative approaches:
- make the operation itself idempotent: instead of
balance = balance + 100, usestatus = 'PAID' where status = 'PENDING'; - with a version number:
update ... where version < :incomingVersion.
So that the processed_events table doesn't grow forever, clean out old rows from time to time. Keeping them longer than the Kafka retention is enough.
Sign up to mark studied questions and save your progress.