Idempotency part 2: Kafka consumers, the idempotent producer and payment-gateway IPNs
Idempotency in messaging and payments: deduplicating Kafka consumers with a processed_message table, the idempotent producer (PID, sequence numbers, max.in.flight ≤ 5) and its limits, a state-machine IPN handler for a VNPay-style gateway, reconciliation, and a summary of what to store and for how long at each layer.
On this page
1. The problem
A Kafka consumer crashes after saving a notification but before committing the offset; after the rebalance, 8,000 customers get "transfer successful" twice. The same month, the payment gateway resends an IPN three times for one order, and the handler awards loyalty points three times.
2. Key idea
Every channel is at-least-once: Kafka redelivers after a crash before the offset commit or during a rebalance; the gateway resends IPNs until it gets the right reply code. So the receiver must deduplicate itself, with a key written in the same transaction as the business change.
| Duplicate source | Dedup key | Reply to the repeat |
|---|---|---|
| Kafka consumer | (consumer_group, message_id) or a business id |
skip, commit offset |
| Producer retry after a lost ack | PID + sequence (handled by the broker) | the broker acks without writing again |
| Gateway IPN | order status + the gateway's transaction id | "already confirmed" |
| An old message arriving after a newer one | version or event_time |
ignore the older one |
2.1 What does the idempotent producer stop?
The broker writes a batch but the ack is lost and the producer retries: without idempotence it's written twice. With enable.idempotence=true the broker remembers the last sequence per (PID, partition) and drops batches it has seen. It's on by default since Kafka 3.0 and needs acks=all and max.in.flight.requests.per.connection ≤ 5.
It does not stop: the application calling send() twice, an outbox republishing, a producer restart (new PID). Consumers still have to deduplicate.
| Approach | Use when | Don't use when |
|---|---|---|
A processed_message table |
the consumer writes to a DB | side effects outside the DB (email, APIs) |
| A "to-do" table + worker | side effects involving money, must not repeat | harmless repeats |
| Accept duplicates | an "order delivered" email twice is fine | refunds, loyalty points |
3. In Java
Dedup and business change in one DataSource transaction.
@KafkaListener(topics = "wallet-transactions", groupId = "notification")
@Transactional
public void onFundTransfer(FundTransferEvent event) {
int fresh = jdbc.update("""
INSERT INTO processed_message (consumer_group, message_id) VALUES ('notification', ?)
ON CONFLICT DO NOTHING""", event.messageId());
if (fresh == 0) return; // already done: skip, offset still commits
notificationRepository.save(Notification.from(event));
}
// Crash before the offset commit: the message comes back, the INSERT hits the primary key, skip.The primary key is (consumer_group, message_id). Keep rows longer than the topic retention plus the longest replay window, and delete in batches. Other languages: the same pattern in Go (sarama, franz-go) or Node.js (kafkajs): marker and business change in one DB transaction.
An idempotent IPN handler
Redirect-style gateways (VNPay and similar) report results two ways. The IPN calls your backend directly, is signed, and is the source of truth. The return URL goes through the browser, can be tampered with, and the tab may close: the frontend only uses it to ask the backend for the real status.
@GetMapping("/payment/ipn")
public IpnReply ipn(@RequestParam Map<String, String> params) {
if (!signature.verify(params)) return IpnReply.INVALID_CHECKSUM; // signature first
Order order = orders.findByTxnRef(params.get("txn_ref")).orElse(null);
if (order == null) return IpnReply.ORDER_NOT_FOUND;
if (order.amountMinor() != Long.parseLong(params.get("amount"))) return IpnReply.INVALID_AMOUNT;
if (order.isFinal()) return IpnReply.ALREADY_CONFIRMED; // a resend
boolean ok = "00".equals(params.get("response_code"));
int changed = ok ? orders.markPaid(order.id(), params.get("gateway_txn_no")) // WHERE status = 'PENDING_PAYMENT'
: orders.markFailed(order.id(), params.get("response_code"));
return changed == 1 ? IpnReply.CONFIRMED : IpnReply.ALREADY_CONFIRMED;
}- The conditional update arbitrates when two IPNs arrive at once; a unique gateway transaction id is the last line of defence.
- A resend must get "already confirmed", not an error, or the gateway keeps resending.
- If the IPN never arrives: a reconciliation job queries the gateway's API for orders
PENDING_PAYMENTlonger than N minutes; past the deadline they becomeEXPIRED.
4. Working with AI
Hand to AI: listeners, the dedup table, Testcontainers tests delivering the same message twice, tests sending IPNs again in parallel.
Check in AI-written code:
- Dedup sits in the same transaction as the business change, not check-then-insert across two transactions.
-
message_idis generated once and stored with the outbox row, or a business key is used. - The producer states
enable.idempotence=trueandacks=allexplicitly. - The IPN handler checks signature and amount before anything else; it only moves from
PENDING_PAYMENT. - IPN resends get the gateway's "already confirmed" code as specified.
5. Exercises
Exercise 1: Review a producer config
The AI configured a producer "for speed": acks=1, retries=10, max.in.flight.requests.per.connection=10, no enable.idempotence, messages without keys. Name the risks and fix it.
Solution to Exercise 1
acks=1andmax.in.flight=10silently disable idempotence; retries after a lost ack create duplicates. (Settingenable.idempotence=trueexplicitly withacks=1throws aConfigExceptionat startup, which is why you should state it.)- In-flight > 1 without idempotence means retries can reorder writes.
acks=1loses data if the leader dies before followers copy it.- No key means no per-account ordering.
Fix: enable.idempotence=true, acks=all, max.in.flight ≤ 5, key by account_id; consumers still deduplicate.
Exercise 2: Read a triple-points incident
Logs: the same txn_ref=ORD-88 has 3 IPN received lines 30 s apart, each followed by points +5000. The handler returned HTTP 200 with body {"status":"error","msg":"order already paid"} for the 2nd and 3rd. Diagnose and fix.
Solution to Exercise 2
- Diagnosis: the handler awards points before checking the status, and resends got an error code, so the gateway kept resending.
- Fix: check
order.isFinal()and do the conditional update first; award points in the same transaction asmarkPaid, only whenchanged == 1. Reply to resends with the gateway's "already confirmed" code. Add a unique(order_id)on the points table as the last line of defence.
Summary
- Every channel is at-least-once; the receiver deduplicates.
- Dedup in the same transaction as the business change, then commit the offset.
- The idempotent producer only stops the client's internal retries; state
enable.idempotence=true,acks=all. - The IPN is the source of truth; the return URL is display only.
- IPN resends get "already confirmed", never an error.
Read more: Part 1: Concepts, APIs and the database.
Practice interview questions on this topic
- How do you design an idempotent Kafka consumer, and how long should you keep the processed-message table?
- How do Kafka transactions and exactly-once work under the hood, and why must a consumer writing to a DB still be idempotent?
- Payment gateway integration: how does IPN differ from the return URL, and what must the IPN handler check?
All Messaging & Kafka questions →All Microservices questions →
Comments
Community rules