Quick revision
The short answer
Each PaymentReceived event carries a unique event id from the producer. In one database transaction, the consumer inserts that id into a processed_events table with a unique constraint and applies the balance change; if the id is already there, the event was applied before and is skipped. The Kafka offset is committed only after the database commit, so a crash causes redelivery, which the table then deduplicates, and old ids are cleaned up after a retention period longer than any possible redelivery.
What to remember
In this answer, we built an idempotent consumer that applies PaymentReceived exactly once to an account balance. The producer gives each event a stable unique id; the consumer records it in processed_events with a unique key in the same transaction as the balance update and skips the event when the id already exists; and the offset is committed only after the database commit, so a crash leads to a redelivery that is deduplicated. A scheduled cleanup removes ids older than any possible redelivery window.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
Each PaymentReceived event carries a unique event id from the producer. In one database transaction, the consumer inserts that id into a processed_events table with a unique constraint and applies the balance change; if the id is already there, the event was applied before and is skipped. The Kafka offset is committed only after the database commit, so a crash causes redelivery, which the table then deduplicates, and old ids are cleaned up after a retention period longer than any possible redelivery.
Why this question is asked
Kafka consumers normally get at-least-once delivery: every event arrives, but some arrive twice, after a rebalance, a crash or a retry. For a notification that might mean a duplicate email. For an account balance it means money appears twice. Interviewers ask this coding question to see whether we know that 'exactly once' for a side effect in a database is something we build in the consumer, and whether we get the order of commits right. In this answer, we will see where duplicates come from, design the table, write the listener, walk through a crash, and finish with cleanup.
1Where Duplicates Come From
A Kafka consumer reads a record, processes it, and then commits its offset, the position in the partition that says 'everything before this is done'. If the consumer crashes after processing but before the offset commit, or if a rebalance moves the partition to another instance at that moment, the record is delivered again. The producer can also send the same event twice when it retries after a lost acknowledgement, unless producer idempotence covers it, and an outbox relay may publish a row twice.
Kafka transactions give exactly-once processing only when the consumer's output is another Kafka topic. Our side effect is a row in PostgreSQL, which is outside Kafka's transaction, so we need the database to recognise duplicates itself. The trick is to give it something it can recognise: a unique id per event.
2The Event and the Table
The producer assigns an id when it creates the event, for example a UUID stored with the payment in its outbox row. It must be the same id on every resend; a new id generated on retry would defeat the whole design.
Notice that the primary key is the event id. Two transactions trying to insert the same id cannot both succeed, even if they run at the same moment on two consumer instances; the database serialises them on the key.
3Writing the Listener
The listener runs one database transaction. It first tries to record the event id, and only if that succeeds does it change the balance. With PostgreSQL we use INSERT ... ON CONFLICT DO NOTHING and look at the row count, rather than letting the insert throw, because a failed statement in PostgreSQL aborts the whole transaction and we could not continue in it.
Notice that the dedup insert and the balance update are in the same transaction. If the update fails, the id is rolled back too, so a retry can apply the event later. If we recorded the id in a separate transaction, a crash between the two could mark an event as processed without ever applying it.
If we use a database without ON CONFLICT, we can let the insert fail and catch Spring's DuplicateKeyException, but then we must make sure the transaction is not left unusable; doing the check with a dedicated insert-or-ignore statement is simpler. Check your database's behaviour.
4Committing the Offset After the Database
The second half of the design is the order of commits. The Spring Boot defaults help here: Spring Kafka's listener container disables Kafka's auto-commit and commits offsets itself after the listener returns (the default ack mode is BATCH, committing after the records from one poll are processed; RECORD commits after each). Because @Transactional commits when the method returns, the database commit always happens before the offset commit.
7 messages in order. Play them, or step through them one at a time.
The balance changed once although the event was processed twice.
So the possible failures are all safe. A crash before the database commit leaves nothing changed and the record is redelivered and applied once. A crash after the database commit but before the offset commit causes a redelivery that the processed_events table recognises and skips. The one order we must never use is committing the offset first, because a crash after that would lose the payment.
5Cleaning Up Old Ids
The table grows by one row per event, forever, unless we clean it. Duplicates only arrive within a bounded window: the time a record can sit unacknowledged plus any replay we might do. Kafka's own retention is the outer limit, because a record older than the topic retention cannot be redelivered. So we keep ids for longer than that, say the topic retention of seven days plus a safety margin, and delete older rows in a scheduled job.
If we ever plan to replay a topic from the start, for example to rebuild something, we must remember that ids older than thirty days are gone, and the replay must go to a fresh consumer or a target that is safe to rebuild. For very large tables, partitioning processed_events by day and dropping old partitions is cheaper than DELETE.
6Follow-up questions
Why not rely on Kafka's exactly-once semantics?
Kafka's exactly-once covers reading from Kafka and writing to Kafka in one Kafka transaction. Our side effect is in PostgreSQL, which Kafka cannot include in its transaction, so a crash can still lead to the database change being applied and the offset not committed. Deduplication in the database is what makes the side effect happen once.
Could we store the Kafka offset in the database instead of an event id?
Yes, storing the last processed offset per partition in the same transaction is another correct approach, and on restart the consumer seeks to it. It deduplicates redeliveries but not a producer that published the same event twice at different offsets, which the event id handles. Many teams use the event id because it covers both.
What if the event has no id?
We ask the producer to add one, because a stable id is the foundation of deduplication. As a stopgap, a hash of the fields that identify the business fact, such as the payment reference, can serve, provided two genuinely different events can never produce the same hash.
7Conclusion
In this answer, we built an idempotent consumer that applies PaymentReceived exactly once to an account balance. The producer gives each event a stable unique id; the consumer records it in processed_events with a unique key in the same transaction as the balance update and skips the event when the id already exists; and the offset is committed only after the database commit, so a crash leads to a redelivery that is deduplicated. A scheduled cleanup removes ids older than any possible redelivery window.
Open with
I would rely on a unique event id that the producer sets once and keeps on every resend. On the consumer side I create a processed_events table with the event id as primary key.
Then, if they want more
In the Kafka listener, inside one database transaction, I first run an insert of the event id with ON CONFLICT DO NOTHING. If it inserted zero rows, the event was already applied, so I log it and return. If it inserted one row, I apply the balance change in the same transaction.
Because both writes commit or roll back together, an event can never be marked processed without being applied. Then the order of commits matters: Spring Kafka commits the offset after the listener returns, and the transaction commits when the method returns, so the database commit happens first.
If the consumer crashes after the database commit and before the offset commit, Kafka redelivers the record, and the dedup insert skips it. I would never commit the offset before the database, because that could lose a payment.
Finally I would clean up processed ids older than the topic retention plus a margin, for example thirty days, with a scheduled job or daily partitions.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- Apache Kafka documentation, Spring for Apache Kafka reference
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Write the core of an idempotent Kafka consumer in Spring that applies a PaymentReceived...": https://scrivio-interview-library.netlify.app/spring-boot/event-driven-patterns/e019e825d8/