Scrivio Interview library
DebuggingIntermediate6 min read · updated 13 November 2026

A payment API supports Idempotency-Key, yet support sees about 30 double charges a day, all from the mobile app. The API gateway retries POSTs once on timeout, and the app's HTTP layer retries failed requests up to three times.

How do you find where the duplicates come from, and what do you fix on the client, the gateway and the server?

Group the duplicate charges by idempotency key: if each pair has two different keys, the client is generating a new key per attempt, most likely in an HTTP interceptor, and the fix is to create the key when the user confirms and reuse it across retries and restarts. Then check that the gateway forwards the header unchanged and only retries POSTs that carry a key, close the server-side race with an atomic insert under a unique constraint, make the key required on payment endpoints, and add metrics for reuse, conflicts and replays.

Why this question is asked

Duplicate charges are among the most damaging bugs a payment system can have: customers lose trust, support spends hours on refunds, and card networks notice. This scenario is common precisely because idempotency has three participants, the client, the gateway and the server, and each one can break it. Interviewers want to see a methodical investigation rather than a guess. In this answer, we will look at how to use the data we already have to locate the cause, then fix each layer in turn: the app's key handling, the gateway's retry policy and the server's race condition, and finish with the guard rails that stop this from coming back.

1Start From the Evidence: Group Duplicates by Key

We have about 30 double charges a day and all of them come from the mobile app. The first step is to pull the two charges of each duplicate pair together with the idempotency key each one was created with, and look at the pattern. There are only a few possibilities, and each one points to a different layer.

If the two charges carry different keys, the server did its job: it saw two different operations. The problem is on the client, which sent a new key on a retry. If the two charges carry the same key, the server let a duplicate through, and the bug is in its check. If one of the charges has no key at all, something removed the header on the way, possibly the gateway. A short SQL query over the payments table, joining charges by user, amount and a time window of a minute, answers this in an afternoon.

SQL
SELECT a.user_id, a.amount, a.idem_key AS key_1, b.idem_key AS key_2,
b.created_at - a.created_at AS gap
FROM payment a JOIN payment b
ON a.user_id = b.user_id AND a.amount = b.amount
AND b.created_at BETWEEN a.created_at AND a.created_at + interval '1 minute'
AND a.id < b.id
WHERE a.created_at > now() - interval '7 days';
-- 212 rows: 205 with key_1 <> key_2, gap 3 to 31 s; 7 with key_1 = key_2, gap under 50 ms
Reading the duplicate pattern
What the pair showsLikely causeLayer to fix
different keys, gaps of secondsnew key generated per HTTP attemptmobile app
one charge without a keyheader dropped or not forwarded on retrygateway
same key, gap of millisecondsread-then-write check racesserver

In a result like this one, the large group with different keys and gaps of several seconds matches the app's retry timing, and the small group with equal keys and tiny gaps points to a race on the server. We will fix both.

2Fixing the App: One Key per Payment, Not per Request

The usual culprit is a well-meaning HTTP interceptor that adds Idempotency-Key: <new UUID> to every outgoing POST. Each of the app's three retries then gets a fresh key, so the server sees four separate payments. The same thing happens if the key is created when the request object is built and the retry logic rebuilds the request.

The fix is to tie the key to the user's intent, not to the HTTP attempt. The key is generated once, when the user taps Confirm, and stored with the pending payment in local storage. Every retry, whether from the HTTP layer, from the user tapping again, or after the app was killed and restarted, sends the stored key. Only when the server returns a final answer is the pending payment and its key cleared.

Java
// Before: a fresh key on every attempt, so retries look like new payments
request.header("Idempotency-Key", UUID.randomUUID().toString());
// After: the key belongs to the pending payment and survives retries and restarts
PendingPayment p = store.findOrCreate(cartId, () -> new PendingPayment(UUID.randomUUID()));
request.header("Idempotency-Key", p.key().toString()); // same value on every retry

3Fixing the Gateway: Forward the Key and Retry Only With One

The gateway retries a POST once on timeout. That is dangerous by itself: a timeout does not mean the server did nothing; often it means the server is still working. A gateway retry is only safe if it carries the same idempotency key, so we check two things in its configuration and logs: that the header is forwarded unchanged on both the original call and the retry, and that no header normalisation or size limit strips it.

