Build an In-Memory Ledger with Deposits and Transfers
Data Structure DesignModel answerLast updated
Implement an in-memory ledger class supporting account creation, deposits and transfers, with clear return codes, invariants, retry safety and concurrency choices.
Design and implement an in-memory ledger for a small bank. The class, called BankSystem, must expose three operations:
bool createAccount(long timestamp, String customerId)int deposit(long timestamp, String customerId, int amount)int pay(long timestamp, String sourceAccountId, String targetAccountId, int amount)
Everything lives in memory. Assume up to roughly 10^5 accounts and 10^6 operations.
What you need to deliver
- A data model for accounts and transactions. Use hash maps keyed by id, not lists, so that looking up an account or a transaction takes constant time.
- The invariants your system guarantees, for example that no balance ever goes below zero.
- Precise return semantics. State what each method returns on success (for example the resulting balance) and on failure (for example a sentinel value), and justify the choice.
- Time and space complexity for each operation.
- A decision on how to handle each of these edge cases:
- repeated or out-of-order timestamps
- insufficient funds
- unknown accounts
- a client retrying a request that may already have been applied
- the concurrency model you assume, and what you would change if multiple threads called the API
Write the code and explain the design choices you made along the way.
Hints
Hint 1
Start with the contract: decide what each method returns for success and failure before coding. A failure value of -1 works for balances because a valid balance is never negative.
Hint 2
Validate everything first and mutate afterwards, so a rejected call leaves no partial changes. Think about which inputs are invalid: unknown ids, non-positive amounts, paying yourself, overdrafts, timestamps that go backwards.
Hint 3
Timestamps cannot identify a retry because two genuine operations can share one. Use a client-supplied request key that maps to a stored result, and for concurrency start with a single lock, then discuss per-account locks acquired in a fixed order.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The task is low-level design: a few well-defined operations over a hash map, with the real value in the stated contracts. I would settle the contracts first, then the data model, then code.
1. Contracts
createAccount(ts, id)returnstrueif a new account with balance 0 was created,falseif the id already exists.deposit(ts, id, amount)returns the new balance, or-1on failure. Failures: unknown account,amount <= 0, or a rejected timestamp.pay(ts, src, dst, amount)returns the source's new balance, or-1on failure. Failures: unknown source or target,src == dst,amount <= 0, insufficient funds, or a rejected timestamp.- Sentinel. Balances are never negative, so
-1cannot be confused with a real result. In a language with optionals, returning an empty value is cleaner; whichever you choose, state it. - Timestamps. The input is expected to be non-decreasing. Defensively, reject an operation whose timestamp is earlier than the last accepted one. Equal timestamps are fine, since many operations can happen in the same millisecond.
2. Data model
| Entity | Fields | Storage |
|---|---|---|
| Account | id, balance, created_at, list of txn ids | map<id, Account> |
| Transaction | txn_id, ts, kind, source, target, amount | map<txn_id, Transaction> |
| Retry cache | request_id to stored result | map<request_id, result> |
A hash map is right because every operation begins with "find the account by id", which is O(1) average. A list would make it O(n). Each account keeps an append-only list of its transaction ids, which costs O(1) amortized and enables history queries later.
3. Invariants
- Every balance is at least 0.
- Conservation:
paymoves money and never creates or destroys it, so total balance equals total successful deposits. - Atomicity: a failed call changes nothing, because all checks precede all writes.
- Accepted timestamps are non-decreasing.
- Every successful mutation has exactly one transaction record, found by id in O(1).
4. Retries and idempotency
If a client times out on pay and retries, it must not be charged twice. Add an optional client-generated idempotency key. The first execution stores its result under the key, and a retry with the same key returns the stored result without re-running. Because the key is an optional trailing argument, the required signatures stay intact.
Production refinements worth naming:
- Store a fingerprint of the request parameters with the result and reject a reused key with different parameters.
- Expire keys after a TTL so the cache stays bounded.
- Do not use the timestamp as the key; distinct operations may share one.
5. Concurrency
The assessment setting is single-threaded, so say so, then explain the upgrade path:
- Simplest correct: one global lock per operation. It is linearizable and adequate at this scale.
- More throughput: one lock per account. For
pay, lock both accounts in a canonical order (for example sorted by id) so that A to B and B to A cannot deadlock. - Distributed: a ledger table with transactional writes and an idempotency table with a unique constraint on the key.
6. Code (Python)
import threading
from dataclasses import dataclass, field
from typing import Dict, List, Optional
FAIL = -1
@dataclass
class Account:
account_id: str
created_at: int
balance: int = 0
txn_ids: List[str] = field(default_factory=list)
@dataclass(frozen=True)
class Transaction:
txn_id: str
ts: int
kind: str
source: Optional[str]
target: str
amount: int
class BankSystem:
def __init__(self) -> None:
self._accounts: Dict[str, Account] = {}
self._txns: Dict[str, Transaction] = {}
self._seen: Dict[str, object] = {}
self._last_ts: Optional[int] = None
self._n = 0
self._lock = threading.Lock()
def _accept_ts(self, ts: int) -> bool:
if self._last_ts is not None and ts < self._last_ts:
return False
self._last_ts = ts
return True
def _record(self, ts, kind, src, dst, amount) -> None:
self._n += 1
tid = f"txn{self._n}"
self._txns[tid] = Transaction(tid, ts, kind, src, dst, amount)
if src is not None:
self._accounts[src].txn_ids.append(tid)
self._accounts[dst].txn_ids.append(tid)
def _run(self, request_id, op):
with self._lock:
if request_id is not None and request_id in self._seen:
return self._seen[request_id]
result = op()
if request_id is not None:
self._seen[request_id] = result
return result
def createAccount(self, timestamp, customerId, request_id=None) -> bool:
def op():
if customerId in self._accounts:
return False
if not self._accept_ts(timestamp):
return False
self._accounts[customerId] = Account(customerId, timestamp)
return True
return self._run(request_id, op)
def deposit(self, timestamp, customerId, amount, request_id=None) -> int:
def op():
acct = self._accounts.get(customerId)
if acct is None or amount <= 0:
return FAIL
if not self._accept_ts(timestamp):
return FAIL
acct.balance += amount
self._record(timestamp, "deposit", None, customerId, amount)
return acct.balance
return self._run(request_id, op)
def pay(self, timestamp, sourceAccountId, targetAccountId, amount,
request_id=None) -> int:
def op():
src = self._accounts.get(sourceAccountId)
dst = self._accounts.get(targetAccountId)
if src is None or dst is None or src is dst or amount <= 0:
return FAIL
if src.balance < amount:
return FAIL
if not self._accept_ts(timestamp):
return FAIL
src.balance -= amount
dst.balance += amount
self._record(timestamp, "pay", sourceAccountId, targetAccountId, amount)
return src.balance
return self._run(request_id, op)
7. Complexity
Each operation does a constant number of hash lookups and one append, so time is O(1) average. Space is O(A + T + R) for accounts, transactions and cached request keys.
8. Common mistakes
- Mutating the source balance before checking the target exists, leaving partial state after a failure.
- Allowing
payfrom an account to itself, or non-positive amounts. - Advancing the "last timestamp" on a call that then fails validation.
- Using the timestamp as a deduplication key.
- Locking two accounts in inconsistent order, which risks deadlock.
- Scanning a list for accounts, giving O(n) per call.
9. Likely follow-ups
Extensions often layered on this base include ranking accounts by total outgoing amount (keep a running outgoing total per account and sort or use a heap for the top n), and scheduled or pending transfers that need acceptance (keep them in a map keyed by transfer id so lookup, accept and expire are O(1)). The data model above supports both without redesign.