Banking API with Thread-Safe Account Operations
Data Structure DesignModel answerLast updated
Build a thread-safe banking system supporting account creation, deposits, and transfers with atomic balance updates.
You need to build a basic banking system that supports multiple concurrent operations. Your implementation must provide the following functionality:
- Create an account with a unique identifier and optional starting balance
- Query the current balance of any account
- Deposit money into an account
- Transfer money from one account to another
- Close an account (only if the balance is zero)
Requirements
- All monetary amounts must be represented as integer cents to avoid floating-point errors
- Balance updates during transfers must be atomic—either both the debit and credit succeed, or neither does
- The system must handle concurrent access safely with no race conditions or lost updates
- Provide meaningful error handling for invalid operations (account not found, insufficient funds, negative amounts, etc.)
- Prevent deadlocks when multiple threads attempt overlapping transfers
Constraints
- Account IDs are strings
- All amounts are non-negative integers representing cents
- Transfers require the source account to have sufficient funds
- An account cannot transfer to itself
- Accounts with non-zero balances cannot be closed
Your solution should demonstrate proper concurrent programming techniques and maintain data consistency under parallel access.
Hints
Hint 1
Represent money as integer cents rather than floating-point to avoid precision errors in financial calculations
Hint 2
Use per-account locks for concurrency control, but acquire them in a consistent order to prevent deadlock
Hint 3
Validate all preconditions before modifying any state—check both accounts exist, amounts are valid, and funds are sufficient before updating balances
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Solution: Thread-Safe Banking System
Approach
The core challenge is maintaining consistency when multiple threads operate on shared account data. We need to prevent race conditions while avoiding deadlock.
Design Decisions
Money representation: Use integers for cents. Floating-point arithmetic (0.1 + 0.2 = 0.30000000000000004) is unacceptable for financial data.
Locking strategy: Each account gets its own lock, allowing independent operations to proceed in parallel. A separate registry lock protects the account dictionary during creation and deletion.
Deadlock prevention: When a transfer needs both account locks, acquire them in sorted order by account ID. This global ordering ensures no circular wait.
Validation before mutation: Check all preconditions first—accounts exist, amount is positive, funds are sufficient. Only after validation passes do we modify balances. This ensures atomicity: either the entire transfer succeeds or nothing changes.
Closure handling: Mark deleted accounts with a closed flag checked after acquiring the lock. This prevents race conditions where one thread looks up an account just before another deletes it.
Key Implementation Points
Account Structure
Each account contains:
account_id: unique identifierbalance: integer centslock: threading lock for this accountclosed: flag indicating the account was deleted
Transfer Logic
- Validate the amount is a positive integer
- Verify source and destination are different
- Look up both accounts from the registry
- Sort accounts by ID and acquire both locks in order
- Verify neither account is closed
- Check sufficient funds in source
- Update both balances atomically
- Release locks and return new balances
The critical insight: once validation passes under both locks, the arithmetic cannot fail, guaranteeing atomicity.
Concurrency Properties
No lost updates: Every balance read-modify-write happens while holding that account's lock.
Transfer atomicity: Both locks are held throughout validation and mutation. No interleaving is possible.
Money conservation: Deposits add money, transfers move it, deletions only succeed at zero balance. The sum across all accounts changes predictably.
Deadlock freedom: Sorted lock acquisition prevents cycles. The registry lock is released before acquiring account locks.
Complexity
- Time: O(1) for all operations (hash lookup plus constant work)
- Space: O(n) for n accounts, each with its own lock
Edge Cases and Errors
- Duplicate account ID: Raise
AccountExistsError - Negative or zero amounts: Raise
InvalidAmountErrorfor deposits and transfers - Boolean amounts: Reject even though
boolsubclassesintin Python - Missing account: Raise
AccountNotFoundError - Self-transfer: Reject to avoid deadlock and signal likely bug
- Insufficient funds: Raise
InsufficientFundsErrorwithout modifying either balance - Non-zero deletion: Reject to prevent accidental money destruction
Code
import threading
from typing import Dict, Tuple
class BankError(Exception):
"""Base exception for banking operations."""
class AccountExistsError(BankError):
pass
class AccountNotFoundError(BankError):
pass
class InvalidAmountError(BankError):
pass
class InsufficientFundsError(BankError):
pass
class InvalidTransferError(BankError):
pass
class _Account:
__slots__ = ("account_id", "balance", "lock", "closed")
def __init__(self, account_id: str, balance: int):
self.account_id = account_id
self.balance = balance
self.lock = threading.Lock()
self.closed = False
def _validate_amount(amount: int, allow_zero: bool = False):
if not isinstance(amount, int) or isinstance(amount, bool):
raise InvalidAmountError("amount must be an integer")
if amount < 0 or (not allow_zero and amount == 0):
raise InvalidAmountError("amount must be positive")
class BankingSystem:
def __init__(self):
self._accounts: Dict[str, _Account] = {}
self._registry_lock = threading.Lock()
def _lookup(self, account_id: str) -> _Account:
with self._registry_lock:
acct = self._accounts.get(account_id)
if acct is None:
raise AccountNotFoundError(account_id)
return acct
@staticmethod
def _check_open(acct: _Account):
if acct.closed:
raise AccountNotFoundError(acct.account_id)
def create_account(self, account_id: str, initial_balance: int = 0) -> int:
_validate_amount(initial_balance, allow_zero=True)
with self._registry_lock:
if account_id in self._accounts:
raise AccountExistsError(account_id)
self._accounts[account_id] = _Account(account_id, initial_balance)
return initial_balance
def get_balance(self, account_id: str) -> int:
acct = self._lookup(account_id)
with acct.lock:
self._check_open(acct)
return acct.balance
def deposit(self, account_id: str, amount: int) -> int:
_validate_amount(amount)
acct = self._lookup(account_id)
with acct.lock:
self._check_open(acct)
acct.balance += amount
return acct.balance
def transfer(self, src_id: str, dst_id: str, amount: int) -> Tuple[int, int]:
_validate_amount(amount)
if src_id == dst_id:
raise InvalidTransferError("cannot transfer to same account")
src = self._lookup(src_id)
dst = self._lookup(dst_id)
first, second = sorted((src, dst), key=lambda a: a.account_id)
with first.lock, second.lock:
self._check_open(src)
self._check_open(dst)
if src.balance < amount:
raise InsufficientFundsError(f"balance {src.balance} < {amount}")
src.balance -= amount
dst.balance += amount
return src.balance, dst.balance
def delete_account(self, account_id: str):
with self._registry_lock:
acct = self._accounts.get(account_id)
if acct is None:
raise AccountNotFoundError(account_id)
with acct.lock:
if acct.balance != 0:
raise InvalidAmountError("cannot delete non-zero balance")
acct.closed = True
del self._accounts[account_id]
This implementation maintains correctness under concurrent access while avoiding common pitfalls like deadlock and lost updates.