The policy should be explicit: the gateway retries POST requests only when they carry an idempotency key, and otherwise not at all. Many teams go further and disable gateway retries for payment routes entirely, leaving retries to the client, which knows the user's intent. Two layers of retries also multiply: one gateway retry times three app retries means up to eight attempts per payment, which adds load exactly when the server is already slow.

4Fixing the Server: Close the Race

The few pairs with the same key and a gap of a few milliseconds come from a race. The server probably checks for the key with a SELECT and inserts it after the payment succeeds. Two attempts arriving together, for example the gateway's retry and the app's retry, both find nothing and both charge the card.

The check must be atomic. The server inserts the key record in state IN_PROGRESS first, protected by a unique constraint on (client_id, key). Exactly one insert wins; the other fails with a unique violation, reads the record, and returns 409 Conflict with Retry-After or the stored response. The payment runs only for the winner, and the record is updated with the result in the same transaction as the payment row where possible.

Step throughTwo attempts with the same key, after the fix
App retryGateway retryPayment APIDatabase
POST /payments key K
INSERT key K IN_PROGRESS
ok
POST /payments key K
INSERT key K IN_PROGRESS
unique violation
409 Conflict, Retry-After: 2
charge + mark K COMPLETED
201 Created

9 messages in order. Play them, or step through them one at a time.

The unique constraint lets exactly one attempt run the charge.

5Guard Rails: Required Keys and Metrics

Payment endpoints should require the key: a request without Idempotency-Key gets 400 with a clear message. Optional keys mean some client will eventually forget them. We also add metrics that would have shown this problem weeks earlier: replays served (same key, completed), conflicts (same key, in progress), rejected reuses (same key, different body), and requests without a key per client version. A sudden drop in replays after an app release, for example, means the new version stopped reusing keys. Finally, we ship the app fix behind telemetry and watch the duplicate count fall towards zero.

6Follow-up questions

How do you handle users who already have duplicates?

Run the grouping query daily until the fix is fully rolled out, and automatically refund or void the second charge of each confirmed pair, with a support note. Since old app versions stay in use for months, the server-side race fix and the gateway change help immediately, while the app fix spreads as users update.

Can the server detect duplicates without a key?

Only heuristically, for example same user, amount and merchant within a minute, and that can block legitimate repeated purchases. It is useful as an alert, not as the mechanism; the key is the only reliable signal of intent.

7Conclusion

In this answer, we used the duplicate pairs themselves to locate the bug: different keys point to the client, missing keys to the gateway, and identical keys with tiny gaps to a server race. We fixed the app to create one key per confirmed payment and reuse it everywhere, made the gateway forward the key and retry only requests that carry one, closed the race with an atomic insert under a unique constraint, made the key mandatory, and added metrics that make key misuse visible.

What to say in the interviewAbout 90 seconds aloud

Open with

I would start from the data rather than guessing. For each duplicate pair, I would pull both charges and their idempotency keys. If the keys differ, the server behaved correctly and the client is sending a new key per attempt.

Then, if they want more

That is the classic bug: an HTTP interceptor that adds a fresh UUID to every POST, so the app's three retries look like four different payments. The fix is to create the key when the user confirms the payment, store it with the pending payment, and reuse it on every retry and even after an app restart. Next, the gateway.

Retrying a POST on timeout is only safe if the same key goes with it, so I would verify it forwards the header unchanged, and set the policy that it only retries POSTs with a key, or not at all on payment routes. Then the server.

If some pairs share the same key with a gap of milliseconds, the server is doing a read-then-write check, and two concurrent attempts both pass. I would make the claim atomic: insert the key as in progress under a unique constraint first, so only one attempt runs the charge and the other gets 409 or the stored response.

Finally I would make the key required on payment endpoints and add metrics for replays, conflicts and key reuse per app version, so we see a regression the day it ships.

About this answer

Last updated
13 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 official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
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 "How do you find where the duplicates come from, and what do you fix on the client, the...": https://scrivio-interview-library.netlify.app/architecture/api-design-at-scale/2ae6fb85fe/