Real-Time Payment Authorization Platform with Encrypted User Vault
System DesignModel answerLast updated
Build the issuer backend that decides approve/decline for card transactions in under 200ms, handles settlement flows, and securely isolates sensitive cardholder information.
You work for a financial institution that provides credit cards to consumers. When someone uses their card at a store, the transaction flows through payment networks to your system, which must respond with an authorization decision before a tight network deadline expires. Later, finalized transaction details arrive and must be reconciled against the cardholder's account balance. The platform must also protect customer identity information from exposure.
What you need to handle
- Evaluate incoming payment requests using card validity, spending limits, and risk signals to produce approve/decline responses.
- Handle authorization adjustments: complete cancellations, partial refunds, and time-limited holds that expire if not finalized.
- Reconcile finalized transactions into permanent account records and produce billing statements each month.
- Provide customers real-time visibility into pending and completed transactions, plus the ability to temporarily disable their card.
- Securely store sensitive customer details: legal name, home address, birth date, government identification numbers, financial information, and card credentials.
Scale and performance constraints
Propose realistic targets and justify them. As a starting point:
- Customer base: 30 million active accounts
- Daily transaction volume: 25 million payments on typical days
- Peak load: approximately 4,000 authorization requests per second during high-traffic periods
- Response time: the payment network allows roughly 1-2 seconds total round-trip; your platform should consume well under 200 milliseconds
- Correctness: two simultaneous purchases on one account must never both succeed if together they exceed the credit limit
- Uptime: target four nines (99.99%) for authorization availability
- Security: if an attacker steals a database backup, they must not be able to read card numbers or identity documents in plaintext
What to deliver
Part 1: System architecture, data models, and how a transaction moves from initial authorization through final posting to the account.
Part 2: Latency breakdown for authorization. What p99 latency can you commit to, where does the time budget get spent, and how do you maintain performance during traffic spikes and partial infrastructure failures?
Part 3: Strategy for storing and accessing sensitive customer data: encryption techniques, tokenization patterns, key custody, permission boundaries, audit trails, and data deletion.
Identify trade-offs explicitly. Address failure scenarios: fraud detection service becomes slow, primary database fails over, duplicate messages arrive from the network. Suggest which capabilities to implement first.
Hints
Hint 1
Think about the concurrency challenge: how do you prevent two near-simultaneous transactions from both approving when the account only has room for one?
Hint 2
Authorization must be fast, so consider what data needs to be co-located or cached versus what can be computed asynchronously.
Hint 3
For the vault, consider the principle of least privilege: which services genuinely need access to plaintext sensitive data versus which can operate on opaque references?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Part 1: Architecture and transaction flow
Core components
Gateway layer: Receives payment network messages, enforces protocol constraints, tracks message identifiers to detect retransmissions, and applies timeout policies. Idempotency is critical—replayed messages must return the original decision without re-executing logic.
Authorization engine: Stateless service instances that orchestrate decision logic. Horizontally scalable; route requests by account identifier for cache affinity when possible.
Account state database: Maintains per-account spending capacity (credit_limit, available_balance, account_status), authorization holds, and card settings. Must support atomic operations to prevent race conditions. Partition by account ID for horizontal scale.
Risk evaluation service: Runs fraud detection models using recently computed features (transaction velocity, merchant patterns, geographic anomalies, device signals). Designed for low-latency inference with fallback rules.
Card preference store: Per-card controls like temporary freezes, merchant category restrictions, and travel notices. Co-located with account data or aggressively cached.
Settlement processor: Batch job that ingests finalized transaction files from networks, matches them to pending holds, writes immutable ledger records, and adjusts holds for differences (like tip amounts or foreign exchange).
Transaction ledger: Append-only store of all posted transactions. Source of truth for statement generation and balance calculations.
Customer API: Powers mobile and web applications with real-time views of pending and posted activity, control settings, and statement access.
Identity vault: Isolated service discussed in Part 3.
Data schema (simplified)
accounts:
account_id (partition key)
credit_limit
available_balance
status (active, suspended, closed)
optimistic_lock_version
cards:
card_token (not the actual PAN)
account_id
status
expiration_date
control_flags
authorization_holds:
hold_id
account_id
network_transaction_id (for idempotency)
amount
merchant_info
state (pending, reversed, settled, expired)
expiration_timestamp
ledger_transactions:
transaction_id
account_id
entry_type
amount
linked_hold_id
posting_timestamp
Transaction lifecycle
-
Arrival: Gateway extracts the card number, merchant details, amount. Checks
network_transaction_idfor duplicates—if seen before, immediately return cached result. -
Lookup: Map card number to
card_token(via hash index in vault), then token to card record and account record. This step uses cached or partitioned reads for speed. -
Parallel checks: Simultaneously fetch fraud score and validate card controls. Set strict timeouts—if fraud service is slow, apply simple rules (approve small amounts under velocity thresholds, decline suspicious patterns).
-
Credit reservation: Execute atomic operation:
UPDATE accounts SET available_balance = available_balance - $amount WHERE account_id = $id AND available_balance >= $amount. If zero rows updated, insufficient funds—decline. This single-row conditional write is the critical concurrency control that prevents double-spending even when two transactions arrive microseconds apart. -
Record and respond: Insert hold record, emit async event (for notifications, analytics), return approval to gateway.
-
Settlement (hours or days later): Match incoming cleared transaction by
network_transaction_id, create immutable ledger entry, mark hold as settled. Handle amount mismatches (tips added after auth). Release any unsettled holds past their expiration window via periodic sweeper. -
Statement generation: Monthly job aggregates ledger entries, computes interest and fees, delivers to customer channels.
Part 2: Authorization latency budget
Networks typically allow 1-2 seconds end-to-end, but that includes multiple network hops and processing at intermediaries. A well-designed issuer platform targets p99 authorization latency under 100-150 milliseconds measured at service boundaries, leaving substantial margin for network delays and retry attempts.
Sample budget breakdown
| Operation | Target latency |
|---|---|
| Gateway message parse and deduplication | 5 ms |
| Card and account lookup (cache hit or single partition) | 10 ms |
| Fraud model inference (parallel with lookups) | 30 ms |
| Atomic balance update (single-region write) | 15 ms |
| Hold record insertion and response assembly | 10 ms |
| Buffer for variance | 30-80 ms |
Techniques to hit targets
Regional architecture: Keep authorization-path components in a single cloud region to minimize network latency. Each account has a home region; cross-region replication is asynchronous for disaster recovery only, not used for live authorization.
Parallelization: Start fraud scoring while fetching account data. Never wait for sequential dependencies that could run concurrently.
Timeouts with fallback: If the fraud service exceeds its SLA (say 50ms), apply rule-based heuristics: approve transactions under $50 at known merchants, decline international transactions without travel notice, approve others with step-up verification later. This trades a small increase in fraud risk for availability.
Caching: Maintain in-memory caches of card-to-account mappings and card control flags with short TTLs (seconds). Cache invalidation on writes ensures consistency without adding read latency.
Hot account handling: Accounts with extremely high transaction rates (corporate cards, shared accounts) can be routed to dedicated partition owners with optimistic locking or single-threaded queues to avoid lock contention in the database.
Capacity planning: Provision for 2-3× observed peak load. Use autoscaling based on CPU and request queue depth, with pre-warmed standby capacity during known high-traffic windows (holidays, major sales events).
Stand-in processing: Payment networks offer a fallback mode where they approve transactions under preset limits if the issuer becomes unreachable. This caps blast radius during total outages but requires careful reconciliation afterward.
Failure mode handling
- Fraud service degraded: Apply simplified rules, log decisions for retroactive review, alert fraud team for manual follow-up on high-risk approvals.
- Database primary failure: Automatic failover to replica (brief read-only window or elevated latency); if extended, activate stand-in processing.
- Duplicate network messages: Idempotency via
network_transaction_idprevents double-charging; return original decision instantly.
Part 3: Sensitive data protection
Tokenization architecture
The actual card number (PAN) and government ID never leave a dedicated vault service. Every other system stores opaque tokens. The vault exposes minimal APIs: create_token(plaintext) → token, retrieve_plaintext(token, justification) → plaintext. Rate limits, strict access control, and separate network segment isolate this component.
On the authorization path, you receive a PAN from the network but only need to look up the account—use a keyed hash index (PAN hashed with a secret → token) to avoid calling retrieve_plaintext on the hot path.
Encryption layers
Envelope encryption: Each sensitive record encrypted with a unique data encryption key (DEK). DEKs are themselves encrypted by a master key stored in a hardware security module (HSM) or cloud KMS. Regular key rotation; compromised backups are useless without access to the KMS.
Field-level encryption: Customer profile fields (birth date, income, address) encrypted individually in application databases, independent of storage-level encryption. Enables selective decryption (e.g., show name and last 4 of address, keep full address encrypted).
Transport security: mTLS between all internal services; TLS 1.3 for external connections.
Access control and audit
Principle of least privilege: Authorization engine never decrypts PAN or national ID—it only needs the token. Support tools show masked values (last 4 digits) by default. Full decryption requires just-in-time approval from a security team member, logged with business justification.
Immutable audit log: Every retrieve_plaintext call writes a tamper-proof record: caller identity, timestamp, purpose code, request trace ID. Anomaly detection alerts on unusual access patterns (volume spikes, after-hours access, access to VIP accounts).
Human access: Support staff use break-glass procedures for emergency account access, automatically triggering review workflows.
Data minimization and lifecycle
- Never persist CVV after authorization completes (regulatory requirement).
- Tokenize PAN immediately upon card issuance; only vault stores plaintext.
- Crypto-shredding: when a customer closes their account and retention period expires, destroy the DEK rather than overwriting every encrypted field—instant, verifiable data destruction.
Trade-offs
Vault adds latency: Mitigated by avoiding vault calls on the hot path (use hash-based token lookup) and caching card-to-account mappings.
Operational complexity: Separate vault infrastructure, key rotation procedures, access approval workflows increase operational burden. Justified by dramatically reducing compliance scope—most services never touch regulated data.
Availability vs. security: If the vault is unavailable, card issuance and customer profile updates fail, but authorizations continue using cached mappings. Accept brief degraded experience for non-authorization workflows rather than centralizing all data.
Implementation priority
- Core authorization flow with idempotency, atomic balance checks, and basic fraud rules—this is the revenue-critical path.
- Settlement and ledger posting—without this, you can't bill customers.
- Vault and tokenization—required for regulatory compliance before launch.
- Customer API and card controls—differentiation and customer experience.
- Advanced fraud models and iterative latency optimization—iterate post-launch based on observed patterns.
Common mistakes: over-engineering fraud detection before proving the core flow works, neglecting idempotency (leads to duplicate charges), underestimating the concurrency challenge on credit checks, treating encryption as an afterthought rather than foundational.