Skip to content
SeeItFlow
System Design · Interview Perspective · 13 chapters · ~40 min read

Splitwise System Design Interview: Questions, Architecture and Trade-offs

Splitwise system design interview guide: how to answer "Design Splitwise" in 40–45 minutes, with clarifying questions, estimates, a six-stage whiteboard build, deep-dive choices, Staff-level questions, a question bank and a revision sheet. An original design, not any company's system.

Mangesh MandlikLast updated: How lessons are made
Interview 01

Clarify the Problem

"Design Splitwise" can mean a bill-splitting calculator, a multi-year ledger across thousands of groups, or a system that also moves real money. Spend the first five minutes turning the prompt into a scope, a set of invariants and a few numbers — each answer below changes something you will later draw.

Question to askWhy it mattersHow the answer changes the design
Does the system move money, or only record who owes whom?Recording obligations is bookkeeping; moving money adds a third party that is authoritative for whether money moved.Default: record only. Manual settlements are member assertions. If in-app payment is in scope, add a Payment Service and a pending → confirmed | failed state machine at Stage 4.
Which split types: equal, exact, percentage, weights?Each has its own validation; three of them produce fractional minor units.Integer minor units, percentages as basis points, and one deterministic rounding rule (largest remainder, ties by ascending user_id) inside the Expense Service.
Can one expense have several payers?A hotel bill fronted by two people is common.expense_payers as its own table whose paid_minor must sum to the total, instead of one payer column.
Can expenses be edited or deleted, and by whom?Edits are frequent, sometimes concurrent, and disputes need history.PUT with If-Match on an expense version; corrections as reversal + replacement ledger entries; deletes as reversals only.
Which currencies, and may balances in different currencies be combined?₹1,000 and $20 cannot be added without choosing a rate and a date.Currency is part of every balance key; no netting across currencies; FX only for labeled display.
Are balances per group, or netted across groups?Cross-group netting couples groups that are otherwise independent.Group is the unit of consistency and later the partition key; a per-user dashboard is a separate, derived view.
Is debt simplification required, and is it binding?Minimizing transfers is NP-hard; a suggestion has no correctness weight.Simplification is a read-only computation over net balances, never a stored obligation.
What must a member see right after adding an expense?Users check their balance immediately; other members tolerate a short delay.Read-your-writes for the writer (group_seq → min_seq), freshness labels (as_of_seq) for everyone else.
How many users, groups, expenses and balance reads?History grows forever; reads outnumber writes.Decides when summing the ledger on every read stops working (Stage 2) and when to partition (Stage 5).
Offline entry and retries from mobile clients?A retry after a timeout is normal client behavior.An Idempotency-Key on every mutation, with at most one effect per key, from Stage 1.

“I'll design a generic shared-expense manager. The system records expenses and settlements as an immutable ledger in integer minor units and derives every balance from it; moving money is an optional provider integration that I'll add late. I'll support equal, exact, percentage and weighted splits with one deterministic rounding rule, keep balances per group and per currency, treat simplification as a suggestion, and make every correction new history rather than an edit. I'll start with one service and one database and add components only when a limit forces them. Does that match what you want?”

One small running example keeps the arithmetic checkable: group Weekend Trip with Asha, Ben and Cara in INR. E1 dinner ₹900 paid by Asha, split equally; E2 taxi ₹600 paid by Ben, exact shares ₹100 / ₹200 / ₹300; S1 Cara pays Asha ₹200. Everywhere else this page uses roles — payer, member, client A and client B.

Interview 02

The 40–45 Minute Plan

A pacing guide, not a script. Each stage starts from a limit you named in the previous one; if the interviewer pulls you into a deep dive, follow and come back.

MinutesStageWhat is on the board at the end
0–5Scope and requirementsScope sentence, functional list, invariants: integer minor units, shares sum exactly to the total, zero-sum per group and currency, history never rewritten, at most one effect per retried write
5–8Estimates~580 writes/s and ~2,315 balance reads/s at peak; ~2,300 ledger rows per group per year; ~3 TB/year
8–18Stage 0, data model, algorithmsClient → Expense Service → Ledger DB; core tables; ledger delta = paid − share; rounding rule; net balance; greedy simplification
18–25Stage 1 — correct writesOne transaction with the idempotency claim and the group_seq bump; PUT + If-Match; reversal + replacement
25–30Stage 2 — read bottleneckRows-scanned arithmetic; balance_projection updated in the write transaction
30–36Stage 3 — outbox and derived viewsOutbox → Outbox Relay → Event Bus → Projection Consumer → User Balance Projection; versioned Balance Cache
36–40Stage 4 — capabilitiesNotification Service, per-currency balances, Payment Service with provider-confirmed settlement
40–45Stage 5 — production and recapFailure responses, rebuilds, hot groups, partitioning by group_id, API Gateway, DR, observability; final board
If time is short, compress Stages 4–5 into one sentence each; never skip the money math or Stage 1.
Interview 03

Back-of-Envelope Estimates That Steer the Design

Three minutes, stated as assumptions. Each number should end in an architectural consequence; numbers that decide nothing are not worth the board space.

textIllustrative assumptions, the same ones used in Complete Design.
Users        10M registered, 1M DAU; ~4M groups, average 5 members
Writes       5M expense writes/day  ≈ 58/s avg  → ~580/s peak (10×)
Reads        20M balance reads/day  ≈ 231/s avg → ~2,315/s peak  (≈ 4 : 1)
Ledger       ~5 rows per expense → 25M rows/day × 200 B ≈ 5 GB/day ≈ 1.8 TB/year
All tables   ≈ 3 TB/year before indexes
History      25M ÷ 4M groups ≈ 6 rows/group/day → ~2,300 rows per group after a year
Notifications ≤ 20M/day, ~2,315/s peak
Stage 2 math ≈ 3,500 group aggregations/s at peak × 2,300 rows ≈ 8M rows/s (year 1),
             ≈ 16M rows/s (year 2)  vs  ≈ 17,500 rows/s reading stored nets
NumberWhat it decides
~580 writes/s at peakOne relational primary handles the write rate; partitioning is not a day-one throughput need.
4:1 reads, history growing ~6 rows/group/day foreverSumming the ledger on every read gets slower every day — the first real limit (Stage 2).
~3 TB/yearStorage, backup time and blast radius — not throughput — eventually force partitioning by group (Stage 5).
Notifications at read-rate scaleDelivery must be asynchronous and outside the write transaction (Stages 3–4).
Hot groups (a trip this weekend)A group's own peak, not the system average, sizes its write path; writes in one group serialize on the group row.
Interview 04

Whiteboard Part 1 — Stage 0, the Data Model and the Money Algorithms

Minutes 8–18. Draw the simplest design that satisfies the functional requirements, put the tables inside it, and prove the arithmetic on the running example. Every later stage changes how this core is protected or read — never the math.

Stage 0 — Client → Expense Service → Ledger DB

Swipe to pan
Stage 0 — Simplest Design: One Service, One Relational DatabaseClient → Expense Service → Ledger DB; a balance is SUM(delta_minor) over the group ledger on every readLedger DBrelational · truthgroups · membershipsexpenses · splitsledger_eventssettlements · auditClientmobile · webExpense Servicesplit math · membershipread = SUM(ledger) each timeAddedExact integer split math, an append-only ledger, membership checks; one primary handles ~580 writes/s.Still openPartial writes, duplicate retries, lost updates, rewritten history; read cost grows with ledger history.
Stage 0: one Expense Service in front of one relational database; balances are summed from the ledger on every read

Draw. Client → Expense Service (REST, membership check, split math, simplification) → one relational Ledger DB. Write: compute shares, insert expense, payers, splits and ledger rows. Read: SELECT user_id, SUM(delta_minor) … GROUP BY user_id over the group's ledger.

