Implement a double-entry financial ledger with idempotent transactions and reversals

Quick Overview

Implement an in-memory double-entry ledger that records transfers between accounts, ignores duplicate transaction IDs, and supports one-time reversals recorded as new entries. It tests append-only data modeling, idempotency, keeping state unchanged on rejected calls, and choosing integer types that hold the largest possible balance.

Implement a double-entry financial ledger with idempotent transactions and reversals

Role: Software Engineer

Category: Software Engineering Fundamentals

Difficulty: medium

Interview Round: Other

Design a financial ledger system that records transactions between accounts following double-entry accounting principles. Every transaction debits one account and credits another by the same amount, ensuring the books always balance. The system must guarantee immutability (ledger entries cannot be modified or deleted once recorded), idempotency (recording a transaction with a duplicate ID has no effect and returns `False`), and support rollback via reversal transactions (a reversal creates a new entry that exactly negates the original by swapping the debit and credit accounts). Accounts start with a balance of `0` and are created automatically on first use. Credits increase an account's balance and debits decrease it. Implement a class `FinancialLedger` with the following methods: - `record_transaction(txn_id: str, debit_account: str, credit_account: str, amount: int) -> bool`: Record a double-entry transaction that debits one account and credits another by the given amount. Returns True if the transaction was recorded successfully. Returns False if the transaction ID already exists (idempotent: no duplicate processing). - `reverse_transaction(original_txn_id: str, reversal_txn_id: str) -> bool`: Reverse a previously recorded transaction by creating a new reversal entry that swaps the debit and credit accounts. Returns True if successful. Returns False if the original transaction does not exist, has already been reversed, or if the reversal transaction ID already exists. - `get_balance(account: str) -> int`: Return the current balance of the specified account. Credits increase the balance and debits decrease it. Returns 0 for accounts with no recorded activity. - `get_transaction_history(account: str) -> List[str]`: Return a list of all transaction IDs (including reversals) that involve the given account, in chronological order. - `get_ledger_size() -> int`: Return the total number of entries in the ledger, including both original transactions and reversal entries. The first example covers balances, a reversal and history: ```text Input: ["FinancialLedger", "record_transaction", "record_transaction", "reverse_transaction", "get_balance", "get_balance", "get_balance", "get_transaction_history", "get_transaction_history", "get_ledger_size"] [[], ["t1", "A", "B", 100], ["t2", "B", "C", 30], ["t1", "r1"], ["A"], ["B"], ["C"], ["B"], ["D"], []] Output: [null, true, true, true, 0, -30, 30, ["t1", "t2", "r1"], [], 3] Explanation: ledger = FinancialLedger() # empty ledger ledger.record_transaction("t1", "A", "B", 100) # True (A -100, B +100) ledger.record_transaction("t2", "B", "C", 30) # True (B -30, C +30; B is now 70) ledger.reverse_transaction("t1", "r1") # True (debits B and credits A by 100) ledger.get_balance("A") # 0 (-100 + 100) ledger.get_balance("B") # -30 (100 - 30 - 100) ledger.get_balance("C") # 30 ledger.get_transaction_history("B") # ["t1", "t2", "r1"] ledger.get_transaction_history("D") # [] (no activity) ledger.get_ledger_size() # 3 (2 originals + 1 reversal) ``` The second example covers idempotency and the one-reversal rule: ```text Input: ["FinancialLedger", "record_transaction", "record_transaction", "reverse_transaction", "reverse_transaction", "get_balance", "get_ledger_size"] [[], ["t1", "X", "Y", 200], ["t1", "X", "Y", 200], ["t1", "r1"], ["t1", "r2"], ["X"], []] Output: [null, true, false, true, false, 0, 2] Explanation: ledger = FinancialLedger() # empty ledger ledger.record_transaction("t1", "X", "Y", 200) # True (X -200, Y +200) ledger.record_transaction("t1", "X", "Y", 200) # False (duplicate t1 ignored) ledger.reverse_transaction("t1", "r1") # True (reverses t1: Y -200, X +200) ledger.reverse_transaction("t1", "r2") # False (t1 already reversed) ledger.get_balance("X") # 0 (original and reversal cancel out) ledger.get_ledger_size() # 2 (1 original + 1 reversal) ``` ```hint One lookup by ID Duplicate detection and reversal both start from a transaction ID. Think about which single structure tells you whether an ID was used and what that transaction contained. ``` ```hint Rejected calls A call that returns False must leave every balance, list and set exactly as it was. Decide where the checks go relative to the writes in each method. ``` ```hint Size of a balance Work out the largest balance the constraints allow before you pick an integer type. ``` ### Constraints & Assumptions - `1 <= amount <= 10^6` - Account names are non-empty strings containing only alphanumeric characters. - Transaction IDs are non-empty strings and must be unique (duplicate IDs are ignored). - At most `10^4` total calls will be made across all methods. - Reversal of a non-existent or already-reversed transaction returns `False`. ### Clarifying Questions to Ask - Can the debit and credit account be the same account, and if so, does the transaction appear once or twice in that account's history? - Can a reversal entry itself be reversed, or only original transactions? - Do originals and reversals share one ID space, so a new transaction cannot reuse a reversal's ID? - If a retry reuses a transaction ID with a different amount or different accounts, is a silent False still the right answer, or should it be reported as a conflict? - Is the ledger called from one thread, or must concurrent calls be safe? ### What a Strong Answer Covers - An append-only entry store with no update or delete path, where a reversal is a new entry with the accounts swapped. - One ID index that gives idempotency and constant-time lookup of the original for a reversal, plus a record of which transactions were already reversed. - Validation before mutation, so a rejected call changes nothing, and every False case of `reverse_transaction`. - Balance bookkeeping that keeps the sum of all balances at zero, using an integer type wide enough for the stated bounds. - The cost of each method, including how history comes back in chronological order. ### Follow-up Questions - How would you make the ledger safe under concurrent calls, and which steps must happen atomically? - How would you support a transaction with more than two legs, such as a payment split between a merchant and a fee account, while keeping debits equal to credits? - How would you persist the ledger so balances survive a restart, and how would you check that stored balances still match the entries? - If a client retries with the same ID but a different payload, how should the API respond?

