A client retries a payment request after a timeout. How do you make sure the customer isn't charged twice?
BackendSenior
In shortMake the operation idempotent: the client sends a unique idempotency key with the request, the server stores the key with the request fingerprint and result in the same transaction as the work, and repeats return the stored result. Downstream calls to the payment provider carry their own idempotency key.
Model answer
A timeout doesn’t tell the client whether the payment happened, so retries are unavoidable. The server must make them safe.
- The client generates an idempotency key (a UUID) per logical operation, stores it with the pending action, and sends it on every retry:
Idempotency-Key: 6f1a…. - The server claims the key atomically: insert
(key, user_id, request_hash, status = IN_PROGRESS)with a unique constraint on(user_id, key). If the insert fails, the key exists:- completed: return the stored response (same status and body);
- in progress: return
409(or wait briefly), so two concurrent duplicates never both execute; - different request hash: return
422, the client reused a key for a different payment.
- Do the work and store the result in the same transaction as the business change (order marked paid, ledger entry), so a crash can’t leave a charged-but-unrecorded state. External calls happen outside the transaction, so record the state machine (created → provider called → succeeded) and resume it.
- Call the provider idempotently: payment providers accept their own idempotency key; derive it from yours, so retrying the provider call can’t double charge either.
- Expire keys after a window (24 hours to a few days), documented for clients.
Webhooks from the provider need the same treatment: dedupe by event id.
What they're looking for
Idempotency keys end to end, atomic storage of key and result, handling concurrent duplicates (in-progress state, unique constraint), fingerprint mismatch, key expiry, and idempotent calls to the provider.
Common mistakes
- Checking for the key and doing the work in separate, non-atomic steps.
- Generating the key on the server for each request.
- Forgetting the call to the payment provider can also be retried.
More backend questions
- What is the N+1 query problem, and how do you find and fix it?Mid-level
- What does Spring Boot's auto-configuration do, and how do you change what it set up?Mid-level
- How does a Spring backend authenticate requests from a mobile app, and how do you make sure users only see their own data?Mid-level
- Your Spring Boot service in Kubernetes keeps restarting with exit code 137. How do you investigate and fix it?Senior