Building a Digital Wallet Transfer Service
System DesignModel answerLast updated
Design a system that enables users to transfer funds between accounts with correct balances, handling failures, retries, and concurrent operations.
You're building a digital wallet service where users maintain balances and transfer funds to each other. Your system must guarantee that every dollar is accounted for correctly, even when servers crash, requests time out, or multiple operations happen simultaneously.
Your design should handle:
- Users creating accounts and checking their current balance
- Initiating fund transfers between two users
- Viewing a complete transaction history
- Surviving system failures without losing or duplicating money
- Handling retried requests that may arrive multiple times
- Processing simultaneous transfers from the same account
What to Design
Provide a complete architecture including:
- API contracts for the key operations
- Data models for accounts, transactions, and balance tracking
- State management for transfers as they progress
- Correctness guarantees preventing money creation or loss
- Concurrency control for simultaneous operations
- Failure handling and system recovery mechanisms
- Production considerations beyond a simple in-memory prototype
Assumptions
- Single currency system for now
- Transfers must be exact: no money appears or vanishes
- Network issues cause clients and background jobs to retry operations
- Multiple transfers can be initiated from one account at the same time
- Bank integration and funding sources are handled elsewhere
Questions to Consider
- Should transfers complete instantly or go through approval stages?
- Can recipients use incoming funds before they finalize?
- How do you distinguish between available funds and funds in flight?
- What fraud prevention and compliance features are needed?
Hints
Hint 1
Think about immutable records - once money moves, keep a permanent log rather than just updating numbers
Hint 2
Consider how you'll make transfer creation idempotent so retries don't create duplicate transactions
Hint 3
Design for pessimistic locking or optimistic versioning to prevent overdrafts when concurrent transfers attempt to spend the same balance
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Core Architecture Principles
The foundation of any financial system is conservation of value and auditability. Money cannot be created, destroyed, or lost during failures. Every operation must be traceable.
API Design
POST /accounts
→ {accountId, initialBalance}
POST /transfers
body: {idempotencyKey, fromAccount, toAccount, amount, metadata}
→ {transferId, status, timestamp}
GET /transfers/{transferId}
→ {transferId, status, from, to, amount, created, updated}
GET /accounts/{accountId}/balance
→ {available, pending, total}
GET /accounts/{accountId}/transactions
→ [{transferId, type, amount, counterparty, timestamp}]
The idempotency key in transfer creation is critical—clients provide a unique key per intended transfer, and submitting the same key multiple times returns the same transfer without creating duplicates.
Data Model: Double-Entry Ledger
Rather than directly updating account balances, use an append-only ledger of entries:
Transfers table:
- transfer_id (primary key)
- idempotency_key (unique index)
- from_account_id
- to_account_id
- amount
- status (pending, completed, failed)
- created_at
- updated_at
Ledger_Entries table:
- entry_id (primary key)
- transfer_id (foreign key)
- account_id (indexed)
- amount (positive = credit, negative = debit)
- balance_after
- created_at
Accounts table:
- account_id (primary key)
- balance_version (for optimistic locking)
- available_balance
- updated_at
Each transfer creates two ledger entries: one debit (negative) for the sender and one credit (positive) for the recipient. This immutable log provides complete audit history.
Transfer State Machine
A transfer progresses through clearly defined states:
- Pending: Created but not yet processed
- Completed: Both debit and credit recorded, funds moved
- Failed: Rejected due to insufficient funds or validation failure
For more complex systems, add intermediate states like reserved (funds held), approved (passed review), or settling (awaiting external confirmation).
Ensuring Atomicity
The debit and credit must succeed or fail together. Use a database transaction:
BEGIN TRANSACTION;
-- Check sufficient balance
SELECT available_balance FROM accounts
WHERE account_id = :from_id FOR UPDATE;
-- Create ledger entries
INSERT INTO ledger_entries
(transfer_id, account_id, amount)
VALUES
(:transfer_id, :from_id, -:amount),
(:transfer_id, :to_id, +:amount);
-- Update account balances
UPDATE accounts SET available_balance = available_balance - :amount
WHERE account_id = :from_id;
UPDATE accounts SET available_balance = available_balance + :amount
WHERE account_id = :to_id;
-- Mark transfer complete
UPDATE transfers SET status = 'completed'
WHERE transfer_id = :transfer_id;
COMMIT;
If any step fails, the entire transaction rolls back.
Handling Idempotency
When a client retries due to timeout, the system must recognize duplicates:
- Client includes an idempotency key with each transfer request
- Before creating a transfer, check if that key exists:
SELECT transfer_id FROM transfers WHERE idempotency_key = :key - If found, return the existing transfer
- If not found, create new transfer atomically using the key as a unique constraint
The database's unique constraint on idempotency_key prevents race conditions where two simultaneous requests with the same key both try to create transfers.
Concurrency Control
Two approaches for preventing overdrafts:
Pessimistic locking (recommended for financial systems):
- Use
SELECT ... FOR UPDATEto lock the sender's account row - Process transfers serially per account
- Simple and safe, but limits throughput
Optimistic locking:
- Include a version number in the accounts table
- During update, check
WHERE version = :expected_version - If version changed, someone else modified it—retry
- Higher throughput but requires retry logic
In-Memory vs. Production
In-memory prototype:
- Hash maps for accounts and transfers
- No durability—data lost on crash
- No real locking—race conditions possible
- Useful for API contracts and business logic demonstration
Production requirements:
- Durable database (PostgreSQL, MySQL) with ACID guarantees
- Write-ahead logging for crash recovery
- Replicas for high availability
- Transaction logs archived for regulatory compliance (often 7 years)
- Point-in-time recovery capabilities
Balance Types
- Available balance: Funds that can be spent now
- Pending balance: Incoming transfers not yet finalized
- Total balance: Available + pending
Calculate on-demand from ledger entries or maintain as denormalized columns updated transactionally.
Additional Production Concerns
Reconciliation: Periodically sum all ledger entries per account and compare to stored balance. Any mismatch triggers investigation.
Monitoring: Track transfer success rates, processing latency, and failed transaction patterns. Alert on anomalies.
Authorization: Verify the requester owns the source account. Use authentication tokens and check account ownership before processing.
Fraud prevention: Rate limits, velocity checks (total transferred per hour), and anomaly detection to block suspicious patterns.
Audit logging: Record every API call, transfer state change, and balance modification with timestamps and actor information.
Reconciliation with external systems: If funds originate from banks, run daily reconciliation jobs comparing internal ledger totals against bank statements.
Common Mistakes
- Updating balances without transactions, leading to inconsistent states during failures
- Forgetting idempotency, causing duplicate transfers on retry
- Using eventual consistency where strong consistency is required
- Not locking accounts during concurrent transfers, allowing overdrafts
- Storing only current balance without maintaining full transaction history
The key insight is treating money movement as immutable events in a ledger rather than mutable account balances, combined with transactional guarantees and idempotency to handle the messiness of distributed systems.