Layered Ledger Service: Cash, Transfers, Fees and Held Funds
Data Structure DesignModel answerLast updated
Design and code a bank ledger that grows in stages: cash operations, per-account statements with failures, internal and external transfers with fees, and delayed transfers that lock funds.
You are asked to build a small in-memory banking engine in five incremental stages. Each stage adds one feature, and the earlier stages must keep working without being rewritten. Only the core service class is judged. Any code that reads action files or prints statements is just scaffolding, and you may hardcode paths there.
You choose the method signatures and the input line format. Assume each input line is one timestamped action: time, kind, the account(s) involved, and an amount.
Ground rules
- Money is in dollars and cents. Print it as
$X.XX. - Times print with a non-padded hour, for example
2020-08-01 7:00:00. - State your assumptions explicitly where the spec is silent. Examples: whether input is time-sorted, whether accounts are created on first use, whether a balance may go negative, and how invalid amounts are treated.
Stage 1: Cash at an ATM
Support checking a balance, depositing cash and withdrawing cash. After processing all actions, print one line per account:
account amount
PEACH1111 $5.00
PEACH2222 $10.00
Decide and document what happens when a withdrawal exceeds the balance.
Stage 2: Per-account statements, failures included
Record every attempted transaction, including failed ones. Each row has: time, account, credit, debit, status, type, balance after.
time account credit debit status type balance
2020-08-01 5:00:00 PEACH2222 $20.00 SUCCESS ATM $20.00
2020-08-01 6:00:00 PEACH2222 $25.00 FAILED ATM $20.00
A failed withdrawal leaves the balance unchanged. Rows are grouped by account and ordered by time, with a deterministic tie-break for equal timestamps.
Stage 3: Instant transfers
Add instant_transfer(...), which moves money between two accounts. Both accounts show the transfer on their statements (a debit for the sender, a credit for the receiver). From here on, statements use a single amount column:
time account amount status type balance
2020-08-01 6:00:00 PEACH1111 $2.00 SUCCESS INSTANT TRANSFER $7.00
Define behavior for an unknown destination and for source equal to destination.
Stage 4: External-bank transfers with a fee
Support transfers to and from an account at another bank. Each external transfer also charges a fee, which appears as its own FEE row that debits the account:
2020-08-01 7:00:00 PEACH2222 $5.00 SUCCESS INSTANT TRANSFER $13.00
2020-08-01 7:00:00 PEACH2222 $0.01 SUCCESS FEE $12.99
State your fee rule (flat or percentage, rounding), whether it applies to both directions, and whether the funds check includes the fee.
Stage 5: Slow transfers
Add a transfer type where, once initiated, the money is unavailable to the sender until it arrives at the destination:
2020-08-01 6:00:00 PEACH1111 $2.00 SUCCESS SLOW TRANSFER $7.00
State how arrival time is determined, whether in-transit money counts toward the balance, and what happens if a transfer cannot complete.
What to deliver
Working code for as many stages as you can, with output that matches the formats above, plus a short explanation of your design, your assumptions and what you would do with more time. Reaching at least Stage 3 or 4 is a reasonable target.
Hints
Hint 1
Store money as integer cents (or Decimal) and never use floats. Format only at the output boundary.
Hint 2
Make an append-only list of transaction records the single source of truth. A record carries time, account, signed amount, status, type and balance after. Statements are views over it, and all balance changes go through one private debit/credit routine.
Hint 3
For transfers, validate everything first (accounts, amount, funds including any fee) and only then apply both legs, so a failure leaves no partial state. Put the fee rule in its own function. For slow transfers, keep a pending queue (a min-heap by arrival time) and settle everything due before processing each new action.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Core design
Money. Use integer cents throughout. 0.1 + 0.2 style drift is unacceptable in a ledger. Parse "12.34" with Decimal into cents once on input, and format cents // 100 and cents % 100 on output. Reject non-positive amounts. My assumption is that they are recorded as FAILED, so the audit trail is complete.
Ledger as source of truth. Each action produces immutable Txn records:
@dataclass(frozen=True)
class Txn:
seq: int # global counter: deterministic tie-break
time: datetime
account: str
amount: int # signed cents: + credit, - debit
status: str # SUCCESS / FAILED
kind: str # ATM, INSTANT TRANSFER, FEE, SLOW TRANSFER
balance_after: int
The balance is stored per account and updated only through two private methods, _credit and _debit. Every public operation is built from those. Statements are produced by filtering the ledger by account and sorting by (time, seq). In stage 2 the credit and debit columns are derived from the sign. In stage 3 and later they collapse into one amount column.
Assumptions I would state out loud.
- Accounts are created on first deposit or as a transfer destination. A withdrawal or transfer from an unknown account fails.
- Balances never go negative. Any debit above the available balance is
FAILED. - Input is processed in file order, and I assume it is time-sorted. Otherwise I would sort by
(time, line number)before processing. - A failed action still gets a row, with the balance unchanged.
Stage-by-stage
Stage 1 and 2. deposit_cash credits and withdraw_cash debits if available >= amount. Both append a Txn either way. Failure appends FAILED with balance_after equal to the current balance.
Stage 3: instant transfer. The key property is atomicity. Validate first (both accounts exist, they differ, amount is positive, source has enough funds), then apply both legs. Because this is single-threaded in-memory code, validate-then-apply is enough. In a real system the two legs would sit inside one database transaction, or you would use a double-entry journal with a shared transfer id. On failure, write a FAILED row on the sender's statement only. On success, write a debit row for the sender and a credit row for the receiver, linked by a shared transfer_id if you want traceability. Reuse _debit and _credit. Do not write a parallel code path.
Stage 4: external transfer and fee. Introduce fee_for(direction, amount) -> int, so the rule can change without touching transfer code. A flat 1 cent is a reasonable default. If the fee is a percentage, state the rounding (for example, round half up to cents). For an outgoing transfer, the funds check is balance >= amount + fee. If it fails, the whole transfer fails, and I would not take the transfer but skip the fee. On success, write the transfer row and then a separate FEE row with the balance after each step, as in the sample ($13.00 then $12.99). Incoming external transfers credit the local account and charge the fee to it. If that would take the balance negative, the cleanest rule is to net the fee against the credit in the check, so the balance never drops below zero. Name this as a decision.
Stage 5: slow transfers. Separate available money from in transit:
- On initiation, debit the sender immediately (the funds are no longer usable). Write a
SLOW TRANSFERrow and push(arrival_time, seq, dest, amount)onto a min-heap. - Before handling any action at time
t, call_settle(t). It pops all pending items witharrival_time <= t, credits the destination and writes a credit row stamped with the arrival time. - Display balance excludes in-transit money, so later checks respect the hold automatically. If the spec wants a total balance, expose
pending_outas a separate figure. - Arrival time can be a fixed delay (for example, 24 hours) or part of the input. Either way the heap handles it. If the destination does not exist at arrival, refund the sender with a compensating credit row. This is the same pattern a real system uses for reversals.
- At end of input, call
_settle(infinity)or leave the items pending, depending on the stated rule.
Complexity
Each action is O(1) amortized, plus O(log p) for the pending heap with p slow transfers. A statement for one account is O(n log n) if you filter and sort the ledger. Keeping a per-account list of transactions makes it O(k log k) for k rows in that account, or O(k) if you append in processing order.
Trade-offs and extensibility
- A per-account list plus a global list costs memory but makes statements cheap. For this scale it is the right call.
- Transfer types (instant, external, slow) can share one
_transfer(src, dst, amount, kind, fee_rule, delay)pipeline, with the differences injected as strategies. That is how stage 5 avoids rewriting stage 3. - Concurrency is out of scope here. In production you would lock accounts in a fixed order, or use a database transaction, to prevent deadlock and double spending.
Common mistakes
- Using floats for money.
- Applying the debit before validating, which leaves half-completed transfers.
- Dropping failed attempts from the statement.
- Checking
balance >= amountbut forgetting the fee. - Sorting rows by time alone, so equal timestamps come out in arbitrary order.
- Crediting a slow transfer immediately, or counting in-transit money as available.
- Mixing file parsing and formatting into the service class.
Walkthrough points for the design discussion
Explain why the ledger is append-only, how each new stage reused _debit and _credit, which assumptions you made where the spec was silent, and what you would add next: idempotency keys for duplicate actions, a reversal mechanism, per-account locking and property-based tests that assert total money is conserved (minus fees).