Design a Money Transfer System with Pending Approvals
Data Structure DesignModel answerLast updated
Build an in-memory banking service supporting accounts, transaction history, and two-party transfers that only settle when the recipient explicitly accepts.
Money Transfer Service with Recipient Approval
You are building a lightweight in-memory financial service. The system needs to manage accounts, record every mutation, and handle transfers that do not settle until the receiving party confirms them.
Requirements
1. Accounts and basic operations
create_account(account_id, initial_balance)— registers a new account with a unique ID and a starting balance (in integer cents; no floats). Reject duplicate IDs and negative balances.deposit(account_id, amount)— adds funds; amount must be a positive integer.withdraw(account_id, amount)— subtracts funds; reject if the resulting balance would go below zero.
2. Transaction history
Every successful mutation appends an immutable record containing:
- a monotonically increasing sequence number
- a wall-clock timestamp
- an operation label:
deposit,withdrawal,transfer_pending,transfer_in,transfer_out - the amount involved
- the balance immediately after the operation
- an optional reference to a related transfer ID
Provide:
get_history(account_id)— returns the full ordered list of records for an accountget_recent(account_id, n)— returns only the lastnrecords
3. Two-party transfers
create_transfer(transfer_id, from_id, to_id, amount)— initiates a transfer inPENDINGstate. No balances change at this point. Atransfer_pendingentry is appended to the sender's history. Transfers expire after a configurable TTL (default 24 hours). Support an optionalidempotency_keyso retried requests do not create duplicate transfers.accept_transfer(transfer_id, account_id)— only the intended recipient may call this. Re-validates that the sender has sufficient funds at acceptance time. Moves the transfer toACCEPTED, debits the sender, and credits the recipient atomically. Appendstransfer_outto the sender andtransfer_into the recipient.reject_transfer(transfer_id, account_id)— only the recipient may call this. Moves the transfer toREJECTED. No balances change.
State rules:
- Valid transitions:
PENDING → ACCEPTED,PENDING → REJECTED,PENDING → EXPIRED - Calling
acceptorrejecton an already-settled transfer is a no-op (return the current status), not an error — unless the caller conflicts with the recorded final state in a way that would be nonsensical. - An expired transfer cannot be accepted or rejected.
What to deliver
Implement the service in the language of your choice. Then:
- State the data structures you chose and why.
- Give the time and space complexity for each operation.
- Discuss at least four edge cases and how you handle them.
- Explain how you prevent deadlocks and ensure exactly-once settlement.
Constraints
- All monetary values are integers (cents). Reject floats or negative amounts.
- No external databases or queues — everything lives in memory.
- The solution must be safe under concurrent calls.
Hints
Hint 1
Funds may be spent between when a transfer is created and when it is accepted. Where exactly should the balance check happen — and under which lock?
Hint 2
To avoid deadlock when locking two accounts at once, establish a consistent lock ordering before you write a single line of concurrent code.
Hint 3
A per-transfer lock plus a sorted two-account lock covers acceptance. But what ordering ensures the transfer lock is always acquired before the account locks, never after?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The service manages three kinds of mutable state: accounts, transfers, and history records. Each deserves its own locking story.
Data structures
Accounts live in a dict account_id → Account. Each Account holds an integer balance in cents, an append-only list of Txn records, and a threading.Lock. Using cents eliminates floating-point rounding entirely.
Transfers live in a dict transfer_id → Transfer. A Transfer is a tiny state machine (PENDING → ACCEPTED | REJECTED | EXPIRED) with its own lock. Keeping the lock on the transfer object, not on a global registry, means two unrelated transfers never block each other.
History is purely an append to the owning account's list. Records carry a global monotonic sequence number (not just a timestamp) so ordering is unambiguous even if the system clock jumps backwards during an NTP correction.
Locking discipline — deadlock prevention
Three rules, applied unconditionally:
- To mutate a single account, acquire that account's lock.
- To mutate two accounts simultaneously (during acceptance), acquire them in ascending account-ID order.
- To settle a transfer, acquire the transfer lock first, then the account locks.
No code path acquires an account lock and then reaches for a transfer lock. There is therefore no lock cycle, and no deadlock is possible. This is the most important design decision to state explicitly in an interview.
Exactly-once settlement
When two concurrent accept_transfer calls race, both first acquire the transfer lock. One wins, changes the status to ACCEPTED, and releases. The second sees ACCEPTED and returns immediately — a pure no-op. The account locks are never even reached by the loser. The same logic applies to concurrent reject calls, or a mixed accept/reject race.
Balance check at acceptance, not creation
The sender's balance is checked inside the combined critical section of accept_transfer, after both the transfer lock and both account locks are held. This is intentional: the sender might have withdrawn funds in the interval between creating and accepting the transfer. Checking at creation time only would allow an overdraft.
Complexity
| Operation | Time | Notes |
|---|---|---|
create_account, deposit, withdraw | O(1) amortized | dict lookup + list append |
create_transfer | O(1) | |
accept_transfer / reject_transfer | O(1) | three locks, constant work |
get_history(id) | O(H) | H = number of records for that account |
get_recent(id, n) | O(n) | slice from the tail |
Space is O(A + T + H) where A is account count, T is transfer count, and H is total history records across all accounts.
Edge cases
- Insufficient funds at acceptance: raise
InsufficientFunds, leave the transferPENDING. The sender can deposit more and the recipient can try again before expiry. Auto-cancelling on failure is a valid alternative — name whichever you pick. - Expired transfers: expiry is evaluated lazily under the transfer lock. No background thread is required; an expired transfer simply cannot transition to any other state.
- Idempotent creation: an optional
idempotency_keymaps to an existingtransfer_id. A client that retries after a network timeout receives the same transfer ID rather than creating a duplicate. - Self-transfers: a transfer where
from_id == to_idis rejected immediately. - Wrong actor: only the designated recipient may accept or reject. Any other caller gets a
TransferError. - Timestamps vs. ordering: wall time is stored for display, but the global sequence counter is the source of truth for ordering. This matters when records from two accounts are interleaved for audit purposes.
Common mistakes
- Checking balance in
create_transferinstead ofaccept_transfer— allows overdraft. - Using
floatfor monetary amounts — introduces rounding errors; always use integer cents orDecimal. - Locking accounts in arbitrary order — creates the potential for deadlock under concurrent transfers between the same two accounts in opposite directions.
- Treating a second
acceptcall on an already-accepted transfer as an error — it should be idempotent.
Python implementation
import itertools
import threading
import time
import uuid
from dataclasses import dataclass, field
from enum import Enum
from typing import Callable, Dict, List, Optional
# ---------------------------------------------------------------------------
# Exceptions
# ---------------------------------------------------------------------------
class BankError(Exception): pass
class AccountNotFound(BankError): pass
class InvalidAmount(BankError): pass
class InsufficientFunds(BankError): pass
class TransferError(BankError): pass
# ---------------------------------------------------------------------------
# Domain objects
# ---------------------------------------------------------------------------
class Status(Enum):
PENDING = "PENDING"
ACCEPTED = "ACCEPTED"
REJECTED = "REJECTED"
EXPIRED = "EXPIRED"
@dataclass(frozen=True)
class Txn:
seq: int
timestamp: float
op: str # deposit | withdrawal | transfer_pending | transfer_in | transfer_out
amount: int # cents
balance: int # balance after this operation
transfer_id: Optional[str] = None
@dataclass
class Account:
id: str
balance: int
history: List[Txn] = field(default_factory=list)
lock: threading.Lock = field(default_factory=threading.Lock)
@dataclass
class Transfer:
id: str
src: str
dst: str
amount: int
created_at: float
expires_at: float
status: Status = Status.PENDING
lock: threading.Lock = field(default_factory=threading.Lock)
# ---------------------------------------------------------------------------
# Service
# ---------------------------------------------------------------------------
class Bank:
def __init__(
self,
clock: Callable[[], float] = time.time,
transfer_ttl_seconds: float = 24 * 3600,
):
self._clock = clock
self._ttl = transfer_ttl_seconds
self._accounts: Dict[str, Account] = {}
self._transfers: Dict[str, Transfer] = {}
self._idem: Dict[str, str] = {} # idempotency_key -> transfer_id
self._registry_lock = threading.Lock()
self._seq_counter = itertools.count()
self._seq_lock = threading.Lock()
# --- internal helpers ---------------------------------------------------
@staticmethod
def _validate_amount(amount: int) -> None:
if not isinstance(amount, int) or isinstance(amount, bool) or amount <= 0:
raise InvalidAmount(f"amount must be a positive integer, got {amount!r}")
def _next_seq(self) -> int:
with self._seq_lock:
return next(self._seq_counter)
def _get_account(self, account_id: str) -> Account:
acct = self._accounts.get(account_id)
if acct is None:
raise AccountNotFound(account_id)
return acct
def _get_transfer(self, transfer_id: str) -> Transfer:
t = self._transfers.get(transfer_id)
if t is None:
raise TransferError(f"unknown transfer {transfer_id!r}")
return t
def _append(
self, acct: Account, op: str, amount: int, transfer_id: Optional[str] = None
) -> None:
# Caller must already hold acct.lock.
acct.history.append(
Txn(self._next_seq(), self._clock(), op, amount, acct.balance, transfer_id)
)
# --- accounts -----------------------------------------------------------
def create_account(self, account_id: str, initial_balance: int = 0) -> None:
if not isinstance(initial_balance, int) or isinstance(initial_balance, bool) \
or initial_balance < 0:
raise InvalidAmount("initial_balance must be a non-negative integer")
with self._registry_lock:
if account_id in self._accounts:
raise BankError(f"account {account_id!r} already exists")
acct = Account(account_id, initial_balance)
with acct.lock:
if initial_balance > 0:
self._append(acct, "deposit", initial_balance)
self._accounts[account_id] = acct
def deposit(self, account_id: str, amount: int) -> int:
self._validate_amount(amount)
acct = self._get_account(account_id)
with acct.lock:
acct.balance += amount
self._append(acct, "deposit", amount)
return acct.balance
def withdraw(self, account_id: str, amount: int) -> int:
self._validate_amount(amount)
acct = self._get_account(account_id)
with acct.lock:
if acct.balance < amount:
raise InsufficientFunds(
f"balance {acct.balance} < withdrawal {amount}"
)
acct.balance -= amount
self._append(acct, "withdrawal", amount)
return acct.balance
# --- transfers ----------------------------------------------------------
def create_transfer(
self,
transfer_id: str,
from_id: str,
to_id: str,
amount: int,
idempotency_key: Optional[str] = None,
) -> str:
self._validate_amount(amount)
if from_id == to_id:
raise TransferError("source and destination accounts must differ")
# Idempotency: return existing transfer_id for duplicate requests.
if idempotency_key:
with self._registry_lock:
if idempotency_key in self._idem:
return self._idem[idempotency_key]
src = self._get_account(from_id)
_ = self._get_account(to_id) # validates recipient exists
now = self._clock()
transfer = Transfer(
id = transfer_id,
src = from_id,
dst = to_id,
amount = amount,
created_at = now,
expires_at = now + self._ttl,
)
with self._registry_lock:
if transfer_id in self._transfers:
raise TransferError(f"transfer {transfer_id!r} already exists")
if idempotency_key:
self._idem[idempotency_key] = transfer_id
self._transfers[transfer_id] = transfer
with src.lock:
self._append(src, "transfer_pending", amount, transfer_id)
return transfer_id
def accept_transfer(self, transfer_id: str, account_id: str) -> Status:
t = self._get_transfer(transfer_id)
if t.dst != account_id:
raise TransferError("only the recipient may accept a transfer")
with t.lock:
# Lazy expiry check — under the transfer lock.
if t.status == Status.PENDING and self._clock() > t.expires_at:
t.status = Status.EXPIRED
if t.status != Status.PENDING:
return t.status # idempotent for already-settled transfers
src = self._get_account(t.src)
dst = self._get_account(t.dst)
# Always acquire account locks in sorted ID order to prevent deadlock.
first, second = sorted([src, dst], key=lambda a: a.id)
with first.lock, second.lock:
if src.balance < t.amount:
raise InsufficientFunds(
f"sender balance {src.balance} < transfer amount {t.amount}"
)
src.balance -= t.amount
dst.balance += t.amount
self._append(src, "transfer_out", t.amount, t.id)
self._append(dst, "transfer_in", t.amount, t.id)
t.status = Status.ACCEPTED
return t.status
def reject_transfer(self, transfer_id: str, account_id: str) -> Status:
t = self._get_transfer(transfer_id)
if t.dst != account_id:
raise TransferError("only the recipient may reject a transfer")
with t.lock:
if t.status == Status.PENDING and self._clock() > t.expires_at:
t.status = Status.EXPIRED
if t.status != Status.PENDING:
return t.status
t.status = Status.REJECTED
return t.status
# --- history ------------------------------------------------------------
def get_history(self, account_id: str) -> List[Txn]:
acct = self._get_account(account_id)
with acct.lock:
return list(acct.history)
def get_recent(self, account_id: str, n: int) -> List[Txn]:
acct = self._get_account(account_id)
with acct.lock:
return list(acct.history[-n:])
Quick smoke test
bank = Bank()
bank.create_account("alice", 10_000)
bank.create_account("bob", 0)
tid = bank.create_transfer("t1", "alice", "bob", 3_000)
bank.deposit("alice", 500) # alice now has 10 500
status = bank.accept_transfer("t1", "bob") # alice → 7 500, bob → 3 000
assert status == Status.ACCEPTED
print(bank.get_recent("alice", 2))
print(bank.get_recent("bob", 1))