Case Study 15 โ€” Payment & Wallet System (Simplified)

Design a simplified digital wallet and payment system like a lightweight PayPal/Venmo โ€” users hold balance, send money, pay merchants, with strong correctness and auditability.

1. Problem

Users can top up a wallet, transfer money to other users or merchants, and view transaction history. The system must never lose or duplicate money, even under retries, crashes, or concurrent transfers.

2. Requirements

Functional (MVP)

  • Register user and create wallet with balance
  • Add money via external payment method (card/bank)
  • Transfer (P2P) to another user by username/phone
  • Pay merchant for an order (integrate with checkout)
  • Withdraw to linked bank account (async settlement)
  • Transaction history with status
  • Idempotent API โ€” client retries must not double-charge
  • Basic fraud checks (velocity limits, max single transfer)

Out of scope (initially)

  • Multi-currency FX
  • Credit/lending
  • Cryptocurrency
  • Full KYC/AML compliance pipeline (mention hooks only)
  • Chargebacks/dispute workflow (complex; note as follow-up)
  • Interest on balance

Non-functional

  • ACID correctness โ€” money conservation: sum of balances + external = constant
  • Strong consistency for balance updates (not eventual for ledger)
  • Durability โ€” no lost transactions after ACK
  • Audit trail โ€” append-only ledger, reconcilable with bank
  • High availability for reads; writes can use careful locking
  • PCI scope minimized โ€” card data tokenized at payment gateway

3. Back-of-the-envelope estimates

These numbers are rough order-of-magnitude math โ€” not a capacity plan. In interviews, the goal is to show you know what to count and which resource breaks first. A useful shortcut: 1 QPS sustained โ‰ˆ 86,400 operations/day. Payment systems have moderate QPS compared to social feeds, but zero tolerance for correctness errors โ€” one duplicate credit is worse than a slow response.

Why we estimate

Wallet systems are ledger-first. Estimates tell us:

  • Transaction volume is low enough for single Postgres early on
  • Ledger row growth drives partitioning strategy (by month)
  • Read QPS (balance checks, history) exceeds writes โ€” but writes need strong consistency
  • Only ~20% of txns hit external payment gateway โ€” most are internal transfers

Assumptions

AssumptionValueWhy it matters
Wallets50MOne per user
Transactions per day10M (transfers + merchant pay + top-ups)Write volume
Average transaction$25Business context (not storage)
Ledger entries per txn2 (debit + credit)Double-entry bookkeeping
Read:write ratio (balance/history)5:1Read scaling
Top-ups share of txns~20%External gateway load
Row size (ledger entry)~200 BStorage math

Step A โ€” Traffic (QPS) with labeled arithmetic

Transaction write QPS:

Transactions/day    = 10,000,000

Average write QPS   = 10,000,000 รท 86,400
                    โ‰ˆ 116 transactions/second
                    โ‰ˆ 115/s (round)

Peak write QPS (rough 4โ€“5ร— for pay-day spikes):

Peak write QPS โ‰ˆ 115 ร— 4 โ‰ˆ 460โ€“500/s

Balance / history read QPS:

Read QPS (avg)  = 115 ร— 5 โ‰ˆ 575/s
Read QPS (peak) = 500 ร— 5 โ‰ˆ 2,500/s

External payment gateway calls (top-ups only):

Top-up fraction    = 20%
Top-up QPS (avg)   = 115 ร— 20% โ‰ˆ 23/s
Top-up QPS (peak)  = 500 ร— 20% โ‰ˆ 100/s

Internal P2P and merchant payments never leave your ledger โ€” no Stripe call.

Step B โ€” Storage

Ledger entries per year:

Txns/day            = 10M
Entries per txn     = 2 (debit + credit)

Entries/day         = 10M ร— 2 = 20M entries/day
Entries/year        = 20M ร— 365 โ‰ˆ 7.3 billion rows/year

Disk per year:

Row size            โ‰ˆ 200 B
Raw data/year       = 7.3B ร— 200 B โ‰ˆ 1.46 TB/year
With indexes        โ‰ˆ 2 TB/year โ†’ partition by month, archive old partitions

Wallet table:

50M wallets ร— ~100 B โ‰ˆ 5 GB โ€” tiny; balance reads are cheap with proper indexes

Step C โ€” Bandwidth / other

API payload size:

Transfer request/response โ‰ˆ 500 Bโ€“1 KB โ€” bandwidth is negligible

Reconciliation (daily batch):

Compare ~2M top-up/withdraw rows/day against gateway settlement CSV
Batch job, not real-time โ€” runs off-peak

Fraud velocity counters (Redis):

One INCR per txn per wallet per day โ†’ 10M keys/day with TTL
Memory โ‰ˆ hundreds of MB โ€” trivial

Step D โ€” Read:write ratio table

