Architecting a Card Network Transaction Switch
System DesignModel answerLast updated
Design a card-network transaction switch that routes authorizations to unreliable issuer banks, prevents duplicate charges, keeps an auditable ledger, and keeps card data tokenized.
Build the Core of a Card Payment Network
You are designing the backend for a worldwide card network. It sits between merchants (via their acquirers) and issuing banks. The network does not hold cardholder funds. Issuers do. Your system routes requests, protects card data, records every transaction accurately, and tracks what each party owes for later settlement.
What the system must do
- Authorization: Ask the issuing bank whether the purchase can be approved against the cardholder's balance or credit limit.
- Capture: Complete the transfer of funds from the issuer's side to the merchant's side after a successful authorization.
- Safe retries: If a merchant retries a call because of a network failure, the cardholder must never be charged twice.
- Refunds and reversals: Support voiding, reversing, and refunding after the fact.
Quality targets
- Throughput and latency: Thousands of transactions per second, with a sub-second response for authorizations.
- Correctness under concurrency: Money must never be created, lost, or spent twice, even when requests race.
- Auditability: Every state change must be recorded for regulators and for reconciliation.
Constraints
- Issuer APIs differ in speed and reliability, and some will be slow or down at times.
- The design must satisfy PCI-DSS, so raw card numbers must be replaced by tokens and kept out of most of the system.
What to cover in your answer
- The merchant-facing API.
- A data model for transaction state, an audit trail, and ledger entries.
- How the system talks to slow or failing external banks.
- Your approach to idempotency and to consistency across services that cannot share a single database transaction.
State your scale assumptions and the trade-offs you make.
Hints
Hint 1
Begin by stating the numbers you assume (average and peak TPS, storage per day, latency budget), and decide which steps must be synchronous and which can run later.
Hint 2
Think of a payment as a state machine. Every change should be a conditional write in one local database transaction that also appends an audit event, a balanced ledger journal, and an outbox record.
Hint 3
You cannot run two-phase commit against a bank. Ask what you do when an issuer call times out and you do not know the outcome, and how compensating actions plus a retry-safe identifier can resolve it.
Hint 4
For idempotency, use a uniqueness constraint on (merchant, key) as the lock, store a hash of the request, and commit the stored response in the same transaction as the state change.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Scope and assumptions
The network routes, tokenizes, records, and tracks obligations. The issuer owns the balance and makes the approve/decline decision.
Assumed scale:
- About 10k TPS average and 50k TPS at peak (roughly 5x during holiday spikes).
- About 860M transactions per day. At around 1 KB per transaction plus events, that is roughly 1 TB per day, retained 7+ years.
- Internal overhead under 50 ms. The issuer round trip dominates, with end-to-end p99 under 1 s and an issuer timeout of about 3-5 s.
- 99.999% availability, multi-region.
- Authorization is synchronous. Capture, clearing, and settlement are asynchronous and batched.
2. Merchant API
All mutating calls require an Idempotency-Key header. Amounts are integers in minor units plus an ISO currency code, never floats.
POST /v1/authorizations {merchant_id, amount, currency, card_token}
POST /v1/authorizations/{id}/capture {amount} # partial allowed
POST /v1/authorizations/{id}/void
POST /v1/transactions/{id}/refunds {amount} # partial allowed
GET /v1/transactions/{id}
Webhook: transaction.updated # async outcomes
Card numbers are swapped for tokens at an edge tokenization service inside the PCI zone. The token-to-PAN mapping lives in an HSM-backed vault. Only the issuer adapter detokenizes, right before calling the bank. This shrinks PCI scope to a small slice of the system.
3. Data model
State machine, enforced in code and by database constraints:
CREATED -> PENDING_AUTH -> AUTHORIZED | DECLINED | AUTH_UNKNOWN
AUTHORIZED -> CAPTURED | VOIDED | EXPIRED
CAPTURED -> SETTLED -> PARTIALLY_REFUNDED | REFUNDED
AUTH_UNKNOWN -> REVERSED | AUTHORIZED
Tables:
- transactions: id (includes shard id), merchant, token, issuer, issuer reference, currency, authorized/captured/refunded amounts, state, version, timestamps.
- transaction_events (append-only): from/to state, payload, actor, timestamp. This is the audit trail, with no updates or deletes.
- idempotency_keys: primary key (merchant_id, key), request hash, status, stored response, transaction id, expiry.
- ledger_entries (double-entry, append-only): journal id, account, debit/credit, amount, currency, transaction id. Invariant: each journal balances. Accounts include issuer receivable, merchant payable, fees, and suspense. Balances are sums, cached as snapshots.
- outbox: events to publish, written in the same local transaction as the state change.
Shard by merchant so the idempotency key, transaction, and ledger rows for a request live together and commit atomically.
4. Architecture
Merchant -> Gateway (auth, rate limit, idempotency)
-> Tokenization edge (PCI zone)
-> Authorization service -> fraud scoring -> BIN routing -> issuer adapters
-> Sharded SQL (state, events, ledger, outbox)
-> Outbox relay -> Kafka -> clearing/settlement, ledger projections, webhooks, analytics
Dealing with slow and unreliable banks
- Bulkheads: each issuer gets its own connection pool, threads, and queue, so one slow bank cannot starve the rest.
- Timeouts and circuit breakers per issuer. Retries reuse the same trace identifiers (STAN/RRN) so the bank can deduplicate.
- Unknown outcomes: on timeout, mark the transaction
AUTH_UNKNOWNand send a reversal or status inquiry. Never assume approval. - Stand-in processing: with a breaker open, approve low-risk transactions within issuer-set limits, log them, and forward later.
- Async capture and clearing through Kafka, so bank latency never blocks the merchant call.
5. Idempotency
- Insert
(merchant_id, key, request_hash, IN_PROGRESS). The unique constraint acts as the lock. - On conflict with a COMPLETED key: matching hash returns the stored response, different hash returns 422.
- On conflict with an IN_PROGRESS key: return 409 with a retry-after, since the first request is still running.
- Write the final response in the same DB transaction as the state change.
Redis can serve as a fast pre-check but never as the source of truth. It can lose keys on failover, which would allow double charges.
6. Concurrency and no double-spend
Use optimistic, conditional updates:
UPDATE transactions
SET state='CAPTURED', captured_amount = captured_amount + :amt, version = version + 1
WHERE txn_id=:id AND state IN ('AUTHORIZED','CAPTURED')
AND captured_amount + :amt <= authorized_amount AND version=:v;
- A capture racing a void: exactly one succeeds, the other sees zero rows updated.
- Over-refunds are blocked with
refunded_amount + :amt <= captured_amount. - The state update, event row, balanced journal, and outbox row commit in one local ACID transaction.
- Distributed locks are unnecessary because the writes are single-shard and row-level.
7. Distributed consistency
Two-phase commit with external banks is not realistic. Use a saga with compensations:
| Step | Compensation |
|---|---|
| Authorization hold | Reversal / void |
| Capture | Refund |
| Settlement | Adjustment journal |
- The outbox guarantees every committed change is eventually published.
- Consumers are idempotent, deduplicating on event id.
- A sweeper drives transactions stuck in
PENDING_AUTHorAUTH_UNKNOWNto a terminal state. - Reconciliation: compare daily issuer and acquirer settlement files against the ledger, and route mismatches to suspense and a review queue.
8. Trade-offs and common mistakes
- Consistency vs availability: per-shard strong consistency is required for money. Cross-region, prefer a home region per merchant with failover and replay rather than multi-master writes.
- Mistakes to avoid: floats for money, treating a timeout as a decline, in-place edits of ledger rows, idempotency keys only in a cache, logging raw PANs, retrying without a stable bank reference, and allowing refunds above captured amounts.
- Observability: per-issuer approval rate, timeout rate, and latency dashboards, plus alerts when the ledger imbalance is nonzero (it should always be zero).