Virtual Currency Ledger with Real-Time Aggregation
System DesignModel answerLast updated
Build a transactional ledger supporting currency transfers, 24-hour flow queries, and 30-day hourly balance history at scale.
You're building the backend for a virtual currency system used in online gaming. Players earn and spend virtual coins through gameplay, purchases, and peer-to-peer exchanges.
Your system must support:
-
Transfers: Move currency between any two accounts atomically. Transfers must never duplicate money, lose money, or allow negative balances.
-
Recent activity summary: For any account, calculate total money received and total money sent in the trailing 24 hours.
-
Historical balance snapshots: For any account, return the account balance at the end of each hour over the past 30 days.
Constraints and context:
- Expect 200 million registered accounts with 50 million active daily
- Roughly 500 million transfers per day (average 6K/sec, peak 50K/sec during events)
- Some accounts are extremely active (popular creator accounts may receive thousands of payments per second)
- Correctness is paramount: this is real money to players
- All operations must be auditable and reproducible
Design the system end-to-end. Include:
- API contracts
- Data schema and storage strategy
- How you guarantee correctness during transfers
- How you efficiently compute 24-hour flows for high-volume accounts
- How you maintain 30-day hourly history without scanning massive transaction logs
- Key architectural trade-offs and failure modes
Hints
Hint 1
Use double-entry bookkeeping: every transfer creates two equal and opposite ledger entries that can be reconciled
Hint 2
Pre-aggregate statistics at hourly granularity as events stream in; combine pre-computed buckets with real-time tail queries for recent windows
Hint 3
Lock accounts in consistent order during transfers to prevent deadlocks; consider whether cross-shard transfers need sagas or distributed transactions
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Solution: Virtual Currency Ledger with Real-Time Aggregation
Requirements and Assumptions
Functional scope:
- Atomic currency transfers between accounts with no money loss or duplication
- Current balance lookup
- 24-hour rolling window of inflows and outflows per account
- Hourly balance time series for any account over 30 days
- Full audit trail with immutable records
Non-functional priorities:
- Correctness over availability. Strong consistency for transfers; prevent negative balances.
- Idempotency. Retries must not create duplicate transfers.
- Immutability. Corrections use compensating transactions, never updates.
- Target latency: transfers <200ms p99, reads <100ms p99.
Scale estimates (stated clearly):
- 200M accounts, 50M DAU
- 500M transfers/day → ~6K TPS average, ~50K TPS peak
- ~200 bytes per ledger entry × 2 entries per transfer → ~200GB/day, ~70TB/year raw
- Hot accounts exist: popular creators may see 10K+ incoming payments/second during promotions
- Hourly stats: up to 720 data points per account (30 days × 24 hours)
API Design
POST /v1/transfers
Idempotency-Key: <client-generated-uuid>
{
"from_account": "acct_123",
"to_account": "acct_456",
"amount": 10000,
"currency": "COIN",
"memo": "purchase"
}
→ 201 { "transfer_id": "...", "status": "COMPLETED", "timestamp": "..." }
GET /v1/accounts/{id}/balance
→ { "balance": 50000, "currency": "COIN", "as_of": "..." }
GET /v1/accounts/{id}/flows/24h
→ { "inflow": 12000, "outflow": 3000, "net": 9000, "window": "..." }
GET /v1/accounts/{id}/balance_history?hours=720
→ {
"snapshots": [
{ "hour": "2024-01-15T00:00:00Z", "balance": 5000, "inflow": 100, "outflow": 50 },
...
]
}
Key decisions:
- Amounts are integers (smallest unit) to avoid floating-point errors.
- Idempotency keys are client-supplied UUIDs for safe retries.
- All timestamps use UTC; hourly buckets align on the hour.
Data Model
accounts
id UUID PRIMARY KEY
owner_id VARCHAR
currency VARCHAR
balance BIGINT NOT NULL DEFAULT 0
version BIGINT NOT NULL DEFAULT 0 -- optimistic lock
status VARCHAR CHECK (IN 'ACTIVE', 'FROZEN')
created_at TIMESTAMP
transfers
id UUID PRIMARY KEY
idempotency_key VARCHAR UNIQUE NOT NULL
from_account UUID NOT NULL
to_account UUID NOT NULL
amount BIGINT NOT NULL CHECK (amount > 0)
currency VARCHAR NOT NULL
status VARCHAR CHECK (IN 'PENDING', 'COMPLETED', 'FAILED')
memo TEXT
created_at TIMESTAMP
INDEX (created_at)
ledger_entries -- append-only, immutable
id BIGINT PRIMARY KEY (auto-increment per partition)
transfer_id UUID NOT NULL
account_id UUID NOT NULL
entry_type VARCHAR CHECK (IN 'DEBIT', 'CREDIT')
amount BIGINT NOT NULL CHECK (amount > 0)
balance_after BIGINT NOT NULL
created_at TIMESTAMP NOT NULL
INDEX (account_id, created_at)
PARTITION BY HASH(account_id)
hourly_aggregates
account_id UUID
hour_start TIMESTAMP
inflow BIGINT DEFAULT 0
outflow BIGINT DEFAULT 0
closing_balance BIGINT NOT NULL
PRIMARY KEY (account_id, hour_start)
TTL 90 days
Core invariants:
- Every transfer produces exactly one DEBIT and one CREDIT of equal amount.
- System-wide sum of all entries equals zero.
- Each entry records
balance_after, enabling point-in-time balance reconstruction and reconciliation.
Architecture
┌─────────────┐
│ Game Client │
└──────┬──────┘
│
┌───▼──────────────┐
│ API Gateway │ (auth, rate limit, routing)
└───┬──────────────┘
│
┌───▼─────────────────┐
│ Transfer Service │ (stateless, handles writes)
└───┬─────────────────┘
│
┌───▼─────────────────┐
│ Ledger Database │ (sharded Postgres/CockroachDB/Spanner)
│ - accounts │
│ - transfers │
│ - ledger_entries │
└───┬─────────────────┘
│ CDC / Outbox
┌───▼─────────────────┐
│ Event Stream │ (Kafka, keyed by account_id)
└───┬─────────────────┘
│
┌───▼──────────────────┐
│ Aggregation Worker │ (consumes stream, updates stats)
└───┬──────────────────┘
│
┌───▼──────────────────┐
│ Aggregates Store │ (Cassandra/ScyllaDB or sharded SQL)
│ - hourly_aggregates │
└─────────────────────┘
▲
│
┌───┴──────────────┐
│ Query Service │ (handles reads, caches hot accounts)
└──────────────────┘
Transfer Execution (Same Shard)
-
Check idempotency: Query
transferstable byidempotency_key. If exists, return stored result immediately. -
Begin transaction:
- Lock both accounts in deterministic order (e.g., ascending account_id) to prevent deadlocks.
- Validate sender balance:
UPDATE accounts SET balance = balance - :amount WHERE id = :from AND balance >= :amount AND status = 'ACTIVE'. - If zero rows updated, rollback with "insufficient funds."
-
Debit sender: Insert ledger entry with
entry_type='DEBIT',balance_after = old_balance - amount. -
Credit receiver: Update receiver balance, insert ledger entry with
entry_type='CREDIT',balance_after = old_balance + amount. -
Record transfer: Insert into
transferswithstatus='COMPLETED'. -
Publish event: Insert outbox record; a separate relay publishes to Kafka asynchronously.
-
Commit transaction.
Cross-shard transfers:
- Option A: Use a distributed SQL database (CockroachDB, Spanner) for native cross-shard ACID transactions.
- Option B: Implement a saga:
- Debit sender, mark transfer
PENDING. - Credit receiver.
- Update transfer to
COMPLETED. - On failure, run compensating debit to receiver or credit back to sender.
Each step is idempotent using
transfer_idas deduplication key.
- Debit sender, mark transfer
24-Hour Flow Calculation
Challenge: Hot accounts may have millions of entries in 24 hours; scanning raw ledger is too slow.
Solution: Hybrid approach combining pre-aggregated buckets and tail queries.
The rolling 24-hour window [now - 24h, now] spans:
- Complete hours in the middle: Query
hourly_aggregatesfor up to 23 full hours. Sum theirinflowandoutflowcolumns. - Partial oldest hour: The hour containing
now - 24his incomplete. Either:- Take the bucket's totals and subtract raw entries before the cutoff, or
- Directly scan raw
ledger_entriesfor that narrow slice.
- Current partial hour: Since
hour_start(now), the bucket may lag. Scan rawledger_entriesfrom the bucket's last update to now, or maintain a live in-memory counter.
Cost: ~25 rows from aggregates + two small range scans on ledger (typically <1000 rows each for active accounts).
Alternative: If product accepts "last 24 complete hours" instead of rolling, reduce to a pure 24-row aggregate query.
Caching: Store results in Redis with 60-second TTL for hot accounts.
30-Day Hourly Balance History
Challenge: Storing 720 dense rows per account for 200M accounts = 144 billion rows. Many hours have zero activity.
Solution: Sparse storage with forward-fill on read.
Write path (streaming aggregator):
- Consume ledger events from Kafka, partitioned by
account_id. - For each event, upsert into
hourly_aggregates:UPDATE hourly_aggregates SET inflow = inflow + :amount, closing_balance = :balance_after WHERE account_id = :account AND hour_start = :hour - Only create rows for hours with activity. Empty hours are omitted.
- Track last-processed
entry_idper partition for exactly-once semantics despite at-least-once Kafka delivery.
Read path:
- Query
hourly_aggregatesfor the account wherehour_startbetweennow - 30dandnow. This returns a sparse set (e.g., 200 rows if the account traded on 200 hours). - Forward-fill gaps: Start with the latest
closing_balancebefore the window. For each subsequent hour, if no row exists, carry forward the previous balance. If a row exists, use itsclosing_balance. - Return up to 720 data points.
Handling late events:
- Bucket entries by their
created_at(event time), not processing time. - Since each entry carries
balance_afterfrom the authoritative ledger, reprocessing events (e.g., during failure recovery) produces correct closing balances.
Retention: Keep hourly aggregates for 90 days with TTL. Archive raw ledger to cold storage (S3/data warehouse) for compliance.
Trade-Offs and Failure Modes
Consistency vs. latency:
- Synchronous aggregation (update stats within the transfer transaction) guarantees zero lag but increases write latency and couples services.
- Asynchronous aggregation (used here) decouples services and scales better, but introduces seconds of lag. For fraud detection or real-time limits, maintain a separate hot counter in Redis.
Sharding strategy:
- Hash-based sharding by
account_idkeeps an account's data co-located but creates hot shards for celebrity accounts. - Mitigation: Use consistent hashing with virtual nodes, or split hot accounts into sub-ledgers.
Failure scenarios:
- Partial write: Transaction rollback ensures atomicity. Outbox pattern ensures events are eventually published.
- Duplicate events: Idempotency keys and deduplication tracking prevent double-processing.
- Aggregator lag: Read path falls back to scanning recent raw entries when aggregates are stale.
- Hot account overload: Rate limit per account, cache aggressively, and consider splitting very hot accounts across sub-accounts.
Reconciliation:
- Periodically sum all ledger entries per account and compare to cached balance.
- Run background jobs to recompute hourly aggregates from raw ledger and validate consistency.
This design balances strict correctness for financial transactions with efficient querying of aggregated statistics at scale, using standard distributed system patterns like double-entry ledgers, event sourcing, and CQRS.