OperationTypePeak QPSConsistency
P2P transfer / merchant payWrite~400/sStrong (ACID)
Top-up / withdrawWrite~100/s externalStrong + async settlement
Get balanceRead~2,500/sStrong (same txn as write)
Transaction historyRead~2,500/sOK from replica
Idempotency checkRead~500/sMust be exact
Reconciliation jobBatch readNightlyCompares ledger vs gateway

Ratio: 5:1 read:write โ€” use read replicas for history; writes stay on primary with row locks.

What the numbers tell us

  • 115โ€“500 txn/s fits single Postgres for years โ€” sharding by user_id is a later problem
  • Double-entry ledger (~7.3B rows/year) โ†’ immutable append-only entries; partition monthly
  • Never "read balance, write balance" without locking โ€” use SELECT FOR UPDATE in same transaction
  • Idempotency keys on every mutating API โ€” client retries are guaranteed at scale
  • Top-ups (~23/s avg) go to Stripe; internal transfers stay in DB โ€” different failure modes
  • Withdrawals are async โ€” debit ledger immediately, settle to bank via queue (1โ€“3 days)
  • Reconciliation job catches orphan gateway charges after crashes

Common mistake for this problem

Updating a balance_cents column without a ledger entry, or doing read-modify-write without row locks. Interviewers want double-entry + single DB transaction + idempotency. Another mistake: treating wallet balance as eventually consistent โ€” money requires strong consistency on writes.

4. High-Level Design (HLD)

Components

ComponentRole
Wallet ServiceCreate wallet, get balance, list transactions
Transfer ServiceP2P and merchant payments between wallets
Payment ServiceTop-up from card, withdraw to bank via gateway
Ledger DBSource of truth โ€” accounts, entries, balances
Payment GatewayStripe/Adyen โ€” tokenized cards, ACH
Fraud ServiceRate limits, blocklists, anomaly flags
ReconciliationDaily match internal vs external settlement
Settlement QueueAsync bank payouts (withdrawals)

Flows

Top-up (add money)

  1. User: POST /wallet/topup with amount, paymentMethodId, idempotency key
  2. Payment Service creates PENDING transaction
  3. Charge gateway โ†’ on success, credit wallet in ledger (single DB txn)
  4. Return updated balance

P2P transfer

  1. User A sends $50 to User B
  2. Fraud check velocity
  3. Single DB transaction: debit A, credit B, insert transfer record
  4. Notify both users (async notification system)

Pay merchant

  1. Checkout calls POST /payments with orderId, amount, merchantWalletId, idempotency key
  2. Debit buyer wallet, credit merchant wallet (minus platform fee optional)
  3. Link orderId on transaction for refunds later

Withdraw

  1. User requests withdrawal โ†’ debit wallet immediately (hold funds)
  2. Enqueue settlement job โ†’ ACH to bank (1โ€“3 days)
  3. On bank confirm: mark COMPLETED; on fail: reverse ledger entry

Trade-offs

ChoiceProsCons
Balance column vs compute from ledgerColumn fast to readDrift risk โ€” use ledger + cached balance updated in same txn
Postgres vs distributed DBACID, familiarVertical scale limits โ€” shard by user_id later
Sync withdrawSimple UXBank is slow โ€” async queue standard
Pessimistic vs optimistic lockingPessimistic safe for moneyContention on hot wallets โ€” optimistic with retry
Single ledger vs event sourcingDouble-entry simpler to explainEvent sourcing great audit โ€” more complexity

Golden rule: Never update balance without a matching ledger entry in the same transaction.

5. Low-Level Design (LLD)

APIs

POST /api/v1/wallets
Body: { userId, currency: "USD" }
โ†’ 201 { walletId, balance: 0 }

GET /api/v1/wallets/:walletId/balance
โ†’ { walletId, balance: "125.50", currency: "USD", asOf: "..." }

POST /api/v1/wallet/topup
Headers: Idempotency-Key: topup-uuid-1
Body: { walletId, amount: "100.00", paymentMethodId: "pm_xxx" }
โ†’ 200 { transactionId, status: "COMPLETED", newBalance: "225.50" }
โ†’ 402 { status: "FAILED", reason: "CARD_DECLINED" }

POST /api/v1/transfers
Headers: Idempotency-Key: xfer-uuid-2
Body: { fromWalletId, toWalletId, amount: "50.00", note: "dinner" }
โ†’ 200 { transferId, status: "COMPLETED" }
โ†’ 409 { error: "INSUFFICIENT_FUNDS" }

POST /api/v1/payments
Headers: Idempotency-Key: pay-order-789
Body: { payerWalletId, merchantWalletId, amount: "49.99", orderId: "ord-789" }
โ†’ 200 { paymentId, status: "COMPLETED" }

