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

  1. 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 integer initial_balance. When initial_balance > 0, append an initial "deposit" record; when initial_balance == 0, start with an empty ledger.
    • get_balance(account_id: str) -> int: Return the account's current balance in cents, or raise AccountNotFound.
    • deposit(account_id: str, amount: int, request_id: Optional[str] = None) -> int: Add amount cents, append a "deposit" record, and return the updated balance.
    • withdraw(account_id: str, amount: int, request_id: Optional[str] = None) -> int: Subtract amount cents, append a "withdrawal" record, and return the updated balance. If balance < amount, raise InsufficientFunds without modifying balance or history.
  2. Per-account ledger history
    • Every Transaction captures a strictly increasing bank-wide sequence number seq, the clock() reading timestamp, type, amount, balance_after, and optional transfer_id.
    • get_history(account_id: str) -> List[Transaction]: Return a chronological copy (oldest first) of all records for account_id (without exposing internal mutable list storage).
    • get_recent_history(account_id: str, n: int) -> List[Transaction]: Return the most recent n records in chronological order (oldest first). Raise InvalidRequest if n is not an integer >= 0.
  3. 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 at created_at + ttl_seconds and append "transfer_pending" entries (with unchanged balances and transfer_id set) to both accounts. Do not check or reserve sender funds at creation time. Reject from_id == to_id or non-positive ttl_seconds with InvalidRequest.
    • Expiration rule: Any "PENDING" transfer becomes "EXPIRED" as soon as clock() >= created_at + ttl_seconds.
    • accept_transfer(transfer_id: str, recipient_id: str) -> str: Only to_id may accept (otherwise raise InvalidRequest). If already "ACCEPTED", return "ACCEPTED" with no side effects. If "REJECTED" or "EXPIRED", raise TransferClosed. If "PENDING" and sender.balance < amount, raise InsufficientFunds while 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: Only to_id may reject (otherwise raise InvalidRequest). If "PENDING", mark "REJECTED" and return "REJECTED". If already "REJECTED" or "EXPIRED", return that current status without side effects. If "ACCEPTED", raise TransferClosed.
    • get_transfer_status(transfer_id: str) -> str: Return "PENDING", "ACCEPTED", "REJECTED", or "EXPIRED" (reflecting deadline expiration immediately), or raise TransferNotFound.
  4. Idempotency via request_id
    • On create_account, deposit, withdraw, and create_transfer, when a non-None request_id is repeated with the exact same method and arguments as a prior successful call, return the original result without mutating state. Reusing a remembered request_id with different method/arguments raises InvalidRequest. Failed calls are not cached under request_id.

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

  • amount on deposits, withdrawals, and transfers must be a positive int (> 0, excluding bool and float); initial_balance and n must be int values >= 0. Invalid types or ranges raise InvalidRequest.
  • ttl_seconds must be a finite positive int or float (> 0, excluding bool and NaN).
  • Single-record operations (create_account, get_balance, deposit, withdraw, create_transfer, accept_transfer, reject_transfer, get_transfer_status) must run in O(1) average time; get_recent_history(account_id, n) must run in O(min(n, h)) time for an account with h records.

