Shared Account Balance API: Preventing Double-Spend at Scale
System DesignModel answerLast updated
Design an API for a shared payment account that keeps the balance consistent when multiple users submit payments simultaneously, at high throughput.
Shared Account Balance API
Two people hold access to the same payment account — think a joint household account or a shared corporate card. Both can initiate a payment at any moment, independently and without coordination.
Your task is to design the API and the backend system that makes this safe.
What you need to cover:
- API contract: endpoints, request and response shapes, relevant HTTP status codes, and how clients handle errors
- Safe retries: how the system guarantees a payment is executed exactly once even if a client retries after a timeout or network failure
- Concurrency control: what happens when two payments hit the same account at the same millisecond — explain the mechanisms, name the trade-offs, and justify your choice
- Data model: what you store and why, including how you reconstruct or verify the balance
- Scaling: the system must handle roughly 1 billion payments per day with bursts reaching 100K writes per second; explain how per-account contention is different from aggregate throughput
- Failure modes and monitoring: what can go wrong and how you detect it
Constraints and assumptions to state explicitly before designing:
- A payment must either fully succeed or fully fail — no partial debits
- The balance must never go negative unless you explicitly allow overdraft
- No double-spend: retrying the same intended payment must not debit the account twice
- p99 latency target: under 200 ms on the write path
A strong answer states its assumptions up front, walks through the hard part (per-account concurrency), explains why it chose one locking strategy over the others, and acknowledges what the design gives up.
Hints
Hint 1
Start by separating two distinct problems: aggregate throughput (solved with horizontal sharding) and per-account contention (solved with locking or atomic writes inside a single shard). Mixing them up leads to over-engineered answers.
Hint 2
A read-modify-write in application code — SELECT balance, check in code, then UPDATE — is the classic double-spend bug. Think about how the database can make the check and the write atomic without two round trips.
Hint 3
Idempotency keys need to be stored durably and their status (in-progress vs. done) needs to be updated in the same transaction as the debit. Think about what happens if the process crashes between the debit and the key update.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core challenge here is not raw throughput — that is solved by sharding. The real problem is per-account linearizability: two concurrent debits on the same account must not both pass a balance check that only one of them should pass.
1. State Your Assumptions First
Interviewers reward candidates who bound the problem before solving it.
Functional requirements
- Shared account supports multiple authorized users debiting concurrently
- Each payment is atomic: fully committed or fully rolled back
- Clients can retry safely without triggering duplicate charges
- Users can read current balance and payment history
Scale assumptions
- ~1B payments/day → ~12K avg writes/sec, ~50–100K at peak
- Read traffic is roughly 10× writes
- Most accounts: under 1 write/sec. Shared/merchant accounts: potentially hundreds/sec
- This last point matters — the hot-account case is where the design breaks if you get it wrong
2. API Design
POST /v1/accounts/{account_id}/payments
Headers:
Authorization: Bearer <token>
Idempotency-Key: <client-generated UUID> ← required
Body:
{ "amount": 4999, "currency": "USD", "payee_id": "m_42", "description": "Groceries" }
Responses:
201 Created → payment succeeded, includes payment_id and balance_after
202 Accepted → processing async (used for slower rails like ACH)
402 → insufficient funds — terminal, do not retry
409 → idempotency key conflict (body changed) or payment in progress
429 → rate limited, Retry-After header present
503 → transient, retry with backoff
Key decisions:
- Amounts as integers in minor units. Never floats for money.
- Idempotency key is mandatory, scoped to
(account_id, key). The same key always returns the same response. - Explicit retryability classes. The client SDK retries 503 and 409-in-progress. It never retries 402 or 400. This distinction matters more than most candidates acknowledge.
3. Data Model
Model the balance as a double-entry ledger — an append-only record of every credit and debit — with a cached balance column for fast reads.
accounts (account_id, balance BIGINT, version BIGINT, currency, status)
payments (payment_id, account_id, amount, payee_id, status, created_at)
ledger_entries (entry_id, account_id, payment_id, amount BIGINT, balance_after, created_at)
idempotency (account_id, idem_key, request_hash, status, response_json, created_at)
outbox (event_id, account_id, payment_id, payload, published_at)
accounts.balance is a derived value updated atomically with each write. A reconciliation job periodically asserts balance == SUM(ledger_entries.amount) and pages on mismatch.
4. Concurrency Control — The Core of the Problem
The bug to avoid:
balance = db.query("SELECT balance FROM accounts WHERE id = ?")
if balance >= amount:
db.execute("UPDATE accounts SET balance = balance - ? WHERE id = ?")
Both Alice's and Bob's requests read 50, both pass the >= 40 check, and both write 10. One debit vanishes. This is the classic lost-update.
Three correct approaches — name all three and pick one:
Option A: Atomic conditional update (preferred for debits)
BEGIN;
UPDATE accounts
SET balance = balance - :amt, version = version + 1
WHERE account_id = :id AND balance >= :amt
RETURNING balance;
-- 0 rows returned → 402, roll back
INSERT INTO ledger_entries ...;
INSERT INTO payments ...;
INSERT INTO outbox ...;
UPDATE idempotency SET status = 'DONE', response = :resp WHERE ...;
COMMIT;
The database's row lock serializes the two updates. The second one re-evaluates balance >= 40 against 10, matches zero rows, and fails. Single round trip, lock held only for the transaction duration. This is the right default.
Option B: Pessimistic locking (SELECT FOR UPDATE)
Explicitly locks the account row before reading, then applies business logic, then writes. Useful when the check is complex — per-user spending caps, fraud rules, multi-leg transfers — because you need the current state before computing the update. Cost: the lock is held longer. Rule: never call an external service while holding this lock. Always set a lock timeout.
Option C: Optimistic locking (version check)
Read version N, compute new balance, UPDATE ... WHERE version = N. If zero rows match, retry. Works well when contention is genuinely low. Under high contention on a shared account it degrades into retry storms and is the wrong choice here.
Recommendation: Use option A or B for debits on shared accounts. Shared accounts are contended by definition. Use READ COMMITTED with row-level locks. SERIALIZABLE is correct but generates more transaction aborts under load.
5. Idempotency and Retries
Flow for every incoming request:
INSERT INTO idempotency (account_id, key, request_hash, status='IN_PROGRESS')with a unique constraint on(account_id, key)- Duplicate key, status DONE → return stored response immediately
- Duplicate key, status IN_PROGRESS → return 409, client retries later
- Duplicate key, hash mismatch → return 409 key-reused (permanent error)
- Run the debit transaction
- Update idempotency status to DONE in the same transaction. If the process crashes, the transaction rolls back and the key stays IN_PROGRESS. A sweeper expires stale IN_PROGRESS entries after a configurable TTL (e.g., 60 seconds).
Retain idempotency keys for 24–72 hours.
Client retry policy: exponential backoff with jitter, reuse the same key, cap total attempts. Never retry terminal errors.
External side effects — notifying a card network, crediting a payee — use a transactional outbox. The ledger write and the outbox row commit in one transaction. A relay process reads the outbox and publishes to a message queue. Consumers deduplicate by payment_id. Delivery is at-least-once; the effect is exactly-once.
6. Scaling
Shard the database by account_id. One account always lives on one shard, so a single-shard ACID transaction is sufficient — no distributed transaction needed.
For genuinely hot accounts (high-volume merchants), options include:
- Queue writes per account in an in-memory layer and batch them; serializes contention outside the database
- Partitioned sub-accounts that periodically reconcile to a parent (more complex, worth mentioning as a follow-up)
Reads (balance, history) can be served from a read replica with a short lag. Flag reads as eventually consistent to the client and offer a ?consistent=true escape hatch that hits the primary.
7. Common Mistakes
- Using floats for monetary amounts
- Forgetting that idempotency key storage must be transactional with the debit
- Recommending optimistic locking for a shared account without acknowledging the retry-storm problem
- Conflating aggregate throughput (sharding solves it) with per-account concurrency (locking solves it)
- Not classifying errors as retryable vs. terminal in the API contract
8. Monitoring
- Alert on
SUM(ledger_entries) != accounts.balancein reconciliation - Track lock wait time and transaction abort rate per shard
- Track idempotency key hit rate to detect client retry storms
- p99 write latency per account shard; alert if one shard diverges (hot-account signal)