Build an Idempotent Financial Account System
Data Structure DesignModel answerLast 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 thetx_idwas 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_idhas 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.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core challenge is maintaining two independent concerns: account balances and transaction history for replay detection. These should be kept separate in your data structures.
Data Structures
Use two dictionaries:
- Balance map:
account_id -> balance_cents. Missing keys implicitly represent zero balance. - Transaction log:
tx_id -> (fingerprint, outcome). The fingerprint captures everything about the request: operation type and all parameters. The outcome is the status string returned.
Processing Pipeline
Every mutating operation follows the same four-step sequence:
Step 1: Input Validation
Check that the amount is a positive integer (rejecting zero, negatives, floats, and booleans). For transfers, additionally verify that the source and destination accounts differ. If validation fails, return "INVALID_TRANSACTION" immediately without recording anything. Invalid input should never consume a tx_id.
Step 2: Idempotency Check
Look up the tx_id in the transaction log:
- If not found, this is a new operation—proceed to step 3.
- If found, compare the stored fingerprint with the current request's fingerprint:
- If they match exactly, return the stored outcome without touching balances (idempotent retry).
- If they differ, return
"INVALID_TRANSACTION"(tx_id collision).
Step 3: Business Logic Check
For withdrawals and transfers, verify that the source account has sufficient balance. Do this check before any balance mutation. This ensures atomicity: if a transfer fails, neither account should change.
Step 4: Apply Changes and Record
If all checks pass (or for deposits, after the idempotency check), update the balance(s) and record the transaction in the log with its fingerprint and outcome. Return the outcome.
Key Design Decisions
What constitutes a fingerprint?
A tuple containing the operation type (e.g., "deposit") and all parameters. For example: ("deposit", "alice", 1000) or ("transfer", "alice", "bob", 400). Two requests are identical only if their fingerprints are identical.
Should failed operations be recorded?
Yes, business logic failures like INSUFFICIENT_FUNDS should be recorded. If a client retries with the same tx_id after a failed withdrawal, they should get the cached failure, even if the account has since been funded. This matches real payment API behavior: a tx_id represents one specific attempt with one outcome. If the client wants to try again, they should use a new tx_id.
Validation failures (malformed input) are not recorded because they never constituted a valid transaction attempt.
Why check funds before mutating?
This ensures atomicity. For a transfer, if you debit the source account first and then discover the destination is invalid (or some other issue), you'd need to roll back. By checking everything first, then mutating, you ensure that once you start mutating, you complete successfully.
Handling unknown accounts
Accounts not in the balance map have an implicit zero balance. Use .get(account_id, 0) instead of defaultdict to avoid accidentally creating keys during reads.
Complexity Analysis
Time: O(1) average per operation. Each operation performs a constant number of dictionary lookups and writes.
Space: O(A + T) where A is the number of accounts with non-zero history and T is the number of unique transaction IDs processed.
Edge Cases to Consider
- Exact retry of a successful deposit: returns
SUCCESS, balance unchanged. - Retrying a
tx_idwith different amount, account, or operation type:INVALID_TRANSACTION. - Zero or negative amount:
INVALID_TRANSACTION(not recorded). - Float or boolean amount:
INVALID_TRANSACTION. - Transfer where source equals destination:
INVALID_TRANSACTION. - Withdrawing the exact balance: succeeds, leaves balance at zero.
- Withdrawing from a never-seen account:
INSUFFICIENT_FUNDS(implicit zero balance). - Retrying a previously failed
INSUFFICIENT_FUNDSoperation: returns cachedINSUFFICIENT_FUNDS.
Implementation
from typing import Dict, Tuple
SUCCESS = "SUCCESS"
INSUFFICIENT_FUNDS = "INSUFFICIENT_FUNDS"
INVALID_TRANSACTION = "INVALID_TRANSACTION"
class Ledger:
def __init__(self):
self._balances: Dict[str, int] = {}
self._tx_log: Dict[str, Tuple[tuple, str]] = {}
def _is_valid_amount(self, amount_cents) -> bool:
"""Check if amount is a positive integer (not bool, not float)."""
return (
isinstance(amount_cents, int)
and not isinstance(amount_cents, bool)
and amount_cents > 0
)
def _check_idempotency(self, tx_id: str, fingerprint: tuple):
"""Return cached result if tx_id exists, or None if new."""
if tx_id not in self._tx_log:
return None
stored_fingerprint, stored_outcome = self._tx_log[tx_id]
if stored_fingerprint == fingerprint:
return stored_outcome # Exact replay
else:
return INVALID_TRANSACTION # Collision
def _save_transaction(self, tx_id: str, fingerprint: tuple, outcome: str) -> str:
"""Record transaction and return outcome."""
self._tx_log[tx_id] = (fingerprint, outcome)
return outcome
def deposit(self, tx_id: str, account_id: str, amount_cents: int) -> str:
# Validate
if not self._is_valid_amount(amount_cents):
return INVALID_TRANSACTION
# Check idempotency
fingerprint = ("deposit", account_id, amount_cents)
cached = self._check_idempotency(tx_id, fingerprint)
if cached is not None:
return cached
# Apply
current = self._balances.get(account_id, 0)
self._balances[account_id] = current + amount_cents
return self._save_transaction(tx_id, fingerprint, SUCCESS)
def withdraw(self, tx_id: str, account_id: str, amount_cents: int) -> str:
# Validate
if not self._is_valid_amount(amount_cents):
return INVALID_TRANSACTION
# Check idempotency
fingerprint = ("withdraw", account_id, amount_cents)
cached = self._check_idempotency(tx_id, fingerprint)
if cached is not None:
return cached
# Check funds
current = self._balances.get(account_id, 0)
if current < amount_cents:
return self._save_transaction(tx_id, fingerprint, INSUFFICIENT_FUNDS)
# Apply
self._balances[account_id] = current - amount_cents
return self._save_transaction(tx_id, fingerprint, SUCCESS)
def transfer(self, tx_id: str, from_account_id: str,
to_account_id: str, amount_cents: int) -> str:
# Validate
if not self._is_valid_amount(amount_cents) or from_account_id == to_account_id:
return INVALID_TRANSACTION
# Check idempotency
fingerprint = ("transfer", from_account_id, to_account_id, amount_cents)
cached = self._check_idempotency(tx_id, fingerprint)
if cached is not None:
return cached
# Check funds
from_balance = self._balances.get(from_account_id, 0)
if from_balance < amount_cents:
return self._save_transaction(tx_id, fingerprint, INSUFFICIENT_FUNDS)
# Apply atomically (both updates succeed together)
self._balances[from_account_id] = from_balance - amount_cents
to_balance = self._balances.get(to_account_id, 0)
self._balances[to_account_id] = to_balance + amount_cents
return self._save_transaction(tx_id, fingerprint, SUCCESS)
def get_balance(self, account_id: str) -> int:
return self._balances.get(account_id, 0)
Common Mistakes
Recording validation failures: Don't store tx_id for malformed requests. They should fail immediately and not consume the identifier.
Checking idempotency after mutation: This creates a race where duplicate requests could both mutate state before either checks the log.
Using operation name alone as fingerprint: The fingerprint must include all parameters. Otherwise deposit("tx", "alice", 100) and deposit("tx", "bob", 100) would look identical.
Mutating before checking funds: A transfer that debits first, then finds insufficient funds in some later check, would leave state inconsistent.
Using defaultdict for balances: Reading from a defaultdict creates keys, which would make "never-seen" accounts distinguishable from zero-balance accounts during debugging.