Designing a Safe Card-Charging Flow with Retries and Storage
System DesignModel answerLast updated
Design a backend flow for charging customers through an external payment provider so no one is billed twice and no payment is lost, then pick what to persist and which database to use.
Your backend service must begin collecting money through an external payments provider (think a hosted card-processing API). Each charge pays for exactly one existing order, with a known amount and currency. You are asked to design the integration and then defend how robust it is.
Questions you may want to settle first
- Does the customer wait on the checkout page for the result, or may the payment finish in the background?
- Do raw card numbers ever touch your servers, or does the provider's client-side form collect them?
- Are refunds and subscriptions in scope, or only one-time charges?
- What does the user see while the result of a payment is still unknown?
Part 1: Failure handling
Describe what can go wrong when your service asks the provider to charge a customer, and how your code reacts to each case. The goals: a customer is never charged twice, and a successful payment is never lost.
Your answer should address:
- Which failures are safe to retry and which are not
- How to make a retry safe when you do not know whether the first request succeeded
- The retry policy, and what happens once retries run out
- How results that arrive late, duplicated, or out of order get applied
Part 2: Persistence
Which payment data must your service store, and which database would you choose? Justify the choice using ACID guarantees and availability.
Your answer should address:
- The records and fields, how they connect to your orders and to the provider's identifiers, and what you must never store
- Database constraints that enforce idempotency and legal state transitions
- A reasoned database choice with a clear stance on consistency versus availability for payment data
Hints
Hint 1
Start from the hardest case: the request timed out and you cannot tell whether the provider charged the card. What property of the request lets you send it again safely?
Hint 2
Persist your own payment record in a 'pending' state before calling the provider, and update it after. Treat the provider's asynchronous notifications as the source of truth, and make handling them safe to repeat and safe to receive out of order.
Hint 3
For storage, think about which uniqueness rules and conditional updates the database itself can enforce, and why a payment ledger should favor consistency over availability.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Core idea
Treat the payment as a small state machine owned by your service, written to the database before and after every external call. Make every operation idempotent, so any step can be retried or replayed without changing the result. Reconcile against the provider to catch whatever slips through.
Part 1: Failure handling
Flow
- Create a
paymentsrow for the order with statuspendingand a generated idempotency key. Commit it. - Call the provider with that key (sent as an idempotency header) plus amount, currency and an order reference in metadata.
- Record the result. The provider's asynchronous notification (webhook) is the authoritative final signal. The synchronous response only gives a fast path.
Failure classes
| Failure | Meaning | Action |
|---|---|---|
| Validation errors, bad parameters | Our bug | Do not retry, alert, fail the payment |
| Card declined, insufficient funds | Definitive business outcome | Do not retry, mark failed, show the user a clear message |
| Authentication or permission errors | Config problem | Do not retry, page someone |
| Rate limiting (429) | Transient | Retry with backoff, honoring any retry-after hint |
| 5xx, network error, timeout | Unknown outcome | Retry with the same idempotency key |
Why the idempotency key matters. On a timeout the charge may or may not exist. Resending the same key makes the provider return the original result instead of creating a second charge. Rules: generate the key once per payment attempt and store it, never regenerate it on retry, and use a new key only for a deliberately new attempt (for example, the customer picks another card). Reusing a key with different parameters is an error, which is a useful safety net.
Retry policy. Exponential backoff with jitter (for example 1s, 2s, 4s, 8s, capped), a small attempt limit, and an overall deadline. Retries from several layers multiply, so retry in one place only. If the user is waiting, stop after a few seconds and show "processing". Do not claim failure.
When retries are exhausted. Leave the payment in pending or unknown, not failed. A background job later queries the provider by idempotency key or by our order reference and settles the state. Only a definitive provider answer moves it to succeeded or failed.
Late, duplicate and out-of-order notifications
- Verify the webhook signature, then store the event ID in a table with a unique constraint. A duplicate insert means "already handled", so return 200.
- Acknowledge quickly and process through a queue, so slow handlers do not trigger provider redeliveries.
- Do not trust arrival order. Apply transitions only if legal (
pending -> succeeded|failed,succeeded -> refunded), using a conditional update such asUPDATE ... SET status='succeeded' WHERE id=? AND status IN ('pending','unknown'). A stale event then becomes a no-op. When in doubt, re-fetch the object from the provider rather than trusting the payload. - Marking the order as paid happens in the same transaction as the payment status change, or through a transactional outbox, so the two can never disagree.
Crash cases. Crash before the provider call: the row stays pending and a sweeper retries with the same key. Crash after the call but before saving the result: the retry returns the original outcome, and the webhook would have fixed it anyway.
Part 2: Storage
Tables
payments:id,order_id,amount_minor(integer cents),currency,status,idempotency_key(UNIQUE),provider_payment_id(UNIQUE, nullable until known),failure_code,created_at,updated_at,version.payment_events:provider_event_id(UNIQUE),payment_id,type,received_at, minimal payload or reference. This gives an audit trail and webhook deduplication.- Optionally
refundsand an append-onlyledger_entriestable for double-entry bookkeeping. - Link to the provider with a customer ID and a payment method ID (a token).
Never store: full card numbers, CVV, or raw magnetic data. Let the provider's client-side form tokenize the card, which keeps you at the lightest PCI scope. Keep secrets and webhook signing keys in a secrets manager, and avoid logging sensitive payloads.
Constraints that enforce correctness
- A unique key on
idempotency_keyand a partial unique index allowing only one active payment per order, so two concurrent checkouts cannot both charge. - Unique
provider_event_idfor webhook dedup. - Money as integers in minor units, with a CHECK that the amount is positive.
- A status CHECK plus conditional updates (or optimistic
version) to prevent illegal transitions.
Database choice. A relational database such as PostgreSQL. Payments need multi-row atomic transactions (payment, order, ledger), unique constraints, and strong consistency, which is exactly what ACID provides. Volume is rarely the problem: even millions of payments per day is a few dozen writes per second on average, well within a single primary, with read replicas for reporting and partitioning by date if needed.
Consistency versus availability. For the payment write path, choose consistency. A brief refusal to accept payments is better than a stale read that allows a double charge or a lost record. Gain availability through synchronous replication to a standby with automatic failover, and by keeping the checkout page degradable ("we'll confirm by email") rather than by adopting eventual consistency for the ledger. Read-only views such as order history can come from replicas or caches.
Reconciliation and monitoring
- A nightly job compares provider records against
paymentsand flags mismatches (charged but not marked paid, and the reverse). - Alert on payments stuck in
pendinglonger than a threshold, webhook failure rate, retry counts, and growing reconciliation drift.
Common mistakes
- Retrying a timeout with a fresh idempotency key, which causes a double charge.
- Marking a payment failed on a timeout.
- Trusting the browser redirect as proof of payment.
- Processing webhooks without dedup or ordering protection.
- Using floating-point money.
- Choosing an eventually consistent store for the ledger.
- Retrying declines.