Thread-Safe Ledger Accounts with Transfer and Absorb Operations
Data Structure DesignModel answerLast updated
Design a concurrency-safe Account class supporting deposits, withdrawals, atomic transfers, and absorbing another account, while preventing overdrafts, deadlocks, and operations on closed accounts.
Build a Thread-Safe Account Class
You are asked to model bank accounts in code. Each Account object holds a balance and a status (open or closed). Several threads may operate on the same accounts at once, so the class must stay correct under concurrency.
Operations
deposit(amount): add money to the account.withdraw(amount): remove money. The balance must never go below zero. If funds are insufficient, returnFalseand change nothing.transfer(target_account, amount): move money from this account to another one. The debit and the credit must appear as a single indivisible step.merge(other_account): pull the full balance ofother_accountinto this account, then closeother_account(balance set to 0, status set to inactive).
Rules
- Operations must be safe when called from many threads simultaneously.
- Illegal states must be prevented. In particular, no money may be sent to a closed account, and an account may not be merged into itself.
- Every account must have a unique
account_id.
Interface
class Account:
def __init__(self, account_id, initial_balance=0.0):
...
def deposit(self, amount):
...
def withdraw(self, amount):
# return False if funds are insufficient
...
def transfer(self, target_account, amount):
...
def merge(self, other_account):
...
Example
acc1 = Account("A", 100)
acc2 = Account("B", 50)
acc1.transfer(acc2, 30)
# acc1: 70, acc2: 80
acc1.merge(acc2)
# acc1: 150, acc2: 0 and inactive
Edge Cases to Handle
- Transferring or withdrawing more than the available balance.
- Merging an account that is already closed.
- Two threads moving money between the same pair of accounts in opposite directions at the same time.
What to Deliver
Explain your design (state, locking strategy, error handling), justify why it is correct, state its complexity, and provide working code.
Hints
Hint 1
Give each account its own lock, and do every read and write of its balance and status while holding it. Think about which checks (such as 'is the account still open?') must happen inside the critical section.
Hint 2
A transfer needs two locks. Picture thread 1 running A to B while thread 2 runs B to A. What happens if each takes its own account's lock first? Find a rule that every thread can follow so a circular wait cannot form.
Hint 3
Do not order locks by the caller-supplied account_id, since IDs might not be comparable. Also consider how to represent money exactly (avoid binary floats) and which failures should return False versus raise an exception.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Each account owns three pieces of state: a balance, an active flag, and a private lock. All access to that state happens under the lock. Single-account operations (deposit, withdraw) take one lock. Two-account operations (transfer, merge) take both locks in a fixed global order, which rules out deadlock.
Key Design Decisions
1. Fine-grained locking. A per-account lock lets unrelated accounts proceed in parallel. A single global lock would be simpler but would serialize everything.
2. Consistent lock ordering to avoid deadlock. Suppose thread 1 runs A.transfer(B) and thread 2 runs B.transfer(A). If each grabs "self first, then target", thread 1 holds A and waits for B while thread 2 holds B and waits for A. Neither progresses. If both always lock the account with the smaller ordering key first, whichever thread arrives second blocks before holding anything, so no cycle can form.
3. Order by an internal sequence number, not by account_id. IDs are supplied by callers and may be of mixed types ("A" vs 7), so comparing them can fail. A monotonically increasing integer assigned at construction is always comparable and unique.
4. Validate inside the critical section. Checking "is the target open?" before taking the locks is a check-then-act race: a concurrent merge could close the target in between, and the credit would land in a dead account. Do the active checks and the balance check after both locks are held.
5. Exact money arithmetic. Use Decimal, converted via Decimal(str(x)), not float, because 0.1 + 0.2 != 0.3 in binary floating point. In production you would often use integer minor units (cents) instead.
6. Error policy. Insufficient funds is an expected business outcome, so return False. Contract violations (closed account, self-transfer, self-merge, non-positive or non-finite amount, wrong type) are caller bugs, so raise exceptions.
7. Unique IDs. A class-level registry guarded by its own lock rejects duplicates. IDs of closed accounts stay reserved so history is never ambiguous.
Why It Is Correct
- Atomic transfer: the balance check, debit and credit all occur while both locks are held, so no thread sees money "in flight" or spends the same funds twice.
- Conservation: each operation either changes nothing or moves exactly
amountbetween two balances. Totals change only through deposit and withdraw. - Merge: under both locks, require both accounts active and distinct, add the full balance to
self, zero the other account and mark it inactive in one step. Since the source is now inactive, a second merge of it raises. - No deadlock: every multi-lock acquisition follows one total order, and no code outside the class runs while locks are held.
Complexity
- Time: O(1) per operation (lock waiting is contention, not algorithmic cost).
- Space: O(1) per account plus O(n) for the ID registry.
Code
import itertools
import threading
from contextlib import contextmanager
from decimal import Decimal, InvalidOperation
class AccountError(Exception):
pass
class InactiveAccountError(AccountError):
pass
class Account:
_registry_lock = threading.Lock()
_used_ids = set()
_seq = itertools.count()
def __init__(self, account_id, initial_balance=0.0):
initial = self._to_amount(initial_balance, allow_zero=True)
with Account._registry_lock:
if account_id in Account._used_ids:
raise ValueError(f"Duplicate account_id: {account_id!r}")
Account._used_ids.add(account_id)
self._order = next(Account._seq)
self.account_id = account_id
self._balance = initial
self._active = True
self._lock = threading.Lock()
@staticmethod
def _to_amount(amount, allow_zero=False):
if isinstance(amount, bool):
raise TypeError("Amount must be numeric")
try:
value = Decimal(str(amount))
except (InvalidOperation, ValueError):
raise TypeError(f"Invalid amount: {amount!r}")
if not value.is_finite():
raise ValueError("Amount must be finite")
if value < 0 or (value == 0 and not allow_zero):
raise ValueError("Amount must be positive")
return value
def _require_active(self):
if not self._active:
raise InactiveAccountError(f"Account {self.account_id!r} is closed")
@staticmethod
@contextmanager
def _locked_pair(a, b):
first, second = (a, b) if a._order < b._order else (b, a)
with first._lock:
with second._lock:
yield
def _check_peer(self, other):
if not isinstance(other, Account):
raise TypeError("Expected an Account")
if other is self:
raise ValueError("Operation requires two distinct accounts")
@property
def balance(self):
with self._lock:
return self._balance
@property
def is_active(self):
with self._lock:
return self._active
def deposit(self, amount):
amt = self._to_amount(amount)
with self._lock:
self._require_active()
self._balance += amt
return True
def withdraw(self, amount):
amt = self._to_amount(amount)
with self._lock:
self._require_active()
if self._balance < amt:
return False
self._balance -= amt
return True
def transfer(self, target_account, amount):
self._check_peer(target_account)
amt = self._to_amount(amount)
with Account._locked_pair(self, target_account):
self._require_active()
target_account._require_active()
if self._balance < amt:
return False
self._balance -= amt
target_account._balance += amt
return True
def merge(self, other_account):
self._check_peer(other_account)
with Account._locked_pair(self, other_account):
self._require_active()
other_account._require_active()
self._balance += other_account._balance
other_account._balance = Decimal(0)
other_account._active = False
return True
Edge Cases
- Overdraft:
withdrawortransferabove the balance returnsFalse, state unchanged. - Invalid amounts: zero, negative, NaN, infinity and
boolare rejected; a zero initial balance is allowed. - Closed accounts: any operation involving an inactive account raises
InactiveAccountError, including merging an already merged account. - Self-operations:
a.transfer(a, x)anda.merge(a)raiseValueError. - Opposing transfers: A to B and B to A at the same time cannot deadlock, and totals stay correct.
- Duplicate IDs: a second
Account("A")raises.
Common Mistakes
- Locking "self then target" with no global order (deadlock).
- Checking
activebefore acquiring locks (check-then-act race). - Using floats for money.
- Ordering locks by
account_idwhen IDs may not be comparable. - Releasing the first lock before the credit is applied, which breaks atomicity.
- Using
id(obj)for ordering without handling ties; a construction-time counter avoids this.
Possible Follow-Ups
- Add a transaction log and idempotency keys so retries do not double-apply.
- Replace in-process locks with database transactions and
SELECT ... FOR UPDATEordered by account key for a distributed version. - Use
try_lockwith timeout and backoff if lock ordering cannot be guaranteed.