Skip to content
SeeItFlow
System Design · Failure & Scale Scenarios · 35 scenarios · ~32 min read

Splitwise System Design Failure, Recovery and Scaling Scenarios

Splitwise system design failure and scale scenarios: 35 pressures applied to the finished design, including retries, edit races, duplicate and reordered events, stale reads, webhook failures, hot groups, corruption and regional loss. Each traces the root cause, response, recovery and the invariant it tests.

Mangesh MandlikLast updated: How lessons are made
Overview

The Architecture Under Test and the Scenario Map

Every scenario on this page starts from the finished Splitwise architecture and asks one question: which established mechanism absorbs this pressure, and what does it cost? Nothing here introduces a new component; when a scenario exposes a limit, the response is the mechanism the design already has, or an operational improvement around it.

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.
The architecture under test: API Gateway, Expense Service and Payment Service over Ledger DB shards partitioned by group_id; outbox relay, event bus, Projection Consumer, User Balance Projection, Balance Cache, Notification Service and the reconciliation and rebuild jobs around them

What is synchronous and what is not. One local transaction on the group's shard claims the idempotency key, checks membership, takes the next group_seq from the group row, writes the expense (or settlement) rows and their ledger_events, updates the group balance projection (balance_projection) and inserts an outbox row. So the ledger and the group balance sheet never disagree on the primary. Everything fed by the Event Bus — the User Balance Projection behind the cross-group dashboard, notifications, and the event-driven cache delete — is at-least-once and eventually consistent, and says how fresh it is with as_of_seq.

ChapterScenariosPressureMechanism that handles itComplete Design
1 · Retries and partial writes01–03Lost responses, crashes mid-write, duplicate scheduler runsOne transaction; idempotency key with request fingerprintCh. 11
2 · Split arithmetic04–05Shares that do not add up; rounding done in several placesServer-side integer math, largest-remainder rule, 422 validationCh. 09
3 · Concurrent edits06–09Two edits, an edit beside a settlement, a delete after repayment, a removal raceIf-Match compare-and-set, group row lock, reversal-only historyCh. 12
4 · Event pipeline and derived views10–17Duplicates, reordering, relay or bus outage, consumer lag, stale cache, driftOutbox at-least-once, sequence-guarded upserts, versioned cache, rebuild from the ledgerCh. 14–15
5 · Provider settlements18–22Duplicate, lost, late or forged webhooks; failures; chargebackspending → confirmed | failed, confirmed → reversed, state guards, reconciliationCh. 16
6 · Multi-currency23–24Accidental netting; moving FX ratesCurrency in every balance key; FX display-only; explicit conversion recordsCh. 16
7 · Authorization25–27Token replay, cross-group access, edits by the wrong memberMembership check in the service on every request; single-use invitationsCh. 18
8 · Scale and load28–31Hot groups, traffic spikes, dashboard fan-out, large-group simplificationGroup-lock ceiling with 429s, cache, User Balance Projection, greedy simplificationCh. 17
9 · Infrastructure and disaster recovery32–35Receipt store outage, failover, corrupted data, regional lossSync standby, PITR, async cross-region replica (RPO > 0), re-derived viewsCh. 17
Scenarios are ordered by the stage that introduced the mechanism they test.

How each case is told. Pressure → root cause in the architecture → how the system responds → recovery and improvement → what to monitor and which invariant is being tested. Timing tables appear only where the interleaving is the lesson.

The running example. Group Weekend Trip (grp-weekend-trip, INR, amounts in paise) with members Asha, Ben and Cara: E1 dinner ₹900 paid by Asha, split equally (exp-1001, group_seq 1); E2 taxi ₹600 paid by Ben, exact 100/200/300 (exp-1002, seq 2); S1 a manual ₹200 settlement from Cara to Asha (set-77, seq 3). After S1 the nets are Asha +30,000, Ben +10,000, Cara −40,000. Most scenarios use roles — payer, member, client A and client B — and reach for these numbers only where the arithmetic matters.

Scenarios 01–03

Retries and Partial Writes

Every money-moving write must survive being retried and must leave either all of its rows or none. Stage 1 solves both inside one relational transaction (Complete Design, Chapter 11); these three scenarios test that transaction from the client side, from the database side and from a background job.

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
The Stage 1 write: idempotency claim, membership check, per-group sequence, expense rows and ledger entries commit together; a reused key with a different body gets 422

Scenario 01 — The client retries after a lost response

Pressure. Asha's phone posts E1. The server commits it, but the response is lost on a flaky connection; the client cannot tell a failure from a lost reply and retries the same request. Root cause. Retrying is correct client behavior, and the network makes the outcome of any request unknowable from the client's side. Without server-side deduplication a retry records a second dinner.

How the system responds

The retry carries the same Idempotency-Key. Its INSERT INTO idempotency_records hits the unique constraint on (actor_user_id, group_id, operation, idempotency_key); the server loads the stored record, finds that the SHA-256 request_hash of the canonical path and body matches, and returns the stored 201 unchanged — no new rows, no second ledger effect, no second activity entry. A retry that arrives while the first attempt is still running waits on the uncommitted key and then replays its result, or proceeds as a fresh request if the first attempt rolled back. The same key with a different body is a client bug and gets 422 IDEMPOTENCY_KEY_CONFLICT with nothing written.

Recovery and improvement

None needed per request: the stored response is the recovery. The improvement work is on the client: generate the key once per user intent and persist it with the queued write (never once per attempt), retry with exponential backoff and jitter, and surface entries queued for longer than the 7-day key retention for the user to confirm instead of sending them silently.

What to monitor · invariant tested

Idempotent replay rate and 422 IDEMPOTENCY_KEY_CONFLICT rate per client version; a jump after a release points at a client that changes the body or regenerates keys. Invariant: a retried write has at most one effect, within the 7-day retention window.

TimeClientServerEffect
t0POST E1 with key K1Claims K1, commits E1 at group_seq 1, stores the 201Asha +60,000, Ben −30,000, Cara −30,000
t1Response lost; client sees a timeout—Unchanged
t2Retries with K1, same bodyUnique violation on K1; hashes match; returns the stored 201 {exp-1001, version 1, group_seq 1}Unchanged — no new rows
t3Buggy retry with K1, total 95,000Hash differs → 422 IDEMPOTENCY_KEY_CONFLICTUnchanged — nothing written
A lost response followed by a retry. The key is scoped to (actor, group, operation), so the same raw key from another user or group is a different request.

Scenario 02 — The process or connection dies in the middle of a write

Pressure. While E2 is being written, the Expense Service is killed, its connection drops, or a constraint fires after the expense head is inserted but before the ledger rows are. Root cause. An expense is several rows — head, version, payers, splits, ledger entries, audit entry. In the Stage 0 design, written as separate statements, a crash between them leaves an expense with no balance effect: the payer and split totals no longer match the ledger, and the group's balances silently omit a real expense.

How the system responds

In Stage 1 all of those rows and the idempotency claim — and, in later stages, the balance_projection update and the outbox row — commit in one local transaction. A crash or dropped connection before COMMIT rolls everything back, including the key claim, so nothing is visible to any reader. The client sees an error or a timeout and retries with the same key; because nothing was stored, the retry runs as a fresh request and succeeds. A crash after COMMIT is Scenario 01: the retry replays the stored response.

