KatInterview

Banking API with Thread-Safe Account Operations

Data Structure DesignModel answer
MediumModel answerData Structure Designconcurrencythreadinglocks

Last 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:

  1. Create an account with a unique identifier and optional starting balance
  2. Query the current balance of any account
  3. Deposit money into an account
  4. Transfer money from one account to another
  5. 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