Say. "An expense is a multi-row fact that needs constraints and transactions, and ~580 writes/s fits one primary, so I start relational. Stage 0 already computes shares on the server in integers and has one source of truth. Here is where it breaks: partial writes, duplicate retries, lost updates, in-place edits that erase history, read cost that grows with history, and side effects bolted into the request. Each of those becomes a stage."

Trade-off to name. One relational primary versus a NoSQL store or microservices from day one: the relational store gives atomic multi-row writes and constraints for free at a write rate it easily handles; splitting into services now buys distributed-transaction problems with no requirement behind them.

Likely follow-up. "Why not store a balance per member pair and update it?" — A mutable counter can drift (double-applied update, missed write) and cannot be audited or recomputed. The immutable ledger is the truth; any stored balance is a derived, rebuildable projection — which is exactly what Stage 2 adds.

The data model

Swipe to pan
usersuser_idgroupslast_seqmembershipsgroup_id, user_idexpensesversion · statusexpense_versionsimmutableexpense_payerspaid_minorexpense_splitsshare_minorledger_eventsdelta_minor · group_seqsettlementspending → confirmed …audit_entriesappend-onlyidempotency_recordsStage 1balance_projectionStage 2outboxStage 3user_balance_summaryStage 3 · per userprovider_eventsStage 4slate = source of truth · green arrows = ledger effects · purple = added by later stages (derived or supporting)
Core snake_case tables: users, groups (last_seq), memberships, expenses (version, status) with expense_versions, expense_payers (paid_minor) and expense_splits (share_minor), ledger_events (delta_minor, group_seq), settlements and audit_entries; tables added by later stages: idempotency_records (1), balance_projection (2), outbox and user_balance_summary (3), provider_events (4)

Draw. groups(last_seq), memberships, expenses head (version, status active|deleted), expense_versions, expense_payers, expense_splits, ledger_events(group_id, group_seq, user_id, currency, delta_minor, source_type, source_id, source_version), settlements(method, status), audit_entries. Index ledger_events(group_id, currency, user_id).

Say. "Amounts are BIGINT minor units — paise — never floats. The ledger is append-only: one row per participant with a nonzero effect, delta = paid − share. Settlements are their own records that also write ledger rows. Balances are derived, so they can always be rebuilt."

Trade-off to name. Storing one immutable row per effect costs storage (~1.8 TB/year) and makes reads aggregate, in exchange for auditability, reversible corrections and rebuildable views. The read cost is solved later without giving up the ledger.

Likely follow-up. "Why separate expense_versions from expenses?" — The head carries the current version for compare-and-set; versions are immutable history that disputes and reversals read.

Algorithms inside the Expense Service

Swipe to pan
ledger_events · exp-1001 v1 · group_seq 1 · INRuser-ashapaid 90,000 − share 30,000+60,000user-benshare 30,000−30,000user-carashare 30,000−30,000Σ delta_minor = 0 per group and currencyAppend-only: a correction adds reversal rows plus new rows; it never edits these
E1 (exp-1001, version 1, group_seq 1): Asha +60,000, Ben −30,000, Cara −30,000 paise — the entries of one expense always sum to zero

Splits and rounding. Equal, exact, percentage (integer basis points summing to 10,000) and weights. Floor every share; give the leftover minor units — always fewer than the number of beneficiaries — one each to the largest fractional remainders, ties broken by ascending user_id. ₹100 over three → 3,334 / 3,333 / 3,333; ₹125.50 at 3333 / 3333 / 3334 bps → 4,183 / 4,183 / 4,184; weights 1:2:2 on ₹1,000 → 20,000 / 40,000 / 40,000 paise. Exact splits and payer lists must sum exactly to the total, otherwise 422 SPLIT_SUM_MISMATCH or PAYER_SUM_MISMATCH and nothing is written.

Net balance. A member's net is the sum of their ledger deltas: paid-for-others minus own share, plus settlements paid, minus settlements received. After E1 and E2: Asha +₹500, Ben +₹100, Cara −₹600; after S1 (Cara → Asha ₹200): +₹300 / +₹100 / −₹400. Every state sums to zero — the arithmetic consequence of validating both sums on every write.

Simplification. Raw pairwise debts after E1 + E2 are four (Ben → Asha 300, Cara → Asha 300, Asha → Ben 100, Cara → Ben 300). Greedy matching of the largest debtor with the largest creditor on the net positions gives Cara → Asha ₹500 and Cara → Ben ₹100. It preserves net positions, not provenance; it is a suggestion that moves no money.

Swipe to pan
RAW PAIRWISE (4 debts)Ashanet +₹500Bennet +₹100Caranet −₹600300100300300Ben→Asha 300 · Asha→Ben 100Cara→Asha 300 · Cara→Ben 300SIMPLIFIED (2 transfers)Ashareceives ₹500Benreceives ₹100Carapays ₹600500100Same nets; a suggestion, not a ledger write
Four raw pairwise debts collapse to two suggested repayments with the same net effect

Trade-off to name. Greedy yields at most (creditors + debtors − 1) transfers in O(n log n), but is not guaranteed minimal: the exact minimum is NP-hard in general. Five members with nets +400, +300, −300, −200, −200 get four greedy transfers where three suffice. Claim "few", never "fewest".

Likely follow-up. "What if percentages are 33.33% three times?" — 9,999 bps is invalid input and is rejected with 422; the server never invents the missing basis point. Full arithmetic: Complete Design, Chapter 09 and Complete Design, Chapter 10.

Interview 05

Whiteboard Part 2 — Stage 1 Correct Writes and Stage 2 the Read Bottleneck

Minutes 18–30. Fix correctness before scale: a double-counted expense is permanently wrong in everyone's history, while a slow read is gradual and measurable. The boxes do not change in Stage 1; the transaction does.

Stage 1a — one transaction and idempotency keys

Swipe to pan
ClientIdempotency-KeyExpenseServiceBEGIN — one local transaction on the group1. claim idempotency key (unique per actor, group, op)2. check membership of actor and participants3. group_seq = ++groups.last_seq (locks group row)4. INSERT expenses, expense_versions, payers, splits5. INSERT ledger_events (Σ delta = 0 per currency)6. store 201 response on the idempotency recordCOMMIT → 201 {expense_id, version, group_seq}Retriessame key, same body →stored 201 replayedsame key, other body →422 IDEMPOTENCY_KEY_CONFLICTconcurrent duplicate →waits on the unique keyCrash before COMMITnothing is visible;the retry starts cleanStage 2 adds balance_projection updates and Stage 3 adds the outbox row —inside this same transaction, never as a separate step
Stage 1: claim the idempotency key, check membership, take the next group_seq, write the expense and its ledger entries, store the response — one commit, then 201

Draw. Inside the Ledger DB box, the transaction in order: INSERT idempotency_records (unique on actor, group, operation, key; request_hash) → membership check → UPDATE groups SET last_seq = last_seq + 1 RETURNING (= group_seq) → expense head, version, payers, splits → ledger_events → stored response → COMMIT → 201 {expense_id, version, group_seq}.

Say. "Everything lives in one database, so one local transaction makes the write all-or-nothing — no saga needed. Clients retry, so every mutation carries Idempotency-Key. A retry with the same body replays the stored 201; the same key with a different body is 422 IDEMPOTENCY_KEY_CONFLICT, not a silent replay. Keys are kept 7 days. Bumping groups.last_seq serializes the group's writes and gives a gap-free group_seq that later stages use for freshness and replay."

Trade-off to name. The group-row lock caps one group at roughly 100–200 short writes/s — far above real groups — in exchange for a total order per group. A global sequence or timestamps would need cross-group coordination or give ties under clock skew.

