Backdated Loan Ledger with Fee-Priority Repayments
Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen
Problem Statement
Design an event-driven loan accounting ledger that tracks two integer balances per loan—principal_balance (initialized to 100000) and fee_balance (initialized to 0)—and expose it through the stream runner process_loan_events:
def process_loan_events(events: List[List]) -> List[List[List[int]]]:
Each incoming item in events has the form [event_type, amount, accounting_sequence], processed strictly in arrival order:
-
Balance Allocation Rules (
Balances,process_fee,process_payment)"FEE": increasesfee_balancebyamountand leavesprincipal_balanceunchanged."PAYMENT": pays downfee_balancefirst (up tomin(amount, fee_balance)sofee_balancenever becomes negative), then subtracts any leftover payment (amount - paid_to_fee) fromprincipal_balance. When a payment exceedsfee_balance + principal_balance,principal_balancebecomes negative to represent an overpayment credit.
-
Out-of-Order Ledger (
LoanLedger,LedgerEntry)LoanLedgerstarts withself.balances = Balances(principal_balance=100000, fee_balance=0)and providesprocess_event(event_type, amount, accounting_sequence) -> List[LedgerEntry], where eachLedgerEntryrecords(accounting_sequence, principal_balance, fee_balance)immediately after that event takes effect.- Events can arrive out of chronological sequence (for instance, a backdated fee arriving after later payments).
- Entries in the returned history must be ordered by ascending
accounting_sequence. When multiple events share the sameaccounting_sequence, keep them in arrival order (newly received events follow earlier arrivals at that sequence). - Avoid recomputing the entire loan from scratch on every arrival: preserve unaffected earlier snapshots and replay only from the newly inserted event's position onward. Keep
self.balancesequal to the state at the end of the timeline (highest sequence). - Validate inputs before mutating ledger state: if
event_typeis neither"PAYMENT"nor"FEE", ifamountis negative or not anint(rejectingbool), or ifaccounting_sequenceis not anint(rejectingbool), raiseValueErrorwith existing state intact.
-
Stream Output
process_loan_events(events)feeds each event into a singleLoanLedgerinstance and collects the resulting history after every step, serializing eachLedgerEntryas[accounting_sequence, principal_balance, fee_balance].
Examples
Example 1
Input:
events = [["PAYMENT", 2000, 2], ["PAYMENT", 800, 6], ["FEE", 250, 4]]
Output:
[
[[2, 98000, 0]],
[[2, 98000, 0], [6, 97200, 0]],
[[2, 98000, 0], [4, 98000, 250], [6, 97450, 0]]
]
Explanation:
- First arrival (PAYMENT 2000 at sequence 2): reduces principal from 100000 to 98000, giving [[2, 98000, 0]].
- Second arrival (PAYMENT 800 at sequence 6): reduces principal further to 97200, giving [[2, 98000, 0], [6, 97200, 0]].
- Third arrival (FEE 250 at sequence 4): slots in between sequences 2 and 6. Sequence 2 stays (98000, 0) without replay; sequence 4 becomes (98000, 250); replaying sequence 6's 800 payment now clears the 250 fee first and applies only 550 toward principal (98000 - 550 = 97450), producing [6, 97450, 0].
Example 2
Input:
events = [["FEE", 400, 5], ["PAYMENT", 150, 5], ["PAYMENT", 600, 1]]
Output:
[
[[5, 100000, 400]],
[[5, 100000, 400], [5, 100000, 250]],
[[1, 99400, 0], [5, 99400, 400], [5, 99400, 250]]
]
Explanation:
- First arrival posts a 400 fee at sequence 5 ((100000, 400)).
- Second arrival ties at sequence 5, so it lands after the fee and partially reduces fee_balance to 250 while principal remains 100000.
- Third arrival is backdated to sequence 1 (before everything else), lowering initial principal to 99400 and shifting the principal balance of both sequence-5 snapshots to 99400.
Constraints
- Starting loan balances are
principal_balance = 100000andfee_balance = 0. 0 <= len(events) <= 2000.- Valid events have
event_type in {"PAYMENT", "FEE"}, integeramount >= 0(not isinstance(amount, bool)), and integeraccounting_sequence(not isinstance(accounting_sequence, bool)); invalid inputs raiseValueError.
Step-by-step walkthrough
Understand the loan rules and settle open edge cases
A loan starts with
principal_balance = 100000andfee_balance = 0. Two kinds of events arrive over time:FEE(amount): addsamounttofee_balanceand leavesprincipal_balanceunchanged.PAYMENT(amount): pays downfee_balancefirst, and applies any leftover money toprincipal_balance:
Incoming PAYMENT | v [ 1. Pay down fee_balance (up to min(amount, fee_balance)) ] | v (any remaining amount = amount - paid_to_fee) [ 2. Reduce principal_balance ]In
LoanLedger, events carry an integeraccounting_sequence(acting as their effective timeline position) and can arrive out of order. After each arrival, we return the full ledger history sorted byaccounting_sequence.Let's state clear, consistent answers to the prompt's clarifying questions up front:
- Partial fee payments: if
amount < fee_balance, the entire payment reducesfee_balanceandprincipal_balancestays untouched. - Overpayments: if a payment exceeds
fee_balance + principal_balance,principal_balancegoes negative (representing a credit owed to the borrower) so no money ever vanishes silently andprincipal + feealways equals100000 + total_fees - total_payments. - Amounts and validation: amounts must be non-negative integers (
0or positive, like cents). Negative amounts, booleans, or unknown event types raiseValueErrorwithout changing the ledger. - Ties on
accounting_sequence: events with the same sequence are ordered in arrival order (a newly arrived event goes after earlier arrivals at that sequence). self.balances: always holds the balances after the final entry on the accounting timeline (self.states[-1]), not the middle-of-history entry of a backdated event.
Part 1: Write immutable balance handlers
Let's trace both payment cases with
fee_balance = 300andprincipal_balance = 100000:- Payment of
100(smaller than fee):paid_to_fee = min(100, 300) = 100,paid_to_principal = 100 - 100 = 0->(100000, 200). - Payment of
1000(larger than fee):paid_to_fee = min(1000, 300) = 300,paid_to_principal = 1000 - 300 = 700->(99300, 0).
Notice one formula handles both cases cleanly:
paid_to_fee = min(amount, balances.fee_balance), andpaid_to_principal = amount - paid_to_fee.Just as important:
process_paymentandprocess_feereturn a brand-newBalancesinstance instead of mutatingbalancesin place. In Part 2 we store theBalancessnapshot after every historical event; marking@dataclass(frozen=True)guarantees a replay of event 3 can never accidentally overwrite the saved snapshot of event 2.from dataclasses import dataclass INITIAL_PRINCIPAL = 100000 EVENT_TYPES = ("PAYMENT", "FEE") # frozen=True makes snapshots immutable so replaying later events can never overwrite saved past states. @dataclass(frozen=True) class Balances: principal_balance: int fee_balance: int @dataclass(frozen=True) class LedgerEntry: accounting_sequence: int principal_balance: int fee_balance: int def check_amount(amount: int) -> None: # Reject booleans explicitly because `bool` is a subclass of `int` in Python. if isinstance(amount, bool) or not isinstance(amount, int) or amount < 0: raise ValueError(f"amount must be a non-negative integer, got {amount!r}") def check_sequence(accounting_sequence: int) -> None: if isinstance(accounting_sequence, bool) or not isinstance(accounting_sequence, int): raise ValueError(f"accounting_sequence must be an integer, got {accounting_sequence!r}") def process_payment(balances: Balances, amount: int) -> Balances: check_amount(amount) paid_to_fee = min(amount, balances.fee_balance) paid_to_principal = amount - paid_to_fee return Balances( principal_balance=balances.principal_balance - paid_to_principal, fee_balance=balances.fee_balance - paid_to_fee, ) def process_fee(balances: Balances, amount: int) -> Balances: check_amount(amount) return Balances( principal_balance=balances.principal_balance, fee_balance=balances.fee_balance + amount, )- Payment of
Why backdated events change later entries — but never earlier ones
Look at Example 1 when
FEE 250at sequence4arrives afterPAYMENT 2000(seq2) andPAYMENT 800(seq6):Before FEE arrives: init (100000, 0) --[PAY 2000 @ seq 2]--> (98000, 0) --[PAY 800 @ seq 6]--> (97200, 0) After FEE 250 @ seq 4 is inserted in the middle: init (100000, 0) --[PAY 2000 @ seq 2]--> (98000, 0) --[FEE 250 @ seq 4]--> (98000, 250) --[PAY 800 @ seq 6]--> (97450, 0) ^ ^ UNCHANGED prefix! 250 went to fee, only 550 to principal!Two key observations jump out from this timeline:
- You cannot just apply a backdated fee to
self.balances. Because sequence4happened before sequence6,PAYMENT 800at sequence6must now absorb that250fee first, changing sequence6's entry from(97200, 0)to(97450, 0). - You do NOT need to replay from the start of the loan. Nothing before sequence
4changed! As long as we saved the post-event snapshot(98000, 0)at sequence2, we can start straight from(98000, 0)and replay only from sequence4onward.
- You cannot just apply a backdated fee to
Key idea: three parallel lists and binary search (`bisect_right`)
Inside
LoanLedger, we maintain three parallel lists kept sorted byaccounting_sequence:index i: 0 1 2 sequences: [ 2, 4, 6 ] events: [ ("PAYMENT", 2000), ("FEE", 250), ("PAYMENT", 800) ] states: [ Balances(98000,0), Balances(98000,250), Balances(97450,0) ]When a new event with
accounting_sequencearrives:- We locate its insertion index
position = bisect.bisect_right(self.sequences, accounting_sequence)inO(log n)time. - Why
bisect_rightinstead ofbisect_left? Whenaccounting_sequenceties with existing entries,bisect_rightplaces the new event to the right of (after) all earlier arrivals at that sequence, preserving arrival order on ties. - We insert into
sequences,events, andstatesatposition, then callself._replay_from(position).
- We locate its insertion index
Implement `LoanLedger.process_event`
Always validate
event_type,amount, andaccounting_sequencebefore inserting into any list. If we inserted intoself.sequencesfirst and then raisedValueErroron a negativeamount, our three parallel lists would have different lengths and corrupt every future call.import bisect from typing import List, Tuple class LoanLedger: def __init__(self): self.balances = Balances(principal_balance=INITIAL_PRINCIPAL, fee_balance=0) self.sequences: List[int] = [] self.events: List[Tuple[str, int]] = [] self.states: List[Balances] = [] def process_event( self, event_type: str, amount: int, accounting_sequence: int ) -> List[LedgerEntry]: # Phase 1: validate every input BEFORE mutating any list so bad calls leave no partial state. if event_type not in EVENT_TYPES: raise ValueError(f"unknown event type: {event_type!r}") check_amount(amount) check_sequence(accounting_sequence) # Phase 2: find insertion slot; bisect_right places equal-sequence ties AFTER older arrivals. position = bisect.bisect_right(self.sequences, accounting_sequence) self.sequences.insert(position, accounting_sequence) self.events.insert(position, (event_type, amount)) self.states.insert(position, Balances(INITIAL_PRINCIPAL, 0)) # Phase 3: recompute only from `position` onward, keeping all earlier snapshots untouched. self._replay_from(position) # Current loan balances reflect the end of the accounting timeline (highest sequence). self.balances = self.states[-1] return self.history()Implement suffix replay, history export, and the judge wrapper
_replay_from(position)grabs the starting state right beforeposition:- If
position == 0(the new event precedes every existing event), start fromBalances(100000, 0). - Otherwise, start from
self.states[position - 1].
Then a simple loop from
positiontolen(self.events) - 1applies each(event_type, amount)and overwritesself.states[i]. If an in-order event lands at the very end (position == n - 1), this loop runs just one iteration!def _replay_from(self, position: int) -> None: if position == 0: state = Balances(principal_balance=INITIAL_PRINCIPAL, fee_balance=0) else: state = self.states[position - 1] for i in range(position, len(self.events)): event_type, amount = self.events[i] state = apply_event(state, event_type, amount) self.states[i] = stateFinally,
history()zipssequencesandstatesintoLedgerEntryobjects, andprocess_loan_events(events)feeds the input stream intoLoanLedgerand formats eachLedgerEntryas[sequence, principal, fee]for the automated judge.- If
Trace Example 1 event by event
Arrival 1: ("PAYMENT", 2000, seq=2) bisect_right([], 2) -> position = 0 (start from (100000, 0)) replay i=0: PAY 2000 -> (98000, 0) sequences = [2] states = [(98000, 0)] returns -> [[2, 98000, 0]] Arrival 2: ("PAYMENT", 800, seq=6) bisect_right([2], 6) -> position = 1 (start from states[0] = (98000, 0)) replay i=1: PAY 800 -> (97200, 0) (i=0 was NOT reprocessed!) sequences = [2, 6] states = [(98000, 0), (97200, 0)] returns -> [[2, 98000, 0], [6, 97200, 0]] Arrival 3: ("FEE", 250, seq=4) bisect_right([2, 6], 4) -> position = 1 (start from states[0] = (98000, 0)) replay i=1: FEE 250 -> (98000, 250) replay i=2: PAY 800 -> 250 to fee, 550 to principal -> (97450, 0) sequences = [2, 4, 6] states = [(98000, 0), (98000, 250), (97450, 0)] returns -> [[2, 98000, 0], [4, 98000, 250], [6, 97450, 0]]Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple import bisect from dataclasses import dataclass INITIAL_PRINCIPAL = 100000 EVENT_TYPES = ("PAYMENT", "FEE") # frozen=True makes snapshots immutable so replaying later events can never overwrite saved past states. @dataclass(frozen=True) class Balances: principal_balance: int fee_balance: int @dataclass(frozen=True) class LedgerEntry: accounting_sequence: int principal_balance: int fee_balance: int def check_amount(amount: int) -> None: # Reject booleans explicitly because `bool` is a subclass of `int` in Python. if isinstance(amount, bool) or not isinstance(amount, int) or amount < 0: raise ValueError(f"amount must be a non-negative integer, got {amount!r}") def check_sequence(accounting_sequence: int) -> None: if isinstance(accounting_sequence, bool) or not isinstance(accounting_sequence, int): raise ValueError(f"accounting_sequence must be an integer, got {accounting_sequence!r}") def process_payment(balances: Balances, amount: int) -> Balances: check_amount(amount) # Pay down fees first; fees can never drop below 0 because we cap at balances.fee_balance. paid_to_fee = min(amount, balances.fee_balance) # Any leftover payment reduces principal (negative principal represents an overpayment credit). paid_to_principal = amount - paid_to_fee return Balances( principal_balance=balances.principal_balance - paid_to_principal, fee_balance=balances.fee_balance - paid_to_fee, ) def process_fee(balances: Balances, amount: int) -> Balances: check_amount(amount) return Balances( principal_balance=balances.principal_balance, fee_balance=balances.fee_balance + amount, ) def apply_event(balances: Balances, event_type: str, amount: int) -> Balances: if event_type == "PAYMENT": return process_payment(balances, amount) if event_type == "FEE": return process_fee(balances, amount) raise ValueError(f"unknown event type: {event_type!r}") class LoanLedger: def __init__(self): self.balances = Balances(principal_balance=INITIAL_PRINCIPAL, fee_balance=0) # Three parallel lists kept sorted by accounting_sequence (ties stay in arrival order): # - sequences[i]: int accounting_sequence of entry i, e.g. [1, 2, 3] # - events[i]: (event_type, amount) tuple of entry i, e.g. [("PAYMENT", 1000), ...] # - states[i]: Balances snapshot right AFTER entry i is applied self.sequences: List[int] = [] self.events: List[Tuple[str, int]] = [] self.states: List[Balances] = [] def process_event( self, event_type: str, amount: int, accounting_sequence: int ) -> List[LedgerEntry]: # Phase 1: validate every input BEFORE mutating any list so bad calls leave no partial state. if event_type not in EVENT_TYPES: raise ValueError(f"unknown event type: {event_type!r}") check_amount(amount) check_sequence(accounting_sequence) # Phase 2: find insertion slot; bisect_right places equal-sequence ties AFTER older arrivals. position = bisect.bisect_right(self.sequences, accounting_sequence) self.sequences.insert(position, accounting_sequence) self.events.insert(position, (event_type, amount)) self.states.insert(position, Balances(INITIAL_PRINCIPAL, 0)) # Phase 3: recompute only from `position` onward, keeping all earlier snapshots untouched. self._replay_from(position) # Current loan balances reflect the end of the accounting timeline (highest sequence). self.balances = self.states[-1] return self.history() def _replay_from(self, position: int) -> None: # Events before `position` never changed, so resume from the snapshot right before `position`. if position == 0: state = Balances(principal_balance=INITIAL_PRINCIPAL, fee_balance=0) else: state = self.states[position - 1] for i in range(position, len(self.events)): event_type, amount = self.events[i] state = apply_event(state, event_type, amount) self.states[i] = state def history(self) -> List[LedgerEntry]: entries = [] for i in range(len(self.sequences)): state = self.states[i] entries.append( LedgerEntry( accounting_sequence=self.sequences[i], principal_balance=state.principal_balance, fee_balance=state.fee_balance, ) ) return entries def process_loan_events(events: List[List]) -> List[List[List[int]]]: ledger = LoanLedger() outputs = [] # Feed events in arrival order and serialize each returned history for the judge. for event_type, amount, accounting_sequence in events: entries = ledger.process_event(event_type, amount, accounting_sequence) rows = [] for entry in entries: rows.append( [entry.accounting_sequence, entry.principal_balance, entry.fee_balance] ) outputs.append(rows) return outputs✅ Submit now — all tests should pass.
Intuition & how it works
Picture a loan as two buckets sitting in a line: a small fee bucket in front (starting at 0) and a large principal bucket behind it (starting at 100000). Every FEE pours money into the front bucket, while every PAYMENT scoops as much as possible out of the front fee bucket first and only uses leftover money to lower the back principal bucket. Now think of the ledger as a dated checkbook register where every line saves the balance snapshot right after that transaction: if a late Tuesday fee arrives in the mail on Thursday, Monday's line cannot change, so you read Monday's saved snapshot, insert Tuesday's fee right after Monday, and recalculate only Tuesday through Thursday.
Why do simpler shortcuts fail? If you maintain only a single live self.balances object without history, adding a late fee of 100 after two payments leaves fee = 100 at the end, missing the fact that the later payment would have paid off that 100 fee instead of reducing principal! On the flip side, re-sorting the entire log and replaying from (100000, 0) on every call wastes work recalculating thousands of untouched prefix events whenever an event arrives near the end of the timeline.
Let's walk through Example 1 (PAYMENT 2000 at seq 2, PAYMENT 800 at seq 6, then a backdated FEE 250 at seq 4):
1. PAY 2000 @ seq 2 -> start (100000, 0) -> [(2, 98000, 0)]
2. PAY 800 @ seq 6 -> resume from seq 2's (98000, 0) -> [(2, 98000, 0), (6, 97200, 0)]
3. FEE 250 @ seq 4 -> insert at index 1; seq 2 stays (98000, 0) untouched!
- apply FEE 250 at seq 4 -> (98000, 250)
- replay PAY 800 at seq 6 -> 250 clears fee, 550 lowers principal -> (97450, 0)
-> [(2, 98000, 0), (4, 98000, 250), (6, 97450, 0)]
Complexity
Let n be the number of events stored in the ledger after the current call, and k (1 <= k <= n) be the number of entries at or after the new event's insertion position (k = 1 for an in-order arrival at the tail; k = n for a backdated arrival before everything else).
- State update per
process_eventcall:O(log n + k). Binary search (bisect_right, which repeatedly halves the sortedsequenceslist to locate the insertion point) takesO(log n)comparisons. Inserting into the three Python lists shiftsk - 1trailing elements inO(k)time, and_replay_fromrunsO(1)arithmetic for each of thekaffected events (O(1)replay work when events arrive in order!). - History return per
process_eventcall:O(n)(making totalprocess_loan_eventsruntimeO(n^2)acrossncalls). Because the required API returns a freshn-entry history list on every call, constructing that output list costsO(n)per call and1 + 2 + ... + n = O(n^2)total output entries acrossnevents. If the API returned onlyself.balancesor thekmodified suffix entries, each call would takeO(log n + k). - Ledger space:
O(n). Apart from the returned output lists,LoanLedgerstores one integer insequences, one(event_type, amount)tuple inevents, and one immutableBalancessnapshot instatesper event.
Edge cases
- Payment smaller than or equal to current fee balance:
paid_to_fee = min(amount, fee_balance)absorbs the entire payment into fees (paid_to_principal = 0), leavingprincipal_balanceunchanged and never lettingfee_balancego negative. - Overpayment (
amount > fee_balance + principal_balance): Fees drop to0andprincipal_balancebecomes negative (for example,-100), cleanly recording a borrower credit while preservingprincipal + fee == 100000 + fees - payments. - Backdated event earlier than all existing events (
position == 0):_replay_from(0)starts fromBalances(100000, 0)instead ofself.states[-1](which in Python would accidentally read the last element ofself.statesif we wroteself.states[position - 1]without checkingposition == 0!). - Ties on
accounting_sequence:bisect_rightplaces a later-arriving event after all earlier arrivals sharing that sequence, soFEE 100 @ seq 5followed byPAYMENT 50 @ seq 5ends at fee50, whereas the reverse arrival order ends at fee100. - Invalid inputs (
amount < 0,amount = True, unknownevent_type): Validation runs before any.insert(...)call, raisingValueErrorwhile leavingsequences,events,states, andself.balancescompletely intact.
Common mistakes
- Mutating
Balancesin place instead of returning a newBalancesobject: Ifprocess_paymentmodifiesbalances.principal_balance -= ...on a mutable object, multiple slots inself.statescan end up aliasing or corrupting earlier historical snapshots during replay. - Forgetting
if position == 0:in_replay_from: Writingstate = self.states[position - 1]unconditionally evaluatesself.states[-1]whenposition == 0, starting the loan from its final state instead of(100000, 0)! - Using
bisect_leftinstead ofbisect_right:bisect_leftinserts a tied sequence before older arrivals at the same sequence, reversing arrival order on same-day events. - Setting
self.balancesto the newly inserted event's state: When a backdated event is inserted at index1of a 10-event ledger,self.balancesmust equalself.states[-1](index9after replay), notself.states[1]. - Inserting into
self.sequencesbefore validatingamount: Ifcheck_amountthen raisesValueError,self.sequenceshas one extra element compared toself.eventsandself.states, breaking every future call.
Alternative approaches
- Append and sort-and-replay from scratch on every event: Store
(sequence, arrival_index, event_type, amount), sort allnevents inO(n log n), and replay allnevents from(100000, 0). Too wasteful for production streams because in-order events still reprocess the entire loan history, but unbeatable as a 15-line brute-force test oracle. - Periodic checkpoints (
statessaved everyBevents): Instead of storing aBalancessnapshot on every single event, store one snapshot everyBevents (a checkpoint). Memory for snapshots drops by a factor ofB, while a backdated event atpositionsteps back at mostBevents to the nearest earlier checkpoint before replaying forward.
Follow-up questions
- Suppose callers only queried the latest balances—or balances at one target sequence—instead of requesting the entire history every time; how could you insert backdated transactions in O(log n) time without replaying later entries? Write each event as a signed number
x(+amountforFEE,-amountforPAYMENT) and consider the prefix sumsS_0 = 0, S_1, ..., S_j(whereS_jis the cumulative sum of the firstjsigned events). Every event changesprincipal + feebyx, whilefeefollowsfee_j = max(0, fee_{j-1} + x_j)because fees cannot drop below zero; by induction, the deepest cumulative dipM_j = min(S_0, S_1, ..., S_j)is the exact total amount ever absorbed by principal, givingprincipal_j = 100000 + M_jandfee_j = S_j - M_j! By storing events in a balanced binary search tree (a self-balancing tree like a treap, keyed by(sequence, arrival_order)) where each subtree caches(subtree_sum, min_prefix_sum)merged via(L_sum + R_sum, min(L_min, L_sum + R_min)), both out-of-order insertions and as-of balance queries run inO(log n)time with zero suffix replay. - How would you design support for voiding a historical transaction—like waiving an old fee or reversing a dishonored payment—while preserving an audit log and fixing downstream balances? Assign each event a unique
event_idand store an indexevent_id -> ledger_entry. To reverse an event while preserving an audit trail (a permanent record showing both the original transaction and its cancellation for accounting compliance), mark the original event at its originalaccounting_sequenceas reversed (so_replay_fromtreats its effective amount as0, or insert a zero-effect reversal marker linked to it) and call_replay_fromfrom that original position. Crucially, you cannot reverse a pastPAYMENT 300simply by appending a newFEE 300today: afterFEE 100thenPAYMENT 300, balances are(99800, 0); undoing the payment at its original position restores(100000, 100), whereas posting a newFEE 300leaves(99800, 300)— the wrong split between principal and fee! - When an upstream message broker retries and delivers duplicate events, how do you guarantee idempotent processing? Making an operation idempotent (meaning processing the exact same request once or several times produces the exact same ledger state) requires the caller to attach a unique idempotency key
event_idto each event, since two legitimate payments of50on the same sequence look identical without an ID. Store a dictionaryseen_events[event_id] = (event_type, amount, accounting_sequence): ifevent_idhas not been seen, process the event and record its payload; ifevent_idwas already seen with the same payload, skip mutation and returnself.history(); if it arrives with a different payload, raiseValueErrorto flag a producer bug. In a database-backed service, write theseen_eventsrow and the ledger update inside the same atomic database transaction so a crash mid-request can never double-apply a payment on retry.
Follow-up questions
- Suppose callers only queried the latest balances—or balances at one target sequence—instead of requesting the entire history every time; how could you insert backdated transactions in O(log n) time without replaying later entries?
- How would you design support for voiding a historical transaction—like waiving an old fee or reversing a dishonored payment—while preserving an audit log and fixing downstream balances?
- When an upstream message broker retries and delivers duplicate events, how do you guarantee idempotent processing?
Similar questions
- Multi-Stage Banking Ledger: Cash, Statements, Fees, and Delayed Transfers
- Two-Bucket Billing Ledger with Retroactive Events
- Loan Servicing Backend for Repayments and Investor Distributions
- Schema-Less In-Memory Record Store
- Deterministic Financial Services for Out-of-Order Loan Events
- In-Memory Record Store with Composable Filter Queries
More Valon interview questions
- Multi-Stage Banking Ledger: Cash, Statements, Fees, and Delayed Transfers Medium
- Deterministic Financial Services for Out-of-Order Loan Events Medium
- Schema-Less In-Memory Record Store Medium Pro
- Loan Servicing Backend for Repayments and Investor Distributions Medium Pro
- In-Memory Record Store with Composable Filter Queries Hard Pro
- In-Memory Relational Table Engine Hard Pro
- Two-Bucket Billing Ledger with Retroactive Events Medium Pro