Recovery and improvement

Nothing to repair. The improvement is a guard against regressions: no network call ever runs inside the transaction (so it stays short and cannot partially fail on a remote system), and the reconciliation checks — every group's ledger sums to zero per currency, and every expense version's splits and payers sum to its total — run continuously, so a code path that ever writes outside the transaction is caught.

What to monitor · invariant tested

Transaction rollback rate by cause; zero-sum and split-sum violations, both of which must stay at 0. Invariant: a write is all or nothing.

Scenario 03 — A recurring-expense job fires twice for the same period

Pressure. A group has a monthly rent expense. The scheduler fails over mid-run, or a job runner retries after a timeout, and the generator for March runs twice. Root cause. Job runners are at-least-once just like mobile clients: “no response yet” does not mean “never ran”.

How the system responds

The generator writes through the normal create-expense transaction with a deterministic key, (recurring_id, period). The second run hits the same idempotency record and replays the first run's result, so March gets exactly one expense, one set of ledger entries and one notification. Two different periods generated concurrently are different keys and both proceed.

Recovery and improvement

If a duplicate was created before the deterministic key existed, it is removed with the normal delete (a reversal, never a row deletion). The symmetric failure — a missed period after a long scheduler outage — is fixed by a catch-up job that walks every period since the last generated one; because each period has its own key, catch-up can safely be re-run.

What to monitor · invariant tested

Runs per (recurring_id, period) above 1, and expected-versus-generated recurring expenses per day (catches skipped periods too). Invariant: a retried write has at most one effect, whether the retry comes from a phone or a scheduler.

Scenarios 04–05

Split Arithmetic at the Boundary

Every amount is an integer number of minor units, every expense's shares and payers sum exactly to its total, and one rounding rule decides who receives a leftover unit (Complete Design, Chapter 09). These two scenarios test that contract where it is most often broken: input from clients.

Scenario 04 — A client submits shares that do not add up

Pressure. The first attempt at E2 arrives as total_minor: 60000 with exact shares 10,000 / 20,000 / 25,000 — a stale form field after a member edited one share. Other variants: a payer total that differs from the expense total, a negative or zero amount, "600.005" for a currency with two decimals, or an absurd value from a client bug that multiplied an amount. Root cause. The client is not trusted to do money arithmetic; anything it sends is input to validate, not a fact to store.

How the system responds

The Expense Service validates before opening the transaction: amounts parse as integers in the currency's minor unit (INR 2 decimals, JPY 0, KWD 3) and are positive and below a documented per-expense ceiling; exact shares must sum to the total (422 SPLIT_SUM_MISMATCH, with the expected and submitted sums); payer amounts must sum to the total (422 PAYER_SUM_MISMATCH). Nothing is written and nothing is auto-corrected — guessing which member should absorb ₹50 would put a number in someone's balance that nobody entered. Amounts are carried as 64-bit integers end to end, so a valid amount can never wrap or lose precision in intermediate arithmetic.

Recovery and improvement

The client fixes its input and resubmits — with a new idempotency key, because the body changed. The rejected request left no record, so even reusing the key would not conflict, but a new intent deserves a new key. A spike after a release is a client regression to fix in the client, never with a server-side workaround.

What to monitor · invariant tested

422 rate by error code and client version. Invariant: shares and payers sum exactly to the total, enforced as a precondition of every write path (manual, recurring, import).

Scenario 05 — Clients and server disagree about rounding

Pressure. A web client previews ₹100 split three ways with floating-point arithmetic and shows 33.33 each; another client gives the extra paisa to the payer; a percentage split arrives as 33.33% / 33.33% / 33.34% in floats. Members see different shares on different devices. Root cause. Rounding implemented in several places, in floating point, with different tie rules.

How the system responds

Shares for equal, percentage and weight splits are computed in one place — the split library inside the Expense Service — in integers: floor every exact share, then hand the leftover units one each to the largest fractional remainders, ties broken by ascending user_id. ₹100 / 3 becomes 3,334 / 3,333 / 3,333 (all remainders tie, so the lowest user_id gets the extra paisa). Percentages are integer basis points that must sum to 10,000: ₹125.50 at 3,333 / 3,333 / 3,334 bps gives floors 4,182 / 4,182 / 4,184 with remainders .915 / .915 / .17, so the two leftover units go to the first two members: 4,183 / 4,183 / 4,184. Weights 1:2:2 on ₹1,000 give 20,000 / 40,000 / 40,000 exactly. Clients display the shares the server returns, or call a preview endpoint that runs the same library.

Recovery and improvement

If a rounding bug ever persisted wrong shares, a sweep finds the affected expenses (the split-sum check plus a recompute-and-compare with the correct rule), and each is corrected through the normal edit path — reversal of the old version plus a replacement — so balances change visibly and explainably instead of being patched in place.

What to monitor · invariant tested

Split-sum assertion failures (must be 0) and preview-versus-committed mismatches per client. Invariant: integer minor units only, and the same input always produces the same shares.

Swipe to pan
E1 Dinner ₹900paid by Asha · equalAshashare 30,000 paiseBenshare 30,000 paiseCarashare 30,000 paise30,000 × 3 = 90,000 paise — shares always sum exactly to the total
E1's equal split: 90,000 paise in, three 30,000-paise shares out. Uneven divisions use the largest-remainder rule with ties by ascending user_id, so the shares still sum exactly to the total
Scenarios 06–09

Concurrent Edits, Deletes and Membership Changes

An expense looks like a mutable document but sits on an append-only, versioned history; every money-moving write in a group serializes on the group row. These four scenarios test what happens when changes overlap (Complete Design, Chapter 11, Complete Design, Chapter 12).

Scenario 06 — Two members edit the same expense

Pressure. Client A and client B both load the ₹1,200 grocery expense exp-2040 at version 4. A corrects the total to ₹1,250; B changes the description and saves the whole form, including the old total. Root cause. A read-then-write across two HTTP requests. With a plain UPDATE, B's save would silently overwrite A's correction — the lost update.

How the system responds

Edits are PUT with If-Match: "4". Inside the edit transaction, UPDATE expenses SET version = version + 1 WHERE expense_id = :id AND version = :expected AND status = 'active' is a compare-and-set. A's request matches, commits version 5 (reversal entries for version 4 plus entries for version 5, under a new group_seq). B's request matches zero rows, rolls back and gets 409 VERSION_CONFLICT with current_version: 5. A request without If-Match gets 428 PRECONDITION_REQUIRED. If A's own successful edit is retried after a lost response, its idempotency key replays the stored result instead of returning a confusing 409.

Recovery and improvement

B's client reloads version 5, shows what changed, reapplies the description and resubmits with If-Match: "5". The server never merges: field-level merging is tolerable for descriptions but dangerous for amounts and splits.

What to monitor · invariant tested

409 rate per group (high in one group means genuinely busy editing; high everywhere means a client not refreshing versions) and 428 rate (a client omitting the header). Invariant: no silent lost update.

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'
Two PUTs with If-Match: "4" on exp-2040: the first commits version 5, the second gets 409 VERSION_CONFLICT instead of overwriting it

