KatInterview

Build an In-Memory Ledger with Deposits and Transfers

Data Structure DesignModel answer
MediumModel answerData Structure Designhash-mapclass-designidempotency

Last updated

Implement an in-memory ledger class supporting account creation, deposits and transfers, with clear return codes, invariants, retry safety and concurrency choices.

Design and implement an in-memory ledger for a small bank. The class, called BankSystem, must expose three operations:

  • bool createAccount(long timestamp, String customerId)
  • int deposit(long timestamp, String customerId, int amount)
  • int pay(long timestamp, String sourceAccountId, String targetAccountId, int amount)

Everything lives in memory. Assume up to roughly 10^5 accounts and 10^6 operations.

What you need to deliver

  1. A data model for accounts and transactions. Use hash maps keyed by id, not lists, so that looking up an account or a transaction takes constant time.
  2. The invariants your system guarantees, for example that no balance ever goes below zero.
  3. Precise return semantics. State what each method returns on success (for example the resulting balance) and on failure (for example a sentinel value), and justify the choice.
  4. Time and space complexity for each operation.
  5. A decision on how to handle each of these edge cases:
    • repeated or out-of-order timestamps
    • insufficient funds
    • unknown accounts
    • a client retrying a request that may already have been applied
    • the concurrency model you assume, and what you would change if multiple threads called the API

Write the code and explain the design choices you made along the way.

Hints

Hint 1

Start with the contract: decide what each method returns for success and failure before coding. A failure value of -1 works for balances because a valid balance is never negative.

Hint 2

Validate everything first and mutate afterwards, so a rejected call leaves no partial changes. Think about which inputs are invalid: unknown ids, non-positive amounts, paying yourself, overdrafts, timestamps that go backwards.

Hint 3

Timestamps cannot identify a retry because two genuine operations can share one. Use a client-supplied request key that maps to a stored result, and for concurrency start with a single lock, then discuss per-account locks acquired in a fixed order.