Build a Charge-Once Card Payment Service Behind a Gateway
System DesignModel answerLast updated
Design an internal payment service that charges a card at most once per order despite retries, timeouts and crashes, and reconciles its records with an external payment provider.
Scenario
Your company runs an order service that must collect money from customers. You own a new internal payment service that sits between the order service and an external card gateway. The gateway exposes a charge API and supports idempotency keys, but it is a remote system that can be slow, return errors, or drop responses.
The order service calls you with:
process_payment(order_id, amount, payment_token)
Design this service so that each order results in exactly one successful charge, even when:
- the order service retries the same call (possibly concurrently),
- your own servers crash mid-request,
- the network drops the gateway's response after the card was actually charged.
Requirements
Functional
- At most one successful charge per
order_id, no matter how many times the call is repeated. - Repeated calls must be safe and return a consistent answer.
- Every payment has a tracked status: Pending, Succeeded or Failed.
Non-functional
- Strong consistency: your stored state must eventually match what the gateway actually did.
- Fault tolerance: the system must survive partial failures anywhere in the request/response path.
What to cover in your answer
- Assumptions about scale, gateway behavior and money representation.
- The API contract, including what callers see when the outcome is not yet known.
- Data model and status lifecycle.
- The request flow, step by step.
- How you handle the case where the gateway charged the card but you never received the acknowledgment.
- How idempotency is enforced across services, not just inside your database.
- How you detect and repair mismatches between your records and the provider's.
- Key trade-offs and common mistakes.
Hints
Hint 1
Networks cannot deliver exactly once. Think of the guarantee as repeated attempts combined with idempotent execution, and ask where the idempotency must be enforced.
Hint 2
Write your intent to your own database before calling the gateway, and introduce a status for 'we do not know what happened'. A timeout must never be treated as a failure.
Hint 3
Reuse the same idempotency key for every retry of an order, and add a background reconciler plus a periodic comparison against the provider's settlement data as a safety net.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Core idea
No network gives true exactly-once delivery. What we can build is at-least-once attempts plus idempotent execution: we keep trying until we know the outcome, and every attempt for the same order collapses into one charge. The idempotency guarantee must extend into the gateway, not stop at our own database. The hard case is the unknown outcome: the card may have been charged but we never saw the response.
Assumptions
- About 10M payments/day: roughly 120 TPS average, 1-2k TPS at peak.
- Gateway p50 around 500 ms, tail of 5-10 s, occasional 5xx and timeouts.
- The gateway supports idempotency keys valid for at least 24 hours (confirm this; the design depends on it).
- Amounts are integers in minor units plus a currency code. Cards are tokenized; we never store raw card numbers.
- Refunds and partial captures are out of scope.
API
POST /payments { order_id, amount, currency, payment_token }
200 { payment_id, status: SUCCEEDED | FAILED, failure_reason? }
202 { payment_id, status: PENDING } // outcome not yet known
409 order_id exists with different amount/currency
GET /payments/{order_id}
Callers may retry freely; every retry returns the same record.
Data model (Postgres)
payments(payment_id PK, order_id UNIQUE, idempotency_key UNIQUE,
amount_minor, currency, payment_token,
status, gateway_charge_id, attempt_count,
lease_expires_at, version, created_at, updated_at)
payment_events(id, payment_id, from_status, to_status, source, payload, ts) -- append-only
outbox(id, payment_id, event_type, payload, published_at)
Status lifecycle: CREATED -> PROCESSING -> SUCCEEDED | FAILED | UNKNOWN. UNKNOWN can go back to PROCESSING (retry with the same key) or directly to a terminal state via reconciliation or webhook. SUCCEEDED and FAILED are terminal and immutable.
Request flow
- Persist intent first.
INSERT ... ON CONFLICT (order_id) DO NOTHING. If the row exists, compare amount and currency (mismatch gives 409). If it is terminal, return the stored result. - Claim the right to call the gateway with a conditional update that moves
CREATED/UNKNOWN(orPROCESSINGwith an expired lease) toPROCESSING, sets a lease of about 30 s and bumps the attempt count. If zero rows are updated, another worker owns it; return 202 or the current state. - Call the gateway with the stable idempotency key (for example
pay:<order_id>) and putorder_idin the charge metadata for later lookup. - Classify the result.
- Success:
SUCCEEDED, store the charge ID. - Definitive decline (insufficient funds, card declined):
FAILED. - Timeout, reset or 5xx:
UNKNOWN. NeverFAILED, because the card may have been charged.
- Success:
- Commit atomically the status change, audit event and outbox row in one local transaction. A relay publishes
payment.succeeded/payment.failedto the order service. This avoids the dual-write problem of updating the DB and a broker separately.
The lost-acknowledgment case
The gateway charged the card, but our process timed out or crashed. Our row is PROCESSING (lease expires) or UNKNOWN. Recovery is either a client retry or the reconciler re-issuing the call with the same idempotency key; the gateway returns the original charge's result rather than creating a second charge. Alternatively, look the charge up by metadata. The cardinal bug is generating a new key on retry, which turns a safe retry into a double charge.
Idempotency across layers
- Order service: sends a stable
order_id. - Our DB:
UNIQUE(order_id)plus the conditional lease update stop concurrent duplicates inside our system. - Gateway: the idempotency key stops duplicates whose outcome we never recorded.
Each layer covers a different failure mode; none alone is sufficient.
Reconciliation
- Fast loop (about every minute): select
UNKNOWNrows andPROCESSINGrows with expired leases older than about a minute, usingFOR UPDATE SKIP LOCKED LIMIT 100so workers do not collide. Query the gateway, transition the record, back off exponentially on errors. Resolve everything well before the key TTL; if a record ages past roughly 12 h, alert a human. - Webhooks: a receiver pushes gateway events onto a queue; a status updater applies them through the same state machine (ignoring changes to terminal rows).
- Daily ledger diff: compare the gateway's settlement report against our
SUCCEEDEDrows by charge ID and amount. A charge with no matching success row means fix state or refund if the order was cancelled. A success row with no charge means investigate. This catches bugs, not only timeouts.
Trade-offs
| Choice | Benefit | Cost |
|---|---|---|
| Sync call with 202 fallback | Fast answer for most users | Callers must handle PENDING |
| Fully async via queue | Absorbs gateway outages and spikes | Slower UX, more components |
| Lease-based ownership | Survives crashed workers | Lease must exceed gateway timeout, otherwise two workers overlap (safe thanks to the key, but noisy) |
| Relying on gateway idempotency | Simple, strong | Limited by key TTL and vendor semantics; reconciliation is the backstop |
Common mistakes
- Calling the gateway before persisting intent, so a crash loses all trace of the attempt.
- Treating a timeout as a failure and letting the user retry with a new key.
- Using a random idempotency key per attempt.
- Allowing transitions out of terminal states (for example a late webhook overwriting
SUCCEEDED). - Updating the DB and publishing an event as two separate writes.
- Storing money as floats or storing raw card data.
- Skipping reconciliation because "the gateway is reliable".