Step-by-step walkthrough

  1. Clarify requirements and design the API

    We need a thread-safe in-memory Bank ledger supporting account creation, overdraft-safe deposits and withdrawals, per-account Transaction logs, and two-phase transfers (PENDING until 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 uses time.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_id on accept_transfer and reject_transfer so 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]
    
  2. Choose O(1) in-memory data structures

    Because every method addresses accounts and transfers by ID, Python dict hash tables give O(1) average lookup time. Inside each Account, an append-only list of frozen Transaction objects supports O(1) amortized appends and O(min(n, h)) tail slicing for get_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 = 1
    

    Declaring Transaction with frozen=True prevents caller code holding a returned record from mutating its amount or balance_after fields.

  3. Model the pending-transfer state machine and lazy expiry

    Each transfer begins in PENDING and transitions at most once into one of three terminal states (ACCEPTED, REJECTED, or EXPIRED). Cents move only along the PENDING -> ACCEPTED transition:

                      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_transfer and reject_transfer idempotent (safe to repeat when a network response drops), retries matching the terminal outcome return cleanly without moving funds a second time, whereas conflicting transitions raise TransferClosed:

    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-deadline PENDING transfer to EXPIRED:

        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
    
  4. Make 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 another 125 cents.

    We accept an optional idempotency key (request_id) on create_account, deposit, withdraw, and create_transfer, storing (signature, result) inside self.requests:

    • Identical retry (same request_id and parameters): Replay the cached return value in O(1) without modifying balances or ledger entries.
    • Conflicting reuse (same request_id with different method or parameters): Raise InvalidRequest.
    • 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)
    
  5. Validate inputs and implement account operations

    In Python, bool subclasses int (isinstance(True, int) is True), so validators must reject booleans before checking isinstance(..., int). Likewise, _validate_positive_ttl writes not (ttl_seconds > 0) instead of ttl_seconds <= 0 because float('nan') <= 0 evaluates to False in IEEE-754 floating-point math, whereas not (ttl_seconds > 0) rejects 0, negatives, and NaN together:

    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_account opens with initial_balance > 0, recording an opening DEPOSIT ensures replaying an account's history from 0 always matches get_balance. withdraw checks account.balance < amount before 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.balance
    
  6. Implement two-phase transfers (create, accept, reject)

    create_transfer verifies both accounts exist, rejects from_id == to_id, creates a PENDING Transfer expiring at now + ttl_seconds, and appends "transfer_pending" entries to both accounts without checking or reserving sender funds.

    accept_transfer samples now = self.clock() once, checks recipient_id == transfer.to_id, runs _expire_if_due(transfer, now), handles idempotent/closed states, verifies sender.balance >= transfer.amount, and moves the cents—all under self.lock so no concurrent withdraw can 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 ACCEPTED
    
  7. Serve transaction history safely and handle concurrency

    Two classic Python traps arise in history queries:

    1. Always copy account.history: Returning the internal list directly would let bank.get_history(a).clear() erase the ledger! Return list(account.history) instead.
    2. Avoid history[-n:] when n == 0: Because -0 == 0 in Python, history[-0:] evaluates to history[0:] and returns every record instead of []! Using start_index = max(0, len(history) - n) and slicing history[start_index:] handles n == 0, 0 < n < len(history), and n >= 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 seq alongside timestamp solves clock ties and wall-clock drift: even if two operations execute during the same clock tick or NTP nudges time.time() backward, seq increases strictly under self.lock. And because private helpers (_get_account, _append_transaction, ...) assume their public caller already holds self.lock, a standard threading.Lock serializes every check-then-act sequence cleanly without reentrancy deadlocks.

  8. Trace a multi-step transfer and overdraft recovery

    Let's walk through Example 2 (A1 opening with 300 cents and A2 opening with 50 cents at t = 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) equals 40, matching get_balance("A1").

  9. 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:

  1. create_account(300) (A1) and create_account(50) (A2): A1 opens at 300 (seq=1 deposit), A2 opens at 50 (seq=2 deposit).
  2. create_transfer(A1, A2, 240, ttl_seconds=120) -> "T1": T1 starts "PENDING" (expires_at = 2120); both accounts log "transfer_pending" while balances stay 300 and 50.
  3. Temporary shortfall and recovery: After withdraw(A1, 100) leaves 200, accept_transfer("T1", "A2") raises InsufficientFunds and keeps T1 "PENDING". Once deposit(A1, 80) restores 280, accept_transfer("T1", "A2") moves 240 cents under self.lock (A1 -> 40, A2 -> 290), logs "transfer_out" and "transfer_in", and sets T1 to "ACCEPTED".
  4. Duplicate retry: Calling accept_transfer("T1", "A2") a second time sees T1.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 two list.append operations, 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 is O(1) and shallow-copying its h immutable Transaction references into a fresh list takes O(h) time.
  • get_recent_history(account_id, n): O(min(n, h)) time. Computing start_index = max(0, len(history) - n) is O(1), and slicing copies only the trailing min(n, h) references.
  • Space: O(A + T + R + H) total memory. One Account per account (O(A)), one Transfer per transfer (O(T)), one (signature, result) entry per request_id (O(R)), and every Transaction record (O(H)).

