KatInterview

Thread-Safe Ledger Accounts with Transfer and Absorb Operations

Data Structure DesignModel answer
MediumModel answerData Structure Designoopconcurrencylocking

Last 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

  1. deposit(amount): add money to the account.
  2. withdraw(amount): remove money. The balance must never go below zero. If funds are insufficient, return False and change nothing.
  3. transfer(target_account, amount): move money from this account to another one. The debit and the credit must appear as a single indivisible step.
  4. merge(other_account): pull the full balance of other_account into this account, then close other_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.