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.
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 ask | Why it matters | How 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.
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.
| Minutes | Stage | What is on the board at the end |
|---|---|---|
| 0–5 | Scope and requirements | Scope 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–8 | Estimates | ~580 writes/s and ~2,315 balance reads/s at peak; ~2,300 ledger rows per group per year; ~3 TB/year |
| 8–18 | Stage 0, data model, algorithms | Client → Expense Service → Ledger DB; core tables; ledger delta = paid − share; rounding rule; net balance; greedy simplification |
| 18–25 | Stage 1 — correct writes | One transaction with the idempotency claim and the group_seq bump; PUT + If-Match; reversal + replacement |
| 25–30 | Stage 2 — read bottleneck | Rows-scanned arithmetic; balance_projection updated in the write transaction |
| 30–36 | Stage 3 — outbox and derived views | Outbox → Outbox Relay → Event Bus → Projection Consumer → User Balance Projection; versioned Balance Cache |
| 36–40 | Stage 4 — capabilities | Notification Service, per-currency balances, Payment Service with provider-confirmed settlement |
| 40–45 | Stage 5 — production and recap | Failure responses, rebuilds, hot groups, partitioning by group_id, API Gateway, DR, observability; final board |
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.
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| Number | What it decides |
|---|---|
| ~580 writes/s at peak | One relational primary handles the write rate; partitioning is not a day-one throughput need. |
| 4:1 reads, history growing ~6 rows/group/day forever | Summing the ledger on every read gets slower every day — the first real limit (Stage 2). |
| ~3 TB/year | Storage, backup time and blast radius — not throughput — eventually force partitioning by group (Stage 5). |
| Notifications at read-rate scale | Delivery 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. |
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
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
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
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.
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.
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
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
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
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.
Depth for each step: Complete Design, Chapter 11, Complete Design, Chapter 12 and Complete Design, Chapter 13.
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
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.
Stage 3b — versioned cache and the consistency contract
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.
Stage 4 — notifications, multi-currency, provider-confirmed settlement
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.
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.
| Topic | What to say | Follow-up and strong answer |
|---|---|---|
| Relay or bus down | Writes 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 drift | A 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 group | Writes 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. |
| Partitioning | Shard 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 recovery | Synchronous 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 Gateway | TLS, 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. |
| Observability | Write 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. |
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.
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 dive | Show in 5–8 minutes | Signal it sends | Where to study |
|---|---|---|---|
| Money math | Largest-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 example | You protect correctness under real inputs, not just the happy path | Complete Design: Splits, Rounding and Net Balances |
| Idempotent write transaction | The statement order; the four retry cases (after commit, concurrent, crashed, different body); key scope and 7-day retention | You know where duplicates come from and why the check lives inside the transaction | Complete Design: One Transaction and Idempotency Keys |
| Edits and history | Lost-update timeline, If-Match compare-and-set, reversal + replacement SQL, delete-after-settlement arithmetic | You keep auditability without sacrificing concurrency | Complete Design: Versioned Edits, Reversals and Deletes |
| Consistency of derived views | Synchronous balance_projection vs event-fed user_balance_summary; seq-guarded upsert; versioned cache with min_seq; the per-view contract | You can say precisely what is strongly consistent, what lags, and how the client knows | Complete Design: Versioned Cache, Read Paths and Consistency |
| Simplification | Greedy with two heaps, the (creditors + debtors − 1) bound, the five-member counterexample, NP-hardness of the exact minimum | You make honest algorithmic claims | Complete Design: Pairwise Debts and Simplification |
| Provider settlement | State machine, webhook verification, provider_events dedupe, state guards, reconciliation, reversal on chargeback | You know who is authoritative for money and treat webhooks as untrusted input | Complete 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.
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.
Given unlimited budget, would you still keep an immutable ledger with derived projections?
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.
- 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.
Why keep the group balance projection synchronous instead of moving it to the event pipeline like the dashboard?
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.
- 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_seqto fall back to the ledger, and the writer's own view becomes eventually consistent — a real product cost to name.
How do you know when a single relational primary is no longer enough?
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.
- 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.
How would you migrate live balance reads from ledger aggregation to the projection without a regression?
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.
- 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.
What do you guarantee about duplicates end to end?
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.
- And for provider payments? — The
settlement_idis the provider's idempotency key,provider_eventsdeduplicates webhooks, and transitions are guarded on the current state.
A regional disaster: what is lost and how do you recover?
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.
- 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.
Where does this design deliberately stop?
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.
- 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.
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
What is the minimum set of entities?
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.
- 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.
Why integer minor units?
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.
- Does the UI work in paise too? — No. The client formats minor units for display; no money arithmetic is ever done on formatted strings.
How are percentage and weight splits rounded?
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.
- 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.
How is a member's net balance derived, and what do the running example's nets look like?
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.
- 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.
Is simplification minimal, and is it binding?
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.
- 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
How is create-expense made idempotent?
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.
- 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.
How do you stop two concurrent edits from overwriting each other?
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.
- 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.
How are a correction and a delete represented?
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.
- 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.
How do you enforce that only group members can touch a group?
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.
- 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.
How does offline expense creation sync safely?
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.
- 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
What is a transactional outbox and why use it here?
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.
- 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.
How does the dashboard projection survive duplicates and reordering?
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.
- 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.
What can a member see right after writing, and what can others see?
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.
- Is that a guarantee? — Read-your-writes on the writing device is; the freshness numbers are monitored targets.
How would you shard, and what doesn't fit?
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.
- 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.
How do you avoid notification spam?
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.
- 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
A member owes ₹1,000 and $20 in the same group. What is their balance?
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.
- 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.
How do you model a provider payment that is pending, confirmed or failed?
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.
- 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
A group's balances don't sum to zero. How do you debug it?
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.
- 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.
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
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,5503. Greedy simplification and its limit
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,0004. The idempotent create-expense transaction
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 DEL5. 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
-- 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 lastThen 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.
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.
| Topic | Weak answer | Strong answer |
|---|---|---|
| Source of truth | A mutable who-owes-whom table updated in place. | An append-only ledger; balances are derived, rebuildable projections; corrections are new entries. |
| Money | Floats 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 order | Draws 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 edits | Last 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. |
| Caching | A 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. |
| Settlement | Balance reduced when the payment is initiated. | pending / confirmed / failed / reversed; balances move only on a verified, deduplicated, state-guarded confirmation. |
| Multi-currency | Converts 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. |
Quick Revision
The night-before pass: the stage ladder, the invariants with their mechanisms, the numbers and the vocabulary.
| Stage | Adds | Limit it removes |
|---|---|---|
| 0 | Client → Expense Service → Ledger DB; balances summed on read | — |
| 1 | One transaction; idempotency key + fingerprint; group_seq; PUT + If-Match; reversal + replacement | Partial writes, duplicate retries, lost updates, erased history |
| 2 | balance_projection updated in the write transaction | Reads that cost O(history) |
| 3 | Outbox → Outbox Relay → Event Bus → Projection Consumer → User Balance Projection; versioned Balance Cache | Lost or coupled side effects, cross-group dashboard, hot reads on the primary |
| 4 | Notification Service; per-currency balances; Payment Service with provider-confirmed settlement | Unserved notification, multi-currency and payment requirements |
| 5 | Reconciliation and Rebuild Jobs, hot-group limits, shards by group_id, API Gateway, standby + replicas, observability | Operating it safely at scale |
- 01Integer minor units; percentages in basis points; largest remainder with ascending
user_idtie-break; shares and payers sum exactly to the total. - 02Ledger delta = paid − share; a group sums to zero per currency; a non-zero sum is a bug that is detected, not patched.
- 03Simplification: greedy, at most (creditors + debtors − 1) transfers, not guaranteed minimal; preserves net positions, not provenance; a suggestion.
- 04One transaction per write: idempotency claim, membership,
group_seq, rows, ledger,balance_projection, outbox, stored response. - 05At most one effect per idempotency key (7 days); same key + different body → 422
IDEMPOTENCY_KEY_CONFLICT. - 06
PUT+If-Match: stale → 409VERSION_CONFLICT, missing → 428; corrections are reversal + replacement, deletes are reversals. - 07Group balance: synchronous, read-your-writes via
min_seq; dashboard and notifications: event-fed, at-least-once delivery, seq-guarded or deduplicated. - 08Settlement:
pending→confirmed|failed,confirmed→reversed; the provider is authoritative; reconciliation after 15 min. - 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.
| Number | Value |
|---|---|
| Peak writes / reads | ~580/s / ~2,315/s (4:1) |
| Ledger growth | 25M 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 |
| Targets | write p99 < 300 ms; group read p99 < 100 ms; dashboard ~2 s p99 |
| Timeouts | idempotency, outbox and bus retention 7 days; cache TTL 300 s; pending settlement check 15 min; outbox age alert 30 s |
| Term | Meaning here |
|---|---|
| Ledger event | Immutable signed delta_minor for one member, one currency, from one expense version or settlement |
group_seq | Gap-free per-group commit number from groups.last_seq; drives as_of_seq, min_seq and sequence guards |
| Group balance projection | balance_projection, updated in the write transaction; derived and rebuildable |
| User Balance Projection | user_balance_summary, per user across groups; maintained by the Projection Consumer from events |
| Transactional outbox | Event row in the write transaction; published at least once by the Outbox Relay |
| Reversal | Entries that exactly negate a previous version's or settlement's entries |