Edge cases

  • Idempotent retries vs. parameter mismatches: Replaying a request_id with identical arguments returns the original output in O(1) without side effects; reusing a request_id with different arguments raises InvalidRequest. Failed calls (such as InsufficientFunds) are never stored so callers can deposit funds and retry.
  • Booleans, floats, NaN, and non-positive values: 0, negatives, 2.5, strings, float('nan'), and bool (True/False) all raise InvalidRequest. Explicitly rejecting isinstance(x, bool) is essential in Python because bool subclasses int.
  • Exact-zero withdrawal: Withdrawing 200 from a 200-cent balance succeeds and leaves 0; withdrawing 201 raises InsufficientFunds with 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_transfer runs, InsufficientFunds is raised while the transfer stays "PENDING" until expires_at.
  • Exact deadline boundary (now >= expires_at): A 60-second transfer created at 2040.0 is "EXPIRED" at 2100.0. Once "ACCEPTED", a transfer never becomes "EXPIRED".
  • get_recent_history boundary values: n = 0 returns [] (sidestepping Python's history[-0:] trap), n > h returns all h entries, and n < 0 raises InvalidRequest.
  • Wall-clock jumps and ties: Even if clock() returns duplicate timestamps or steps backward slightly, Transaction.seq guarantees 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) or Decimal.
  • 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_transfer hits InsufficientFunds: A temporary shortfall should leave the transfer "PENDING" so the sender can deposit funds before expiration.
  • Slicing history[-n:] blindly: When n == 0, -0 == 0, so history[0:] returns the entire history instead of [].
  • Returning account.history without copying: Handing out the internal list lets caller code mutate or clear ledger entries outside self.lock.
  • Depending on a background thread for expiration: Background timers can lag; lazy expiry (now >= expires_at checked on every transfer access) guarantees exact deadline cutoffs.
  • Checking balances outside a lock: Splitting if sender.balance >= amount: and sender.balance -= amount across unlocked steps allows concurrent threads to overdraw or double-settle.

Alternative approaches

  • Per-account locks with canonical lock ordering: Give each Account its own mutex so unrelated deposits run concurrently. Whenever accept_transfer locks two accounts, acquire min(from_id, to_id) before max(from_id, to_id) to avoid deadlock (Thread A holding A1 waiting on A2 while Thread B holds A2 waiting on A1).
  • 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 external VAULT account for cash-in/cash-out) so auditing reduces to verifying SUM(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, and idempotency_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 as UPDATE transfers SET status = 'ACCEPTED' WHERE id = :tid AND status = 'PENDING' AND expires_at > :now alongside UPDATE accounts SET balance = balance - :amt WHERE id = :from_id AND balance >= :amt after locking both account rows in sorted id order (SELECT ... FOR UPDATE). Writing the idempotency_keys record 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 each to_id to its currently "PENDING" transfer IDs so listing open incoming requests runs in O(k) time for k active transfers rather than scanning all T historical transfers. To sweep expired transfers proactively, push (expires_at, transfer_id) onto a min-heap (a priority queue exposing the earliest deadline in O(1) time and popping in O(log T) time) drained by a background worker, while retaining _expire_if_due as 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_at alongside (signature, result) in self.requests and maintain a chronological collections.deque of (created_at, request_id) entries so keys older than a fixed retention window (commonly 24 hours in payment APIs) are evicted from the front in O(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

Similar questions

More HubSpot interview questions

All 13 HubSpot questions →