Building a Reliable Credit Top-Up Billing Backend
System DesignModel answerLast updated
Design a billing service that sells API credits through an external payment provider, crediting each successful payment exactly once despite retries, timeouts, and partial failures.
Design a Credit Top-Up Billing Service
Your company sells usage credits for its API. Customers buy credit packs, and card processing is handled by an outside payment provider (think of a hosted gateway with webhooks). Design the backend that starts purchases, confirms them with the provider, and adds credits to the customer's balance.
What the system must do
- A customer can start a purchase for a given amount.
- The service must confirm with the provider that money was actually collected.
- Each successful payment must raise the customer's balance exactly once.
- Every money movement must be recorded in an auditable history.
Quality requirements
- Correctness: Balances must never be wrong. No duplicate credits and no lost credits. Delayed credits are acceptable; incorrect ones are not.
- Idempotency: Users double-click, clients retry after timeouts, and the provider may deliver the same notification repeatedly. All of these must be safe.
- Durability: Once the service acknowledges a payment, that fact cannot be lost.
- Throughput: Sustain about 1,000 requests per second.
What to cover in your answer
- API design: the endpoint that starts a payment, and the shape and verification of the callback (webhook) the provider sends with status updates.
- Data model: a schema that supports double-entry bookkeeping (accounts, journal and ledger entries, and supporting tables).
- Architecture: how you handle retries, enforce idempotency, and avoid race conditions when changing balances.
Failure scenarios you must address
- The provider is slow or intermittently down.
- The provider tells you a payment succeeded, but your own database write fails afterwards.
Hints
Hint 1
Treat the problem as two systems with no shared transaction. Decide which side is the source of truth for 'money was captured' and design every step so it can be repeated safely.
Hint 2
Put uniqueness in the database: a per-user idempotency key, a unique provider event id, and one journal entry per payment. Combine this with a payment state machine and a conditional status update, so duplicate webhooks become no-ops.
Hint 3
Never conclude failure from a provider timeout. Leave the payment pending and run a reconciler that polls the provider and calls the same idempotent 'apply success' routine the webhook uses. Use an outbox for downstream events so you avoid dual writes.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Overview
The core difficulty is keeping money correct when your database and the payment provider cannot share a transaction. The design therefore rests on four ideas: idempotency everywhere, an explicit payment state machine, atomic local transactions backed by unique constraints, and a reconciliation loop as a backstop. Boxes and arrows matter less than these.
1. Requirements and scale
- Assume one-time credit purchases using the provider's hosted checkout or payment-intent flow, so card data never reaches our servers and PCI scope stays small.
- 1,000 RPS of initiations at roughly 5 writes each (payment, idempotency record, outbox row, two ledger legs) is about 5K writes/s. One well-tuned Postgres primary can handle this; shard by
user_idonly if growth requires it. - If about 10% of requests turn into payments, that is roughly 100/s, around 8.6M/day, and billions of ledger rows per year. Partition ledger tables by time.
- Correctness bar: exactly-once credit per captured payment; delay is tolerable, error is not.
2. API design
Start a payment
POST /v1/payments
Headers: Idempotency-Key: <uuid>, Authorization: Bearer ...
Body: { "credit_pack_id": "pack_20", "currency": "USD" }
201 -> { "payment_id": "pay_123", "status": "PENDING", "client_secret": "..." }
- The key is scoped to
(user_id, key). Replaying it returns the stored response. - Same key with a different body:
422. Same key while the first call is still running:409. - Derive the amount server-side from the pack id; never trust a client-supplied price.
Provider webhook
POST /v1/webhooks/provider
Header: Provider-Signature: t=<ts>,v1=<hmac>
Body: { "event_id": "evt_789", "type": "payment.succeeded", "data": { "ref": "pi_abc", "amount": 2000, "metadata": {"payment_id": "pay_123"} } }
- Verify the HMAC over the raw body, reject timestamps older than about 5 minutes, and dedupe on
event_id. - Return 2xx only after the event is durably stored, so the provider retries anything else.
- Also check that amount and currency match our payment row.
3. Data model
payments(id, user_id, amount_cents, currency, status, provider_ref UNIQUE, version, ...)
UNIQUE(user_id, idempotency_key)
CREATED -> PENDING -> SUCCEEDED | FAILED | EXPIRED ; SUCCEEDED -> REFUNDED
idempotency_keys(user_id, key, request_hash, response, status, expires_at)
accounts(id, owner_id, type, currency, balance_cents)
types: USER_CREDITS, PROVIDER_CLEARING, REVENUE
journal_entries(id, payment_id UNIQUE, kind, created_at)
ledger_entries(id, journal_id, account_id, direction, amount_cents > 0, created_at) -- append-only
processed_webhooks(event_id PK, payload, received_at)
outbox(id, aggregate_id, event_type, payload, published_at NULL)
- A successful top-up writes one journal with two legs: debit
PROVIDER_CLEARING, creditUSER_CREDITS. Debits equal credits per journal. - Ledger rows are never updated. Refunds and fixes are new reversing entries.
balance_centsis a cached projection updated in the same transaction and always recomputable from the ledger.UNIQUE(journal_entries.payment_id)is the final guard: a second credit for the same payment cannot commit.
4. Flows
Initiation
- One transaction inserts the idempotency record (
IN_PROGRESS) and aCREATEDpayment. A unique violation means a duplicate, so return the stored result. - Call the provider with our
payment_idas the provider-side idempotency key, using a timeout and bounded exponential backoff with jitter. Our retries are then safe on their end too. - Save
provider_ref, move toPENDING, store the response on the idempotency record, and return it. - On timeout, stay
PENDING. Never assume failure; the reconciler resolves it.
Confirmation (webhook or reconciler), a single transaction
- Insert
event_idintoprocessed_webhooks; on conflict return 200 and stop. UPDATE payments SET status='SUCCEEDED' WHERE id=? AND status='PENDING'. Zero rows changed means no-op.- Insert the journal and both ledger legs.
- Update the cached balance.
- Insert an outbox row
PaymentSucceeded.
Then return 200.
5. Deep dives
Provider says success but our write fails. We return non-2xx or crash, so the provider redelivers (often for days). Because the whole update is one transaction guarded by unique constraints, a retry either applies cleanly or no-ops. The reconciler backs this up by querying the provider for payments stuck in PENDING beyond N minutes and calling the same apply-success function. One code path serves both, so correctness lives in one place.
Outbox. Writing to the DB and then to a message bus is a dual write; a crash in between loses or invents events. Inserting the event row in the ledger transaction makes them atomic. A relay (polling or CDC) publishes at-least-once, and consumers dedupe by event id.
Balance races. Prefer an atomic conditional update inside the ledger transaction: UPDATE accounts SET balance = balance + :amt WHERE id = :id, and for spends add AND balance >= :amt and check the row count. Alternatives are SELECT ... FOR UPDATE on the account row, or optimistic versioning with retries. Hot accounts are rare for per-user balances, so row-level contention is fine.
Provider outages. Use timeouts, retries with backoff, and a circuit breaker. Keep accepting initiations where possible (payment stays CREATED/PENDING) or fail fast with a retryable error; a background job retries stuck CREATED rows.
Reconciliation. Besides polling pending payments, compare daily settlement files against the ledger and alert on mismatches (money captured with no credit, or credit with no capture). Also verify that the sum of ledger legs is zero and that cached balances match recomputed ones.
Trade-offs
- Synchronous provider call in the request path is simpler but ties latency to the provider; an async queue-driven call improves resilience at the cost of more states.
- A single Postgres keeps transactions simple; sharding by user preserves single-shard transactions because each payment touches one user's accounts (the clearing account should be per-shard to avoid a global hot row).
Common mistakes
- Marking a payment failed on a timeout, then crediting twice when the webhook arrives.
- Crediting from the client redirect instead of a verified webhook or provider lookup.
- Checking for duplicates in application code without a unique constraint.
- Updating balances without a ledger, leaving no audit trail.
- Returning 200 to the webhook before the data is committed.
- Trusting the amount from the client or from an unverified payload.