Overview: Implement an in-memory double-entry ledger that records transfers between accounts, ignores duplicate transaction IDs, and supports one-time reversals recorded as new entries. It tests append-only data modeling, idempotency, keeping state unchanged on rejected calls, and choosing integer types that hold the largest possible balance.

General logo
General
Nov 25, 2026
mediumSoftware EngineerOtherSoftware Engineering Fundamentals
0
0

Design a financial ledger system that records transactions between accounts following double-entry accounting principles. Every transaction debits one account and credits another by the same amount, ensuring the books always balance.

The system must guarantee immutability (ledger entries cannot be modified or deleted once recorded), idempotency (recording a transaction with a duplicate ID has no effect and returns False), and support rollback via reversal transactions (a reversal creates a new entry that exactly negates the original by swapping the debit and credit accounts).

Accounts start with a balance of 0 and are created automatically on first use. Credits increase an account's balance and debits decrease it.

Implement a class FinancialLedger with the following methods:

  • record_transaction(txn_id: str, debit_account: str, credit_account: str, amount: int) -> bool : Record a double-entry transaction that debits one account and credits another by the given amount. Returns True if the transaction was recorded successfully. Returns False if the transaction ID already exists (idempotent: no duplicate processing).
  • reverse_transaction(original_txn_id: str, reversal_txn_id: str) -> bool : Reverse a previously recorded transaction by creating a new reversal entry that swaps the debit and credit accounts. Returns True if successful. Returns False if the original transaction does not exist, has already been reversed, or if the reversal transaction ID already exists.
  • get_balance(account: str) -> int : Return the current balance of the specified account. Credits increase the balance and debits decrease it. Returns 0 for accounts with no recorded activity.
  • get_transaction_history(account: str) -> List[str] : Return a list of all transaction IDs (including reversals) that involve the given account, in chronological order.
  • get_ledger_size() -> int : Return the total number of entries in the ledger, including both original transactions and reversal entries.

