Harden a Two-Step Charge-and-Record Payment Flow
System DesignModel answerLast updated
Diagnose every failure mode in a naive charge-then-write endpoint, then redesign it to survive crashes, timeouts, retries, and concurrent duplicates.
Hardening a Two-Step Charge-and-Record Payment Flow
Your team owns a payment endpoint that does two things in sequence: it asks an external payment processor to collect money from a customer, then records that payment in the application's own database. The current implementation looks roughly like this:
def pay(order_id, user_id, amount):
charge = processor.charge(user_id, amount) # outbound HTTP call
db.insert_payment(order_id, user_id, amount, charge.id, status="paid")
return {"status": "paid"}
The processor supports three things you can rely on:
- An idempotency key on charge requests, so the same key sent twice does not produce a second charge.
- A status lookup endpoint that lets you query the outcome of a prior charge by its key.
- Webhooks that push the final result of a charge to your server asynchronously.
Always confirm what a real processor actually offers before depending on any of these in production.
Clarifying questions to consider before answering
Before designing a solution, think through:
- Who can retry a timed-out request — the client, your server, or both?
- Can a charge land in a "pending" state, or does every call resolve to success or decline immediately?
- How long does the processor remember an idempotency key, and what does it return on a duplicate submission?
- Does one order always map to exactly one charge attempt?
Part 1 — Enumerate the failure modes
Walk through every way the code above can fail. For each failure, describe the resulting state: what happened to the customer's money, and what is (or is not) in your database.
Your answer should address:
- What happens when the process crashes or the network times out between the processor call and the database write
- What happens when the exact same payment is submitted twice — by the client retrying, by the server retrying, or both happening at once
- Why wrapping both steps in a local database transaction does not solve the problem
Part 2 — Make the operation retry-safe
Redesign the flow so that any number of retries of the same payment — whether they originate from the client, the server, or a load balancer — never produce a second charge or a duplicate database record.
Your answer should address:
- Where the payment attempt identity comes from, who generates it, and how long it should be retained
- How the server recognises a duplicate request, including two identical requests that arrive simultaneously
- How the idempotency key is threaded through to the processor call
Part 3 — Guarantee every charge is eventually resolved
Some charge attempts will end in an unknown state: the server crashed mid-flight, the processor call timed out with no response, or the webhook never arrived. Redesign the flow so that no charge attempt can get permanently stuck, and explain how each unknown outcome is eventually resolved.
Your answer should address:
- The full set of states a payment record can be in, and which transitions between them are valid
- Every path by which a non-final payment gets resolved, who is responsible for each path, and the time bound on resolution
- How the system behaves when the same result arrives more than once, or when results arrive out of order
Part 4 — Place the lock correctly
At any given moment, a client retry, an inbound webhook, and a background recovery job might all try to act on the same payment record. Describe where you would put a lock, at what granularity, and whether it should be held while the outbound processor call is in flight.
Your answer should address:
- What actually requires mutual exclusion and what does not
- The concrete cost of holding a lock or an open database transaction across a network call
- Techniques that achieve the same safety guarantee without a long-held lock
Hints
Hint 1
Start by asking what the possible outcomes of `processor.charge()` are — not just success and failure, but also the case where you genuinely do not know what happened. That third outcome is the root of most of the hard problems here.
Hint 2
An idempotency key only works if it is generated before the outbound call and stored durably before anything else. Think about what needs to exist in your database before the processor is ever contacted.
Hint 3
Separate the question of mutual exclusion from the question of durability. You can keep critical sections very short by using optimistic concurrency or conditional database updates instead of holding a lock across the network call.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
What a Strong Answer Covers
Part 1 — Failure modes
The code has three distinct classes of problems.
Crash or timeout between the charge and the write.
The processor call succeeds and the customer's card is charged. Before db.insert_payment runs, the server process crashes, the pod is killed, or the database times out. The customer lost money, but your database has no record of it. This is the most dangerous failure because it is silent.
A subtler variant: the processor call itself times out. You do not know whether the charge went through. If you return an error to the client and the client retries, and your server calls processor.charge again without an idempotency key, the card gets charged twice.
Unprotected retries and concurrent submissions.
Without any deduplication, a client that retries on a 500 or a network timeout, a mobile client that taps the button twice, or two browser tabs submitting simultaneously will each trigger a separate processor.charge call and a separate database row. The customer is charged multiple times.
Local transactions cannot span external calls.
Wrapping both lines in BEGIN / COMMIT provides no help here. Database transactions enforce atomicity within the database. They have no knowledge of what the processor did. If you open a transaction, call the processor, and then the database write fails or the transaction rolls back, the charge is already gone from the processor's side. You cannot roll back a network call.
Part 2 — Safe retries with idempotency
The fix starts with generating a payment attempt token — a stable UUID that represents this specific payment attempt — before any external call is made.
Where it comes from: The client should generate this token and include it in the request. If the client is unreliable, the server can generate it on the first submission and return it to the client, but then the client must send it back on every retry. The token must live at least as long as the retry window.
Storing it before calling the processor:
def pay(order_id, user_id, amount, payment_token):
# Upsert: create with status=pending if not exists, return existing if already present
payment = db.upsert_payment(
token=payment_token,
order_id=order_id,
user_id=user_id,
amount=amount,
status="pending"
)
if payment.status in ("paid", "failed"):
return {"status": payment.status} # already resolved, return cached result
charge = processor.charge(
user_id=user_id,
amount=amount,
idempotency_key=payment_token # same token goes to the processor
)
db.update_payment(payment_token, processor_charge_id=charge.id, status="paid")
return {"status": "paid"}
The upsert uses a unique constraint on payment_token. Two concurrent requests with the same token race on that constraint; one wins and proceeds, the other receives the existing row and short-circuits. The processor also receives the same token as its idempotency key, so even if two requests get through to it, the processor charges only once.
Part 3 — Tracking every charge to a final state
The payment record needs a state machine with these states:
pending → charging → paid
→ failed
→ unknown
- pending: record created, processor not yet called
- charging: processor call is in flight
- paid / failed: terminal states from the processor
- unknown: processor call returned no clear answer (timeout, 5xx, process crash mid-flight)
Before calling the processor, transition the record to charging. After a clear response, transition to paid or failed. On a timeout or crash, the record stays in charging or moves explicitly to unknown.
Three resolution paths:
-
Synchronous success/failure. The processor returns a clear result. Update the record immediately.
-
Webhook. The processor posts the outcome asynchronously. The webhook handler looks up the payment by
processor_charge_id, validates the new state is a valid transition from the current one, and applies it. Webhooks must be idempotent: applying the same webhook twice should be a no-op, not an error. -
Background recovery sweep. A job runs every few minutes and queries for records stuck in
chargingorunknownfor longer than some threshold (e.g. 5 minutes). For each, it calls the processor's status lookup endpoint with the original idempotency key. The result is applied as if it were a webhook. This job gives every stuck payment a time-bounded resolution and is the safety net when webhooks are delayed or missed.
Out-of-order results — for instance, a webhook arriving after the recovery job already resolved the payment — are handled by checking that the incoming transition is valid before applying it. A paid → failed transition should be rejected; a paid → paid transition is a no-op.
Part 4 — Lock placement
What needs mutual exclusion: The check-then-act sequence — "is this payment already resolved? no → proceed to charge" — must not run concurrently for the same token. Without coordination, two threads could both read pending and both call the processor.
What does not need a long lock: The outbound network call itself. Holding a database row lock or an open transaction for the full duration of a processor call (which may take hundreds of milliseconds or time out after seconds) is expensive. It pins a database connection, blocks other waiters on the same row, and dramatically increases the blast radius of slow external calls.
Preferred approach — optimistic concurrency with a short conditional update:
UPDATE payments
SET status = 'charging'
WHERE token = $1 AND status = 'pending'
RETURNING *;
Only the thread whose UPDATE returns a row proceeds to call the processor. The others get zero rows back, read the current state, and either return a cached result or wait and retry. The database lock is held only for the duration of the single-row write, not across the network call.
Distributed lock as an alternative: A Redis lock keyed on payment_token with a short TTL (e.g. 10–30 seconds) works if the database approach is unavailable, but it introduces a new dependency and requires careful TTL tuning — too short and a slow processor call lets a second thread in; too long and a crashed holder blocks the record.
Common mistake: Holding a SELECT FOR UPDATE lock open while calling the processor. This makes the database a bottleneck and turns every processor slowdown into a cascading lock-wait across all threads touching payment records.
Observability
Any complete answer should mention alerting on payments stuck in charging beyond the expected maximum processing time, a counter for state transition conflicts (indicating duplicate processing), and a nightly reconciliation job that compares your database totals against the processor's settlement report to catch any discrepancy the real-time paths missed.