KatInterview

Build an In-Memory Ledger with Delayed Rewards and Account Merging

Data Structure DesignModel answer
MediumModel answerData Structure Designdesignhash-mapheap

Last 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

  1. 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_id with the same payload must not apply it twice.

  2. Top-k senders

    • top_outgoing(k) returns the k accounts 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.
  3. 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.
  4. 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.