The first example covers balances, a reversal and history:

Input:
["FinancialLedger", "record_transaction", "record_transaction", "reverse_transaction", "get_balance", "get_balance", "get_balance", "get_transaction_history", "get_transaction_history", "get_ledger_size"]
[[], ["t1", "A", "B", 100], ["t2", "B", "C", 30], ["t1", "r1"], ["A"], ["B"], ["C"], ["B"], ["D"], []]

Output: [null, true, true, true, 0, -30, 30, ["t1", "t2", "r1"], [], 3]

Explanation:
ledger = FinancialLedger()                      # empty ledger
ledger.record_transaction("t1", "A", "B", 100)  # True    (A -100, B +100)
ledger.record_transaction("t2", "B", "C", 30)   # True    (B -30, C +30; B is now 70)
ledger.reverse_transaction("t1", "r1")          # True    (debits B and credits A by 100)
ledger.get_balance("A")                         # 0       (-100 + 100)
ledger.get_balance("B")                         # -30     (100 - 30 - 100)
ledger.get_balance("C")                         # 30
ledger.get_transaction_history("B")             # ["t1", "t2", "r1"]
ledger.get_transaction_history("D")             # []      (no activity)
ledger.get_ledger_size()                        # 3       (2 originals + 1 reversal)

The second example covers idempotency and the one-reversal rule:

Input:
["FinancialLedger", "record_transaction",  "record_transaction",  "reverse_transaction", "reverse_transaction", "get_balance", "get_ledger_size"]
[[],                ["t1", "X", "Y", 200], ["t1", "X", "Y", 200], ["t1", "r1"],          ["t1", "r2"],          ["X"],         []]

Output: [null, true, false, true, false, 0, 2]

Explanation:
ledger = FinancialLedger()                      # empty ledger
ledger.record_transaction("t1", "X", "Y", 200)  # True    (X -200, Y +200)
ledger.record_transaction("t1", "X", "Y", 200)  # False   (duplicate t1 ignored)
ledger.reverse_transaction("t1", "r1")          # True    (reverses t1: Y -200, X +200)
ledger.reverse_transaction("t1", "r2")          # False   (t1 already reversed)
ledger.get_balance("X")                         # 0       (original and reversal cancel out)
ledger.get_ledger_size()                        # 2       (1 original + 1 reversal)

Constraints & Assumptions

  • 1 <= amount <= 10^6
  • Account names are non-empty strings containing only alphanumeric characters.
  • Transaction IDs are non-empty strings and must be unique (duplicate IDs are ignored).
  • At most 10^4 total calls will be made across all methods.
  • Reversal of a non-existent or already-reversed transaction returns False .

Clarifying Questions to Ask Guidance

  • Can the debit and credit account be the same account, and if so, does the transaction appear once or twice in that account's history?
  • Can a reversal entry itself be reversed, or only original transactions?
  • Do originals and reversals share one ID space, so a new transaction cannot reuse a reversal's ID?
  • If a retry reuses a transaction ID with a different amount or different accounts, is a silent False still the right answer, or should it be reported as a conflict?
  • Is the ledger called from one thread, or must concurrent calls be safe?

What a Strong Answer Covers Guidance

  • An append-only entry store with no update or delete path, where a reversal is a new entry with the accounts swapped.
  • One ID index that gives idempotency and constant-time lookup of the original for a reversal, plus a record of which transactions were already reversed.
  • Validation before mutation, so a rejected call changes nothing, and every False case of reverse_transaction .
  • Balance bookkeeping that keeps the sum of all balances at zero, using an integer type wide enough for the stated bounds.
  • The cost of each method, including how history comes back in chronological order.

Follow-up Questions Guidance

  • How would you make the ledger safe under concurrent calls, and which steps must happen atomically?
  • How would you support a transaction with more than two legs, such as a payment split between a merchant and a fee account, while keeping debits equal to credits?
  • How would you persist the ledger so balances survive a restart, and how would you check that stored balances still match the entries?
  • If a client retries with the same ID but a different payload, how should the API respond?