Design a Usage-Based Billing System with Holds, Batches, and Reconciliation
System DesignModel answerLast updated
Design a billing platform that authorizes funds, captures final amounts in batches, reconciles against processor settlements, and guarantees no customer is ever charged twice.
Scenario
You're building the billing infrastructure for a cloud platform that charges customers based on measured consumption — think compute time, API calls, or storage. Customers provide a payment method upfront. The platform periodically estimates what they owe, reserves those funds, then settles the final amount once usage is confirmed.
Your system must interact with one or more external card processors that are outside your control: they time out, return ambiguous status codes, and send settlement reports on their own schedule.
What You Need to Design
1. Authorization and capture flow The platform reserves an estimated amount on a customer's card before the billing period ends (an authorization or "hold"). Once actual usage is known, it captures the real amount, which may be lower than the hold. If billing is cancelled, the hold is released without charging anything.
2. Batch charge submission At the end of a billing cycle, thousands of customers are billed simultaneously. Charges must be grouped and submitted to processors in batches rather than one at a time. The system must handle partial batch failures gracefully and resume without re-submitting what already went through.
3. Reconciliation Every night (or on demand), the processor sends a settlement report listing what it actually processed and settled. Your internal records must be compared against that report. Any discrepancy — a charge your system thinks succeeded but the processor never saw, or a processor entry with no matching internal record — must be detected, classified, and resolved.
4. Idempotency Retries happen everywhere: a client retries a timed-out HTTP request, an internal job queue delivers a message twice, a batch is re-run after a crash. No customer should be charged more than once for the same billing event, regardless of how many times any part of the system retries.
Constraints
- Money must be conserved: no amount can appear or disappear without a recorded, auditable entry.
- Processor calls can time out or return an outcome-unknown error. Your system must handle the case where you don't know whether the charge went through.
- The system should scale to tens of thousands of charges per billing cycle, with hold placements happening continuously throughout the day.
Expected Discussion
Walk through your data model, the state machine for a single payment, how you enforce idempotency at the database and processor layers, how batching works end-to-end, and how reconciliation catches and heals discrepancies. Call out where consistency is hardest and how you'd handle it.
Address the following clarifying questions as part of your answer, or explain how the answers would change your design:
- What daily volume and peak rate are expected?
- Do holds have a processor-enforced expiry window?
- Are multiple currencies in scope?
- What are the latency requirements for the hold step vs. the batch capture step?
- Where does card data live, and what compliance constraints apply?
Hints
Hint 1
Start by drawing the states a single payment moves through — PENDING_AUTH, AUTHORIZED, CAPTURED, RELEASED, FAILED — and ask yourself what database-level mechanism prevents two concurrent requests from moving it to the same terminal state simultaneously.
Hint 2
Idempotency for your own database is solved with a unique key per billing event, but idempotency for processor calls is trickier: if a call times out you don't know the outcome. Think about what you store before the call, and how you use the processor's own idempotency-key header to safely retry without issuing a second charge.
Hint 3
Reconciliation is a matching problem: you have two lists of transactions (yours and the processor's) that need to be joined on a shared reference ID. Think about the four possible match outcomes — matched, internal-only, processor-only, amount mismatch — and what the right remediation action is for each one.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Clarifying Questions and How Answers Shape the Design
Before designing anything, nail down volume and constraints:
- Volume: 50k charges per billing cycle (end of month), continuous hold placements at ~20/sec peak. Batching is a must; real-time one-by-one capture doesn't scale.
- Hold expiry: most card networks expire authorizations in 7–30 days. Captures must happen before expiry or the hold must be refreshed.
- Currencies: start single-currency; multi-currency adds FX conversion and per-currency settlement reports — isolate that complexity behind a
currencycolumn from day one. - Latency: hold placement is user-facing (< 2s); batch captures are background jobs (minutes to hours is fine).
- Card data: never stored in your own database. A PCI-compliant vault or processor tokenization handles raw card numbers. Your system stores processor tokens only.
Payment State Machine
Every charge lives as a row in a payments table and moves through a strict set of states:
CREATED → AUTHORIZING → AUTHORIZED → CAPTURING → CAPTURED
↘ AUTH_FAILED ↘ CAPTURE_FAILED
↘ RELEASING → RELEASED
State transitions are enforced with an optimistic-lock pattern:
UPDATE payments
SET status = 'AUTHORIZED', processor_auth_id = $1, updated_at = now()
WHERE id = $2 AND status = 'AUTHORIZING';
-- 0 rows updated = transition lost; caller retries or raises alert
This prevents two concurrent workers from both marking a payment as captured. Never allow a payment to jump from AUTHORIZED directly to CAPTURED in application code without going through CAPTURING — the intermediate state is your crash-recovery signal.
Ledger: Double-Entry for Auditable Money Movements
Balances are never stored as a mutable number. Instead, a ledger_entries table records every debit and credit:
ledger_entries(id, payment_id, account_from, account_to, amount, currency, created_at)
An authorization creates two entries: customer's funds-on-hold account is debited, a liability account is credited. Capture moves funds from liability to revenue. Release reverses the hold. The current balance of any account is always SELECT SUM(credit) - SUM(debit) FROM ledger_entries WHERE account = ?. This makes the audit trail immutable and makes reconciliation a query, not a guess.
Idempotency: Two Layers
Layer 1 — your own database. Every billable event (end of a billing cycle for a customer) has a stable billing_event_id generated deterministically (e.g., SHA256(customer_id + period_end)). The payments table has a UNIQUE constraint on billing_event_id. A duplicate insert fails at the database level, not in application logic.
Layer 2 — processor calls. This is the hard part. When you call the processor to place a hold:
- Write an
idempotency_keysrow with(key, payment_id, status=PENDING)before making the HTTP call. - Include the key in the processor request header (
Idempotency-Key). - On success or explicit failure, update the row to
COMPLETEDand transition the payment state. - On timeout or unknown error, leave the row as
PENDING.
When a retry comes in, look up the existing key row. If PENDING, re-send to the processor with the same key — the processor will return the cached result if it processed it, or treat it as a fresh attempt if it didn't. If COMPLETED, return the stored result immediately without touching the processor. This pattern handles the worst case: "I sent a charge request and never got a response."
Batch Processing
A billing-cycle job does the following:
- Query all customers whose period just ended and whose
billing_eventhas nopaymentrow yet. Insert payment rows inCREATEDstatus atomically with the idempotency key, usingINSERT ... ON CONFLICT DO NOTHING. - Group payments into batches of ~500, matching the processor's batch file format.
- Submit each batch. Record per-payment outcomes as they arrive.
- On partial failure, any payment still in
CAPTURINGafter a timeout is picked up by a background sweeper job that re-queries the processor for its status using the stored idempotency key.
The key design decision: the job is resumable. Re-running it after a crash will skip payments already in a terminal state and retry only those still in-flight.
Reconciliation
Once a day, the processor delivers a settlement file (SFTP or API). Reconciliation is a three-step process:
Step 1 — Ingest: parse the file and load it into a processor_settlements staging table keyed on processor_transaction_id.
Step 2 — Match: join payments against processor_settlements on processor_auth_id / processor_capture_id. Four outcomes:
| Internal state | Processor record | Classification | Action |
|---|---|---|---|
| CAPTURED | Present, amounts match | ✅ Matched | Mark reconciled |
| CAPTURED | Absent | ⚠️ Missing settlement | Investigate; may need to re-query processor |
| CAPTURED | Present, amount differs | ⚠️ Amount mismatch | Alert ops; do not auto-resolve |
| Absent | Present | ⚠️ Ghost charge | Urgent: may be a duplicate that leaked through; freeze and investigate |
Step 3 — Remediate: automated resolution handles the clear cases (re-query processor API for missing settlements). Amount mismatches and ghost charges are routed to a human-reviewed queue.
A common mistake is trying to auto-resolve amount mismatches. Small differences may be legitimate (processor fees), large ones may be fraud. Flag first, automate carefully.
Common Mistakes to Avoid
- Storing balance as a mutable column: any crash mid-transaction corrupts it. Use a ledger.
- Generating idempotency keys in the client: if the client regenerates the key on retry, you lose the protection. Keys must be stable across retries.
- Treating a processor timeout as a failure: it may have succeeded. Always re-query before retrying a charge.
- Running reconciliation against live payment rows: join against a point-in-time snapshot or a staging table to avoid race conditions with concurrent updates.
- No expiry tracking for holds: an expired, un-captured hold means the customer's card isn't actually reserved. Track
auth_expires_atand refresh or release before expiry.