POST /api/v1/wallet/withdraw
Headers: Idempotency-Key: wd-uuid-3
Body: { walletId, amount: "200.00", bankAccountId: "ba_xxx" }
โ†’ 202 { withdrawalId, status: "PENDING_SETTLEMENT" }

GET /api/v1/wallets/:walletId/transactions?cursor=...
โ†’ { transactions: [{ id, type, amount, counterparty, status, createdAt }] }

Use string decimal amounts in API ("49.99") โ€” never float.

Schema

wallets (
  wallet_id       UUID PRIMARY KEY,
  user_id         UUID NOT NULL UNIQUE,
  currency        CHAR(3) DEFAULT 'USD',
  balance_cents   BIGINT NOT NULL DEFAULT 0 CHECK (balance_cents >= 0),
  version         INT NOT NULL DEFAULT 0,  -- optimistic locking
  status          VARCHAR(20) DEFAULT 'ACTIVE',
  created_at      TIMESTAMPTZ NOT NULL
)

ledger_entries (
  entry_id        UUID PRIMARY KEY,
  transaction_id  UUID NOT NULL,
  wallet_id       UUID NOT NULL REFERENCES wallets,
  direction       CHAR(6) NOT NULL,  -- DEBIT or CREDIT
  amount_cents    BIGINT NOT NULL CHECK (amount_cents > 0),
  balance_after   BIGINT NOT NULL,
  entry_type      VARCHAR(30),  -- TOPUP, TRANSFER, PAYMENT, WITHDRAW, FEE, REVERSAL
  created_at      TIMESTAMPTZ NOT NULL
)

transactions (
  transaction_id  UUID PRIMARY KEY,
  idempotency_key VARCHAR(128) UNIQUE NOT NULL,
  type            VARCHAR(30) NOT NULL,
  status          VARCHAR(20) NOT NULL,  -- PENDING, COMPLETED, FAILED, REVERSED
  metadata        JSONB,  -- orderId, gatewayRef, counterpartyWalletId
  created_at      TIMESTAMPTZ NOT NULL,
  completed_at    TIMESTAMPTZ
)

transfers (
  transfer_id     UUID PRIMARY KEY,
  transaction_id  UUID UNIQUE REFERENCES transactions,
  from_wallet_id  UUID NOT NULL,
  to_wallet_id    UUID NOT NULL,
  amount_cents    BIGINT NOT NULL
)

withdrawals (
  withdrawal_id   UUID PRIMARY KEY,
  transaction_id  UUID UNIQUE,
  wallet_id       UUID NOT NULL,
  amount_cents    BIGINT NOT NULL,
  bank_account_id TEXT NOT NULL,
  settlement_status VARCHAR(20),  -- PENDING, SENT, COMPLETED, FAILED
  gateway_payout_id TEXT
)

-- Platform float account for money entering/leaving system
system_accounts (
  account_code    VARCHAR(30) PRIMARY KEY,  -- EXTERNAL_IN, EXTERNAL_OUT, FEES
  wallet_id       UUID  -- optional linked wallet for accounting
)

Index: (wallet_id, created_at DESC) on ledger_entries for history.

Modules

WalletController / WalletService / BalanceReader
TransferController / TransferService
PaymentController / TopupService / WithdrawService
LedgerService / DoubleEntryBookkeeper
IdempotencyMiddleware / TransactionRepository
GatewayClient / SettlementWorker
FraudService / VelocityLimiter
ReconciliationJob

Key algorithm โ€” idempotent request handling

function withIdempotency(idempotencyKey, operation):
  existing = transactions.findByKey(idempotencyKey)
  if existing:
    return existing.responseSnapshot  # same result as first call

  result = operation()
  transactions.save(idempotencyKey, result, COMPLETED)
  return result

Store full response body on first success so retries are bit-identical.

Key algorithm โ€” P2P transfer (double-entry)

function transfer(fromWalletId, toWalletId, amountCents, idempotencyKey):
  return withIdempotency(idempotencyKey, lambda:
    if fromWalletId == toWalletId: fail INVALID
    if amountCents <= 0: fail INVALID
    fraud.check(fromWalletId, amountCents)

    begin transaction
      txnId = uuid()

      fromW = repo.selectWalletForUpdate(fromWalletId)
      toW   = repo.selectWalletForUpdate(toWalletId)

      if fromW.balance_cents < amountCents:
        rollback; return INSUFFICIENT_FUNDS

      newFromBalance = fromW.balance_cents - amountCents
      newToBalance   = toW.balance_cents + amountCents

      repo.updateWallet(fromWalletId, newFromBalance, fromW.version)
      repo.updateWallet(toWalletId, newToBalance, toW.version)

      repo.insertLedger(txnId, fromWalletId, DEBIT,  amountCents, newFromBalance, TRANSFER)
      repo.insertLedger(txnId, toWalletId,   CREDIT, amountCents, newToBalance,   TRANSFER)
      repo.insertTransfer(txnId, fromWalletId, toWalletId, amountCents)
      repo.insertTransaction(txnId, idempotencyKey, TRANSFER, COMPLETED)
    commit

    notifyAsync(fromWalletId, toWalletId, txnId)
    return { transferId: txnId, status: COMPLETED }
  )

