Transactions and locking · Scenario
Customer charged twice
Practise this out loud
Say your answer out loud to an AI interviewer that follows up, and get a score for it.
Practise by voiceThe interviewer asks
A customer was charged twice for one order. The logs show our pay API was called twice, 3 seconds apart, after their app showed a timeout. What do you do, and how do you make sure it can't happen again?
Then
Follow-ups the interviewer asks next
- What do you check first?
- What do you do for this customer, and for others, right now?
- Why did the retry create a second charge?
- You add "check if a payment exists, then insert". It still happens under load. Why?
- Design the idempotency key: who makes it, where is it stored, how long is it kept?
- The gateway times out and you don't know whether the charge happened. What does your system do?
- How do you catch double charges automatically?
- What do you tell support and the customer?
- Have you built idempotent APIs before?
The answer
What a strong answer covers
- Clarifies: one customer or many, a user double tap or an automatic retry, two gateway charges or two orders.
- Stops the damage: refunds the duplicate, finds all orders with more than one successful payment in the period, and turns off the automatic client retry until the fix ships.
- Cause: the client retries after its own timeout while the first request is still running; the server treats the retry as a new payment.
- Idempotency key: the client creates one per checkout attempt and sends it in a header. The server stores
(user_id, key)with a unique constraint, the request hash, the state and the saved response. It inserts the key first (INSERT … ON CONFLICT DO NOTHING); a repeat gets the saved response, or "still processing". Keys live at least 24 hours (Stripe's documented practice). - A "check, then insert" in code is a race; only a unique constraint in the database closes it. Also a partial unique index: one successful payment per order.
- Passes an idempotent reference to the gateway too (one gateway order per order).
- Unknown outcome: mark the payment PENDING, never call the gateway inside a database transaction, and settle it from the gateway's webhook or a status poll; daily reconciliation catches the rest.
- PostgreSQL 19's
INSERT … ON CONFLICT DO SELECTreturns the existing row in one statement, which makes "get or create" simpler. - Communicates: support gets the refund details and timeline; the customer gets a clear message.
The red pen
Common traps
Avoid:"disable retries" as the fix; an in-memory set of seen requests on one server; checking for an existing payment without a unique constraint.
Practise this out loud
Say your answer out loud to an AI interviewer that follows up, and get a score for it.
Practise by voicePractise questions like this out loud
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.