Quick revision
The short answer
We let the database reject the duplicate: a unique constraint on the payment reference or the message id means a second insert of the same payment cannot create a second row. We insert with ON CONFLICT DO NOTHING in PostgreSQL (or catch DuplicateKeyException), record the processed message id in the same transaction as the payment, and commit the Kafka offset only after the database commit, so a redelivered message simply finds the row already there.
What to remember
In this answer, we made a Kafka payment consumer idempotent by moving the duplicate check into the database. A unique constraint on the payment reference or message id rejects the second row, ON CONFLICT DO NOTHING or a caught DuplicateKeyException lets the consumer skip it, a processed-messages table covers events without a natural key, and committing the Kafka offset only after the database commit makes every redelivery harmless.
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.
We let the database reject the duplicate: a unique constraint on the payment reference or the message id means a second insert of the same payment cannot create a second row. We insert with ON CONFLICT DO NOTHING in PostgreSQL (or catch DuplicateKeyException), record the processed message id in the same transaction as the payment, and commit the Kafka offset only after the database commit, so a redelivered message simply finds the row already there.
Why this question is asked
Kafka consumers get at-least-once delivery by default: if the consumer crashes after writing to the database but before committing its offset, the message comes again after the restart or the rebalance. For most data that is a nuisance; for payments it means charging or recording money twice. Interviewers ask this coding question because the right answer is short but every piece matters: where the uniqueness lives, how the insert behaves on a duplicate, and in what order the two commits happen. In this answer, we will see why duplicates arrive, write the broken consumer, make it idempotent with a unique constraint and ON CONFLICT, add a processed-messages table, and get the commit order right.
1Why the Same Message Arrives Twice
A Kafka consumer reads a message, processes it, and then commits its offset, which is a bookmark that tells Kafka this partition has been handled up to here. If the consumer dies between processing and committing, the bookmark still points before the message, so the next consumer of that partition reads it again. Rebalances, timeouts and deploys all create the same gap.
There is no ordering of the two steps that removes the gap entirely. If we commit the offset first and then crash before writing, we lose the payment, which is worse. So we accept that a message may be processed twice and make the second processing harmless. An operation is idempotent when doing it twice has the same effect as doing it once.
2The Broken Consumer
Here is the naive version. It works perfectly until the first redelivery.
Nothing in this code or in the table knows that the two messages describe the same payment. The database will happily store both rows, because from its point of view they are two different inserts.
3Let a Unique Constraint Decide
The fix starts in the schema. Every payment event carries something that identifies the payment itself: a payment reference created by the sender, or at least a message id. We put a unique constraint on it, so the database guarantees there can only be one row per payment, whatever our code does and however many consumers run in parallel.
Notice that we check the row count. ON CONFLICT DO NOTHING returns 0 when the row already existed, so follow-up work such as crediting the ledger runs only once. A business key such as the payment reference is better than the Kafka message id, because it also catches duplicates that the producer itself sent twice with different message ids.
On MySQL, or with JPA, we can instead insert and catch DuplicateKeyException (Spring's translation of a unique key violation; through JPA it may surface as DataIntegrityViolationException). But there is a catch on PostgreSQL: a failed statement aborts the whole transaction, so after catching the exception we cannot run further SQL in it. That is why ON CONFLICT is the cleaner choice there.
4Recording Processed Message Ids
Sometimes the event does not map to a single insert. It may update a balance, write several rows or call another table, and there is no natural unique key to lean on. Then we keep a separate table of processed message ids and insert into it first, in the same transaction as the business work.
Because the marker row and the business writes commit together, they cannot drift apart: either both exist or neither does. If we recorded the id in a different transaction, or in Redis, a crash between the two could leave a payment without a marker, or a marker without a payment.
5Commit the Offset After the Database
The last piece is the order of the two commits. With Spring Kafka's default settings, the listener container commits offsets itself after the listener method returns, and the listener's @Transactional commits the database transaction before the method returns. So the database commit happens first and the offset commit second, which is exactly what we want.
7 messages in order. Play them, or step through them one at a time.
The unique constraint turns the second delivery into a no-op.
If the consumer crashes between the two commits, the message is redelivered, the insert finds the existing row, and nothing changes. The redelivery has become harmless. What we must avoid is committing the offset before the database work, for example with auto-commit on a timer (enable.auto.commit=true) or an acknowledgement sent at the start of the method, because a crash then loses the payment entirely.
6Follow-up questions
Why not just check whether the payment exists before inserting?
Because two consumers, or a retry racing with the original, can both check, both see nothing and both insert. A check in the application is not atomic with the insert. The unique constraint is enforced by the database at the moment of the insert, so it holds even under concurrency.
How long should processed message ids be kept?
Longer than the longest possible redelivery window, which in practice is the topic's retention period plus a margin for replays. A scheduled job can delete markers older than that. If the business key is unique forever, as a payment reference should be, the payment row itself is the marker and nothing needs cleaning up.
Do Kafka transactions make this unnecessary?
No. Kafka's exactly-once support covers reading from and writing to Kafka topics inside one Kafka transaction. A write to PostgreSQL is outside that boundary, so it can still happen twice. The database write needs its own idempotency.
7Conclusion
In this answer, we made a Kafka payment consumer idempotent by moving the duplicate check into the database. A unique constraint on the payment reference or message id rejects the second row, ON CONFLICT DO NOTHING or a caught DuplicateKeyException lets the consumer skip it, a processed-messages table covers events without a natural key, and committing the Kafka offset only after the database commit makes every redelivery harmless.
Open with
Kafka gives me at-least-once delivery, so I assume the same payment message can arrive twice, for example after a crash between the database write and the offset commit.
Then, if they want more
I make the write idempotent in the database rather than in application logic. First, I add a unique constraint on a business key, ideally the payment reference, or on the message id if there is no better key. Then the consumer inserts with INSERT ...
ON CONFLICT (reference) DO NOTHING in PostgreSQL and checks the row count: one means a new payment, so it continues with the follow-up work, and zero means a duplicate, so it logs and returns. On MySQL or with JPA I can catch DuplicateKeyException instead, but on PostgreSQL a failed insert aborts the transaction, so ON CONFLICT is cleaner.
If the event touches several tables without a natural key, I insert the message id into a processed_message table first, in the same transaction as the business writes, so both commit or neither does.
Finally, I make sure the offset is committed after the database commit, which is the default with Spring Kafka's container-managed acknowledgements and a transactional listener, and I never use auto-commit on a timer. Then a redelivery finds the row already there and does nothing.
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
- Spring Data JPA reference, Hibernate ORM documentation, Spring Framework reference, Transaction management
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 "A Kafka consumer inserts payments and may receive the same message twice. Make the write...": https://scrivio-interview-library.netlify.app/databases/locking-and-concurrency-control/e349226c0a/