In-Memory Banking Ledger and Pending Transfers
Medium · Coding & Algorithms · Software Engineer · Online Assessment
Problem Statement
Build a thread-safe, in-memory Bank ledger service in Python where monetary values are stored in integer cents. Every public method must execute safely under concurrent multi-threaded requests and use an injectable clock callable (defaulting to time.time) for timestamps and deadlines.
Constants, Records, and Exceptions
from dataclasses import dataclass
from typing import Callable, List, Optional
DEPOSIT = "deposit"
WITHDRAWAL = "withdrawal"
TRANSFER_PENDING = "transfer_pending"
TRANSFER_IN = "transfer_in"
TRANSFER_OUT = "transfer_out"
PENDING = "PENDING"
ACCEPTED = "ACCEPTED"
REJECTED = "REJECTED"
EXPIRED = "EXPIRED"
DEFAULT_TRANSFER_TTL = 24 * 60 * 60 # seconds
class BankError(Exception): ...
class InvalidRequest(BankError): ...
class AccountNotFound(BankError): ...
class TransferNotFound(BankError): ...
class InsufficientFunds(BankError): ...
class TransferClosed(BankError): ...
@dataclass(frozen=True)
class Transaction:
seq: int
timestamp: float
type: str
amount: int
balance_after: int
transfer_id: Optional[str] = None
Required Bank Interface and Behavior
- Accounts and direct balance changes
create_account(initial_balance: int = 0, request_id: Optional[str] = None) -> str: Create an account with a unique ID and non-negative integerinitial_balance. Wheninitial_balance > 0, append an initial"deposit"record; wheninitial_balance == 0, start with an empty ledger.get_balance(account_id: str) -> int: Return the account's current balance in cents, or raiseAccountNotFound.deposit(account_id: str, amount: int, request_id: Optional[str] = None) -> int: Addamountcents, append a"deposit"record, and return the updated balance.withdraw(account_id: str, amount: int, request_id: Optional[str] = None) -> int: Subtractamountcents, append a"withdrawal"record, and return the updated balance. Ifbalance < amount, raiseInsufficientFundswithout modifying balance or history.
- Per-account ledger history
- Every
Transactioncaptures a strictly increasing bank-wide sequence numberseq, theclock()readingtimestamp,type,amount,balance_after, and optionaltransfer_id. get_history(account_id: str) -> List[Transaction]: Return a chronological copy (oldest first) of all records foraccount_id(without exposing internal mutable list storage).get_recent_history(account_id: str, n: int) -> List[Transaction]: Return the most recentnrecords in chronological order (oldest first). RaiseInvalidRequestifnis not an integer>= 0.
- Every
- Two-phase transfers with expiration
create_transfer(from_id: str, to_id: str, amount: int, ttl_seconds: float = DEFAULT_TRANSFER_TTL, request_id: Optional[str] = None) -> str: Create a transfer in"PENDING"state expiring atcreated_at + ttl_secondsand append"transfer_pending"entries (with unchanged balances andtransfer_idset) to both accounts. Do not check or reserve sender funds at creation time. Rejectfrom_id == to_idor non-positivettl_secondswithInvalidRequest.- Expiration rule: Any
"PENDING"transfer becomes"EXPIRED"as soon asclock() >= created_at + ttl_seconds. accept_transfer(transfer_id: str, recipient_id: str) -> str: Onlyto_idmay accept (otherwise raiseInvalidRequest). If already"ACCEPTED", return"ACCEPTED"with no side effects. If"REJECTED"or"EXPIRED", raiseTransferClosed. If"PENDING"andsender.balance < amount, raiseInsufficientFundswhile keeping the transfer"PENDING". Otherwise debit the sender, credit the recipient, append"transfer_out"and"transfer_in"records, mark"ACCEPTED", and return"ACCEPTED".reject_transfer(transfer_id: str, recipient_id: str) -> str: Onlyto_idmay reject (otherwise raiseInvalidRequest). If"PENDING", mark"REJECTED"and return"REJECTED". If already"REJECTED"or"EXPIRED", return that current status without side effects. If"ACCEPTED", raiseTransferClosed.get_transfer_status(transfer_id: str) -> str: Return"PENDING","ACCEPTED","REJECTED", or"EXPIRED"(reflecting deadline expiration immediately), or raiseTransferNotFound.
- Idempotency via
request_id- On
create_account,deposit,withdraw, andcreate_transfer, when a non-Nonerequest_idis repeated with the exact same method and arguments as a prior successful call, return the original result without mutating state. Reusing a rememberedrequest_idwith different method/arguments raisesInvalidRequest. Failed calls are not cached underrequest_id.
- On
Examples
Example 1
now = 500.0
bank = Bank(clock=lambda: now)
acct = bank.create_account(250, request_id="open-a") # -> "A1" (logs deposit 250)
now = 505.0
bank.deposit(acct, 125, request_id="dep-1") # -> 375
bank.deposit(acct, 125, request_id="dep-1") # -> 375 (idempotent replay)
now = 510.0
# bank.withdraw(acct, 400) -> raises InsufficientFunds (balance stays 375)
bank.withdraw(acct, 175) # -> 200
recent = bank.get_recent_history(acct, 2)
# [(r.type, r.amount, r.balance_after) for r in recent] ==
# [("deposit", 125, 375), ("withdrawal", 175, 200)]
Walk-through: Opening acct with 250 cents writes an initial "deposit" entry. Depositing 125 moves the balance to 375, while replaying request_id="dep-1" returns 375 without adding a duplicate entry. Attempting to withdraw 400 raises InsufficientFunds, withdrawing 175 leaves 200, and get_recent_history(acct, 2) returns the final two records in chronological order.
Example 2
now = 2000.0
bank = Bank(clock=lambda: now)
sender = bank.create_account(300)
recipient = bank.create_account(50)
tx = bank.create_transfer(sender, recipient, 240, ttl_seconds=120) # PENDING; balances stay 300, 50
now = 2010.0
bank.withdraw(sender, 100) # sender -> 200
now = 2020.0
# bank.accept_transfer(tx, recipient) -> raises InsufficientFunds; tx stays PENDING
now = 2030.0
bank.deposit(sender, 80) # sender -> 280
now = 2040.0
bank.accept_transfer(tx, recipient) # -> "ACCEPTED" (sender -> 40, recipient -> 290)
bank.accept_transfer(tx, recipient) # -> "ACCEPTED" (idempotent retry)
tx2 = bank.create_transfer(sender, recipient, 25, ttl_seconds=60)
now = 2100.0
bank.get_transfer_status(tx2) # -> "EXPIRED" (2100.0 >= 2040.0 + 60)
bank.reject_transfer(tx2, recipient) # -> "EXPIRED"
Walk-through: tx logs "transfer_pending" on both accounts without locking funds. After sender drops to 200, accepting 240 fails with InsufficientFunds while keeping tx "PENDING". Once sender deposits 80 (280 >= 240), acceptance succeeds atomically (40 and 290) and ignores duplicate retries. Meanwhile tx2 reaches its 60-second deadline at 2100.0 and transitions to "EXPIRED".
Constraints
amounton deposits, withdrawals, and transfers must be a positiveint(> 0, excludingboolandfloat);initial_balanceandnmust beintvalues>= 0. Invalid types or ranges raiseInvalidRequest.ttl_secondsmust be a finite positiveintorfloat(> 0, excludingboolandNaN).- Single-record operations (
create_account,get_balance,deposit,withdraw,create_transfer,accept_transfer,reject_transfer,get_transfer_status) must run inO(1)average time;get_recent_history(account_id, n)must run inO(min(n, h))time for an account withhrecords.
Step-by-step walkthrough
Clarify requirements and design the API
We need a thread-safe in-memory
Bankledger supporting account creation, overdraft-safe deposits and withdrawals, per-accountTransactionlogs, and two-phase transfers (PENDINGuntil accepted by the recipient, or canceled via rejection or deadline expiration).Before writing code, lock in five design choices that keep arithmetic and concurrency rock-solid:
- Represent all money as integer cents, never
float. Binary floating-point arithmetic introduces rounding error (0.1 + 0.2 == 0.30000000000000004), causing historical ledger sums to drift away from balances. - Assign monotonic internal IDs (
"A1","A2", ... for accounts;"T1","T2", ... for transfers). - Accept an injectable
clock(Bank(clock=...)). Production usestime.time, while tests step a deterministic fake clock forward to verify 24-hour transfer deadlines instantly without sleeping. - Raise explicit domain exceptions (
InvalidRequest,AccountNotFound,TransferNotFound,InsufficientFunds,TransferClosed) so callers can separate bad parameters from business-rule failures. - Verify
recipient_idonaccept_transferandreject_transferso neither the sender nor an unrelated account can settle or cancel someone else's transfer.
create_account(initial_balance=0, request_id=None) -> account_id (str) get_balance(account_id) -> cents (int) deposit(account_id, amount, request_id=None) -> new_balance (int) withdraw(account_id, amount, request_id=None) -> new_balance (int) create_transfer(from_id, to_id, amount, ttl_seconds=86400, request_id=None) -> transfer_id (str) accept_transfer(transfer_id, recipient_id) -> "ACCEPTED" reject_transfer(transfer_id, recipient_id) -> "REJECTED" | "EXPIRED" get_transfer_status(transfer_id) -> status (str) get_history(account_id) -> List[Transaction] get_recent_history(account_id, n) -> List[Transaction]- Represent all money as integer cents, never
Choose O(1) in-memory data structures
Because every method addresses accounts and transfers by ID, Python
dicthash tables giveO(1)average lookup time. Inside eachAccount, an append-onlylistof frozenTransactionobjects supportsO(1)amortized appends andO(min(n, h))tail slicing forget_recent_history(account_id, n):@dataclass(frozen=True) class Transaction: seq: int # Strictly increasing bank-wide sequence number (orders ties/clock jumps) timestamp: float # Reading from the injected clock when this entry was recorded type: str # One of DEPOSIT, WITHDRAWAL, TRANSFER_PENDING, TRANSFER_IN, TRANSFER_OUT amount: int # Positive integer number of cents balance_after: int # Account balance in cents immediately after this entry transfer_id: Optional[str] = None @dataclass class Account: account_id: str balance: int # history: chronological list of immutable Transaction records, oldest -> newest history: List[Transaction] = field(default_factory=list) @dataclass class Transfer: transfer_id: str from_id: str to_id: str amount: int created_at: float expires_at: float status: str = PENDING class Bank: def __init__(self, clock: Optional[Callable[[], float]] = None) -> None: self.clock: Callable[[], float] = clock if clock is not None else time.time # Single mutex serializing all public reads and writes so check-then-act steps stay atomic. self.lock = threading.Lock() # accounts: maps account_id (e.g. "A1") -> Account(account_id, balance, history) self.accounts: Dict[str, Account] = {} # transfers: maps transfer_id (e.g. "T1") -> Transfer(..., status) self.transfers: Dict[str, Transfer] = {} # requests: maps request_id -> (argument_signature_tuple, cached_return_value) for idempotency self.requests: Dict[str, Tuple[tuple, object]] = {} self.next_account_num: int = 1 self.next_transfer_num: int = 1 self.next_seq: int = 1Declaring
Transactionwithfrozen=Trueprevents caller code holding a returned record from mutating itsamountorbalance_afterfields.Model the pending-transfer state machine and lazy expiry
Each transfer begins in
PENDINGand transitions at most once into one of three terminal states (ACCEPTED,REJECTED, orEXPIRED). Cents move only along thePENDING -> ACCEPTEDtransition:accept (sender balance >= amount) create ---> PENDING ---------------------------> ACCEPTED (cents move once) | \ reject | \ now >= expires_at v v REJECTED EXPIRED (canceled; no cents move)To make
accept_transferandreject_transferidempotent (safe to repeat when a network response drops), retries matching the terminal outcome return cleanly without moving funds a second time, whereas conflicting transitions raiseTransferClosed:Current status accept_transfer(id, recipient) reject_transfer(id, recipient) -------------- ----------------------------------------- ---------------------------------- PENDING Move money -> ACCEPTED Set status -> REJECTED (if sender is short: InsufficientFunds, and status stays PENDING!) ACCEPTED Return "ACCEPTED" (no-op) Raise TransferClosed REJECTED Raise TransferClosed Return "REJECTED" (no-op) EXPIRED Raise TransferClosed Return "EXPIRED" (no-op)Rather than relying on a background timer thread (which can lag behind the clock), we enforce lazy expiry: every operation touching a transfer calls
_expire_if_due(transfer, now)first to flip any past-deadlinePENDINGtransfer toEXPIRED:def _expire_if_due(self, transfer: Transfer, now: float) -> None: """Lazy expiry: flip PENDING -> EXPIRED as soon as now reaches or passes expires_at.""" # Boundary is '>=': a 60s transfer created at t=1000 is already EXPIRED at t=1060. if transfer.status == PENDING and now >= transfer.expires_at: transfer.status = EXPIREDMake network retries safe with idempotency keys
In Example 1, if a client calls
deposit("A1", 125, request_id="dep-1")and the response is lost over the network, retrying that call must not add another125cents.We accept an optional idempotency key (
request_id) oncreate_account,deposit,withdraw, andcreate_transfer, storing(signature, result)insideself.requests:- Identical retry (same
request_idand parameters): Replay the cached return value inO(1)without modifying balances or ledger entries. - Conflicting reuse (same
request_idwith different method or parameters): RaiseInvalidRequest. - Failed call (such as
InsufficientFunds): Skip caching so the caller can add funds and retry cleanly.
def _check_idempotent_replay( self, request_id: Optional[str], signature: tuple, ) -> Tuple[bool, object]: """Return (True, previous_result) on an exact retry, or raise if reused with different args.""" if request_id is None or request_id not in self.requests: return False, None previous_signature, previous_result = self.requests[request_id] if previous_signature != signature: raise InvalidRequest( f"request_id {request_id!r} was already used with different parameters" ) return True, previous_result def _save_idempotent_result( self, request_id: Optional[str], signature: tuple, result: object, ) -> None: """Cache successful results by request_id; failed calls are skipped so callers can fix & retry.""" if request_id is not None: self.requests[request_id] = (signature, result)- Identical retry (same
Validate inputs and implement account operations
In Python,
boolsubclassesint(isinstance(True, int)isTrue), so validators must reject booleans before checkingisinstance(..., int). Likewise,_validate_positive_ttlwritesnot (ttl_seconds > 0)instead ofttl_seconds <= 0becausefloat('nan') <= 0evaluates toFalsein IEEE-754 floating-point math, whereasnot (ttl_seconds > 0)rejects0, negatives, andNaNtogether:def _validate_positive_cents(amount: object) -> None: """Ensure amount is a strictly positive integer (cents), rejecting bool and float.""" # In Python isinstance(True, int) is True, so reject bool explicitly; reject float to avoid rounding drift. if isinstance(amount, bool) or not isinstance(amount, int) or amount <= 0: raise InvalidRequest( f"amount must be a positive integer number of cents, got {amount!r}" ) def _validate_non_negative_int(value: object, field_name: str) -> None: """Ensure value is an integer >= 0 (used for initial_balance and history count n).""" if isinstance(value, bool) or not isinstance(value, int) or value < 0: raise InvalidRequest( f"{field_name} must be a non-negative integer, got {value!r}" ) def _validate_positive_ttl(ttl_seconds: object) -> None: """Ensure ttl_seconds is a positive int or float, rejecting bool, NaN, and non-numbers.""" if isinstance(ttl_seconds, bool) or not isinstance(ttl_seconds, (int, float)): raise InvalidRequest( f"ttl_seconds must be a positive number, got {ttl_seconds!r}" ) # Using 'not (ttl_seconds > 0)' rejects 0, negatives, and float('nan') (NaN > 0 is False). if not (ttl_seconds > 0): raise InvalidRequest(f"ttl_seconds must be positive, got {ttl_seconds!r}")When
create_accountopens withinitial_balance > 0, recording an openingDEPOSITensures replaying an account's history from0always matchesget_balance.withdrawchecksaccount.balance < amountbefore deducting anything:def create_account( self, initial_balance: int = 0, request_id: Optional[str] = None, ) -> str: with self.lock: signature = ("create_account", initial_balance) already_seen, cached_id = self._check_idempotent_replay(request_id, signature) if already_seen: return str(cached_id) _validate_non_negative_int(initial_balance, "initial_balance") account_id = f"A{self.next_account_num}" self.next_account_num += 1 account = Account(account_id=account_id, balance=initial_balance) self.accounts[account_id] = account # Record a positive opening balance as a deposit so replaying history reproduces balance. if initial_balance > 0: self._append_transaction(account, DEPOSIT, initial_balance, self.clock()) self._save_idempotent_result(request_id, signature, account_id) return account_id def withdraw( self, account_id: str, amount: int, request_id: Optional[str] = None, ) -> int: with self.lock: signature = ("withdraw", account_id, amount) already_seen, cached_balance = self._check_idempotent_replay(request_id, signature) if already_seen: return int(cached_balance) _validate_positive_cents(amount) account = self._get_account(account_id) # Strict '<' allows withdrawing the exact remaining balance down to 0 cents. if account.balance < amount: raise InsufficientFunds( f"{account_id} has {account.balance}, needs {amount}" ) account.balance -= amount self._append_transaction(account, WITHDRAWAL, amount, self.clock()) self._save_idempotent_result(request_id, signature, account.balance) return account.balanceImplement two-phase transfers (create, accept, reject)
create_transferverifies both accounts exist, rejectsfrom_id == to_id, creates aPENDINGTransferexpiring atnow + ttl_seconds, and appends"transfer_pending"entries to both accounts without checking or reserving sender funds.accept_transfersamplesnow = self.clock()once, checksrecipient_id == transfer.to_id, runs_expire_if_due(transfer, now), handles idempotent/closed states, verifiessender.balance >= transfer.amount, and moves the cents—all underself.lockso no concurrentwithdrawcan slip between the balance check and debit:def create_transfer( self, from_id: str, to_id: str, amount: int, ttl_seconds: float = DEFAULT_TRANSFER_TTL, request_id: Optional[str] = None, ) -> str: with self.lock: signature = ("create_transfer", from_id, to_id, amount, ttl_seconds) already_seen, cached_transfer_id = self._check_idempotent_replay( request_id, signature ) if already_seen: return str(cached_transfer_id) _validate_positive_cents(amount) _validate_positive_ttl(ttl_seconds) sender = self._get_account(from_id) receiver = self._get_account(to_id) if from_id == to_id: raise InvalidRequest("cannot transfer to the same account") now = self.clock() transfer_id = f"T{self.next_transfer_num}" self.next_transfer_num += 1 self.transfers[transfer_id] = Transfer( transfer_id=transfer_id, from_id=from_id, to_id=to_id, amount=amount, created_at=now, expires_at=now + ttl_seconds, ) # Balances do not change while PENDING; log transfer_pending on both accounts at identical now. self._append_transaction(sender, TRANSFER_PENDING, amount, now, transfer_id) self._append_transaction(receiver, TRANSFER_PENDING, amount, now, transfer_id) self._save_idempotent_result(request_id, signature, transfer_id) return transfer_id def accept_transfer(self, transfer_id: str, recipient_id: str) -> str: with self.lock: now = self.clock() transfer = self._get_transfer(transfer_id) if transfer.to_id != recipient_id: raise InvalidRequest("only the recipient can accept a transfer") # Refresh expiry before checking status so past-deadline PENDING transfers become EXPIRED. self._expire_if_due(transfer, now) # Idempotent retry: accepting an already ACCEPTED transfer returns ACCEPTED with no side effects. if transfer.status == ACCEPTED: return ACCEPTED if transfer.status != PENDING: raise TransferClosed(f"transfer {transfer_id} is {transfer.status}") sender = self.accounts[transfer.from_id] receiver = self.accounts[transfer.to_id] # Validate funds at acceptance time; if short, keep PENDING so sender can deposit before expiry. if sender.balance < transfer.amount: raise InsufficientFunds( f"{sender.account_id} has {sender.balance}, needs {transfer.amount}" ) # Atomically move cents, append matching ledger entries, and mark ACCEPTED under self.lock. sender.balance -= transfer.amount receiver.balance += transfer.amount self._append_transaction(sender, TRANSFER_OUT, transfer.amount, now, transfer_id) self._append_transaction(receiver, TRANSFER_IN, transfer.amount, now, transfer_id) transfer.status = ACCEPTED return ACCEPTEDServe transaction history safely and handle concurrency
Two classic Python traps arise in history queries:
- Always copy
account.history: Returning the internal list directly would letbank.get_history(a).clear()erase the ledger! Returnlist(account.history)instead. - Avoid
history[-n:]whenn == 0: Because-0 == 0in Python,history[-0:]evaluates tohistory[0:]and returns every record instead of[]! Usingstart_index = max(0, len(history) - n)and slicinghistory[start_index:]handlesn == 0,0 < n < len(history), andn >= len(history)uniformly.
def get_history(self, account_id: str) -> List[Transaction]: with self.lock: # Return a shallow copy so callers cannot mutate the internal history list. return list(self._get_account(account_id).history) def get_recent_history(self, account_id: str, n: int) -> List[Transaction]: """Return the last n records in chronological order (oldest -> newest).""" with self.lock: _validate_non_negative_int(n, "n") history = self._get_account(account_id).history # Compute start index explicitly: Python's history[-0:] equals history[0:] and would return all rows! start_index = max(0, len(history) - n) return history[start_index:]Recording
seqalongsidetimestampsolves clock ties and wall-clock drift: even if two operations execute during the same clock tick or NTP nudgestime.time()backward,seqincreases strictly underself.lock. And because private helpers (_get_account,_append_transaction, ...) assume their public caller already holdsself.lock, a standardthreading.Lockserializes every check-then-act sequence cleanly without reentrancy deadlocks.- Always copy
Trace a multi-step transfer and overdraft recovery
Let's walk through Example 2 (
A1opening with300cents andA2opening with50cents att = 2000):Time Call Result A1 A2 Ledger entries appended ---- -------------------------------------- ----------------- --- --- ----------------------------------- 2000 create_account(300) "A1" 300 - seq 1: A1 deposit 300 (bal 300) 2000 create_account(50) "A2" 300 50 seq 2: A2 deposit 50 (bal 50) 2000 create_transfer(A1, A2, 240, ttl=120) "T1" (PENDING) 300 50 seq 3,4: transfer_pending on A1,A2 2010 withdraw(A1, 100) 200 200 50 seq 5: A1 withdrawal 100 (bal 200) 2020 accept_transfer(T1, A2) InsufficientFunds 200 50 (none — T1 stays PENDING!) 2030 deposit(A1, 80) 280 280 50 seq 6: A1 deposit 80 (bal 280) 2040 accept_transfer(T1, A2) "ACCEPTED" 40 290 seq 7: A1 out 240; seq 8: A2 in 240 2040 accept_transfer(T1, A2) [retry] "ACCEPTED" 40 290 (none — idempotent!) 2040 create_transfer(A1, A2, 25, ttl=60) "T2" (PENDING) 40 290 seq 9,10: transfer_pending on A1,A2 2100 get_transfer_status(T2) "EXPIRED" 40 290 (lazy expiry: 2100 >= 2040 + 60)Replaying
A1's balance-changing records (+300 - 100 + 80 - 240) equals40, matchingget_balance("A1").Complete solution
from typing import Callable, Dict, List, Optional, Tuple import threading import time from dataclasses import dataclass, field # Operation types stored in per-account transaction history. DEPOSIT = "deposit" WITHDRAWAL = "withdrawal" TRANSFER_PENDING = "transfer_pending" TRANSFER_IN = "transfer_in" TRANSFER_OUT = "transfer_out" # Transfer lifecycle states. REJECTED and EXPIRED are the two canceled terminal states. PENDING = "PENDING" ACCEPTED = "ACCEPTED" REJECTED = "REJECTED" EXPIRED = "EXPIRED" DEFAULT_TRANSFER_TTL = 24 * 60 * 60 # 24 hours in seconds class BankError(Exception): """Base class for every domain error raised by Bank.""" class InvalidRequest(BankError): """Bad caller input: non-positive amount, reused request_id with different args, wrong recipient, etc.""" class AccountNotFound(BankError): """The requested account_id does not exist.""" class TransferNotFound(BankError): """The requested transfer_id does not exist.""" class InsufficientFunds(BankError): """Completing the withdrawal or transfer acceptance would leave a negative balance.""" class TransferClosed(BankError): """The transfer has already reached a conflicting terminal state (ACCEPTED, REJECTED, or EXPIRED).""" @dataclass(frozen=True) class Transaction: seq: int # Strictly increasing bank-wide sequence number (orders ties/clock jumps) timestamp: float # Reading from the injected clock when this entry was recorded type: str # One of DEPOSIT, WITHDRAWAL, TRANSFER_PENDING, TRANSFER_IN, TRANSFER_OUT amount: int # Positive integer number of cents balance_after: int # Account balance in cents immediately after this entry transfer_id: Optional[str] = None @dataclass class Account: account_id: str balance: int # history: chronological list of immutable Transaction records, oldest -> newest history: List[Transaction] = field(default_factory=list) @dataclass class Transfer: transfer_id: str from_id: str to_id: str amount: int created_at: float expires_at: float status: str = PENDING def _validate_positive_cents(amount: object) -> None: """Ensure amount is a strictly positive integer (cents), rejecting bool and float.""" # In Python isinstance(True, int) is True, so reject bool explicitly; reject float to avoid rounding drift. if isinstance(amount, bool) or not isinstance(amount, int) or amount <= 0: raise InvalidRequest( f"amount must be a positive integer number of cents, got {amount!r}" ) def _validate_non_negative_int(value: object, field_name: str) -> None: """Ensure value is an integer >= 0 (used for initial_balance and history count n).""" if isinstance(value, bool) or not isinstance(value, int) or value < 0: raise InvalidRequest( f"{field_name} must be a non-negative integer, got {value!r}" ) def _validate_positive_ttl(ttl_seconds: object) -> None: """Ensure ttl_seconds is a positive int or float, rejecting bool, NaN, and non-numbers.""" if isinstance(ttl_seconds, bool) or not isinstance(ttl_seconds, (int, float)): raise InvalidRequest( f"ttl_seconds must be a positive number, got {ttl_seconds!r}" ) # Using 'not (ttl_seconds > 0)' rejects 0, negatives, and float('nan') (NaN > 0 is False). if not (ttl_seconds > 0): raise InvalidRequest(f"ttl_seconds must be positive, got {ttl_seconds!r}") class Bank: def __init__(self, clock: Optional[Callable[[], float]] = None) -> None: self.clock: Callable[[], float] = clock if clock is not None else time.time # Single mutex serializing all public reads and writes so check-then-act steps stay atomic. self.lock = threading.Lock() # accounts: maps account_id (e.g. "A1") -> Account(account_id, balance, history) self.accounts: Dict[str, Account] = {} # transfers: maps transfer_id (e.g. "T1") -> Transfer(..., status) self.transfers: Dict[str, Transfer] = {} # requests: maps request_id -> (argument_signature_tuple, cached_return_value) for idempotency self.requests: Dict[str, Tuple[tuple, object]] = {} self.next_account_num: int = 1 self.next_transfer_num: int = 1 self.next_seq: int = 1 # ---------- internal helpers (caller must already hold self.lock) ---------- def _get_account(self, account_id: str) -> Account: account = self.accounts.get(account_id) if account is None: raise AccountNotFound(account_id) return account def _get_transfer(self, transfer_id: str) -> Transfer: transfer = self.transfers.get(transfer_id) if transfer is None: raise TransferNotFound(transfer_id) return transfer def _append_transaction( self, account: Account, op_type: str, amount: int, now: float, transfer_id: Optional[str] = None, ) -> None: entry = Transaction( seq=self.next_seq, timestamp=now, type=op_type, amount=amount, balance_after=account.balance, transfer_id=transfer_id, ) self.next_seq += 1 account.history.append(entry) def _check_idempotent_replay( self, request_id: Optional[str], signature: tuple, ) -> Tuple[bool, object]: """Return (True, previous_result) on an exact retry, or raise if reused with different args.""" if request_id is None or request_id not in self.requests: return False, None previous_signature, previous_result = self.requests[request_id] if previous_signature != signature: raise InvalidRequest( f"request_id {request_id!r} was already used with different parameters" ) return True, previous_result def _save_idempotent_result( self, request_id: Optional[str], signature: tuple, result: object, ) -> None: """Cache successful results by request_id; failed calls are skipped so callers can fix & retry.""" if request_id is not None: self.requests[request_id] = (signature, result) def _expire_if_due(self, transfer: Transfer, now: float) -> None: """Lazy expiry: flip PENDING -> EXPIRED as soon as now reaches or passes expires_at.""" # Boundary is '>=': a 60s transfer created at t=1000 is already EXPIRED at t=1060. if transfer.status == PENDING and now >= transfer.expires_at: transfer.status = EXPIRED # ---------- account operations ---------- def create_account( self, initial_balance: int = 0, request_id: Optional[str] = None, ) -> str: with self.lock: signature = ("create_account", initial_balance) already_seen, cached_id = self._check_idempotent_replay(request_id, signature) if already_seen: return str(cached_id) _validate_non_negative_int(initial_balance, "initial_balance") account_id = f"A{self.next_account_num}" self.next_account_num += 1 account = Account(account_id=account_id, balance=initial_balance) self.accounts[account_id] = account # Record a positive opening balance as a deposit so replaying history reproduces balance. if initial_balance > 0: self._append_transaction(account, DEPOSIT, initial_balance, self.clock()) self._save_idempotent_result(request_id, signature, account_id) return account_id def get_balance(self, account_id: str) -> int: with self.lock: return self._get_account(account_id).balance def deposit( self, account_id: str, amount: int, request_id: Optional[str] = None, ) -> int: with self.lock: signature = ("deposit", account_id, amount) already_seen, cached_balance = self._check_idempotent_replay(request_id, signature) if already_seen: return int(cached_balance) _validate_positive_cents(amount) account = self._get_account(account_id) account.balance += amount self._append_transaction(account, DEPOSIT, amount, self.clock()) self._save_idempotent_result(request_id, signature, account.balance) return account.balance def withdraw( self, account_id: str, amount: int, request_id: Optional[str] = None, ) -> int: with self.lock: signature = ("withdraw", account_id, amount) already_seen, cached_balance = self._check_idempotent_replay(request_id, signature) if already_seen: return int(cached_balance) _validate_positive_cents(amount) account = self._get_account(account_id) # Strict '<' allows withdrawing the exact remaining balance down to 0 cents. if account.balance < amount: raise InsufficientFunds( f"{account_id} has {account.balance}, needs {amount}" ) account.balance -= amount self._append_transaction(account, WITHDRAWAL, amount, self.clock()) self._save_idempotent_result(request_id, signature, account.balance) return account.balance # ---------- transfer operations ---------- def create_transfer( self, from_id: str, to_id: str, amount: int, ttl_seconds: float = DEFAULT_TRANSFER_TTL, request_id: Optional[str] = None, ) -> str: with self.lock: signature = ("create_transfer", from_id, to_id, amount, ttl_seconds) already_seen, cached_transfer_id = self._check_idempotent_replay( request_id, signature ) if already_seen: return str(cached_transfer_id) _validate_positive_cents(amount) _validate_positive_ttl(ttl_seconds) sender = self._get_account(from_id) receiver = self._get_account(to_id) if from_id == to_id: raise InvalidRequest("cannot transfer to the same account") now = self.clock() transfer_id = f"T{self.next_transfer_num}" self.next_transfer_num += 1 self.transfers[transfer_id] = Transfer( transfer_id=transfer_id, from_id=from_id, to_id=to_id, amount=amount, created_at=now, expires_at=now + ttl_seconds, ) # Balances do not change while PENDING; log transfer_pending on both accounts at identical now. self._append_transaction(sender, TRANSFER_PENDING, amount, now, transfer_id) self._append_transaction(receiver, TRANSFER_PENDING, amount, now, transfer_id) self._save_idempotent_result(request_id, signature, transfer_id) return transfer_id def accept_transfer(self, transfer_id: str, recipient_id: str) -> str: with self.lock: now = self.clock() transfer = self._get_transfer(transfer_id) if transfer.to_id != recipient_id: raise InvalidRequest("only the recipient can accept a transfer") # Refresh expiry before checking status so past-deadline PENDING transfers become EXPIRED. self._expire_if_due(transfer, now) # Idempotent retry: accepting an already ACCEPTED transfer returns ACCEPTED with no side effects. if transfer.status == ACCEPTED: return ACCEPTED if transfer.status != PENDING: raise TransferClosed(f"transfer {transfer_id} is {transfer.status}") sender = self.accounts[transfer.from_id] receiver = self.accounts[transfer.to_id] # Validate funds at acceptance time; if short, keep PENDING so sender can deposit before expiry. if sender.balance < transfer.amount: raise InsufficientFunds( f"{sender.account_id} has {sender.balance}, needs {transfer.amount}" ) # Atomically move cents, append matching ledger entries, and mark ACCEPTED under self.lock. sender.balance -= transfer.amount receiver.balance += transfer.amount self._append_transaction(sender, TRANSFER_OUT, transfer.amount, now, transfer_id) self._append_transaction(receiver, TRANSFER_IN, transfer.amount, now, transfer_id) transfer.status = ACCEPTED return ACCEPTED def reject_transfer(self, transfer_id: str, recipient_id: str) -> str: with self.lock: now = self.clock() transfer = self._get_transfer(transfer_id) if transfer.to_id != recipient_id: raise InvalidRequest("only the recipient can reject a transfer") self._expire_if_due(transfer, now) # Idempotent cancel: if already REJECTED or EXPIRED, return its current canceled status. if transfer.status in (REJECTED, EXPIRED): return transfer.status if transfer.status == ACCEPTED: raise TransferClosed(f"transfer {transfer_id} was already accepted") transfer.status = REJECTED return REJECTED def get_transfer_status(self, transfer_id: str) -> str: with self.lock: transfer = self._get_transfer(transfer_id) self._expire_if_due(transfer, self.clock()) return transfer.status # ---------- history queries ---------- def get_history(self, account_id: str) -> List[Transaction]: with self.lock: # Return a shallow copy so callers cannot mutate the internal history list. return list(self._get_account(account_id).history) def get_recent_history(self, account_id: str, n: int) -> List[Transaction]: """Return the last n records in chronological order (oldest -> newest).""" with self.lock: _validate_non_negative_int(n, "n") history = self._get_account(account_id).history # Compute start index explicitly: Python's history[-0:] equals history[0:] and would return all rows! start_index = max(0, len(history) - n) return history[start_index:]✅ Submit now — all tests should pass.
Intuition & how it works
Think of a two-phase transfer like handing a friend a dated paper check while each account owner keeps a stamped passbook. Writing the check (create_transfer) stamps a "transfer_pending" memo in both passbooks, yet zero cents leave the sender's vault. Funds move only when the recipient walks up to the teller (accept_transfer): inside one locked transaction, the teller confirms the check has neither expired nor already been settled, verifies the sender currently has enough cents, moves the money, and stamps "transfer_out" and "transfer_in" into the two passbooks.
A naive design—storing float balances in a plain dictionary without a lock or retry tracking—fails in four predictable ways. Floating-point arithmetic (0.1 + 0.2) introduces sub-cent drift; two threads calling withdraw(180) on a 300-cent balance simultaneously can both pass balance >= 180 and leave -60; a retried deposit or accept_transfer after a network timeout moves money twice; and relying solely on a periodic background timer lets recipients cash overdue transfers.
Here is how Bank processes Example 2 cleanly in integer cents starting at t = 2000:
create_account(300)(A1) andcreate_account(50)(A2):A1opens at300(seq=1deposit),A2opens at50(seq=2deposit).create_transfer(A1, A2, 240, ttl_seconds=120)->"T1":T1starts"PENDING"(expires_at = 2120); both accounts log"transfer_pending"while balances stay300and50.- Temporary shortfall and recovery: After
withdraw(A1, 100)leaves200,accept_transfer("T1", "A2")raisesInsufficientFundsand keepsT1"PENDING". Oncedeposit(A1, 80)restores280,accept_transfer("T1", "A2")moves240cents underself.lock(A1 -> 40,A2 -> 290), logs"transfer_out"and"transfer_in", and setsT1to"ACCEPTED". - Duplicate retry: Calling
accept_transfer("T1", "A2")a second time seesT1.status == "ACCEPTED"and returns"ACCEPTED"with no balance or ledger changes.
Complexity
Let A be the number of accounts, T the number of transfers, R the number of cached request_id keys, H the total ledger entries across all accounts, and h the number of ledger entries on one account:
create_account,get_balance,deposit,withdraw,create_transfer,accept_transfer,reject_transfer,get_transfer_status: O(1) average time. Each call performs a constant number of dictionary (dict) lookups/inserts and at most twolist.appendoperations, which run in amortized O(1) time (constant average cost per append across dynamic array resizes).get_history(account_id): O(h) time. Looking up the account isO(1)and shallow-copying itshimmutableTransactionreferences into a fresh list takesO(h)time.get_recent_history(account_id, n): O(min(n, h)) time. Computingstart_index = max(0, len(history) - n)isO(1), and slicing copies only the trailingmin(n, h)references.- Space: O(A + T + R + H) total memory. One
Accountper account (O(A)), oneTransferper transfer (O(T)), one(signature, result)entry perrequest_id(O(R)), and everyTransactionrecord (O(H)).
Edge cases
- Idempotent retries vs. parameter mismatches: Replaying a
request_idwith identical arguments returns the original output inO(1)without side effects; reusing arequest_idwith different arguments raisesInvalidRequest. Failed calls (such asInsufficientFunds) are never stored so callers can deposit funds and retry. - Booleans, floats, NaN, and non-positive values:
0, negatives,2.5, strings,float('nan'), andbool(True/False) all raiseInvalidRequest. Explicitly rejectingisinstance(x, bool)is essential in Python becauseboolsubclassesint. - Exact-zero withdrawal: Withdrawing
200from a200-cent balance succeeds and leaves0; withdrawing201raisesInsufficientFundswith zero ledger mutations. - Shortfall at acceptance time: Creating a transfer larger than the sender's current balance succeeds; if the sender is still short when
accept_transferruns,InsufficientFundsis raised while the transfer stays"PENDING"untilexpires_at. - Exact deadline boundary (
now >= expires_at): A 60-second transfer created at2040.0is"EXPIRED"at2100.0. Once"ACCEPTED", a transfer never becomes"EXPIRED". get_recent_historyboundary values:n = 0returns[](sidestepping Python'shistory[-0:]trap),n > hreturns allhentries, andn < 0raisesInvalidRequest.- Wall-clock jumps and ties: Even if
clock()returns duplicate timestamps or steps backward slightly,Transaction.seqguarantees a strict bank-wide total order.
Common mistakes
- Storing balances as
float: Binary floating-point rounding (0.1 + 0.2 != 0.3) corrupts cent-exact balances; always store integer minor units (cents) orDecimal. - Deducting or holding funds inside
create_transfer: Pending transfers must leave balances unchanged until accepted and validate sender funds at acceptance time. - Canceling a transfer when
accept_transferhitsInsufficientFunds: A temporary shortfall should leave the transfer"PENDING"so the sender can deposit funds before expiration. - Slicing
history[-n:]blindly: Whenn == 0,-0 == 0, sohistory[0:]returns the entire history instead of[]. - Returning
account.historywithout copying: Handing out the internallistlets caller code mutate or clear ledger entries outsideself.lock. - Depending on a background thread for expiration: Background timers can lag; lazy expiry (
now >= expires_atchecked on every transfer access) guarantees exact deadline cutoffs. - Checking balances outside a lock: Splitting
if sender.balance >= amount:andsender.balance -= amountacross unlocked steps allows concurrent threads to overdraw or double-settle.
Alternative approaches
- Per-account locks with canonical lock ordering: Give each
Accountits own mutex so unrelated deposits run concurrently. Wheneveraccept_transferlocks two accounts, acquiremin(from_id, to_id)beforemax(from_id, to_id)to avoid deadlock (Thread A holdingA1waiting onA2while Thread B holdsA2waiting onA1). - Explicit hold balances (
available = ledger - reserved): Card networks reserve funds up front so settlement cannot bounce; clarify product requirements first since holds change observable withdrawal behavior. - Double-entry journal: Record every movement as balanced debit/credit pairs summing to
0(using an externalVAULTaccount for cash-in/cash-out) so auditing reduces to verifyingSUM(signed_amount) == 0.
Follow-up questions
-
How would you migrate this single-process ledger to a horizontally scaled service backed by PostgreSQL while preserving atomicity and idempotency? Persist
accounts,transfers,transactions, andidempotency_keys(with a unique index on(caller_id, request_id)) in PostgreSQL, wrapping each operation in a single ACID transaction. Replace the in-process mutex with conditional SQL updates—such asUPDATE transfers SET status = 'ACCEPTED' WHERE id = :tid AND status = 'PENDING' AND expires_at > :nowalongsideUPDATE accounts SET balance = balance - :amt WHERE id = :from_id AND balance >= :amtafter locking both account rows in sortedidorder (SELECT ... FOR UPDATE). Writing theidempotency_keysrecord inside the same database transaction ensures a crash can never move money without also persisting the cached response. -
How could you support fast lookups of a recipient's open incoming transfers and proactively clean up millions of expired records? Maintain an auxiliary index
open_by_recipient: Dict[str, Set[str]]mapping eachto_idto its currently"PENDING"transfer IDs so listing open incoming requests runs inO(k)time forkactive transfers rather than scanning allThistorical transfers. To sweep expired transfers proactively, push(expires_at, transfer_id)onto a min-heap (a priority queue exposing the earliest deadline inO(1)time and popping inO(log T)time) drained by a background worker, while retaining_expire_if_dueas the authoritative synchronous guard. -
Because the idempotency cache currently grows without bound, how would you cap its memory footprint without breaking client retries? Record
created_atalongside(signature, result)inself.requestsand maintain a chronologicalcollections.dequeof(created_at, request_id)entries so keys older than a fixed retention window (commonly 24 hours in payment APIs) are evicted from the front inO(1)amortized time per write. Pair that TTL with client retry budgets bounded well below 24 hours, and scope keys by(authenticated_client_id, request_id)so independent tenants cannot collide.
Follow-up questions
- How would you migrate this single-process ledger to a horizontally scaled service backed by PostgreSQL while preserving atomicity and idempotency?
- How could you support fast lookups of a recipient's open incoming transfers and proactively clean up millions of expired records?
- Because the idempotency cache currently grows without bound, how would you cap its memory footprint without breaking client retries?
Similar questions
- Account Ledger with Scheduled Transfers and Merges
- Locate the Special Guest Using knows(a, b)
- Detect a Spammer Account in Linear Oracle Queries
- Thread-Safe Account Ledger and Transfers
- Verify Sequential Role Assignments Under Seat Caps
- Weather Ingestion and Sub-10-Minute Temperature API
More HubSpot interview questions
- Target Compensation, Package Mix, and Role Leveling Medium
- Design a Global On-Demand Video Streaming Platform Hard
- JavaScript Prototype Delegation and Call-Site 'this' Binding Medium Pro
- Framing Your Current Engineering Role, Ownership Scope, and Track Alignment Medium Pro
- Account Ledger with Scheduled Transfers and Merges Medium Pro
- Weather Ingestion and Sub-10-Minute Temperature API Hard Pro
- Hourly Weather Data Ingestion Service Easy Pro
- Locate the Special Guest Using knows(a, b) Easy Pro
- Detect a Spammer Account in Linear Oracle Queries Medium Pro
- Thread-Safe Account Ledger and Transfers Medium Pro