Lock ordering: Always lock wallets in sorted wallet_id order to prevent deadlocks on circular transfers.

Key algorithm โ€” top-up with external gateway

function topup(walletId, amountCents, paymentMethodId, idempotencyKey):
  return withIdempotency(idempotencyKey, lambda:
    begin transaction
      txnId = uuid()
      repo.insertTransaction(txnId, idempotencyKey, TOPUP, PENDING)
    commit

    charge = gateway.charge(paymentMethodId, amountCents, idempotencyKey)

    if charge.failed:
      repo.updateTransaction(txnId, FAILED)
      return charge.error

    begin transaction
      w = repo.selectWalletForUpdate(walletId)
      newBalance = w.balance_cents + amountCents
      repo.updateWallet(walletId, newBalance, w.version)
      repo.insertLedger(txnId, walletId, CREDIT, amountCents, newBalance, TOPUP)
      repo.insertLedger(txnId, SYSTEM_EXTERNAL_IN, DEBIT, amountCents, ..., TOPUP)
      repo.updateTransaction(txnId, COMPLETED, metadata={ gatewayRef: charge.id })
    commit

    return { transactionId: txnId, newBalance }
  )

If crash after charge succeeds but before credit: reconciliation job finds orphan gateway charge and completes credit.

Key algorithm โ€” withdrawal with settlement

function withdraw(walletId, amountCents, bankAccountId, idempotencyKey):
  return withIdempotency(idempotencyKey, lambda:
    begin transaction
      w = repo.selectWalletForUpdate(walletId)
      if w.balance_cents < amountCents: return INSUFFICIENT_FUNDS
      newBalance = w.balance_cents - amountCents
      repo.updateWallet(walletId, newBalance, w.version)
      txnId = uuid()
      repo.insertLedger(txnId, walletId, DEBIT, amountCents, newBalance, WITHDRAW)
      repo.insertWithdrawal(txnId, walletId, amountCents, bankAccountId, PENDING)
      repo.insertTransaction(txnId, idempotencyKey, WITHDRAW, PENDING)
    commit

    settlementQueue.push({ withdrawalId, txnId, bankAccountId, amountCents })
    return { withdrawalId, status: PENDING_SETTLEMENT }
  )

function settlementWorker(job):
  payout = gateway.createPayout(job.bankAccountId, job.amountCents, job.idempotencyKey)
  if payout.success:
    repo.updateWithdrawal(job.withdrawalId, COMPLETED, payout.id)
    repo.updateTransaction(job.txnId, COMPLETED)
  else:
    reverseWithdrawal(job.txnId)  # credit wallet back, REVERSAL entries

Concurrency & correctness

RiskMitigation
Double top-up on retryIdempotency key passed to gateway + DB unique constraint
Lost update on balanceSELECT FOR UPDATE or optimistic version check
Deadlock Aโ†’B and Bโ†’ALock wallets in deterministic order
Negative balanceCHECK constraint + debit only inside locked transaction
Orphan gateway chargeReconciliation cron matches unsettled charges
Hot merchant walletShard not needed until extreme; serial writes acceptable with lock

Invariant (interview gold): Sum of all user balances + system accounts = total money in system. Every transaction has balanced debits and credits.

Fraud / limits (Redis)

key = velocity:{walletId}:{YYYYMMDD}
INCR key
EXPIRE key 86400
if value > DAILY_LIMIT: reject

if amountCents > SINGLE_TXN_MAX: reject

6. Scale evolution

StageChange
MVPSingle Postgres, monolith, Stripe for top-up/withdraw
500 tx/sRead replicas for history; connection pooling
ShardingShard wallets by hash(user_id); cross-shard transfers via escrow account (hard)
Multi-regionSingle primary for ledger (avoid split-brain); or CRDT not suitable for money
Event sourcingAppend-only event log + projections for audit-heavy regulators

Cross-shard transfers are hard โ€” prefer single-shard wallet per user or two-phase commit with saga + compensation.

7. Recap

  • Money systems are ledger-first: double-entry, immutable entries, balance updated atomically
  • Idempotency keys everywhere โ€” clients, gateway, and internal txn table
  • Use DB transactions + row locks, not "read balance then write" without locking
  • Withdrawals are async; always plan reconciliation and reversal paths

Practice: Write double-entry pseudocode for a $50 P2P transfer. Explain what happens if the app crashes after Stripe charges but before wallet credit.