Likely follow-up. "Two retries arrive at the same time?" — The second INSERT into idempotency_records waits on the first's uncommitted key; if the first commits, the second replays its response; if it rolls back, the second proceeds. A check-then-insert outside the transaction would race.

Stage 1b — versioned edits, reversals and deletes

Swipe to pan
exp-2040 Groceries ₹1,200 — both editors loaded version 4Edit A: PUT If-Match "4"amount ₹1,250Edit B: PUT If-Match "4"split change1 row updated → version 5reversal + new entries · 2000 rows → 409 VERSION_CONFLICTcurrent_version: 5 · reloadcommits first4 is staleUPDATE expenses SET version = version + 1 WHERE expense_id = … AND version = 4 AND status = 'active'
exp-2040 at version 4: two PUT requests with If-Match "4"; one commits version 5, the other gets 409 VERSION_CONFLICT

Draw. PUT /v1/groups/{group_id}/expenses/{expense_id} with If-Match: "4". In the transaction: UPDATE expenses SET version = version + 1 WHERE expense_id = :id AND version = :expected AND status = 'active'; zero rows → rollback, 409 VERSION_CONFLICT {current_version}. Then reversal rows negating the old version's entries, new rows for the new version, one new group_seq. Delete = version check + status = 'deleted' + reversals only.

Say. "Two members editing one expense from stale screens is normal, so a stale version is rejected, not merged. Ledger rows are never updated or deleted: a correction is reversal plus replacement, so the balance is exactly as if the right amount had been entered and the story stays visible. A missing If-Match is 428 PRECONDITION_REQUIRED. The idempotency key still matters on edits — a retried successful edit would otherwise get 409 from its own first attempt."

Trade-off to name. Optimistic concurrency versus a pessimistic edit lock: conflicts are rare and an edit spans human think time, so holding a lock is worse than an occasional 409. Field-level merging is attractive for descriptions but dangerous for amounts and splits.

Likely follow-up. "Deleting an expense after someone already settled it?" — The settlement is a separate fact and stays; the arithmetic may flip a balance's direction. The system never silently forgives or drops a settlement.

Stage 2 — the read bottleneck

Swipe to pan
Ledger rows read per group balance request (average group)~6day 1~1,1506 months~2,3001 year~4,6002 yearsSUM on read (Stages 0–1)~3,500 aggregations/s at peak≈ 8M rows/s (year 1)≈ 16M rows/s (year 2)balance_projection (Stage 2)~5 rows per group, any age≈ 17,500 rows/s at peak~5 extra row updates per writered = rows aggregated per read · green = projection rows per read (constant)
Rows scanned per second when every read aggregates the ledger: ~8M/s in year 1, ~16M/s in year 2, versus ~17,500/s reading stored nets

Draw. Next to the estimates: ~3,500 group aggregations/s at peak × ~2,300 rows ≈ 8M rows/s, doubling every year. Then add balance_projection(group_id, currency, user_id, net_minor, last_applied_seq) inside the Ledger DB box, updated by the same write transaction.

Say. "Writes are flat but each read scans history, and the longest-lived groups are the most read. Indexes, replicas and a cache slow the growth but keep O(history) reads. Group balances change only when the group's ledger changes, under a lock the write already holds — so I maintain them in that transaction: about five extra row updates per write, and a read becomes one row per member. The aggregation query becomes the reconciliation check."

