KatInterview

Building a Reliable Credit Top-Up Billing Backend

System DesignModel answer
HardModel answerSystem Designidempotencydouble-entry-ledgerwebhooks

Last 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

  1. API design: the endpoint that starts a payment, and the shape and verification of the callback (webhook) the provider sends with status updates.
  2. Data model: a schema that supports double-entry bookkeeping (accounts, journal and ledger entries, and supporting tables).
  3. 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.