Build an In-Memory Ledger with Delayed Rewards and Account Merging
Data Structure DesignModel answerLast updated
Design an in-memory ledger that handles idempotent transfers, top-k senders, rewards posted 24 hours after a purchase, and account merging, and explain how you would test and scale it.
Design and implement an in-memory ledger service. Describe your data structures, write the core code, and explain how you would test it.
Required features
-
Accounts and transfers
create_account(id, initial_balance)transfer(txn_id, from_id, to_id, amount)
A transfer must be rejected if the amount is not positive, either account does not exist, or the source lacks sufficient funds. It must be atomic: either both balances change or neither does. It must also be idempotent: replaying the same
txn_idwith the same payload must not apply it twice. -
Top-k senders
top_outgoing(k)returns thekaccounts with the largest total amount sent out across all of their transfers.- State your output format, your tie-breaking rule, and the time and space complexity. A running per-account total is expected, rather than rescanning history.
-
Purchases with delayed reward
purchase(txn_id, account_id, amount)deducts the purchase and earns a 2% reward.- The reward must be credited exactly 24 hours after the purchase.
- Describe how pending rewards are stored, how they are posted (scheduler or sweep), and how posting stays idempotent and safe across a crash.
-
Merging accounts
merge_account(primary_id, duplicate_id)combines balances and transaction histories.- Future operations that name the duplicate must be redirected to the primary.
- Reconcile any pending rewards and any transaction IDs that appear on both sides.
Also discuss
- Single-threaded versus multi-threaded assumptions, and what locking you would use.
- Unit tests for edge cases: insufficient funds, duplicate transfers, simultaneous merges, and rewards that fall due at or around the 24-hour boundary.
Hints
Hint 1
Store money as integer cents and pass an explicit timestamp into every operation. That makes the 24-hour logic deterministic and easy to test.
Hint 2
Keep a min-heap of pending rewards ordered by due time. Before each operation, pop and post everything whose due time is at or before the current timestamp, and record a posted key so a reward can never be credited twice.
Hint 3
For merging, move the duplicate's balance, outgoing total and history to the primary once, then record an alias from duplicate to primary. Resolve aliases like union-find, and look up the destination account only when a reward is posted.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Overview
Use one in-memory store, with every public operation running atomically against it and taking an explicit timestamp ts.
| Concern | Structure |
|---|---|
| Balances, outgoing totals, history | Dicts keyed by account id, money in integer cents |
| Idempotency | txns: txn_id -> (fingerprint, result) |
| Pending rewards | Min-heap of (due_ts, txn_id, account_id, cents) |
| Exactly-once posting | posted set of reward keys |
| Merged accounts | alias: duplicate -> primary, resolved like union-find with path compression |
Key design choices
- Time is an input. Each operation first calls
_settle(ts), which pops every reward withdue_ts <= tsand credits it. This sweep replaces a background scheduler, so tests are deterministic and there is no race between a timer thread and user calls. - Idempotency is global and payload-checked. A retried
txn_idwith an identical payload returns the stored result and changes nothing. The same id with a different payload is rejected. Failed operations are not recorded, so a client can retry after fixing the cause (for example, after funding the account). - Merges are lazy. Move balance, outgoing total and history once, then set
alias[dup] = primary. Pending rewards are left untouched. Each still names the original account, and the alias is resolved only at posting time. This also handles chained merges.
Feature details
Transfer. Validate everything first (amount > 0, both accounts resolve, the two roots differ, balance is sufficient), then mutate: debit, credit, add to the sender's outgoing total, append history, record the txn. Validation before mutation, plus a single lock, gives atomicity.
Top-k. Keep outgoing[account] updated on each transfer (O(1)). Return (account_id, total) pairs sorted by total descending, ties broken by id ascending, including accounts with total 0. With heapq.nsmallest(k, ..., key=(-total, id)) a query costs O(n log k). If queries dominate, keep a sorted container of (-total, id). Each transfer then costs O(log n) and a query is an O(k) slice.
Reward. On purchase, deduct the amount, compute cents * 2 // 100 (integer floor), and if it is positive push (ts + 24h, txn_id, account, reward). A purchase under 50 cents earns nothing. In _settle, build key "cashback:" + txn_id, skip if already in posted, otherwise credit the resolved account, log the history entry with the due time, and add the key to posted. The first operation with ts >= due posts the reward, so nothing is visible before the boundary and everything is visible at it.
Merge. Reject unknown ids and the case where both resolve to the same root. Add the duplicate's balance and outgoing total to the primary, merge histories by timestamp, then set the alias. Because transaction ids are global, the same id cannot exist on both accounts. A retry that still names the duplicate matches its stored fingerprint, because fingerprints use the ids as the caller passed them.
Code sketch
import heapq, threading
DELAY = 24 * 3600 * 1000
class BankError(Exception): pass
class Ledger:
def __init__(self):
self.lock = threading.RLock()
self.bal, self.out, self.hist = {}, {}, {}
self.alias, self.txns = {}, {}
self.pending, self.posted = [], set()
def _root(self, a):
r = a
while r in self.alias: r = self.alias[r]
while a != r:
self.alias[a], a = r, self.alias[a]
return r
def _need(self, a):
r = self._root(a)
if r not in self.bal: raise BankError("unknown account")
return r
def _settle(self, ts):
while self.pending and self.pending[0][0] <= ts:
due, tid, acct, c = heapq.heappop(self.pending)
key = "cashback:" + tid
if key in self.posted: continue
r = self._root(acct)
self.bal[r] += c
self.hist[r].append((due, "reward", key, c))
self.posted.add(key)
def transfer(self, ts, tid, src, dst, amt):
with self.lock:
self._settle(ts)
fp = ("transfer", src, dst, amt)
if tid in self.txns:
if self.txns[tid][0] != fp: raise BankError("txn id reused")
return self.txns[tid][1]
if amt <= 0: raise BankError("bad amount")
s, d = self._need(src), self._need(dst)
if s == d: raise BankError("same account")
if self.bal[s] < amt: raise BankError("insufficient funds")
self.bal[s] -= amt; self.bal[d] += amt
self.out[s] += amt
self.hist[s].append((ts, "out", tid, -amt))
self.hist[d].append((ts, "in", tid, amt))
self.txns[tid] = (fp, True)
return True
def purchase(self, ts, tid, acct, amt):
with self.lock:
self._settle(ts)
fp = ("purchase", acct, amt)
if tid in self.txns:
if self.txns[tid][0] != fp: raise BankError("txn id reused")
return self.txns[tid][1]
if amt <= 0: raise BankError("bad amount")
r = self._need(acct)
if self.bal[r] < amt: raise BankError("insufficient funds")
self.bal[r] -= amt
self.hist[r].append((ts, "purchase", tid, -amt))
reward = amt * 2 // 100
if reward:
heapq.heappush(self.pending, (ts + DELAY, tid, acct, reward))
self.txns[tid] = (fp, True)
return True
def merge(self, ts, primary, dup):
with self.lock:
self._settle(ts)
p, d = self._need(primary), self._need(dup)
if p == d: raise BankError("already merged")
self.bal[p] += self.bal.pop(d)
self.out[p] += self.out.pop(d)
self.hist[p] = sorted(self.hist[p] + self.hist.pop(d))
self.alias[d] = p
(create_account and top_outgoing follow the descriptions above.)
Complexity
With n live accounts, P pending rewards, and h history length:
- Transfer, purchase, create: O(α(n)) for alias lookup, plus O(log P) for a purchase push.
_settle: O(m log P) for m due rewards, amortized across operations.top_outgoing(k): O(n log k), or O(k) with a sorted container.- Merge: O(h_p + h_d) for the history merge.
- Space: O(n + T + P) for T recorded transactions.
Concurrency and crash safety
- Baseline: one
RLockaround every public method. This is correct and enough for an assessment. - Scaling: per-account locks taken in sorted id order to avoid deadlock. A merge locks both roots and then re-resolves them, since another merge may have changed them in the meantime.
- Simultaneous merges:
merge(A,B)andmerge(B,A)serialize. The second sees one shared root and is rejected, so no balance is counted twice. - Crash safety: append every operation (including "reward posted") to a write-ahead log and fsync before applying it. On recovery, replay the log and rebuild the heap from purchases whose reward key is not in
posted. Idempotent posting makes a crash between logging and applying harmless.
Tests to write
- Insufficient funds leaves both balances unchanged and does not record the txn, so a retry after funding succeeds.
- Replaying a transfer with the same payload changes nothing. Replaying with a different payload errors.
- Reward absent at due minus 1 ms, present exactly at due, and not doubled by later operations.
- A purchase under 50 cents schedules no reward.
- A reward for a purchase made before a merge lands on the primary, including after chained merges.
- Merging in both directions, and merging an account with itself, is rejected the second time.
- Top-k tie-breaking and k larger than the number of accounts.
Common mistakes
- Using floats for money.
- Mutating before validating, leaving a half-applied transfer.
- Rewriting pending rewards on merge instead of resolving the alias at posting time.
- Recording failed operations as idempotent results.
- Relying on a wall-clock timer, which makes the 24-hour behavior untestable.