Implement an idempotent double-entry transaction ledger with balances and history
Role: Software Engineer
Category: Software Engineering Fundamentals
Difficulty: medium
Interview Round: Other
Design a double-entry transaction ledger that records transfers between accounts. Each transaction debits one account and credits another by the same amount, maintaining the fundamental accounting invariant.
The ledger must guarantee idempotency: if a transaction request is retried with the same idempotency key (for example, after a network failure), it must not be recorded again. Instead, the original result of that transaction is returned. A key counts as used once any request carrying it has been processed, even if that request was rejected.
The system should support querying the current balance of any account and retrieving the transaction history for a given account in chronological order. An account exists as soon as a transfer names it. Accounts can have negative balances. Transfers from an account to itself are rejected.
Implement the following methods:
- `recordTransaction(idempotency_key: str, from_account: str, to_account: str, amount: int) -> str` records a transfer of `amount` from `from_account` to `to_account`. If `idempotency_key` was already used, it returns the original result without processing the request again. It returns `"success"` if the transfer is recorded, or a rejection reason string otherwise. A transfer from an account to itself returns `"rejected: same account"`.
- `getBalance(account: str) -> int` returns the current balance of the account, or 0 for an account with no transaction history.
- `getTransactionHistory(account: str) -> List[str]` returns the account's transactions in chronological order. Each entry is formatted as `"{key}: debit {amount} to {counterparty}"` or `"{key}: credit {amount} from {counterparty}"`.
- `getTransactionCount() -> int` returns the total number of unique successful transactions recorded in the ledger.
Example 1:
```text
ledger = TransactionLedger()
ledger.recordTransaction("t1", "alice", "bob", 100) -> "success"
ledger.recordTransaction("t2", "bob", "carol", 30) -> "success"
ledger.recordTransaction("t1", "alice", "bob", 100) -> "success"
ledger.recordTransaction("t3", "carol", "carol", 5) -> "rejected: same account"
ledger.getBalance("alice") -> -100
ledger.getBalance("bob") -> 70
ledger.getBalance("carol") -> 30
ledger.getBalance("dave") -> 0
ledger.getTransactionHistory("bob") -> ["t1: credit 100 from alice", "t2: debit 30 to carol"]
ledger.getTransactionCount() -> 2
```
The second `t1` call is a retry, so it returns the stored `"success"` and leaves the balances alone. `t3` is rejected, so only `t1` and `t2` count. Bob received 100 and sent 30, which leaves him at 70.
Example 2:
```text
ledger = TransactionLedger()
ledger.recordTransaction("k1", "a1", "a1", 50) -> "rejected: same account"
ledger.recordTransaction("k1", "a1", "b2", 50) -> "rejected: same account"
ledger.recordTransaction("k2", "a1", "b2", 50) -> "success"
ledger.getBalance("b2") -> 50
ledger.getTransactionHistory("a1") -> ["k2: debit 50 to b2"]
ledger.getTransactionCount() -> 1
```
The second `k1` call reuses a key whose first request was rejected, so it gets the stored rejection back even though the new accounts differ. Only `k2` moves money.
```hint What a retry must return
A retry has to return exactly what the first call with that key returned. Decide what you store for each key, and at which point in `recordTransaction` you look it up.
```
```hint Keeping history ordered
Chronological order is easy if history is written at the moment a transfer is applied. Think about how many accounts need an entry per transfer, and from whose point of view each entry is worded.
```
### Constraints & Assumptions
- `amount` is an integer from 1 to 1,000,000.
- Account names are non-empty strings containing only lowercase letters and digits.
- Idempotency keys are non-empty strings.
- There is no minimum balance, so balances can go negative.
- At most 10,000 calls are made across all methods.
### Clarifying Questions to Ask
- If a retry reuses a key with a different amount or different accounts, should the ledger return the stored result or report a conflict?
- Does a rejected request use up its idempotency key, so that key can never succeed later?
- Can several threads call the ledger at once, and can two concurrent calls carry the same key?
- Is chronological order the order of calls, or a timestamp supplied with each request?
### What a Strong Answer Covers
- Where the idempotency lookup sits relative to validation and state changes, and whether rejected results are stored.
- How each successful transfer keeps the debit and credit paired so the balances across all accounts always sum to zero.
- How per-account history is built so it comes back in order and in the exact string format, with the counterparty named from that account's side.
- The time cost of each method, including how `getTransactionCount` avoids rescanning every key.
- Edge cases: unknown accounts, retries with a changed payload, and balance overflow in languages with fixed-width integers.
### Follow-up Questions
- How would you detect a retry that reuses a key with a different payload, and what would you return?
- How would you make `recordTransaction` safe when two threads submit the same key, or opposite transfers between the same two accounts, at the same moment?
- How would you support reversing a transaction without editing or deleting history?
- If the ledger were stored in a database, how would you keep the idempotency record and both postings atomic?
Overview: Implement an in-memory double-entry ledger that records transfers between accounts, ignores retried requests that reuse an idempotency key, and answers balance, history and transaction count queries. It tests idempotent API design, keeping an accounting invariant, and choosing data structures that keep each operation fast.