Scenario 07 — An edit and a settlement land in the same group at the same moment

Pressure. Asha corrects E1 from ₹900 to ₹960 at the same instant Cara records S1, her ₹200 repayment. Root cause in a naive design. If “the balance” were one mutable field per member, both writes would read it, add their effect and write it back, and one effect would be lost. Note also that a settlement is not attached to an expense: it is a transfer between two members that moves their nets.

How the system responds

Neither write updates a balance by read-modify-write against stale data. Both are appends, and both take the group row lock with UPDATE groups SET last_seq = last_seq + 1, so they serialize: each gets its own group_seq and applies its balance_projection deltas under that lock. Locks are always taken in the same order — the expense (or settlement) row first, then the group row — so the two cannot deadlock. Whichever commits first, the result is the same: from Asha +30,000, Ben +10,000, Cara −40,000 after S1, the correction adds +4,000 / −2,000 / −2,000, giving Asha +34,000, Ben +8,000, Cara −42,000, still zero-sum.

Recovery and improvement

Nothing to recover. The cost is that writes within one group run one at a time — a few milliseconds each — which matters only for hot groups (Scenario 28).

What to monitor · invariant tested

Lock wait time on group rows, and the projection-versus-ledger reconciliation (must find 0 mismatches). Invariant: concurrent writes compose; the ledger is zero-sum per currency after every commit.

Scenario 08 — An expense is deleted after a repayment was recorded

Pressure. After S1, Asha deletes E1, believing it was a duplicate. Root cause. A settlement records money that really moved; the expense that motivated it can still turn out to be wrong. A row deletion would erase the context of the repayment and make the group's history unexplainable.

How the system responds

A delete is the edit transaction without a replacement: If-Match check, status = 'deleted', reversal entries that negate E1's entries exactly, an audit entry. Nothing is erased, and S1 is untouched — the system never silently forgives or drops a settlement. The arithmetic may now point the other way: Asha −30,000 (she still owes her ₹100 taxi share and received ₹200 she is no longer owed), Ben +40,000, Cara −10,000. The activity history shows E1, its deletion and S1 as separate, timestamped facts.

Recovery and improvement

If the deletion was a mistake, the expense is recreated (or a future product offers “restore”, which is just another versioned write). If the group wants Cara's money back, that is a new settlement from Asha to Cara, recorded going forward. The UI warns before deleting an expense when settlements have been recorded since it was created — a warning, not a block, because the decision belongs to the members.

What to monitor · invariant tested

Deletes followed by large balance swings, and support tickets tagged “balance flipped after delete”. Invariant: corrections never erase history.

Scenario 09 — A member is removed while a write naming them is in flight

Pressure. One member adds an expense that includes Ben as a participant at the moment an admin removes Ben from the group. Root cause. The client checked membership when the form loaded, seconds earlier; that check is stale by the time the request commits.

How the system responds

Membership is checked by the Expense Service inside the write transaction, not by the client and not by the gateway. Removal is itself a write on the same group that sets the membership's left_at under the same group row lock, and the expense transaction checks its participants' memberships after taking that lock, so the two serialize: if the removal commits first, the expense's participant check fails and the request is rejected with a validation error naming the inactive participant; if the expense commits first, Ben is in it and the removal then sees a non-zero balance. Products usually block removing a member whose net is non-zero in any currency until it is settled, because removing them would strand real debts.

Recovery and improvement

The creator decides how to proceed — exclude Ben, or re-add him and resubmit (a new request with a new key). A former member keeps read access to the history they were part of.

What to monitor · invariant tested

Rejections for inactive participants, and an audit query asserting no committed expense references a participant who was not active at its group_seq. Invariant: a write cannot bind a non-member into a group's balances.

Scenarios 10–17

The Event Pipeline and Derived Views

Stage 2 keeps the group balance sheet (balance_projection) inside the write transaction; Stage 3 adds a transactional outbox, an Outbox Relay, an Event Bus keyed by group_id, a Projection Consumer that maintains the User Balance Projection (user_balance_summary) for dashboards, a versioned Balance Cache and, at Stage 4, the Notification Service (Complete Design, Chapter 13, Complete Design, Chapter 14, Complete Design, Chapter 15). Every scenario below lives downstream of the commit — so none of them can lose a write or make a group's balance sheet disagree with its ledger on the primary.

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 expense rows, ledger entries, balance_projection update and outbox row commit in one transaction; the relay publishes afterwards, at least once, and consumers make each event's effect idempotent

Scenario 10 — An event is delivered twice

Pressure. The Outbox Relay publishes E1's event, then crashes before setting published_at, and publishes it again on restart. Or the Projection Consumer writes its effect and crashes before committing its bus offset, so the same event is redelivered. Root cause. Delivery is at-least-once by design, not exactly-once; duplicates are a normal operating condition, not an edge case.

How the system responds

Every consumer makes its effect idempotent and records it together with its progress in one local transaction, committing the bus offset only afterwards. The Projection Consumer writes each member's absolute net_after_minor with the event's group_seq, guarded by WHERE last_applied_seq < :seq, so a second copy matches no row and changes nothing. The Notification Service has a unique constraint on (event_id, recipient_user_id), so nobody is notified twice. The group balance sheet is not involved at all: it was updated once, in the write transaction.

Recovery and improvement

Nothing to recover. Each event has effect once because every consumer's write is idempotent — at-least-once delivery plus idempotent application, which is the only honest claim for this pipeline.

What to monitor · invariant tested

Duplicate (no-op) rate per consumer; a rising rate points at relay restarts or consumer crash loops. Invariant: a duplicated event has no duplicated effect.