Trade-off to name. Synchronous projection (slightly heavier writes, always equal to the ledger, read-your-writes by construction) versus an asynchronous projection fed by events (lighter writes, but the writer's own balance becomes eventually consistent — the one view users check right after writing).

Likely follow-up. "Why is the group balance not eventually consistent when the dashboard is?" — Because balance_projection is updated inside the write transaction; it commits atomically with the ledger rows, so on the primary it is never ahead of or behind them. Only views built from events — the per-user dashboard, notifications, cache invalidation — lag.

Swipe to pan
Stage 2 — Read Bottleneck: Group Balances Become a Projectionbalance_projection(group, currency, user) is updated inside the same write transactionLedger DBrelational · truthgroups · membershipsexpenses · splitsledger_eventssettlements · auditidempotency_recordsbalance_projectionClientmobile · webExpense Servicetxn + projection updateReconciliationprojection vs ledgerNEWread = projection lookupAddedA group sheet is one indexed lookup; the writer reads its own write; a job checks projection vs ledger.Still openDashboards span groups, side effects must not sit in the transaction, hot sheets still hit the primary.
Stage 2: the same components, with balance_projection maintained inside the write transaction
Interview 06

Whiteboard Part 3 — Stage 3 Outbox, Derived Views and Cache; Stage 4 Capabilities

Minutes 30–40. Three needs remain after Stage 2: side effects with no reliable trigger, a dashboard that spans groups, and hot reads on the primary. Then the three unserved requirements: notifications, multi-currency and in-app payment.

Stage 3a — outbox, relay, event bus, Projection Consumer

Swipe to pan
one write transactionexpense rows + ledger_eventsbalance_projectionoutbox row (event_id, group_seq)Outbox RelayFOR UPDATE SKIP LOCKEDEvent Buskey group_idConsumersdedupe event_id / seq guardpollat least onceCrash after publish, before marking published → the row is sent again. Duplicates and reordering areexpected; consumers make them harmless. Published rows are purged after 7 days.
The write transaction also inserts an outbox row; the Outbox Relay publishes it afterwards, retriably and at least once

Draw. Add an outbox row (event_id, group_id, group_seq, event_type, payload with each member's net_after_minor) to the same transaction. Outside the DB: Outbox Relay (FOR UPDATE SKIP LOCKED, marks published_at) → Event Bus (key group_id, 7-day retention) → Projection Consumer → User Balance Projection (user_balance_summary, keyed by user).

Say. "Calling the notifier inside the transaction couples writes to a slow provider; publishing after commit loses the event on a crash. With an outbox the event exists if and only if the write committed. The relay is at least once — it can duplicate and reorder — so every consumer is idempotent: the dashboard row is an absolute net_after_minor upsert guarded by WHERE last_applied_seq < :seq, so a duplicate or older event changes nothing. The write path still depends only on the database."

Trade-off to name. Outbox versus change data capture: CDC is a fine transport for the relay, but explicit domain events are a stable contract that does not leak the schema. Versus a distributed transaction: brokers support it poorly and it makes writes unavailable whenever the bus is.

Likely follow-up. "Does the bus need exactly-once delivery?" — No. Delivery is at-least-once, not exactly-once; each event has at most one effect because consumers apply it idempotently and commit their offset only after their local write.

Swipe to pan
Event Busseq 42: net_afterProjection Consumerabsolute value + seq guardUser Balance Projectionuser_balance_summaryUPSERT net_minor = :net_after, last_applied_seq = 42WHERE last_applied_seq < 42 -- older or repeated event: 0 rowsRedelivered seq 42 → no-op · late seq 41 after 42 → no-op · same result in any delivery orderThe consumer also deletes the group's Balance Cache key
Event Bus → Projection Consumer (absolute value + sequence guard) → User Balance Projection; a duplicate or older event is a no-op

Stage 3b — versioned cache and the consistency contract

Swipe to pan
ClientGET …/balances?min_seq=NExpense ServiceBalance Cache{sheet, as_of_seq}balance_projectionprimaryhit and as_of_seq ≥ N → 200miss or older than N200 + as_of_seq; SET if newerInvalidation: Expense Service deletes the key after commit (fast path) · Projection Consumer deletes it on the event· safety TTL 300 s bounds any missed delete · write responses return group_seq for the next min_seq
Read path: return a cached sheet only if its as_of_seq ≥ min_seq; otherwise read balance_projection and set-if-newer

Draw. Balance Cache beside the Expense Service: key balance:{group_id}:{currency}, value {sheet, as_of_seq}, filled set-if-newer. Invalidation: best-effort DEL by the Expense Service after commit, DEL again by the Projection Consumer on the event; safety TTL 300 s.

Say. "Writes return group_seq; the client sends it as min_seq, so the writer never gets an older sheet. Other members may briefly see the previous sheet, labeled with as_of_seq. A plain TTL cache can't tell fresh from stale — the version can."

Trade-off to name. Hit rate versus freshness. A fill racing a commit can briefly repopulate an old sheet; the event-driven DEL removes it, and the 300 s TTL is the backstop, not the freshness mechanism. Read replicas were rejected because their lag is invisible to the caller.

Likely follow-up. "Can someone settle up from a cached balance?" — A settlement records an amount the member chooses; it is validated against currency and membership, not against a cached sheet. The settle screen should read with min_seq or bypass the cache so the member decides on the freshest sheet.

Swipe to pan
Stage 3 — Transactional Outbox, Event Bus, Derived Views, Versioned Cacheoutbox row in the write transaction → relay (at least once) → bus keyed by group_id → idempotent consumersLedger DBrelational · truthgroups · membershipsexpenses · splitsledger_eventssettlements · auditidempotency_recordsbalance_projectionoutboxClientmobile · webExpense Servicetxn + outbox · readsBalance Cacheas_of_seq · TTL 300 sNEWUser Balance Projectionper user · asyncNEWProjection Consumerseq guard · cache DELNEWOutbox Relayat least onceNEWEvent Buskey group_id · 7 dNEWReconciliationprojection vs ledgerset-if-newer · DELAddedOutbox Relay, Event Bus, Projection Consumer → User Balance Projection, Balance Cache (set-if-newer).Still openNotifications, multiple currencies and in-app payments are still unserved.
Stage 3: outbox, Outbox Relay, Event Bus, Projection Consumer, User Balance Projection and a versioned Balance Cache around the unchanged write transaction

Stage 4 — notifications, multi-currency, provider-confirmed settlement

Swipe to pan
pendingno ledger effectconfirmedledger entries writtenfailedno ledger effectreversedreversal entriesproviderverified webhookfailedrefund · chargeback· disputemanual: created confirmed (member assertion)Transitions are guarded(WHERE status = 'pending');late or duplicate webhookschange nothing
Settlement states: pending → confirmed (ledger entries written) or failed (no entries); confirmed → reversed on refund or chargeback; manual settlements are created confirmed

Draw. Notification Service on the bus (unique on (event_id, recipient_user_id)). Currency inside every balance key; FX Rate Snapshots used only for labeled display. Payment Service ↔ Payment Provider (external) and POST /v1/payments/webhooks/{provider}.

Say. "A provider settlement commits as pending with no ledger rows. The Payment Service calls the provider outside the transaction, with settlement_id as the provider's idempotency key. A verified webhook (signature, timestamp), deduplicated in provider_events, moves pending → confirmed with WHERE status = 'pending' and writes ledger rows, projection and outbox in one transaction; failed writes nothing. A refund moves confirmed → reversed with reversal entries. Reconciliation polls anything pending after 15 minutes. INR and USD are separate zero-sum ledgers; converting is an explicit member-initiated record, never automatic."

Trade-off to name. Responsiveness versus truth: showing a payment as settled at initiation feels fast but reduces a debt by money that may never move. Show pending clearly; move balances only on confirmation.

Likely follow-up. "A failed webhook arrives after confirmed?" — The state guard matches no row; the event is flagged for reconciliation, not applied. The provider's record of money movement wins, and any correction is written as new ledger entries.

Swipe to pan
Stage 4 — Notifications, Multi-Currency, Provider-Confirmed SettlementNew consumers fan out from the bus; a balance moves only on a verified, deduplicated confirmationLedger DBrelational · truthgroups · membershipsexpenses · splitsledger_eventssettlements · auditidempotency_recordsbalance_projectionoutboxprovider_eventsClientmobile · webExpense Servicetxn + outbox · readsBalance Cacheas_of_seq · TTL 300 sUser Balance Projectionper user · asyncProjection Consumerseq guard · cache DELNotification Servicededupe event_idNEWOutbox Relayat least onceEvent Buskey group_id · 7 dPayment Providerexternal · authorityNEWPayment Serviceverified webhooksNEWFX Rate Snapshotsdisplay onlyNEWReconciliationzero-sum · providerset-if-newer · DELpay · webhookAddedNotification Service, Payment Service + webhooks, per-currency balances, display-only FX snapshots.Still openOperating it: relay and consumer failure, rebuilds, hot groups, storage growth, DR, abuse (Stage 5).
Stage 4: Notification Service and Payment Service join as an event consumer and a provider adapter; FX rates are display-only
Interview 07

Whiteboard Part 4 — Stage 5 Production Readiness and the Final Board

Minutes 40–45. Production readiness is not more boxes; it is knowing, for each mechanism, what happens when it fails, how it recovers and what you watch. Cover it in a table-like sweep, then recap the board in one breath.

TopicWhat to sayFollow-up and strong answer
Relay or bus downWrites still commit and group balances stay correct; outbox rows accumulate; dashboard and notifications fall behind. Alert when the oldest unpublished row is > 30 s old."Is anything lost?" — No: the row stays until published; the relay resumes from the oldest unpublished row.
Projection driftA reconciliation job compares balance_projection with SUM(delta_minor) and checks zero-sum per group and currency; both mismatch counts must be 0."How do you repair?" — Under the group lock, recompute from the ledger and set last_applied_seq to groups.last_seq; large groups build a shadow, catch up, swap. Never patch the ledger to match a view.
Hot groupWrites in one group serialize on the group row: ~100–200 short writes/s, lower for very large groups. Per-group rate limit (429 + Retry-After), short transactions, cache for read bursts, notification digests."Drop the group lock for hot groups?" — No; the sequence is what makes projections, freshness markers and replay correct.
PartitioningShard by group_id via a group directory; every money-moving write stays single-shard; one relay per shard; per-user data (user_balance_summary) in a separate store fed by events; archive dormant groups."What doesn't fit?" — The cross-group dashboard; that is why it is an event-fed, eventually consistent view.
Disaster recoverySynchronous in-region standby (no acknowledged write lost on a single-node failure) plus an asynchronous cross-region replica and PITR."Cross-region RPO?" — Seconds, not zero. Clients retry with the same idempotency keys; provider reconciliation re-checks recent confirmations; bus and caches are re-derived.
API GatewayTLS, token validation, request limits, per-user and per-group rate limits."Does it authorize?" — No. It authenticates; membership is checked by the owning service on every request.
ObservabilityWrite p99 < 300 ms, group read p99 < 100 ms; 409 and 422 rates, replay rate, outbox age, consumer lag, cache bypass rate, projection mismatches, zero-sum violations, pending settlements by age, webhook signature failures."Which alert pages someone?" — Zero-sum violations and projection mismatches (must be 0), outbox age, and settlements stuck pending.
Swipe to pan
ledger_eventsgroup_seq 1 … NRebuild Jobreplay in seq ordershadow tablenets as of seq Ncompare → swapapply seq > N, then cut overLive events while the rebuild runsseq 40seq 41seq 42seq 41 againlast_applied_seq = 42→ duplicate is a no-opSequence-guarded, absolute-value upserts make replay and redelivery idempotent:applying the same history twice gives the same balances, never doubled ones
Repair: replay the ledger in group_seq order into a shadow projection, compare, swap; a redelivered sequence is a no-op
Swipe to pan
Final Architecture — Group-Partitioned Ledger, Derived and Rebuildable ViewsThe gateway authenticates; services authorize; every money write is one local transaction on its group shardLedger DB shardsby group_idgroups · membershipsexpenses · splitsledger_eventssettlements · auditidempotency_recordsbalance_projectionoutboxprovider_eventsClientmobile · webAPI Gatewayauthn · rate limitsNEWExpense Servicetxn + outbox · readsBalance Cacheas_of_seq · TTL 300 sUser Balance Projectionper user · asyncProjection Consumerseq guard · cache DELNotification Servicededupe event_idOutbox Relayat least onceEvent Buskey group_id · 7 dPayment Providerexternal · authorityPayment Serviceverified webhooksFX Rate Snapshotsdisplay onlyReconciliationzero-sum · providerRebuild Jobsledger → viewsNEWStandby + Replicassync · cross-regionNEWset-if-newer · DELpay · webhookScaleLedger DB sharded by group_id, sync standby + async cross-region replica, rebuild and reconciliation jobs.RuleThe ledger is the source of truth; projections, cache, dashboard and notifications are derived.
Final architecture: Client → API Gateway → Expense Service and Payment Service over Ledger DB shards (by group_id) holding the ledger, balance_projection and outbox; Outbox Relay → Event Bus → Projection Consumer (User Balance Projection, cache DEL) and Notification Service; versioned Balance Cache; Payment Provider; FX Rate Snapshots (display-only); Reconciliation and Rebuild Jobs; Standby + Replicas

The 30-second recap. "Expense Service writes an append-only ledger in integer minor units, in one transaction that also claims the idempotency key, bumps the group sequence, updates the group balance projection and inserts an outbox row. Edits are If-Match compare-and-set plus reversals. Group reads come from the projection through a versioned cache with min_seq for read-your-writes. The outbox feeds the dashboard, cache invalidation and notifications at least once with idempotent consumers. Provider settlements move balances only on a verified confirmation. Everything is partitioned by group, and every derived view is rebuildable from the ledger." Production depth: Complete Design, Chapter 17 and Complete Design, Chapter 19; incident walkthroughs on Failure & Scale Scenarios.

Interview 08

Choosing a Deep Dive

Most interviewers stop the walkthrough once and say "go deeper on X". If they let you choose, pick the area where the invariant is most at risk and show a mechanism, not a list of buzzwords. Each option below fits in 5–8 minutes.

Deep diveShow in 5–8 minutesSignal it sendsWhere to study
Money mathLargest-remainder allocation in integers with the user_id tie-break; validation of payers and splits; why every expense's deltas sum to zero; the ₹125.50 basis-point exampleYou protect correctness under real inputs, not just the happy pathComplete Design: Splits, Rounding and Net Balances
Idempotent write transactionThe statement order; the four retry cases (after commit, concurrent, crashed, different body); key scope and 7-day retentionYou know where duplicates come from and why the check lives inside the transactionComplete Design: One Transaction and Idempotency Keys
Edits and historyLost-update timeline, If-Match compare-and-set, reversal + replacement SQL, delete-after-settlement arithmeticYou keep auditability without sacrificing concurrencyComplete Design: Versioned Edits, Reversals and Deletes
Consistency of derived viewsSynchronous balance_projection vs event-fed user_balance_summary; seq-guarded upsert; versioned cache with min_seq; the per-view contractYou can say precisely what is strongly consistent, what lags, and how the client knowsComplete Design: Versioned Cache, Read Paths and Consistency
SimplificationGreedy with two heaps, the (creditors + debtors − 1) bound, the five-member counterexample, NP-hardness of the exact minimumYou make honest algorithmic claimsComplete Design: Pairwise Debts and Simplification
Provider settlementState machine, webhook verification, provider_events dedupe, state guards, reconciliation, reversal on chargebackYou know who is authoritative for money and treat webhooks as untrusted inputComplete Design: Notifications, Multi-Currency and Settlement

The internal mechanisms behind each option — data structures, SQL and consumer code — are on Architecture Deep Dive; the alternatives and when they win are on Trade-offs & Decisions.

Interview 09

Staff-Level Follow-Ups

Senior and staff interviews probe boundaries: what the design guarantees, what it only targets, when it should change, and how you would change it safely.

Q

Given unlimited budget, would you still keep an immutable ledger with derived projections?

Strong answer angle

Yes. The choice is driven by correctness and auditability, not cost. Budget buys more replicas, faster rebuilds and more frequent reconciliation, but it does not remove the need for an authoritative, replayable record that corrections, disputes and recovery depend on. A mutable balance field is wrong at any budget because its risk is trust, not throughput.

Likely follow-ups
  • What would the budget change? — Performance and operations levers: lower dashboard lag, faster replay, more aggressive caching, more frequent provider reconciliation — not the correctness model.
Q

Why keep the group balance projection synchronous instead of moving it to the event pipeline like the dashboard?

Strong answer angle

The group sheet is the view a member checks immediately after writing, it lives in the same database as the ledger, and it changes only under the group lock the write already holds. Updating it in the transaction costs about five row updates and gives read-your-writes by construction. The dashboard spans groups — after partitioning, spans shards — so it cannot be in the transaction and is event-fed instead.

Likely follow-ups
  • When would you make it asynchronous? — If very large groups made the in-transaction upserts a measurable share of write latency. Then reads would need min_seq to fall back to the ledger, and the writer's own view becomes eventually consistent — a real product cost to name.
Q

How do you know when a single relational primary is no longer enough?

Strong answer angle

Watch measured signals, not a group count: write p99 approaching the 300 ms target, storage and backup/restore time growing (~3 TB/year), maintenance windows and blast radius. Throughput (~580 writes/s peak) is not what forces it. The domain is naturally partitioned by group, so the move is sharding by group_id behind a group directory.

Likely follow-ups
  • Is there a cheaper first step? — Yes for reads: the versioned cache, and replicas only where the caller can tolerate visible lag. For storage: archiving dormant groups. Neither helps blast radius, which is what finally justifies sharding.
Q

How would you migrate live balance reads from ledger aggregation to the projection without a regression?

Strong answer angle

Backfill balance_projection from the ledger per group under the group lock, start maintaining it in the write transaction, then shadow-read: serve the old aggregation, compare with the projection for every read, alert on mismatch. Cut over per cohort once mismatches stay at zero, and keep the aggregation as the reconciliation job.

Likely follow-ups
  • Which groups do you verify hardest? — Long-lived groups that use every split type and have had edits, deletes and settlement reversals — the cases a spot check on simple groups misses.
Q

What do you guarantee about duplicates end to end?

Strong answer angle

Two layers. At the API, a retried write with the same key and body has at most one effect, within the 7-day retention; a different body under the same key is rejected with 422. In the pipeline, delivery is at-least-once, not exactly-once; every consumer is idempotent (seq-guarded upserts, unique (event_id, recipient_user_id) for notifications) so a redelivered event has no second effect. Naming only one layer is a common gap.

Likely follow-ups
  • And for provider payments? — The settlement_id is the provider's idempotency key, provider_events deduplicates webhooks, and transitions are guarded on the current state.
Q

A regional disaster: what is lost and how do you recover?

Strong answer angle

Each shard has a synchronous in-region standby and an asynchronous cross-region replica, so cross-region RPO is seconds, not zero. After failover the last acknowledged writes may be missing: clients re-send queued writes with the same idempotency keys, reconciliation re-checks recent provider confirmations against the provider, and the bus and caches are re-derived from outbox and ledger. Restores from PITR are drilled.

Likely follow-ups
  • Could you make cross-region RPO zero? — Synchronous cross-region commit would add a round trip to every write and couple availability to two regions; for this product that cost usually exceeds the benefit. State it as a choice, not an impossibility.
Q

Where does this design deliberately stop?

Strong answer angle

No cross-group netting, no automatic currency conversion, no guaranteed-minimal simplification, no merge of concurrent edits, no claim of exactly-once delivery, and no SLA promise on dashboard freshness — those are targets (~2 s p99) that are monitored. Saying where a design stops is a stronger answer than a broad guarantee. See Complete Design: Guarantees and Honest Limits.

Likely follow-ups
  • How would you add cross-group netting if the product insisted? — As an explicit, member-confirmed settlement pair across two groups, written as two single-group transactions linked by an id — never as a shared balance that couples groups.
Interview 10

Question Bank

The questions that come up most, with the answer an interviewer is listening for and one follow-up each. Use it to rehearse out loud; a real interview samples a handful.

Modeling and money math

Q

What is the minimum set of entities?

Strong answer angle

Groups (with last_seq), memberships, expenses with immutable versions, payers and splits, ledger events (one signed delta_minor per affected member, per currency), settlements and audit entries. Balances are derived from ledger events, never stored as the primary fact.

Likely follow-ups
  • Why not a running balance per member pair? — It can drift through a double-applied or missed update and cannot be recomputed or audited. A stored balance is fine only as a derived projection that can be rebuilt from the ledger.
Q

Why integer minor units?

Strong answer angle

Binary floating point cannot represent most decimal fractions, so float arithmetic accumulates error, and the invariant is that shares sum exactly to the total. Store integer paise (cents; JPY has 0 decimals, KWD 3) and percentages as integer basis points.

Likely follow-ups
  • Does the UI work in paise too? — No. The client formats minor units for display; no money arithmetic is ever done on formatted strings.
Q

How are percentage and weight splits rounded?

Strong answer angle

Floor each exact share, then give the leftover minor units one each to the largest fractional remainders, ties broken by ascending user_id. ₹125.50 at 3333 / 3333 / 3334 bps: floors 4,182 / 4,182 / 4,184 leave 2 paise, which go to the two .915 remainders → 4,183 / 4,183 / 4,184 = 12,550. The result depends only on the inputs and is never more than one paisa from the exact share.

Likely follow-ups
  • Basis points that sum to 9,999? — Rejected with 422 at validation; the server never invents a missing basis point.
  • Why not let the last member absorb the remainder? — It is deterministic but biased — the same member always pays the extra unit and can be off by more than one paisa when several shares round down.
Q

How is a member's net balance derived, and what do the running example's nets look like?

Strong answer angle

Net = sum of the member's ledger deltas: paid-for-others minus own share, plus settlements paid, minus settlements received. E1 (₹900 equal, paid by Asha) gives +600 / −300 / −300; adding E2 (₹600 exact 100/200/300, paid by Ben) gives Asha +₹500, Ben +₹100, Cara −₹600; S1 (Cara pays Asha ₹200) gives +₹300 / +₹100 / −₹400. Every state sums to zero.

Likely follow-ups
  • Why must every state sum to zero? — Each write validates payers and shares against the same total, so each write's deltas sum to zero; a non-zero group sum therefore signals a bug, which a continuous check detects.
Q

Is simplification minimal, and is it binding?

Strong answer angle

Neither. Greedy largest-debtor/largest-creditor matching gives at most (creditors + debtors − 1) transfers but can miss the optimum (five members +400, +300, −300, −200, −200: greedy 4, optimum 3; the exact minimum is NP-hard). It is a read-only suggestion computed per currency from net positions, returned with its as_of_seq; members may settle any other way.

Likely follow-ups
  • Does it change who is net positive? — No. It preserves every member's net position, but not provenance — it may suggest paying someone you never directly owed.

Correct writes

Q

How is create-expense made idempotent?

Strong answer angle

The client sends Idempotency-Key. Inside the write transaction the server inserts into idempotency_records, unique on (actor_user_id, group_id, operation, idempotency_key), storing a SHA-256 request_hash and, before commit, the response. A retry with the same body replays the stored 201; a different body under the same key is 422 IDEMPOTENCY_KEY_CONFLICT; records are kept 7 days. Each key has at most one effect.

Likely follow-ups
  • Why not dedupe on payer + amount + description within a minute? — Wrong both ways: two genuine ₹150 coffees are not duplicates, and a retry an hour later from an offline queue is.
Q

How do you stop two concurrent edits from overwriting each other?

Strong answer angle

PUT with If-Match: "<version>"; the transaction does UPDATE expenses SET version = version + 1 WHERE expense_id = :id AND version = :expected AND status = 'active'. Zero rows → 409 VERSION_CONFLICT with current_version; missing header → 428 PRECONDITION_REQUIRED. The loser reloads, reapplies its change and resubmits.

Likely follow-ups
  • When would pessimistic locking win? — If edits to the same expense were frequent enough that 409 retries cost more than brief serialization — unlikely here, but it is the break-even condition to name.
Q

How are a correction and a delete represented?

Strong answer angle

As new history. A correction appends reversal entries negating the previous version and entries for the new one under a new group_seq; a delete sets status = 'deleted' and appends reversals only. Ledger rows are never updated or deleted, so "why did my balance change on Tuesday" always has an answer.

Likely follow-ups
  • Correcting E1 from ₹900 to ₹960? — Reversal −60,000 / +30,000 / +30,000, replacement +64,000 / −32,000 / −32,000: net change +4,000 / −2,000 / −2,000 paise.
Q

How do you enforce that only group members can touch a group?

Strong answer angle

Object-level authorization on every request: the owning service checks memberships for the group in the path, inside the write transaction for mutations. Authentication alone (a valid token) is not authorization; the API Gateway only authenticates.

Likely follow-ups
  • The exploit if you skip it? — Broken object-level authorization: any logged-in user could read or write another group by enumerating ids. The response is 403 FORBIDDEN_NOT_A_MEMBER.
Q

How does offline expense creation sync safely?

Strong answer angle

The client stores the expense with its idempotency key and replays it through the normal create endpoint on reconnect, so a replay after a dropped response is harmless. An offline edit carries the version it was based on; if someone else changed the expense meanwhile it gets 409 and the user resolves it.

Likely follow-ups
  • What does the client show before sync? — The entry marked pending-sync and excluded from authoritative balances, optionally merged into the display as a labeled estimate. Entries older than the 7-day key retention are surfaced for the user to confirm.

Reads, events and consistency

Q

What is a transactional outbox and why use it here?

Strong answer angle

The write transaction inserts the event as an outbox row, so the event exists if and only if the write committed. The Outbox Relay publishes unpublished rows to the Event Bus and marks them; a crash before marking republishes, so delivery is at-least-once.

Likely follow-ups
  • Why not publish to the bus right after commit? — A crash between commit and publish loses the event forever; a bus outage would force you to fail acknowledged writes or drop events.
Q

How does the dashboard projection survive duplicates and reordering?

Strong answer angle

Each event carries each affected member's absolute net_after_minor and the group_seq. The Projection Consumer upserts user_balance_summary with WHERE last_applied_seq < :seq, so a duplicate or an older event matches no row and changes nothing; no reordering buffer is needed, and a skipped intermediate state is superseded by the newer absolute value.

Likely follow-ups
  • If it is wrong anyway? — Fix the bug, then replay the bus (7-day retention) or rebuild from balance_projection; the upsert is idempotent, so the rebuild can run while live events continue.
Q

What can a member see right after writing, and what can others see?

Strong answer angle

The writer: their write, because the response carries group_seq, the next read sends it as min_seq, and any cached sheet older than that is bypassed for balance_projection, which already includes the write. Others: normally ~1–2 s behind via the versioned cache, worst case the 300 s safety TTL, always labeled with as_of_seq. The dashboard: eventually consistent, ~2 s p99 target.

Likely follow-ups
  • Is that a guarantee? — Read-your-writes on the writing device is; the freshness numbers are monitored targets.
Q

How would you shard, and what doesn't fit?

Strong answer angle

By group_id: every money-moving transaction is scoped to one group, so the group's ledger, versions, projection, idempotency records and outbox live on one shard and no write spans shards. A group directory maps groups to shards and lets a hot group move.

Likely follow-ups
  • What doesn't fit? — Per-user views — the dashboard and the user → groups index — which live in a separate store keyed by user, fed by events.
Q

How do you avoid notification spam?

Strong answer angle

The Notification Service consumes events, notifies only affected members other than the actor, deduplicates on (event_id, recipient_user_id), applies per-user preferences and sends digests for very busy groups.

Likely follow-ups
  • Should a confirmed provider payment bypass digests? — Reasonably yes — it is rare and high-signal. Name it as an explicit product exception.

Currency and settlement

Q

A member owes ₹1,000 and $20 in the same group. What is their balance?

Strong answer angle

Two balances. Currency is part of every balance key, each currency sums to zero across the group, and simplification and settlement run per currency. A combined figure is computed only for display from a dated FX Rate Snapshot and labeled as an estimate.

Likely follow-ups
  • They want to settle the USD debt in rupees? — An explicit member-initiated conversion record that closes the USD positions and opens INR positions at the recorded rate — zero-sum in each currency, never automatic.
Q

How do you model a provider payment that is pending, confirmed or failed?

Strong answer angle

pending on initiation with no ledger rows; a verified, deduplicated webhook moves pending → confirmed with a state guard and writes ledger rows, projection and outbox in one transaction; failed writes nothing; confirmed → reversed on refund or chargeback with reversal entries. Manual settlements are member assertions, created confirmed and disputable.

Likely follow-ups
  • What if the webhook never arrives? — Reconciliation queries the provider for settlements pending longer than 15 minutes and runs a daily comparison; confirmation is idempotent, so webhook and reconciliation cannot double-apply.

Operations

Q

A group's balances don't sum to zero. How do you debug it?

Strong answer angle

Recompute from ledger_events directly to see whether the ledger or only a projection is wrong. If the ledger: find the source record whose own entries don't net to zero (a write that bypassed the transaction, or a split-math bug). Repair with an explicit, audited correcting or reversal entry — never edit rows in place — and re-verify.

Likely follow-ups
  • How should it have been caught earlier? — A continuous zero-sum and projection-drift check with an alert at any value above 0, and unit tests with hand-computed expected shares for every split type.

Incident-style walkthroughs of these failures are on Failure & Scale Scenarios; the alternatives behind each answer are compared on Trade-offs & Decisions.

Interview 11

Whiteboard and Pseudocode Exercises

Hands-on tasks an interviewer may ask you to do at the board rather than describe. Practice each one in 3–4 minutes, narrating as you write.

1. Draw the schema and name the critical constraints

Draw the tables from Interview 04's data-model diagram and name the constraints out loud: unique (actor_user_id, group_id, operation, idempotency_key) on idempotency_records; primary key (expense_id, version, user_id) on payers and splits; expenses.version for compare-and-set; index ledger_events(group_id, currency, user_id) for aggregation and reconciliation; primary key (group_id, currency, user_id) on balance_projection; unique (provider, provider_event_id) on provider_events; unique (event_id, recipient_user_id) on notifications.

2. Allocation with deterministic rounding

textOne function for equal, percentage and weighted splits; integers end to end, so no floating-point value ever enters the computation.
function allocate(total_minor, parts):      // parts: [{user_id, weight}]
  // equal: weight 1 each; percentage: basis points (must sum to 10,000); weights: positive ints
  W = sum(p.weight for p in parts)
  for p in parts:
    p.share = (total_minor * p.weight) div W   // floor, integers only
    p.rem   = (total_minor * p.weight) mod W   // fractional remainder, scaled by W
  leftover = total_minor - sum(p.share)       // always < len(parts)
  for p in sort(parts, key = (-p.rem, p.user_id)).first(leftover):
    p.share += 1                              // largest remainder, ties by ascending user_id
  assert sum(p.share) == total_minor
  return parts

// ₹125.50 at [3333, 3333, 3334] bps: products 41,829,150 / 41,829,150 / 41,841,700
// floors 4,182 / 4,182 / 4,184 (12,548), remainders 9,150 / 9,150 / 1,700
// leftover 2 → asha, ben → 4,183 / 4,183 / 4,184 = 12,550

3. Greedy simplification and its limit

textO(n log n) and few transfers, but not guaranteed minimal: nets +400, +300, −300, −200, −200 give 4 greedy transfers where 3 suffice.
function simplify(nets):                   // user_id -> net_minor, one currency
  creditors = maxHeap((net, user_id) for net > 0)   // ties by ascending user_id
  debtors   = maxHeap((-net, user_id) for net < 0)
  transfers = []
  while creditors and debtors:
    c = creditors.pop(); d = debtors.pop()
    amount = min(c.amount, d.amount)
    transfers.append({from: d.user_id, to: c.user_id, amount_minor: amount})
    if c.amount > amount: creditors.push(c.amount - amount, c.user_id)
    if d.amount > amount: debtors.push(d.amount - amount, d.user_id)
  return transfers                           // ≤ creditors + debtors − 1 transfers

// After E1 + E2: creditors Asha 50,000, Ben 10,000; debtor Cara 60,000
// → Cara → Asha 50,000, Cara → Ben 10,000

4. The idempotent create-expense transaction

Swipe to pan
ClientIdempotency-KeyAPI Gatewaytoken · rate limitExpense Servicecompute sharesLedger DB · one transaction1. idempotency claim · membership2. group_seq = last_seq + 13. expense, version, payers, splits4. ledger_events (Σ = 0)5. balance_projection upserts6. outbox row · stored responseCOMMIT → 201 {group_seq}After commit (never inside the transaction)• best-effort DEL of balance:{group_id}:{currency} in the Balance Cache• Outbox Relay → Event Bus → Projection Consumer (dashboard, cache DEL) and Notification Service — at least once• a retry with the same key replays the stored 201; a crash before COMMIT leaves nothing behind
Create-expense path: one transaction commits the idempotency record, expense, ledger entries, balance projection and outbox row before 201
textThe key claim and the financial writes share one transaction; a check outside it would race. The stored response is replayed unchanged.
POST /v1/groups/{group_id}/expenses
Idempotency-Key: <client-generated UUID>
{ "total_minor": 90000, "currency": "INR", "split_type": "equal",
  "payers": [ { "user_id": ..., "paid_minor": 90000 } ], "beneficiaries": [ ... ] }

compute and validate shares in the service   // 422 SPLIT_SUM_MISMATCH / PAYER_SUM_MISMATCH
BEGIN
  INSERT idempotency_records (actor_user_id, group_id, 'create_expense', key,
                              request_hash = sha256(canonical path + body), expires 7 days)
    on unique violation → ROLLBACK; load the record:
       same request_hash  → return stored response (201, same body)
       different hash     → 422 IDEMPOTENCY_KEY_CONFLICT
  check membership                          // 403 FORBIDDEN_NOT_A_MEMBER, rolls back the claim
  UPDATE groups SET last_seq = last_seq + 1 RETURNING last_seq   // :seq, serializes the group
  INSERT expenses (version 1, status 'active'), expense_versions, expense_payers, expense_splits
  INSERT ledger_events (one row per participant, group_seq = :seq, sum = 0)
  UPSERT balance_projection (... last_applied_seq = :seq) RETURNING net_minor   // Stage 2
  INSERT outbox (event_id, group_id, group_seq, 'expense.created', effects)    // Stage 3
  UPDATE idempotency_records SET response_status = 201, response_body = ...
COMMIT
→ 201 { expense_id, version: 1, group_seq: :seq }; then best-effort cache DEL

5. The edit-conflict timeline

Draw two clients loading an expense at version 4. Client A sends PUT …/expenses/exp-2040 with If-Match: "4"; its UPDATE … WHERE version = 4 AND status = 'active' matches one row, appends reversals and replacement entries, and commits version 5. Client B's identical request matches zero rows and gets 409 VERSION_CONFLICT {current_version: 5}; B reloads, reapplies and resubmits with If-Match: "5" and a new idempotency key. Nothing is merged silently and nothing is dropped silently.

6. The sequence-guarded projection update and a rebuild

sqlAbsolute value plus sequence guard: duplicates and older events are no-ops, so no dedup table or reordering buffer is needed.
-- Projection Consumer, per affected member in the event, one local transaction
INSERT INTO user_balance_summary (user_id, group_id, currency, net_minor, last_applied_seq)
VALUES (:user_id, :group_id, :currency, :net_after_minor, :group_seq)
ON CONFLICT (user_id, group_id, currency) DO UPDATE
SET net_minor = EXCLUDED.net_minor, last_applied_seq = EXCLUDED.last_applied_seq
WHERE user_balance_summary.last_applied_seq < EXCLUDED.last_applied_seq;
-- then DEL balance:{group_id}:{currency}; commit the bus offset last

Then narrate a rebuild: for balance_projection, take the group lock, recompute SUM(delta_minor) per member and currency, replace the rows and set last_applied_seq = groups.last_seq (very large groups: shadow table, catch up, swap). For user_balance_summary, replay current nets through the same guarded upsert while live events continue. Verify zero-sum per currency before declaring done.

7. The settlement state machine

Draw pending → confirmed (verified webhook or reconciliation; ledger rows written), pending → failed (no entries), confirmed → reversed (refund or chargeback; settlement_reversal entries), and a manual settlement entering directly at confirmed. Mark where the state guard sits (WHERE status = 'pending') and what happens to a late contradictory webhook (flagged, not applied).

8. Debug a zero-sum violation

Given a group whose INR entries sum to non-zero: bypass projections and sum ledger_events; group by (source_type, source_id, source_version) and find the source whose entries don't net to zero; identify the cause (a write outside the transaction, a rounding bug); post an audited correcting entry; re-run the check; add the failing case as a unit test.

Interview 12

Strong vs Weak Answers

The pass/fail line is rarely raw knowledge. It is whether each claim is anchored to an invariant and a mechanism, or is an assumption presented as a fact.

TopicWeak answerStrong answer
Source of truthA mutable who-owes-whom table updated in place.An append-only ledger; balances are derived, rebuildable projections; corrections are new entries.
MoneyFloats like 33.33, rounded however the language does it.Integer minor units, basis points, largest remainder with ascending user_id tie-break; shares sum exactly to the total.
Architecture orderDraws Kafka, Redis and six microservices in minute two.Starts with Client → Expense Service → Ledger DB and adds each component because a named limit demands it.
Retries"We dedupe on the server" with no mechanism, or a check outside the transaction.Idempotency key scoped to actor, group and operation, request fingerprint, claimed in the write transaction; 422 on a different body.
Concurrent editsLast write wins.PUT + If-Match; one winner, 409 VERSION_CONFLICT for the other; reversal + replacement.
Group balance freshness"Balances are eventually consistent everywhere" or "always real-time".Group balance updated in the write transaction; writer reads with min_seq; other viewers see as_of_seq; only event-fed views lag.
Delivery"Kafka gives exactly-once."At-least-once delivery, idempotent consumers, at most one effect per event and per idempotency key.
CachingA balance cache with a 60 s TTL.Versioned cache with as_of_seq, min_seq bypass, set-if-newer fills, DEL on commit and on event, 300 s TTL backstop.
Simplification"Greedy finds the minimum number of transfers."Few, not fewest; the exact minimum is NP-hard; preserves net positions, not provenance; a suggestion.
SettlementBalance reduced when the payment is initiated.pending / confirmed / failed / reversed; balances move only on a verified, deduplicated, state-guarded confirmation.
Multi-currencyConverts everything to one currency at a live rate.Separate zero-sum ledgers per currency; FX display-only and labeled; explicit conversion records.
Scale and DR"Shard by user"; "RPO zero".Shard by group_id (every write is single-group); per-user views event-fed; cross-region RPO is seconds.
The same knowledge, stated precisely versus vaguely.
Interview 13

Quick Revision

The night-before pass: the stage ladder, the invariants with their mechanisms, the numbers and the vocabulary.

StageAddsLimit it removes
0Client → Expense Service → Ledger DB; balances summed on read—
1One transaction; idempotency key + fingerprint; group_seq; PUT + If-Match; reversal + replacementPartial writes, duplicate retries, lost updates, erased history
2balance_projection updated in the write transactionReads that cost O(history)
3Outbox → Outbox Relay → Event Bus → Projection Consumer → User Balance Projection; versioned Balance CacheLost or coupled side effects, cross-group dashboard, hot reads on the primary
4Notification Service; per-currency balances; Payment Service with provider-confirmed settlementUnserved notification, multi-currency and payment requirements
5Reconciliation and Rebuild Jobs, hot-group limits, shards by group_id, API Gateway, standby + replicas, observabilityOperating it safely at scale
Key takeaways
  1. 01Integer minor units; percentages in basis points; largest remainder with ascending user_id tie-break; shares and payers sum exactly to the total.
  2. 02Ledger delta = paid − share; a group sums to zero per currency; a non-zero sum is a bug that is detected, not patched.
  3. 03Simplification: greedy, at most (creditors + debtors − 1) transfers, not guaranteed minimal; preserves net positions, not provenance; a suggestion.
  4. 04One transaction per write: idempotency claim, membership, group_seq, rows, ledger, balance_projection, outbox, stored response.
  5. 05At most one effect per idempotency key (7 days); same key + different body → 422 IDEMPOTENCY_KEY_CONFLICT.
  6. 06PUT + If-Match: stale → 409 VERSION_CONFLICT, missing → 428; corrections are reversal + replacement, deletes are reversals.
  7. 07Group balance: synchronous, read-your-writes via min_seq; dashboard and notifications: event-fed, at-least-once delivery, seq-guarded or deduplicated.
  8. 08Settlement: pending → confirmed | failed, confirmed → reversed; the provider is authoritative; reconciliation after 15 min.
  9. 09Partition by group_id; hot group ~100–200 writes/s on the group lock; cross-region RPO is seconds, not zero; the gateway authenticates, services authorize.
NumberValue
Peak writes / reads~580/s / ~2,315/s (4:1)
Ledger growth25M rows/day, ~1.8 TB/year; ~3 TB/year all tables
Rows per group~2,300 after one year
Read aggregation at peak≈ 8M rows/s (year 1), 16M (year 2) vs ≈ 17,500 with the projection
Targetswrite p99 < 300 ms; group read p99 < 100 ms; dashboard ~2 s p99
Timeoutsidempotency, outbox and bus retention 7 days; cache TTL 300 s; pending settlement check 15 min; outbox age alert 30 s
Illustrative assumptions and monitored targets, not guarantees.
TermMeaning here
Ledger eventImmutable signed delta_minor for one member, one currency, from one expense version or settlement
group_seqGap-free per-group commit number from groups.last_seq; drives as_of_seq, min_seq and sequence guards
Group balance projectionbalance_projection, updated in the write transaction; derived and rebuildable
User Balance Projectionuser_balance_summary, per user across groups; maintained by the Projection Consumer from events
Transactional outboxEvent row in the write transaction; published at least once by the Outbox Relay
ReversalEntries that exactly negate a previous version's or settlement's entries