Design a Financial Platform with Transfers and Analytics
System DesignModel answerLast updated
Architect a core banking platform covering auth, accounts, ATM flows, intra- and inter-bank transfers, and time-windowed transaction analytics.
The Problem
You are tasked with designing the backend infrastructure for a retail banking platform. The platform needs to handle the full lifecycle of customer money movement, from day-to-day account access to cross-bank wire transfers.
Your design must support all of the following capabilities:
- Authenticated access — users log in securely, with a second verification step.
- Account creation — customers can open new accounts, which involves identity verification.
- ATM operations — cash deposits and withdrawals via ATM terminals.
- Internal transfers — moving money between accounts held at the same institution.
- External transfers — sending and receiving funds through interbank payment networks.
- Transaction analytics — querying aggregate statistics (totals, counts, breakdowns) over any user-specified time range.
What to Cover
Walk through each of the following areas. You do not need equal depth on every point, but you should touch all of them and go deep where the interviewer probes.
Architecture and services Identify the major services and how they communicate. Which boundaries are synchronous vs. asynchronous? What are the core data stores?
Data modeling Design the schemas for accounts, balances, transactions, and audit records. Explain how you represent money, why your schema prevents balance corruption, and how you support long-term auditability.
API design and idempotency Sketch the key endpoints. Explain how clients can safely retry any operation without risk of double-charging or duplicate transfers.
Concurrency and double-spend prevention How do you ensure two concurrent withdrawals cannot both succeed when only one has sufficient funds? What happens under high contention on a single account?
Consistency and recovery What consistency level do you target for balance writes? How does the system recover if a transfer fails midway through?
External network integration How do you integrate with ATM networks (which use ISO 8583 messaging) and interbank rails (ACH, wire, real-time payment networks)? How do you handle delayed settlement and returns?
Analytics How do you serve sub-second responses to time-window queries (e.g., "total outflows for account X between Jan 1 and Mar 31") at scale, without placing that query load on the transactional database?
Reliability and operations What are the key SLIs and SLOs? What do your dashboards, alerting rules, and on-call runbooks look like? How do you handle dependency failures gracefully?
Security Cover authentication, authorization, encryption in transit and at rest, and any compliance-driven controls (e.g., PCI-DSS, audit log integrity).
Constraints and Expectations
- The system serves roughly 20 million customers and 50 million accounts.
- Peak load is around 10,000 transactions per second; average is closer to 1,200 TPS.
- ATM authorization must complete end-to-end within 2 seconds; your internal budget is under 300 ms.
- Analytics queries over up to one year of data should return within 1 second.
- Transaction records must be retained and auditable for at least 7 years.
- Money must never be created or destroyed by a system fault — every cent must be accounted for at all times.
There is no single correct answer. The interviewer is evaluating how you reason about trade-offs, handle failure scenarios, and defend your choices under follow-up questions.
Hints
Hint 1
Start by separating the money-critical write path (balance mutation) from everything else. A single Ledger Service that is the only component allowed to write balances gives you one place to enforce all invariants — double-entry balance, idempotency, and audit — rather than spreading that logic across every caller.
Hint 2
Model transfers as state machines persisted to durable storage, not as in-memory orchestration. If the process crashes between the debit and the credit, the system needs to know exactly where it left off and what compensating action to take. Sagas with append-only compensation entries (never deletes or overwrites) are the standard pattern here.
Hint 3
For analytics, the key insight is that your OLTP database is the wrong tool for time-window aggregation at scale. Think about how to move data off the transactional path — a transactional outbox feeding Kafka, stream processing into a columnar store, and pre-aggregated rollup tables — so analytics queries never compete with balance writes.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify Scope and Scale First
Before drawing any boxes, nail down what "correctness" means for this system. The central constraint is that money is conserved: no transfer may create or destroy value, even under partial failure. Everything else — availability, latency, analytics — is secondary to that.
Back-of-envelope sizing
- 100M transactions/day ≈ 1,200 TPS average, 10K TPS peak.
- Each transaction produces at least two ledger entries at ~300 bytes each → ~60 GB/day of ledger data, ~22 TB/year.
- ATM auth must complete in under 300 ms internally to meet the 2-second end-to-end SLA.
- Analytics must return in under 1 second over up to 1 year of data — roughly 22 TB. That rules out ad-hoc scans on the OLTP database.
2. API Design and Idempotency
Every mutating endpoint requires an Idempotency-Key header (a client-generated UUID). The key is stored in the same database transaction as the business write, so there is no race between the write and the key record.
POST /v1/auth/login {username, password} → {mfa_challenge_id}
POST /v1/auth/verify {challenge_id, otp} → {access_token, refresh_token}
POST /v1/accounts {customer_id, type, currency} → {account_id}
POST /v1/transfers {from_account, to_account, amount, currency,
type: INTERNAL|ACH|WIRE|RTP}
→ {transfer_id, status: PENDING|POSTED|FAILED}
GET /v1/transfers/{id}
POST /internal/atm/authorize {card_token, atm_id, amount, stan} → {auth_code}
POST /internal/atm/complete {auth_code, dispense_confirmed}
GET /v1/accounts/{id}/stats ?from=&to=&granularity=day → {buckets[]}
The idempotency_keys table maps (client_id, key) to (request_hash, response, status). On retry: same hash → return stored response; different hash → 422 Unprocessable. ATM networks use (network_id, atm_id, STAN, transmission_date) as the natural composite key.
Common mistake: storing the idempotency key in a separate transaction from the business write. That creates a window where the write succeeded but the key was never recorded, so a retry causes a duplicate.
3. Data Model
The foundation is a double-entry, append-only ledger. Balances are computed from entries and cached in a balances row — they are never the source of truth, just a performance optimization.
-- Money amounts are always stored as integer minor units (cents). Never floats.
customers(customer_id, name_enc, ssn_token, kyc_status, created_at)
credentials(customer_id, pw_hash_argon2, mfa_secret_enc,
failed_attempts, locked_until)
accounts(account_id, customer_id, type, currency, status, created_at)
balances(account_id PK,
available BIGINT, -- ledger minus active holds
ledger BIGINT, -- sum of all settled entries
version BIGINT, -- optimistic lock
updated_at)
transactions(txn_id, idempotency_key UNIQUE, type, status,
amount, currency, initiator, external_ref,
created_at, posted_at)
ledger_entries(entry_id, txn_id, account_id,
direction ENUM('DR','CR'), amount BIGINT,
balance_after BIGINT, created_at)
-- INDEX(account_id, created_at)
holds(hold_id, account_id, amount, txn_id, expires_at, status)
audit_log(event_id, actor, action, resource,
before_hash, after_hash, ts, prev_hash) -- hash-chained
outbox(id, aggregate_id, event_type, payload, published BOOL)
Key invariant: for every transaction, SUM(DR entries) = SUM(CR entries). A database check constraint or a nightly reconciliation job enforces this. Any break pages the on-call team immediately.
The audit log is hash-chained (prev_hash covers the previous row), making retroactive tampering detectable. Records are also shipped to WORM storage (e.g., S3 Object Lock) for the 7-year retention requirement.
4. Architecture Overview
Clients / ATM Terminals
│
CDN / WAF / DDoS scrubbing
│
API Gateway (authn, rate limiting, mTLS for ATM/partner connections)
│
┌────┴──────────────────────────────────────────────┐
│ Identity Service (OAuth2/OIDC, MFA, risk scoring) │
│ Account Service (onboarding, KYC vendor, lifecycle)│
│ ATM Gateway (ISO 8583 ↔ internal, HSM PIN) │
│ Transfer Orchestrator (saga state machine) │
│ Ledger Service (SOLE writer of balances/entries) │
│ Payment Adapters (ACH/Nacha, Fedwire, RTP/FedNow) │
│ Fraud Service (synchronous scoring on writes) │
└───────────────────────────────────────────────────┘
│
Ledger DB: sharded Postgres/Aurora or Spanner/CockroachDB (shard by account_id)
│
Kafka (fed by transactional outbox)
│
Flink → ClickHouse/Druid (analytics, sub-second time-window queries)
Flink → Fraud feature store
Nightly → S3/Iceberg data lake (regulatory reporting)
The Ledger Service is the only component that writes to balances and ledger_entries. Everything else calls it. This concentrates invariant enforcement in one place.
5. Key Deep Dives
Double-spend prevention
BEGIN;
INSERT INTO idempotency_keys ...; -- unique constraint aborts on duplicate
SELECT available FROM balances
WHERE account_id = $1 FOR UPDATE; -- serialize concurrent debits
-- application check: available >= amount
INSERT INTO ledger_entries VALUES (DR $1, CR $2, ...);
UPDATE balances
SET available = available - $amt,
ledger = ledger - $amt,
version = version + 1
WHERE account_id = $1 AND version = $expected_version;
INSERT INTO outbox ...;
COMMIT;
To avoid deadlocks on multi-account transactions, always lock rows in ascending account_id order. For high-contention accounts (e.g., a GL clearing account receiving thousands of credits per second), split the account into N sub-accounts and aggregate on read — credits don't need to check balance, so they fan out freely.
Cross-shard and inter-bank transfers
Same shard: one ACID transaction, as above.
Cross-shard (intra-bank): use a saga. Debit source into an internal suspense account, then credit destination from suspense. Each step is idempotent and keyed by transfer_id. Compensation is a reversing ledger entry, never a delete. Money always sits in some account at every point, keeping the ledger balanced.
Inter-bank (ACH/Wire/RTP): modeled as a state machine: INITIATED → FUNDS_HELD → SUBMITTED → SETTLED | RETURNED. ACH is batched into Nacha files; returns (R01, R09, etc.) arrive days later and trigger compensating entries. Fedwire and RTP/FedNow are near-real-time and final on acknowledgment. A daily reconciliation job matches settlement files against the ledger; any discrepancy pages finance ops.
ATM flow
- Authorization: translate ISO 8583 to internal format, verify PIN in the HSM, place a hold on
availablebalance. Response must arrive in under 300 ms. - Completion: dispenser confirmation promotes the hold to a settled debit entry.
- Stand-in: if the core is unreachable, the ATM Gateway can authorize up to a configured limit using cached balance snapshots, then reconcile on reconnect.
- Reversal: if the dispenser jams after auth, the hold expires automatically (TTL-based) or is explicitly released via a reversal message.
Analytics
The OLTP database cannot handle time-window aggregation at scale without impacting write latency. The approach:
- Every committed transaction publishes an event via the transactional outbox to Kafka.
- Flink consumes the stream and writes pre-aggregated rollups (hourly, daily) into ClickHouse, partitioned by
(account_id, date). - The
GET /v1/accounts/{id}/statsendpoint queries ClickHouse, not the ledger DB. For granular windows, it stitches pre-aggregated buckets and adds a small real-time tail from a Redis counter.
This keeps analytics query latency under 1 second for year-long windows while isolating OLTP from analytical load.
6. Reliability and Operations
SLOs
- ATM auth success rate: 99.99% (4 nines); p99 latency < 300 ms.
- Transfer posting: 99.95%; p99 < 2 s.
- Analytics queries: 99.9%; p99 < 1 s.
Alerting rules
- Ledger imbalance detected by reconciliation → PagerDuty P0 immediately.
- ATM auth error rate > 0.1% over 5 minutes → P1.
- Outbox lag > 30 seconds → P2 (risk of analytics staleness).
- Failed login spike (10× baseline) → security team alert.
Runbooks should cover: payment network adapter outage (fail open with holds, batch on reconnect), shard failover (promote read replica, replay outbox), HSM unreachable (fail closed on ATM PIN, not stand-in), and reconciliation break (freeze affected accounts, notify compliance).
7. Security Controls
- Passwords hashed with Argon2id; MFA via TOTP or push notification.
- All inter-service calls use mTLS; ATM/partner connections use dedicated mTLS with certificate pinning.
- PII (SSN, name) encrypted at rest with envelope encryption (KMS-managed keys); only tokenized references stored in most tables.
- Card PINs never touch application memory — verified in an HSM directly.
- RBAC on all internal APIs; operations staff cannot modify ledger entries directly, only trigger compensating transactions through the Ledger Service.
- Audit log shipped to WORM storage; hash chain makes tampering detectable.
Common Mistakes to Avoid
- Storing amounts as floats. Floating-point arithmetic is non-associative. Always use integers (cents) or a fixed-point type.
- Updating the balance row without a ledger entry. The balance row is a cache. Mutating it without a corresponding entry destroys auditability and makes reconciliation impossible.
- Synchronous calls to external payment networks on the hot path. ACH and wire are asynchronous by nature. Treating them as synchronous causes timeouts, retries, and duplicate submissions.
- Skipping idempotency on compensation. Saga compensating steps can also be retried. They need their own idempotency keys, not just the original transaction key.