sqlThe Projection Consumer's upsert: absolute value plus sequence guard, idempotent and order-tolerant
INSERT INTO user_balance_summary (user_id, group_id, currency, net_minor, last_applied_seq)
VALUES (:user, :group, :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;
-- a duplicate or older event matches no row: no effect

Scenario 11 — Events for one group arrive out of order

Pressure. Two relay workers claim different batches with FOR UPDATE SKIP LOCKED; the worker holding E2's row (seq 2) publishes before the one holding E1's (seq 1). The bus preserves per-partition order only in the order things were published, so the consumer sees seq 2, then seq 1. Root cause. Parallel publishing trades strict order for throughput and availability.

How the system responds

When seq 1 arrives after seq 2, the guard last_applied_seq < 1 is false and the older event is a no-op; the member already holds the newer absolute net from seq 2. Skipping an intermediate state is harmless because a newer absolute value supersedes it. No reordering buffer is needed and the consumer never waits for a gap to fill. Notifications are independent per event and display the event's own time, so their order does not matter. The group balance sheet is again unaffected — it never comes from the bus.

Recovery and improvement

None. A relay that must publish strictly in order would need a single worker per group or shard, which turns one slow publish into a stall; the guard makes that unnecessary.

What to monitor · invariant tested

Out-of-order no-ops per consumer (expected to be non-zero with several relay workers). Invariant: derived views converge to the newest committed state regardless of delivery order.

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; an older or duplicate event is a no-op

Scenario 12 — The Outbox Relay crashes or the Event Bus is down

Pressure. The relay process crash-loops after a bad deploy, or the bus cluster is unavailable for ten minutes during peak. Root cause. The relay and bus sit after the commit; their availability is deliberately not a precondition of a write.

How the system responds

Writes keep committing and group balances stay correct, because the ledger, balance_projection and the outbox row are all in the write transaction. The Expense Service's fast-path cache delete after commit still runs, so readers of the group sheet see new writes as usual; only the event-driven second delete is delayed. Unpublished outbox rows accumulate — at the ~580 commits/s planning peak, about 350,000 rows in ten minutes. Dashboards and notifications fall behind and say so through their as_of_seq. When the relay returns, it resumes from the oldest unpublished row; anything published twice across the crash is absorbed as in Scenario 10.

Recovery and improvement

Supervise the relay for fast restart and run several workers so one crash does not stop publishing. Keep a partial index on unpublished rows so draining a backlog stays cheap, and drain at a bounded rate so the catch-up burst does not overload consumers.

What to monitor · invariant tested

Age of the oldest unpublished outbox row, alerting at about 30 s, and outbox backlog size. Invariant: the event pipeline can delay derived views but cannot lose or corrupt a committed write.

Scenario 13 — The Projection Consumer falls behind

Pressure. A burst across many groups, or a slow user_balance_summary store, makes the consumer process events more slowly than they are produced; consumer lag grows from milliseconds to minutes. Root cause. The dashboard is an asynchronous view; its freshness is a monitored budget (p99 ≤ 2 s from commit), not a guarantee.

How the system responds

Only the cross-group dashboard is stale, and each group on it carries its as_of_seq, so the client can label it (“updated 3 min ago”). A user who just wrote can see the write immediately in the group sheet (read with min_seq) and on their dashboard as an optimistic, pending-marked merge of their own committed effect — a display aid, never a stored balance. Group balance sheets, settlements and expense detail are unaffected.

Recovery and improvement

Scale consumers out up to the number of bus partitions; keying by group_id keeps each group's events on one partition, and the sequence guard makes even a reprocessed range safe. Fix the slow dependency, then let the backlog drain. If the consumer will not catch up within bus retention, use Scenario 17's rebuild instead.

What to monitor · invariant tested

Consumer lag per partition against the 2 s target, and the gap between groups.last_seq and the dashboard's last_applied_seq for sampled groups. Invariant: staleness is visible and bounded by monitoring, never presented as instantaneous.

Scenario 14 — A member sees a balance from before the latest write

Pressure. Cara records S1 and her phone shows the new balance, but Ben, who opened the group a second earlier, still sees Cara owing the old amount. Root cause. A Balance Cache sits in front of balance_projection to absorb group-sheet reads (up to ~2,315/s at peak, concentrated on hot groups). Any cache can return an entry from before the latest commit; a plain TTL cache could do so for the whole TTL with no way to tell.

How the system responds

The cache is versioned. Key balance:{group_id}:{currency} holds the sheet with its as_of_seq; fills are set-if-newer, so an older sheet can never replace a newer one. The Expense Service deletes the key right after commit (fast, best effort) and the Projection Consumer deletes it again when the event arrives (reliable, outbox-driven). The writer sends the group_seq from its write response as min_seq, so any entry older than that is bypassed in favor of the primary projection — read-your-writes on the device that wrote. One race remains: a reader that loaded the projection just before the commit can repopulate the key just after the fast-path delete; the event-driven delete removes it, typically within a second or two, and the 300 s safety TTL bounds the worst case if an invalidation is lost. Ben's stale view is labeled with its as_of_seq throughout.

Recovery and improvement

If the cache is unavailable, reads fall back to the primary projection — O(members) rows per read — roughly 1,160 sheets/s × 5 members ≈ 6,000 rows/s at peak — which the primary can absorb for a while. Flushing the cache is always safe. A persistent rise in stale serves means invalidations are being lost (consumer down, or a fast-path delete failing) — fix that, do not shorten the TTL.

What to monitor · invariant tested

Cache hit ratio, min_seq bypass rate, and sampled age of served entries (groups.last_seq − as_of_seq). Invariant: the writer sees their own write on the device that wrote (via min_seq); other viewers see a labeled, short-lived previous sheet.

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 satisfies min_seq; otherwise read balance_projection and set-if-newer; deletes on commit and on the event, 300 s safety TTL as a backstop

Scenario 15 — A derived view disagrees with the ledger

Pressure. The reconciliation job reports that a group's balance_projection rows differ from SUM(delta_minor) over its ledger — a bug in a new write path, or a manual SQL fix applied to one table but not the other. Separately, a Projection Consumer bug writes wrong values into user_balance_summary for one event type. Root cause. Every view other than the ledger is derived; a derived view can only go wrong through a code path or person writing it outside the designed mechanism.

How the system responds

Writes continue. The ledger stays authoritative: when a view disagrees with it, the view is wrong. Group projection (balance_projection): take the group's lock, recompute the sum per member and currency, replace the rows and set last_applied_seq to groups.last_seq; for a very large group, build into a shadow table up to a known sequence, apply newer entries under the lock and swap. Then delete the group's cache key. Dashboard projection (user_balance_summary): fix the consumer, then replay from the bus (7-day retention) or regenerate from balance_projection through the same sequence-guarded upsert — idempotent, so it can run while live events continue.

Recovery and improvement

Find the code path or manual change that caused the drift before closing the incident. Keep the rebuild path tested in production on a schedule, because it is both the recovery and the only trustworthy one.

What to monitor · invariant tested

Projection-versus-ledger mismatches and zero-sum violations per group and currency — both must be 0 — and dashboard-versus-projection mismatches on sampled users. Invariant: every derived view can be rebuilt from the ledger.

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; redelivered events during the rebuild are no-ops

Scenario 16 — The Notification Service or push provider is down

Pressure. The push provider returns errors for an hour, or the Notification Service itself is down, while members keep adding expenses. Root cause. Notifications are a downstream effect of committed writes; a slow or failing push provider must not be able to slow or fail a write.

How the system responds

Nothing on the write path changes: the service is an event consumer, never called from the transaction. Its events stay on the bus, and on recovery it resumes from its offset, deduplicating on (event_id, recipient_user_id) so a reprocessed event does not notify twice. Sends that fail are retried with backoff. Members who open the app see everything, because the activity history is read directly from audit_entries in the group's database and is never behind the ledger.

Recovery and improvement

Decide explicitly what a backlog means: an hour-old push is still useful, a day-old one is noise — skip sends older than a threshold and let activity history cover them, and collapse bursts in very busy groups into digests.

What to monitor · invariant tested

Notification consumer lag, send failure rate per provider, and notifications skipped as too old. Invariant: an expense is recorded and its balances are correct whether or not anyone was told about it.

Scenario 17 — A consumer is offline longer than the bus retains events

Pressure. A consumer is broken over a long weekend and its lag passes the bus's 7-day retention, or the bus runs short of disk under a long backlog. Root cause. The bus is a bounded transport, not a permanent record; the outbox rows behind it are also purged 7 days after publishing.

How the system responds

Events falling off the bus is not data loss: the ledger and balance_projection hold every fact permanently. A full bus rejects publishes, the relay backs off, and outbox rows wait in the database — writes are unaffected; watch the database's storage while it lasts. To recover a consumer that is past retention, rebuild its view instead of replaying: regenerate user_balance_summary from balance_projection through the sequence-guarded upsert, then resume the consumer from the latest offset. Notifications for the gap are skipped; activity history covers them.

Recovery and improvement

Alert on consumer lag long before retention (hours, not days), and size bus retention against the longest consumer outage the team is willing to repair by replay rather than rebuild.

What to monitor · invariant tested

Consumer lag as a fraction of retention, bus disk utilization, outbox backlog. Invariant: projections are rebuildable from the ledger without the bus.

Scenarios 18–22

Provider Settlements

A provider settlement is committed as pending with no ledger effect; the Payment Service calls the provider outside any transaction with the settlement_id as its idempotency key; a verified, deduplicated webhook moves it to confirmed (writing ledger entries, projection updates and an outbox row in one transaction) or to failed (no entries); a refund or chargeback moves confirmed → reversed. The provider is authoritative for whether money moved (Complete Design, Chapter 16). The examples use a provider settlement set-91: Cara pays Asha ₹200 after S1, when Cara's net is −40,000.

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, chargeback or dispute. Manual settlements are created confirmed

Scenario 18 — The confirmation webhook arrives twice

Pressure. The provider delivers the success webhook for set-91; the handler commits, but its 200 response is lost, so the provider redelivers. Some providers also send two distinct success events for one payment. Root cause. Providers deliver webhooks at least once, like every other pipeline here.

How the system responds

After the signature and timestamp check, the handler inserts into provider_events with a unique (provider, provider_event_id). A redelivery violates the constraint, rolls back and still answers 200 so the provider stops retrying. A second, distinct success event passes that check but hits the state guard UPDATE settlements SET status = 'confirmed' … WHERE status = 'pending', matches zero rows and writes nothing. Either way Cara's net moves from −40,000 to −20,000 once.

Recovery and improvement

None. Acknowledge quickly (record, then 200) so provider retries do not escalate.

What to monitor · invariant tested

Duplicate webhook rate per provider and guarded no-op transitions. Invariant: a duplicated provider event has no duplicated effect.

Scenario 19 — The provider call times out, and the payment then fails

Pressure. The Payment Service's call to create the payment times out; later the provider reports the bank transfer as failed (insufficient funds). Root cause. The outcome of a remote call is unknown on timeout, and bank-backed payments can stay pending for minutes before failing.

How the system responds

The call is retried with the same provider idempotency key (settlement_id), so the provider returns the original payment instead of creating a second charge. While pending, the settlement has no ledger rows and no group_seq: it is shown separately as “₹200 pending” and never reduces anyone's balance. The verified failed webhook runs the same guarded transition to failed, writing nothing. The payer is offered a retry, which is a new settlement with a new key, not a resurrection of the failed one.

Recovery and improvement

None. A design that reduced the balance on “initiated” would now need a compensating reversal and would have shown Asha money that never arrived — the reason pending never counts.

What to monitor · invariant tested

Pending → failed rate per provider and payment method; an assertion that no ledger row references a settlement whose status is not confirmed or reversed. Invariant: balances move only on a provider-confirmed payment.

TimeEventSettlementLedger rowsCara's net
t0POST /settlements, method provider, ₹200pendingnone−40,000
t0 + 1 sProvider call times out; retried with key set-91pendingnone−40,000
t0 + 90 sVerified webhook: payment failedfailednone−40,000
A pending-then-failed provider settlement never touches the balance

Scenario 20 — The payment succeeds but the webhook never arrives

Pressure. The provider moves the money, but its webhook is lost — the endpoint was down during the provider's retry window, or the provider gave up. Root cause. Push notifications from a third party cannot be the only way to learn an outcome.

How the system responds

A reconciliation job asks the provider about every settlement still pending after 15 minutes. When the provider reports success, the job runs the same confirm transaction as the webhook — state guard, group_seq, ledger entries, balance_projection, outbox row — so the two paths cannot both apply. If the original webhook finally arrives later, it is a new provider event that hits the guard and changes nothing. A daily comparison of the provider's report with confirmed settlements catches the opposite gap.

Recovery and improvement

Nothing manual for the common case. If reconciliation itself is down, pending settlements simply wait; nothing is wrongly applied.

What to monitor · invariant tested

Pending settlements by age (alert on anything past the reconciliation window that is still pending), and webhook endpoint availability. Invariant: every provider outcome is eventually reflected, once.

Scenario 21 — A late, contradictory or forged webhook arrives

Pressure. A failed webhook arrives after set-91 was confirmed; a success webhook carries a different amount or currency from the settlement; someone posts a fabricated success to the webhook URL, or replays an old genuine one. Root cause. The webhook endpoint is public input; the provider may also send events out of order.

How the system responds

Webhooks are untrusted until verified: a bad signature or a timestamp outside the allowed window is rejected and changes nothing; a replayed genuine event is caught by provider_events. A verified event that does not fit the current state — failed after confirmed, or an amount or currency that differs (the guard includes amount_minor and currency) — matches no row and is flagged for reconciliation instead of applied. Reconciliation asks the provider; its record of money movement wins, and any correction is written as new entries (for a reversal, Scenario 22).

Recovery and improvement

Flagged events go to a review queue with the provider's answer attached. A spike in signature failures is a security signal, not an outage.

What to monitor · invariant tested

Signature failures, flagged state mismatches, and time-to-resolution of flagged events. Invariant: no unverified or state-inconsistent event moves a balance.

Scenario 22 — A confirmed payment is refunded or charged back

Pressure. Weeks after set-91 was confirmed, the payer's bank charges the payment back. Separately, a member disputes a manual settlement (“I never received that ₹200 in cash”). Root cause. Real money movements can be undone after the fact; history must show both the payment and its reversal.

How the system responds

The verified chargeback event moves confirmed → reversed and, under a new group_seq, writes settlement_reversal entries that exactly negate the settlement's entries — Cara's net returns from −20,000 to −40,000 — plus the projection update and outbox row in the same transaction. The original settlement row and entries are untouched, so the activity history shows the payment and its reversal as separate facts. A disputed manual settlement goes through the same reversal path, initiated by the members; manual settlements are assertions, never presented as verified payments.

Recovery and improvement

How the payer now repays is a new settlement, recorded going forward. Chargeback-driven reversals are rare enough to notify both parties explicitly.

What to monitor · invariant tested

Reversals by source (provider chargeback, refund, member dispute). Invariant: corrections append; nothing is rewritten.

Scenarios 23–24

Multi-Currency

Every expense and settlement keeps its own currency, currency is part of every balance key, simplification runs per currency, FX rates are used only for labeled display, and the only cross-currency write is an explicit, member-initiated conversion record that is zero-sum in each currency (Complete Design, Chapter 16). The example: a $20 souvenir on the trip stays a USD position.

Scenario 23 — A bug or a request tries to net two currencies

Pressure. A new feature sums delta_minor across a group without grouping by currency, so 2,000 US cents are added to INR paise. Or a member tries to settle a USD debt with a rupee settlement. Root cause. Integer minor units remove floating-point error but say nothing about the unit: 2,000 cents and 2,000 paise are not the same value.

How the system responds

balance_projection and user_balance_summary are keyed by (group, currency, user), so a correct read path cannot mix currencies, and the per-currency zero-sum check flags any write path that does. A settlement in a currency in which the payer owes the recipient nothing is rejected with 422 CURRENCY_MISMATCH. The balance sheet shows one block per currency (INR and USD), and suggested repayments are computed per currency.

Recovery and improvement

If a mixing bug reached stored data, the affected entries are found by the zero-sum check and corrected with reversals and properly denominated replacements. Make currency a required field in every API and library signature, with no default to “the group's currency”.

What to monitor · invariant tested

Zero-sum violations per currency (must be 0) and CURRENCY_MISMATCH rate. Invariant: no netting across currencies without an explicit conversion record.

Scenario 24 — Exchange rates move, or the rate feed fails

Pressure. The rupee weakens 3% against the dollar; members ask why the “total in INR” changed although nobody added anything. Or the FX rate provider is down. Root cause. A converted total is a function of a rate snapshot, and rates change daily.

How the system responds

Stored balances do not change: the $20 position is still 2,000 cents. Only the display-only “everything in INR” view changes, and it is labeled as an estimate with the rate's time and source from the FX Rate Snapshot. When the rate feed fails, the converted view shows the last snapshot with its age, or is hidden; balances, settlement and simplification are unaffected because none of them uses a rate. If members agreed to settle the USD debt in rupees, that conversion record carries its own recorded rate and is part of the immutable history; later market moves do not touch it.

Recovery and improvement

A conversion recorded with a wrong rate (an integration bug, not a market move) is corrected like any other record: reverse it and record a new conversion at the corrected rate.

What to monitor · invariant tested

Age of the newest rate snapshot per currency pair. Invariant: FX is display-only; stored balances never float with the market.

Scenarios 25–27

Authorization

The API Gateway authenticates (TLS, token validation, rate limits) but does not authorize. Whether a user may read or change a group's data is checked by the service that owns that data, on every request (Complete Design, Chapter 18). These scenarios probe that boundary.

Scenario 25 — An invitation token is replayed

Pressure. An old invitation link — already used, expired or revoked — is reused from a forwarded message thread, or two people race to accept the same single-use link. Root cause. Possession of a token is not entitlement; links leak.

How the system responds

Tokens are single-use, expire, are scoped to one group and, for email invites, one address. Acceptance is a guarded transition, UPDATE invitations SET accepted_at = now(), accepted_by = :user WHERE invitation_id = :id AND accepted_at IS NULL AND revoked_at IS NULL AND expires_at > now(), in the same transaction that inserts the membership. A used, expired or revoked token matches no row and gets an explicit “invitation no longer valid”; of two concurrent accepts, exactly one matches. Existing memberships are unaffected.

Recovery and improvement

If a leaked token was used before detection, the admin removes the unintended member (Scenario 09's path) and issues a fresh invitation.

What to monitor · invariant tested

Rejections by reason (used, expired, revoked, wrong address); repeated attempts on one token suggest leakage. Invariant: membership is granted only by a token whose server-side state allows it at the moment of use.

Scenario 26 — A user requests another group's expense by id

Pressure. A user who is not in Weekend Trip calls GET /v1/groups/grp-weekend-trip/expenses/exp-1001, or iterates guessed ids, or requests a receipt URL for an expense they cannot see. Root cause. A valid access token proves who the caller is, not what they may touch; ids are often guessable.

How the system responds

The Expense Service checks that the caller is a current member of the group (or a former member, for read access to the history they were part of) on every object access, and that the expense belongs to the group in the path. Otherwise it returns 403 FORBIDDEN_NOT_A_MEMBER — the same response whether or not the target exists, so probing reveals nothing. Receipts are served only through short-lived signed URLs issued after the same check, never as public links.

Recovery and improvement

Accounts that probe many groups are rate-limited at the gateway and flagged for the abuse pipeline. Non-sequential ids are defense in depth, never a substitute for the check.

What to monitor · invariant tested

403 rate per caller and the number of distinct groups a caller is denied; enumeration patterns. Invariant: object-level authorization on every request.

Scenario 27 — A member edits an expense they are not allowed to change

Pressure. A member who joined after E1 tries to change its amount; the product allows only the expense's creator and the group's admins to edit or delete. Root cause. Group membership alone does not imply permission to change someone else's record; the UI hiding an edit button is not enforcement.

How the system responds

The edit policy is checked against memberships before the edit transaction starts. The request gets 403 and never reaches the If-Match compare-and-set, so it cannot cause a version conflict or a new version. Smaller, trusted groups can relax the policy as a product setting; the check stays server-side either way.

Recovery and improvement

If someone should have had edit rights, that is a role change through group administration, separate from the expense path. Edits by compromised accounts remain visible in the append-only audit trail and are corrected by reversal.

What to monitor · invariant tested

403 rate on edit endpoints, distinct from 409 conflicts. Invariant: only authorized members can change an expense, and every change is attributable.

Scenarios 28–31

Scale and Load

The capacity plan assumes ~580 writes/s and ~2,315 balance reads/s at peak, with history growing about 6 ledger rows per group per day (Complete Design, Chapter 05). Averages are not the problem; skew is. These four scenarios test the hot group, the system-wide spike, the user with many groups and the very large group (Complete Design, Chapter 17).

Scenario 28 — A hot group: long history, read bursts and write bursts

Pressure. A ten-year household group has 50,000 ledger rows; a 200-member festival group is adding expenses every few seconds while hundreds of members refresh its balance sheet. Root cause. Three different costs. Reads that aggregate history grow without bound — the Stage 0 design would sum 50,000 rows per read. Reads concentrate on a few keys. And every money-moving write in a group serializes on the group row, so one group has a write ceiling.

How the system responds

History no longer matters for reads: the sheet is one balance_projection row per member, activity is cursor-paginated on (created_at, audit_id), and the versioned cache absorbs read bursts (each write costs one fast-path delete plus one event-driven delete). Writes are bounded by the group lock: with transactions of a few milliseconds, one group tops out around 100–200 short writes/s, and a 200-member group — which writes up to 200 ledger and projection rows per expense — nearer a few dozen. That is far above what real groups do. Above the limit, the gateway's per-group rate limit returns 429 with Retry-After, and clients back off; retries are safe because of idempotency keys.

Recovery and improvement

Keep the transaction short (no network calls inside it), insert ledger and projection rows in batches, send notification digests for very large groups, and move a hot group to its own shard via a group-directory override so it cannot affect its neighbors (this isolates the group; it does not raise its own ceiling). The one thing not to do is drop the group lock for hot groups: the gap-free group_seq is what makes projections, freshness markers and replay correct.

What to monitor · invariant tested

Per-group write rate and lock wait time, per-group 429s, per-group read latency outliers. Invariant: a gap-free, serialized per-group order, at a stated cost.

Scenario 29 — A sudden system-wide traffic spike

Pressure. A press mention and a wave of invitations push traffic to several times the planned peak within minutes — sign-ups, group creation, expense writes and balance reads together. Root cause. The planned peak is already 10× the daily average; a spike beyond it saturates whichever layer has least headroom, usually database connections on the busiest shards.

How the system responds

The gateway's per-user and per-group rate limits turn excess into explicit, retryable 429 responses rather than timeouts; clients back off with jitter, and their retries cannot duplicate anything. The stateless Expense Service scales out, but database connections are pooled and capped so more servers do not mean more load on the primary. Read pressure is shed to the Balance Cache and to user_balance_summary, which keep the group sheet and dashboard off the hot path. Asynchronous views fall further behind and show it through as_of_seq.

Recovery and improvement

Prioritize when shedding: money-moving writes and group balance reads first, dashboards next, notifications last. After the spike, the async pipeline drains on its own. Load-test above the planned peak, and keep headroom per shard rather than for the fleet average.

What to monitor · invariant tested

Request rate versus rate-limit thresholds, 429 share, connection-pool saturation per shard, relay and consumer lag. Invariant: under overload the system refuses explicitly; it never half-applies or duplicates a write.

Scenario 30 — A user with many groups opens the dashboard

Pressure. A user who belongs to 60 groups — trips, households, clubs — spread across several shards opens “total balance across all my groups”. Root cause. The dashboard is a cross-group view in a system partitioned by group. Reading each group's balance_projection would be 60 lookups across shards per dashboard load; with ~1,160 dashboard reads/s at peak, that fan-out is the cost the Stage 3 design removes.

How the system responds

The Projection Consumer maintains user_balance_summary, keyed by user, so a dashboard is one single-key read returning one row per group and currency — the same cost for 2 groups or 60, wherever the groups live. The trade is freshness: each row is eventually consistent (target p99 ≤ 2 s) and carries its group's as_of_seq. Totals are shown per currency, and a converted total, if any, is a labeled estimate.

Recovery and improvement

For pathological cases (bots or test accounts in thousands of groups), paginate the dashboard and cap per-user membership through abuse controls. If the summary is ever suspected wrong, it is regenerated from balance_projection (Scenario 15).

What to monitor · invariant tested

Dashboard latency by group-count bucket, and consumer lag. Invariant: the dashboard is a derived view, labeled with its freshness, never a second source of balances.

Scenario 31 — Debt simplification on a very large group

Pressure. A 150-member club asks for suggested repayments. Root cause. Finding the minimum number of transfers that settles every member is NP-hard; an exact solver's running time can explode with member count, and the result must still be correct.

How the system responds

Simplification is a stateless computation over one balance snapshot, per currency: greedily match the largest creditor with the largest debtor until every net is zero — O(n log n), at most (creditors + debtors − 1) transfers. It is not guaranteed minimal: for nets +400, +300, −300, −200, −200 greedy produces 4 transfers where 3 suffice. It always preserves every member's net position (not who originally paid whom), and the result is returned with the snapshot's as_of_seq as a suggestion; nothing moves until members record settlements.

Recovery and improvement

If the transfer count matters for some product tier, add a time-boxed exact search for small groups and keep greedy as the fallback — never relax the net-preservation check. A cheap post-check (applying the suggested transfers zeroes every net) runs on every result.

What to monitor · invariant tested

Simplify latency by member count and post-check failures (must be 0). Invariant: simplification preserves net positions and is a suggestion, not an obligation.

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
Raw pairwise debts after E2 collapse to two suggested transfers — Cara → Asha ₹500 and Cara → Ben ₹100 — preserving every member's net
Scenarios 32–35

Infrastructure Failure and Disaster Recovery

Each shard has a synchronous in-region standby and an asynchronous cross-region replica, with point-in-time backups; the Event Bus and caches are not backed up because they are re-derived from the outbox and the ledger (Complete Design, Chapter 17). These scenarios test those choices, from a minor dependency outage to the loss of a region.

Scenario 32 — Receipt storage is unavailable

Pressure. A member adds an expense with a receipt photo while object storage is throttling or down. Root cause. A receipt is evidence for an expense, not part of its arithmetic; coupling the two would make an object-store outage block money-moving writes.

How the system responds

Creating the expense and attaching its receipt are separate operations. The expense commits normally; the upload — to object storage, through a short-lived signed URL issued after the membership check — fails with a retryable error. The client retries the attachment later against the existing expense, with its own idempotency key so a retry cannot attach the same receipt twice.

Recovery and improvement

Nothing to repair in the ledger. The client keeps the photo queued and retries in the background.

What to monitor · invariant tested

Upload error rate and storage health, tracked separately from write success. Invariant: financial correctness never depends on a receipt.

Scenario 33 — The primary database fails during a write

Pressure. A shard's primary dies while transactions are in flight. Root cause. A single-node failure; the question is what was acknowledged.

How the system responds

The synchronous in-region standby is promoted, typically within minutes. A transaction that committed was replicated before its COMMIT returned, so no acknowledged write is lost on a single failure; an uncommitted one never happened. Clients that got an error or timeout retry with the same key: if the commit had made it, the idempotency record replicated with it and the stored 201 is replayed; if not, the retry runs fresh. The relay reconnects and resumes from the oldest unpublished outbox row; republished events are no-ops. During the failover the shard rejects writes with retryable errors; other shards are unaffected.

Recovery and improvement

Rehearse failover in drills, and keep connection retry and DNS or proxy switch-over fast. If the standby was lagging or unavailable at the moment of failure (synchronous replication degraded to asynchronous), treat the event as Scenario 35 for that shard.

What to monitor · invariant tested

Replication lag and sync-standby health, failover duration, retry spike during failover. Invariant: an acknowledged write survives a single-node failure.

Scenario 34 — Corrupted data or a destructive mistake is discovered

Pressure. The zero-sum check fails for one group's INR ledger; or a bad migration deleted ledger rows on one shard; or an operator ran an UPDATE against ledger_events during an investigation. Root cause. Replication copies mistakes faithfully — the standby and replicas have the same damage. Only point-in-time history can tell the right state from the wrong one.

How the system responds

Writes elsewhere continue; the affected groups can be put into a read-only “under review” state so members are not shown balances computed from damaged input. Investigation comes before repair. To recover destroyed data, restore a point-in-time backup into a side instance to just before the incident and diff it against production for the affected groups. Missing ledger rows are restored from that copy with an audit record of the repair; wrong values are corrected with new reversal and replacement entries, never another in-place UPDATE. Then rebuild balance_projection, regenerate user_balance_summary and flush the cache for those groups, and rerun the zero-sum and drift checks before lifting the review state.

Recovery and improvement

Remove direct write access to ledger tables from operators (support corrections use the reversal path, with operator identity recorded); run migrations against a restored copy first; test restores regularly — an untested backup is a hope, not a plan.

What to monitor · invariant tested

Zero-sum violations, projection drift and integrity checks (all 0), plus backup and restore-drill success. Invariant: the ledger stays authoritative and every repair is itself auditable.

Scenario 35 — A whole region is lost

Pressure. The primary region — primaries, standbys, relay, bus, cache — becomes unavailable. Root cause. The cross-region replica is asynchronous, so the last seconds of acknowledged writes may not have reached it: cross-region RPO is seconds, not zero. At the 580 writes/s planning peak, 5 seconds of replication lag is roughly 2,900 acknowledged writes at risk.

How the system responds

After confirming the outage from outside the region, the team promotes each shard's cross-region replica and switches traffic. Writes the replica has are complete — rows, idempotency records and outbox rows replicated together, transaction by transaction — so the new region is consistent, just possibly behind. Recovery of the gap relies on two mechanisms: clients retry their queued or unacknowledged writes with the same idempotency keys (a write lost with its record executes again, correctly, once), and payment reconciliation re-checks recent provider confirmations, re-applying any confirmation lost in the gap through the guarded transition. The relay in the new region publishes the outbox rows it finds; user_balance_summary is regenerated from balance_projection where needed; the cache starts empty. Writes that were acknowledged, lost, and never retried by their client are a real loss and are communicated as such.

Recovery and improvement

Before reopening writes, run zero-sum and drift checks on the groups with writes in the final minutes. State RPO and RTO honestly, rehearse regional failover, and keep cross-region lag monitored as a first-class signal.

What to monitor · invariant tested

Cross-region replication lag (it is the RPO), failover drill results, post-failover retry and reconciliation volume. Invariant: after failover every group's ledger is internally consistent and zero-sum, even if it is missing its last seconds.

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: Ledger DB shards with a synchronous standby and an asynchronous cross-region replica; the event bus, projections and cache are re-derived from the outbox and the ledger rather than backed up
Scale walkthroughs

Scale Walkthroughs

The scenarios above describe what breaks; this chapter puts numbers on how the design behaves as load grows. Every figure follows the illustrative assumptions of Complete Design, Chapter 05 — 10M registered users, 1M daily active, ~4M groups, 5M expense writes and 20M balance reads a day, peak = 10× average — and is a teaching estimate, not a benchmark.

Growth from 100K to 10M users

Registered usersDaily activeExpense writes/dayWrites/s (avg → peak)Balance reads/s at peak
100,00010,00050,000≈ 0.6 → 6≈ 23
1,000,000100,000500,000≈ 6 → 58≈ 231
10,000,0001,000,0005,000,000≈ 58 → 580≈ 2,315
Linear scaling of the Chapter 05 assumptions. One well-provisioned primary handles even the last row's write rate; what grows without bound is history.

Write amplification per expense

A five-participant expense is roughly 22 row writes in one transaction: the expense head, version and payer rows, 5 split rows, 5 ledger rows, 5 balance_projection upserts, the groups.last_seq update, the outbox row, the audit entry and the idempotency claim plus its stored response. At ~580 writes/s that is ~12,800 row writes/s at peak, all in short transactions with no network calls inside. An edit writes reversal plus replacement entries, so about twice the ledger rows of a create.

Reads and why Stage 2 exists

Peak reads split roughly into ~1,160 group sheets/s and ~1,160 dashboards/s. Summing the ledger on every read would mean ~3,500 group aggregations/s over ~2,300 rows per average group after one year — about 8M rows/s, doubling the next year — against ~17,500 rows/s for reading stored per-member nets. That gap is why balance_projection is maintained in the write transaction, and why a cache outage (Scenario 14) is survivable: the fallback is O(members), not O(history).

Hot-group skew and cache effectiveness

A group sheet changes a few times an hour but is read constantly while a trip is under way. A hot group read 50 times a second and written once a minute gets a cache hit rate near 99%, with misses at O(members) cost. Invalidation traffic is about two deletes per write (fast path plus event-driven) — ~1,160 deletes/s at peak — which a cache cluster absorbs easily. The per-group write ceiling (~100–200 short writes/s) is the limit that does not move with hardware (Scenario 28).

Partitioning by group

Throughput does not force partitioning; storage and blast radius do. At ~1.8 TB/year of ledger and ~3 TB/year across all tables before indexes, an illustrative 16 shards by group_id hold ~250,000 groups and under 0.2 TB of new rows per year each, with backups, restores and migrations that finish in reasonable time. Every money-moving transaction stays on one shard. Per-user data — the user → groups index and user_balance_summary — lives in a separate store fed by events, which is why the dashboard is asynchronous (Scenario 30).

Rebuild and backlog arithmetic

OperationIllustrative sizeIllustrative time
Rebuild one average group's balance_projection~2,300 ledger rows after a yearMilliseconds, under the group lock
Rebuild a 10-year household group~50,000 rowsWell under a second with an index on (group_id, currency, user_id); shadow build for anything larger
Regenerate user_balance_summary from balance_projection~20M rows (4M groups × 5 members)~17 min for one worker at 20,000 upserts/s; about a minute across 16 shards in parallel
Drain a 10-minute relay outage~350,000 outbox rows at peakA few minutes at a bounded publish rate of several thousand rows/s
Assumptions for this exercise, not measurements. The point is the shape: per-group repairs are cheap, fleet-wide ones parallelize by shard.

Notification fan-out

With up to 4 other members per expense, notifications reach ≤ 20M/day and ~2,315/s at peak — read-rate scale, which is why they are an event consumer with their own retries, preferences and digests, and never part of the write transaction (Scenario 16).

Indexes that the scenarios rely on

ledger_events on (group_id, currency, user_id) for reconciliation sums and on (source_type, source_id, source_version) for reversals; a partial index on outbox where published_at IS NULL for the relay; memberships keyed (group_id, user_id) for the per-request authorization check; audit_entries on (group_id, created_at, audit_id) for cursor-paginated activity; the unique key on idempotency_records plus an expires_at index for the 7-day purge.

RPO and RTO

In-region: RPO ≈ 0 for a single-node failure (synchronous standby) and an RTO of minutes. Cross-region: RPO of seconds (asynchronous replica) and an RTO from tens of minutes to a few hours, dominated by verification and traffic switch-over. At peak, each second of cross-region lag is ~580 acknowledged writes that depend on client retries to be recovered (Scenario 35). These are illustrative targets of the kind a design document must state explicitly, not an SLA.

Key takeaways
  1. 01Writes depend only on the group's database shard: relay, bus, cache, consumer, notification and receipt-store outages delay derived views or side features but never lose or corrupt a balance.
  2. 02Retries at every layer — phones, schedulers, the outbox relay, provider webhooks — are made harmless by idempotency: a scoped key with a request fingerprint on writes, sequence-guarded absolute upserts and unique constraints downstream. Delivery is at-least-once, not exactly-once.
  3. 03The group balance sheet is updated in the write transaction and never lags its ledger on the primary; only the dashboard, notifications and other viewers' cached sheets lag, always labeled with as_of_seq.
  4. 04Edits use PUT with If-Match and fail with 409 VERSION_CONFLICT instead of overwriting; edits, deletes, refunds and chargebacks append reversals and never erase history.
  5. 05A provider settlement moves balances only on a verified, deduplicated, state-guarded confirmation; pending never counts, and reconciliation catches lost or contradictory webhooks.
  6. 06Every derived view is rebuildable from the ledger, and zero-sum and drift checks must stay at 0.
  7. 07Honest limits: one group's write rate is bounded by its group lock (~100–200 short writes/s), greedy simplification is not minimal, and cross-region failover can lose the last seconds of acknowledged writes (RPO > 0).