Implement a thread-safe account ledger with atomic, deadlock-free transfers
Role: Software Engineer
Category: Software Engineering Fundamentals
Difficulty: medium
Interview Round: Other
Design a thread-safe account ledger that manages multiple bank accounts. The system must support creating accounts, depositing and withdrawing funds, transferring money between accounts, and querying balances. Any method may be called from several threads at the same time.
The transfer operation must be atomic: either both the debit and the credit succeed, or neither does. The system must prevent deadlocks when multiple concurrent transfers involve overlapping accounts. This is achieved by always acquiring account locks in a deterministic order.
All monetary values are integers representing cents. Operations that would result in a negative balance must be rejected. Transfers between the same account are not allowed.
Implement the following methods:
- `create_account(account_id: str, initial_balance: int) -> bool`: Create a new account with the given ID and initial balance. Returns `True` if the account was created successfully, `False` if the account already exists or the initial balance is negative.
- `deposit(account_id: str, amount: int) -> bool`: Deposit the specified amount into the account. Returns `True` on success, `False` if the account does not exist or the amount is non-positive.
- `withdraw(account_id: str, amount: int) -> bool`: Withdraw the specified amount from the account. Returns `True` on success, `False` if the account does not exist, the amount is non-positive, or there are insufficient funds.
- `transfer(from_id: str, to_id: str, amount: int) -> bool`: Atomically transfer the specified amount from one account to another. Acquires locks in sorted order to prevent deadlocks. Returns `True` on success, `False` if either account does not exist, the accounts are the same, the amount is non-positive, or the source has insufficient funds.
- `get_balance(account_id: str) -> int`: Return the current balance of the specified account, or `-1` if the account does not exist.
Example 1 (transfers):
```text
Input:
["AccountLedger", "create_account", "create_account", "transfer", "transfer", "transfer", "transfer", "get_balance", "get_balance", "get_balance"]
[[], ["alice", 1000], ["bob", 250], ["alice", "bob", 300], ["bob", "alice", 600], ["alice", "alice", 100], ["alice", "carol", 50], ["alice"], ["bob"], ["carol"]]
Output: [null, true, true, true, false, false, false, 700, 550, -1]
Explanation:
ledger = AccountLedger() # initialize empty ledger
ledger.create_account("alice", 1000) # True (alice: 1000)
ledger.create_account("bob", 250) # True (bob: 250)
ledger.transfer("alice", "bob", 300) # True (alice: 700, bob: 550)
ledger.transfer("bob", "alice", 600) # False (insufficient funds, bob only has 550)
ledger.transfer("alice", "alice", 100) # False (same account)
ledger.transfer("alice", "carol", 50) # False (carol does not exist)
ledger.get_balance("alice") # 700
ledger.get_balance("bob") # 550
ledger.get_balance("carol") # -1 (carol does not exist)
```
Example 2 (single-account operations):
```text
Input:
["AccountLedger", "create_account", "create_account", "withdraw", "withdraw", "get_balance", "deposit", "withdraw", "get_balance"]
[[], ["acc1", 500], ["acc1", 100], ["acc1", 200], ["acc1", 400], ["acc1"], ["acc1", 100], ["acc1", 400], ["acc1"]]
Output: [null, true, false, true, false, 300, true, true, 0]
Explanation:
ledger = AccountLedger() # initialize empty ledger
ledger.create_account("acc1", 500) # True (acc1: 500)
ledger.create_account("acc1", 100) # False (acc1 already exists)
ledger.withdraw("acc1", 200) # True (acc1: 300)
ledger.withdraw("acc1", 400) # False (insufficient funds, acc1 only has 300)
ledger.get_balance("acc1") # 300
ledger.deposit("acc1", 100) # True (acc1: 400)
ledger.withdraw("acc1", 400) # True (acc1: 0)
ledger.get_balance("acc1") # 0
```
```hint Where the check happens
Picture two threads each withdrawing 300 cents from an account that holds 500. Look at which reads have to happen while the account's lock is held.
```
```hint Shared state besides balances
Per-account locks protect balances, but the map from account IDs to accounts is shared too. Think about two threads creating the same ID at the same moment.
```
### Constraints & Assumptions
- `1 <= number of operations <= 10^4`
- Account IDs are non-empty strings.
- `0 <= initial_balance, amount <= 10^6`, in cents.
- Transfers between the same account are rejected.
- Operations that would cause a negative balance are rejected.
### Clarifying Questions to Ask
- Can an account be closed or deleted, or does it exist for the life of the ledger?
- When another thread holds an account's lock, should a call wait, or may it fail fast?
- Does `get_balance` have to reflect in-flight transfers consistently, or is a read that misses an in-progress update acceptable?
- Is a transaction history required, or only current balances?
### What a Strong Answer Covers
- The validation and return value of every method, checked before any balance changes.
- Where each lock is taken, with every balance check made while the lock guarding that balance is held.
- Why a fixed order for the two transfer locks rules out deadlock, and how the locks are released on every exit path, including early returns.
- How account creation and lookup stay safe when two threads create the same ID or one thread looks up an account another thread is creating.
- Time and space cost per operation, and the trade-off against a single ledger-wide lock.
### Follow-up Questions
- How would you support an operation that moves money among three or more accounts in one atomic step?
- How would you add an append-only transaction history so that any balance can be rebuilt from its entries?
- What changes if accounts can be closed while other threads are transferring into them?
- How would you keep the same guarantees if the balances lived in a database or were spread across services?
Overview: Implement an account ledger that creates accounts, handles deposits and withdrawals, and moves money between accounts while many threads call it at once. It tests per-account locking, check-then-act races, atomic transfers, and deadlock prevention through a consistent lock order.