Design a thread-safe in-memory ledger with atomic transfers
Role: Software Engineer
Category: Software Engineering Fundamentals
Difficulty: medium
Interview Round: Other
Design a thread-safe in-memory ledger that manages financial accounts. The ledger supports creating accounts with an initial balance, transferring funds between accounts, depositing, withdrawing, and querying balances.
All operations must be atomic and thread-safe. A transfer must fail if the source account has insufficient funds or if either account does not exist. Deposits and withdrawals must also validate account existence, and sufficient funds where applicable.
If a `get_balance` query is made for a non-existent account, return `-1`.
Implement a class `InMemoryLedger` with these methods:
- `create_account(account_id: str, initial_balance: int) -> bool` creates a new account with the given initial balance. It returns `True` if the account was created, or `False` if an account with that ID already exists.
- `transfer(from_account: str, to_account: str, amount: int) -> bool` moves `amount` from `from_account` to `to_account`. It returns `True` if the transfer succeeded, or `False` if either account does not exist or the source has insufficient funds.
- `get_balance(account_id: str) -> int` returns the current balance of the account, or `-1` if the account does not exist.
- `deposit(account_id: str, amount: int) -> bool` adds `amount` to the account. It returns `True` on success, or `False` if the account does not exist.
- `withdraw(account_id: str, amount: int) -> bool` subtracts `amount` from the account. It returns `True` on success, or `False` if the account does not exist or has insufficient funds.
Example:
```python
ledger = InMemoryLedger()
ledger.create_account("alice", 100) # -> True
ledger.create_account("bob", 50) # -> True
ledger.create_account("alice", 10) # -> False (alice already exists)
ledger.transfer("alice", "bob", 30) # -> True (alice: 70, bob: 80)
ledger.transfer("bob", "carol", 10) # -> False (carol does not exist)
ledger.withdraw("bob", 100) # -> False (bob has only 80)
ledger.deposit("bob", 20) # -> True (bob: 100)
ledger.get_balance("bob") # -> 100
ledger.get_balance("carol") # -> -1
```
```hint Check and update together
For a withdrawal or a transfer, think about what another thread can do between the moment you read a balance and the moment you write the new one.
```
```hint How fine-grained the locking needs to be
Decide how coarse your locking can be at the stated scale. If you split it into finer locks, trace two transfers that touch the same two accounts in opposite directions.
```
### Constraints & Assumptions
- `1 <= number of operations <= 10⁴`
- `0 <= initial_balance, amount <= 10⁹`
- `account_id` consists of lowercase English letters and digits.
- At most `1000` distinct accounts.
- Any method can be called from many threads at the same time.
### Clarifying Questions to Ask
- Should a transfer from an account to itself succeed, and with what effect on the balance?
- Can an amount be negative, and if so, should it be rejected?
- Are accounts ever closed or deleted?
- Does the ledger need to keep a history of transactions, or only the current balances?
### What a Strong Answer Covers
- Which shared state the lock or locks protect, and why each validation must sit in the same critical section as the update it guards.
- How a transfer stays atomic, so no thread can observe the debit without the matching credit.
- The trade-off between one lock for the whole ledger and per-account locks, including how deadlock is avoided if the locks are split.
- Edge cases: missing accounts, insufficient funds, duplicate account creation, a transfer from an account to itself, and balance overflow in languages with fixed-width integers.
### Follow-up Questions
- If one lock became the bottleneck under heavy traffic, how would you split it while keeping transfers atomic and deadlock-free?
- How would you add a transaction history that can reconstruct any account's balance at a past point in time?
- How would you make the ledger survive a process crash without losing acknowledged operations?
- How would you make transfer requests idempotent so that a client retry does not move money twice?
Overview: Design a thread-safe in-memory ledger that creates accounts, moves money between them, and handles deposits, withdrawals and balance queries atomically. Tests lock scope, check-then-act races, atomic transfers, and the trade-off between one ledger-wide lock and per-account locks with a deadlock-free order.