KatInterview

Build an Idempotent Financial Account System

Data Structure DesignModel answer
HardModel answerData Structure Designfinancial-systemsidempotencydata-structures

Last updated

Create an in-memory account manager that enforces balance rules, prevents duplicate processing via transaction IDs, and detects conflicting retries.

Overview

You need to build an in-memory system that tracks account balances and processes financial operations safely. The system must prevent accounts from going negative, handle network retry scenarios gracefully, and detect when clients accidentally reuse identifiers incorrectly.

Requirements

Implement a Ledger class that manages accounts (each identified by a string) and their balances (stored as integer cents). The class should support three mutating operations and one query:

class Ledger:
    def __init__(self):
        pass

    def deposit(self, tx_id: str, account_id: str, amount_cents: int) -> str:
        pass

    def withdraw(self, tx_id: str, account_id: str, amount_cents: int) -> str:
        pass

    def transfer(self, tx_id: str, from_account_id: str, to_account_id: str, amount_cents: int) -> str:
        pass

    def get_balance(self, account_id: str) -> int:
        pass

Operation Semantics

Each mutating operation accepts a tx_id (transaction identifier) that clients use to ensure safe retries. If a client calls an operation with a tx_id that was previously used with identical parameters, the system must return the original result without modifying any balances. If a client reuses a tx_id with different parameters, the operation must fail.

Deposit: Add funds to an account.

Withdraw: Remove funds from an account. Fails if the account has insufficient balance.

Transfer: Move funds from one account to another atomically. Fails if the source account has insufficient balance. Transferring to the same account is invalid.

Get Balance: Return the current balance. Accounts that have never been referenced have a balance of zero.

Return Values

Mutating operations return one of three status strings:

  • "SUCCESS" — The operation completed successfully, or this is an exact replay of a prior successful operation.
  • "INSUFFICIENT_FUNDS" — The account lacks sufficient balance for the withdrawal or transfer.
  • "INVALID_TRANSACTION" — The input is malformed (non-positive amount, self-transfer), or the tx_id was previously used with different parameters.

Rules and Constraints

  • All amounts must be positive integers (in cents). Zero, negative, floating-point, or boolean values are invalid.
  • Accounts start implicitly at zero balance; you don't need to pre-create them.
  • Account IDs and transaction IDs are non-empty strings.
  • Transfers must be atomic: if a transfer fails, neither account should be modified.
  • Once a tx_id has been used, its outcome is permanently associated with that identifier and the parameters that were used.

Example Usage

ledger = Ledger()

ledger.deposit("tx_1", "alice", 1000)  # -> "SUCCESS"
ledger.get_balance("alice")            # -> 1000

# Attempt to withdraw more than available
ledger.withdraw("tx_2", "alice", 1500) # -> "INSUFFICIENT_FUNDS"
ledger.get_balance("alice")            # -> 1000 (unchanged)

# Replay the exact same deposit (same tx_id, same params)
ledger.deposit("tx_1", "alice", 1000)  # -> "SUCCESS"
ledger.get_balance("alice")            # -> 1000 (still, not 2000)

# Reuse tx_id with different amount
ledger.deposit("tx_1", "alice", 500)   # -> "INVALID_TRANSACTION"

# Transfer funds between accounts
ledger.transfer("tx_3", "alice", "bob", 400) # -> "SUCCESS"
ledger.get_balance("alice")                   # -> 600
ledger.get_balance("bob")                     # -> 400

Hints

Hint 1

Track two separate pieces of state: current balances per account, and a history of processed transaction IDs with their parameters and outcomes.

Hint 2

For idempotency checking, create a fingerprint of each operation that captures the operation type and all its parameters, then compare fingerprints when a tx_id is reused.

Hint 3

Validate inputs before checking idempotency so that malformed requests never consume a tx_id. Check funds before mutating balances so that failed operations remain atomic.