Skip to content
SeeItFlow
System Design · 20 components · ~32 min read

Splitwise Architecture Deep Dive: Ledgers, Balances and Debt Simplification

Splitwise architecture deep dive: integer-minor-unit money, the append-only ledger, split and debt-simplification algorithms, atomic idempotent writes, the outbox and balance projections, the versioned cache, settlement and recovery. Components follow the order the design introduces them, using one running example group.

Mangesh MandlikLast updated: How lessons are made
Component 01

Domain Model and Boundaries

Stage 0 is one Expense Service in front of one relational database (Complete Design, Chapter 06). Before any table exists, the design has to decide what owns what (Complete Design, Chapter 07). This component names the two aggregate boundaries, group and expense, because almost every bug class later on comes from a write that crossed one of them.

Group as the ownership boundary

A group owns its memberships and every expense, settlement, ledger row and balance inside it. Nothing computes a balance, a debt or a simplification across two groups. A user in five groups has five independent sets of balances. The cross-group dashboard (Component 14) displays one figure per group and never merges obligations. The group also carries last_seq, the counter that orders its money-moving commits (Component 11). Every query and authorization check is scoped by its group_id, and from Stage 5 so is partitioning (Component 18). A group has a default currency for the UI, but each expense carries its own currency (Component 16).

Swipe to pan
GroupWeekend Trip · INRMembershipAsha · creatorMembershipBen · memberMembershipCara · memberExpensepayers + beneficiaries + split
A group owns memberships and expenses. A user_id only means something inside a group when there is an active membership row

Expense identity; payer and beneficiary are roles

An expense has its own identity: a head row with version and status (active | deleted), plus immutable content for each version (expense_versions, expense_payers, expense_splits). Creating or correcting an expense writes all of these, together with its ledger rows, in one transaction. Payer and beneficiary are roles on an (expense, version, user) triple, not kinds of user. In E1, Asha is both the payer and one of three beneficiaries, which is the normal case. A single paid_by column cannot represent several payers, or a payer who is not a beneficiary. Two join tables keyed by (expense_id, version, user_id) can represent every combination (Component 07).

Aggregate boundary

A boundary inside which an invariant is enforced atomically. The expense version is the boundary for "payers sum to the total" and "shares sum to the total". The group is the boundary for ordering (group_seq), membership, and zero-sum per currency. Balances are derived from the ledger (Component 08) or from a projection kept in the same transaction (Component 13), never edited directly.

Key takeaways
  1. 01Group is the ownership, ordering and partition boundary. The expense version is the atomic boundary for one financial event. Nothing is netted across groups
  2. 02Payer and beneficiary are roles on (expense, version, user), and the two routinely overlap
  3. 03Membership is a stored fact in memberships, never inferred from a user_id appearing in an expense
  4. 04Each expense carries its own currency; the group default currency is only a UI default
Component 02

Money and Precision

The first data-model decision is the type of every amount (Complete Design, Chapter 07). Stage 0 already computes shares on the server in integer minor units, and every later mechanism depends on that. Zero-sum checks, reversals that negate exactly, and projections that equal ledger sums all require exact arithmetic.

Minor units are per-currency data

INR's minor unit is the paisa, with 2 decimals, so ₹900.00 is stored as 90000. The exponent varies by currency: JPY has 0 decimals and KWD has 3. Converting a typed decimal string to minor units therefore looks up the exponent in a currency table, and it happens exactly once, at the API edge. Inside the system, amounts travel as *_minor integers (total_minor, paid_minor, share_minor, net_minor). Adding a second currency (Component 16) needs no change to any arithmetic.

pseudocodeParsing happens once, at the edge, from the string itself. Parsing into a float first and then multiplying by 100 already loses the value
function toMinorUnits(decimalString, currency):          // only at the edge, e.g. a typed "125.50"
    exp = CURRENCY_EXPONENT[currency]                     // INR 2, USD 2, JPY 0, KWD 3
    (whole, frac) = splitOnDecimalPoint(decimalString)
    if len(frac) > exp:
        return Invalid("AMOUNT_TOO_PRECISE")              // "10.005" INR is rejected, never rounded silently
    return int(whole) * 10^exp + int(padRight(frac, exp, "0"))   // string -> integer; no float on the way

function validateAmount(amountMinor, currency):
    if not isInteger(amountMinor):                return Invalid("AMOUNT_NOT_INTEGER")
    if amountMinor <= 0:                          return Invalid("AMOUNT_NOT_POSITIVE")
    if amountMinor > MAX_AMOUNT_MINOR[currency]:  return Invalid("AMOUNT_EXCEEDS_BOUND")
    return Valid(amountMinor)

Overflow bounds

Amounts, deltas and nets are signed 64-bit integers (BIGINT), whose limit is about 9.2×10^18, far beyond any shared expense. A per-currency sanity bound on each input (MAX_AMOUNT_MINOR) catches malformed or abusive values. The intermediate to watch is total × weight in the largest-remainder routine (Component 05); with basis points it stays below 2^63 for totals under about 9×10^14 minor units, so the input bound plus a weight cap keeps it in range. PostgreSQL returns SUM over BIGINT as NUMERIC, so aggregations cannot overflow silently.

Key takeaways
  1. 01Every amount is an integer count of minor units, from the API edge to the ledger
  2. 02The minor-unit exponent comes from a currency table (INR 2, JPY 0, KWD 3) and is never hardcoded as ×100
  3. 03BIGINT leaves enormous headroom; per-currency input bounds keep split-math intermediates in range
  4. 04A float in the money path is a correctness defect, not a style choice
Component 03

Ledger Representation

The central data-model decision is that balances are not stored facts. They are sums over an append-only journal, ledger_events (Complete Design, Chapter 07). Stage 0 already writes ledger rows, and Stage 1 forbids ever updating them (Complete Design, Chapter 12). This component covers the row format, the zero-sum property of each write, and how a reversal is represented.

Swipe to pan
ledger_events · exp-1001 v1 · group_seq 1 · INRuser-ashapaid 90,000 − share 30,000+60,000user-benshare 30,000−30,000user-carashare 30,000−30,000Σ delta_minor = 0 per group and currencyAppend-only: a correction adds reversal rows plus new rows; it never edits these
E1 (exp-1001, version 1, group_seq 1): user-asha +60,000, user-ben −30,000, user-cara −30,000 paise. Each participant gets one signed delta, and the deltas sum to zero

One committed write, deltas that sum to zero

Each money-moving commit writes one row per participant whose effect is non-zero, with delta_minor = paid_minor − share_minor. All rows of the commit are tagged with its group_seq. The rows of one commit sum to zero by themselves; for E1, 60,000 − 30,000 − 30,000 = 0. That follows because the payer sum and the split sum both equal the total (Component 07). This per-commit property is stronger than the group-wide check (Component 08), and it lets one expense be reversed without touching any other. The service asserts sum(deltas) == 0 before COMMIT, so a bug fails the write instead of corrupting the group.

Source references

Every row carries source_type (expense, expense_reversal, settlement, settlement_reversal), plus source_id and source_version. Any balance can therefore be explained back to the exact record and version that produced it. A reversal is a new set of rows under a new group_seq, carrying the negated deltas of the version it cancels. It never updates or deletes the original rows.

Deleting E1, traced

group_sequser_iddelta_minorsource_typesource_id / version
1user-asha+60,000expenseexp-1001 / 1
1user-ben−30,000expenseexp-1001 / 1
1user-cara−30,000expenseexp-1001 / 1
4user-asha−60,000expense_reversalexp-1001 / 1
4user-ben+30,000expense_reversalexp-1001 / 1
4user-cara+30,000expense_reversalexp-1001 / 1
Deleting E1 after E2 and S1 (group_seq 2 and 3) appends commit 4. The original rows stay untouched.

For each member, the original row and its reversal sum to zero. E1 disappears from every balance, but the ledger now holds six rows: the charge and its cancellation, both permanently visible. An edit is the same reversal plus the new version's rows, in the same commit (Component 12).

Key takeaways
  1. 01Every financial fact is an INSERT. UPDATE and DELETE are not granted on ledger_events
  2. 02The rows of one committed write sum to zero, and the service asserts this before COMMIT
  3. 03source_type, source_id and source_version tie every row to the record and version that produced it
  4. 04A delete or correction appends negated rows under a new group_seq, and the history stays readable
Component 04

Transactional Relational Schema

The ledger needs a schema around it (Complete Design, Chapter 07). Complete Design lists the DDL. This component maps each invariant to the constraint or write-path check that enforces it, separates what the database can enforce from what it cannot, and shows which tables each later stage adds.

Swipe to pan
usersuser_idgroupslast_seqmembershipsgroup_id, user_idexpensesversion · statusexpense_versionsimmutableexpense_payerspaid_minorexpense_splitsshare_minorledger_eventsdelta_minor · group_seqsettlementspending → confirmed …audit_entriesappend-onlyidempotency_recordsStage 1balance_projectionStage 2outboxStage 3user_balance_summaryStage 3 · per userprovider_eventsStage 4slate = source of truth · green arrows = ledger effects · purple = added by later stages (derived or supporting)
Tables: groups, memberships, expenses with expense_versions, expense_payers and expense_splits, ledger_events and settlements. idempotency_records, balance_projection, outbox, user_balance_summary and provider_events arrive in later stages
TableKeyConstraint or enforcementStage
groupsgroup_idlast_seq is incremented once per money-moving commit; that row lock serializes the group’s writes0 / 1
memberships(group_id, user_id)role; left_at IS NULL means a current member; rows are never deleted0
expensesexpense_idversion is the If-Match compare-and-set target; status is active or deleted0 / 1
expense_versions(expense_id, version)Immutable; total_minor > 0, currency, split_type1
expense_payers / expense_splits(expense_id, version, user_id)paid_minor > 0, share_minor >= 0; the service checks that both sums equal the total inside the transaction0
ledger_eventsevent_id; index (group_id, currency, user_id)INSERT-only grant; the rows of one group_seq sum to zero0
settlementssettlement_idmethod manual or provider; status pending, confirmed, failed or reversed; amount_minor > 00 / 4
idempotency_recordsUNIQUE (actor_user_id, group_id, operation, idempotency_key)request_hash, stored response, expires_at = +7 days1
balance_projection(group_id, currency, user_id)net_minor, last_applied_seq; updated inside the write transaction2
outboxoutbox_id (= event_id)group_id, group_seq, event_type, payload, published_at3
user_balance_summary(user_id, group_id, currency)Lives in a separate per-user store; sequence-guarded upserts3
provider_eventsUNIQUE (provider, provider_event_id)Webhook deduplication4

What the database enforces, and what it cannot

Keys, foreign keys, CHECK constraints and unique indexes enforce identity, group scoping, sign and deduplication. The sum invariants are different. "Payers and shares equal the total" and "a commit's deltas sum to zero" each span several rows, and a row-level CHECK cannot express that. The Expense Service enforces them inside the write transaction before COMMIT, and the reconciliation jobs verify them afterwards (Component 20). A deferred trigger that re-sums each commit is possible as defense in depth, at the cost of extra reads on every write.

Why expense content is versioned rather than updated

The head row (expenses: version, status) is kept apart from the immutable versions. An edit therefore changes exactly one mutable field, expenses.version, and that field is the compare-and-set target for optimistic concurrency (Component 12). Every older version stays readable. The activity feed can show "Dinner ₹900 → corrected to ₹960", and a reversal can be cross-checked against the exact rows it negates. Every money-bearing table carries group_id, which later becomes the partition key, so every write stays a single-shard local transaction (Component 18).

Key takeaways
  1. 01Keys, FKs, CHECKs and unique indexes enforce identity, scoping, sign and deduplication
  2. 02Multi-row sum invariants are enforced by the service inside the transaction and verified by reconciliation jobs
  3. 03Only expenses.version is mutable for an edit; content versions and ledger rows are append-only
  4. 04Each stage adds named tables: idempotency_records (1), balance_projection (2), outbox and user_balance_summary (3), provider_events (4)
Component 05

Equal Split and the Rounding Rule

The Stage 0 create path computes shares on the server (Complete Design, Chapter 09). The equal split is the common case, and the simplest instance of the single rounding rule that every split type shares. Each beneficiary gets the floor of their exact share, the leftover minor units go to the largest fractional remainders, and ties are broken by ascending user_id. This component implements that rule once, and Component 06 reuses it for percentages and weights.

pseudocodeLargest remainder in pure integers. All remainders share the denominator W, so comparing product mod W ranks them exactly as the true fractions would
// One allocation routine for every split type; weights are positive integers.
//   equal:      every weight = 1
//   percentage: weight = basis points (validated to sum to 10,000)
//   weights:    weight = the member's integer weight
function allocateLargestRemainder(totalMinor, weights):   // weights: [{ userId, weight }]
    W = sum(w.weight for w in weights)
    shares = []
    for w in weights:
        product = totalMinor * w.weight                    // exact integer, no float
        shares.append({ userId: w.userId,
                        share:  product div W,             // floor
                        rem:    product mod W })           // fractional part, scaled by W
    leftover = totalMinor - sum(s.share for s in shares)   // 0 <= leftover < len(weights)

    ranked = shares.sortBy(s => (-s.rem, s.userId))        // largest remainder first, ties by ascending userId
    for i in 0 .. leftover - 1:
        ranked[i].share += 1
    return shares                                          // sums to totalMinor by construction
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: ₹900 split equally over three members gives 30,000 paise each, with no leftover

Traced

For E1, 90,000 × 1 ÷ 3 = 30,000 with remainder 0 for every member, so the leftover is 0 and each share is 30,000. For ₹100.00 over the same three members, each product is 10,000. The floor is 3,333 with remainder 1, the floors sum to 9,999, and one paisa is left over. All remainders tie, so the lowest user_id, user-asha, gets it: 3,334 / 3,333 / 3,333. Any server, retry or client preview computes the same answer, because nothing depends on request order or hash-map iteration order.

Why a stateless tie-break

The sort costs O(n log n) over tens of beneficiaries, so speed is irrelevant; determinism is not. The client preview must match the server, and a support agent must be able to state why one member paid one paisa more. A rotating rule is fairer over many expenses but needs per-group state inside the transaction to remove a bias of at most one minor unit. If the rule ever changes, history does not, because corrections negate stored ledger rows instead of recomputing old shares (Component 12).

Key takeaways
  1. 01One routine, largest remainder in integers, serves equal, percentage and weighted splits
  2. 02Leftover minor units go to the largest remainders, ties by ascending user_id; each share is within one minor unit of exact
  3. 03₹100 over three gives 3,334 / 3,333 / 3,333; E1 divides evenly at 30,000 each
  4. 04The allocation sums to the total by construction, so no separate fix-up step exists
Component 06

Exact, Percentage and Weighted Splits

The other three split types use the same Stage 0 create path (Complete Design, Chapter 09). An exact split only needs validation. Percentages and weights call Component 05's largest-remainder routine with a different weight vector, so there is exactly one rounding rule in the codebase.

Exact split: validation only

pseudocodeThe caller chose the amounts; the server only rejects anything that does not sum exactly to the total
function validateExactSplit(totalMinor, splits):            // splits: [{ userId, shareMinor }]
    if any(s.shareMinor < 0 for s in splits):   return Invalid("NEGATIVE_SHARE")
    if hasDuplicates(s.userId for s in splits): return Invalid("DUPLICATE_BENEFICIARY")
    actual = sum(s.shareMinor for s in splits)
    if actual != totalMinor:
        return Invalid("SPLIT_SUM_MISMATCH",                 // 422, nothing written
                       expected_total_minor = totalMinor, actual_split_sum_minor = actual)
    return Valid(splits)

E2's first attempt gives Cara ₹250 instead of ₹300. The shares sum to 55,000 against a 60,000 total, so the request returns 422 SPLIT_SUM_MISMATCH before anything is written. The corrected request becomes E2.

Percentages and weights: one routine, two inputs

pseudocodeBasis points make the 100% check an exact integer comparison; the allocation itself is Component 05
function percentageSplit(totalMinor, entries):              // entries: [{ userId, bps }], 1% = 100 bps
    if sum(e.bps for e in entries) != 10000:
        return Invalid("SPLIT_SUM_MISMATCH", expected_bps = 10000)   // reject, never rescale
    if any(e.bps <= 0 for e in entries): return Invalid("NON_POSITIVE_WEIGHT")
    return allocateLargestRemainder(totalMinor, [{ userId: e.userId, weight: e.bps } for e in entries])

function weightedSplit(totalMinor, entries):                // entries: [{ userId, weight }]
    if any(e.weight <= 0 for e in entries): return Invalid("NON_POSITIVE_WEIGHT")
    return allocateLargestRemainder(totalMinor, entries)

₹125.50 at 33.33% / 33.33% / 33.34%, traced

Memberbps12,550 × bpsFloor (÷ 10,000)RemainderFinal
user-asha3,33341,829,1504,1829,1504,183
user-ben3,33341,829,1504,1829,1504,183
user-cara3,33441,841,7004,1841,7004,184

The floors sum to 12,548, leaving 2 paise. The two largest remainders belong to Asha and Ben (9,150 each), so each gets one, giving 4,183 / 4,183 / 4,184 = 12,550. The common shortcut where the last member absorbs the remainder would give Cara 12,550 − 8,364 = 4,186. That is almost two paise above her exact share of 4,184.17, and the result depends on who happens to be last. Largest remainder keeps every share within one paisa of exact.

Weights 1 : 2 : 2 on ₹1,000 give W = 5. The products 100,000, 200,000 and 200,000 all divide by 5, so the shares are 20,000 / 40,000 / 40,000 with nothing left over. On ₹1,000.01 (100,001 paise) the remainders are 1, 2 and 2 fifths of a paisa. The floors sum to 100,000, and the one leftover paisa goes to the largest remainder. Ben and Cara tie, and the tie-break by user_id picks Ben: 20,000 / 40,001 / 40,000.

Key takeaways
  1. 01Exact splits are validated with an integer sum check; a mismatch is 422 SPLIT_SUM_MISMATCH
  2. 02Percentages are integer basis points summing to exactly 10,000; weights are positive integers
  3. 03Both reuse the single largest-remainder routine: ₹125.50 at 3333/3333/3334 bps gives 4,183 / 4,183 / 4,184
  4. 04"Last member absorbs the remainder" is biased and order-dependent; the design does not use it
Component 07

Multiple Payers

Stage 0's write accepts a list of payers, not a single paid_by column (Complete Design, Chapter 09). The payer side therefore needs its own sum invariant, checked independently of the split side. The two sides may use different rules, for example exact payer amounts with a percentage split.

pseudocodeOne code path covers both cases; a single payer is just a payer list with one entry
function validatePayers(totalMinor, payers):                 // payers: [{ userId, paidMinor }]
    if any(p.paidMinor <= 0 for p in payers):    return Invalid("NON_POSITIVE_PAYMENT")
    if hasDuplicates(p.userId for p in payers):  return Invalid("DUPLICATE_PAYER")
    if sum(p.paidMinor for p in payers) != totalMinor:
        return Invalid("PAYER_SUM_MISMATCH")                  // 422
    return Valid(payers)

function ledgerDeltas(payers, splits):
    delta = map()                                            // userId -> signed minor units
    for p in payers: delta[p.userId] += p.paidMinor
    for s in splits: delta[s.userId] -= s.shareMinor
    rows = [(u, d) for (u, d) in delta if d != 0]            // a member who paid exactly their share gets no row
    assert sum(d for (u, d) in rows) == 0                    // follows from both sums equalling the total
    return rows

Example: a ₹900 dinner paid 50,000 by one member and 40,000 by a second, split equally three ways. The deltas are +20,000, +10,000 and −30,000, and they sum to zero.

Why both sums are anchored to the stored total

A check of only sum(payers) == sum(shares) would accept an expense whose two sides agree with each other but not with its own total_minor. For example, a client bug could send ₹850 on both sides of a ₹900 expense. The ledger would still balance, but the expense record, the activity feed and every export would show a total that nothing actually accounts for. Each side is therefore checked against the stored total directly.

Pairwise attribution with several payers

Net balances do not need to know who paid for whom, but the pairwise view does (Component 09). With several payers, each beneficiary's share is attributed to the payers in proportion to paid_minor, using the same largest-remainder routine with the payers' amounts as weights. In the two-payer dinner, a beneficiary's 30,000 share splits 50,000 : 40,000. The floors are 16,666 and 13,333, with remainders 60,000 and 30,000 (out of 90,000), so the leftover paisa goes to the first payer: 16,667 and 13,333.

Key takeaways
  1. 01Payer contributions have their own sum invariant: positive amounts that sum exactly to total_minor (422 PAYER_SUM_MISMATCH)
  2. 02Each member's ledger delta is paid − share; zero deltas produce no row; single-payer is the one-element case
  3. 03Both sides are checked against the stored total, never only against each other
  4. 04Pairwise attribution across several payers reuses largest remainder, weighted by paid_minor
Component 08

Net Balance Computation

In Stage 0 a balance read is an aggregation over the ledger (Complete Design, Chapter 06, Complete Design, Chapter 09). That query is the definition of a balance. Later stages only make it cheaper (Component 13) and keep it as the reconciliation check (Component 20).

sqlThe definition of a balance: the sum of every signed delta for one member, group and currency
SELECT user_id, SUM(delta_minor) AS net_minor
FROM ledger_events
WHERE group_id = :group_id
  AND currency = :currency
GROUP BY user_id;

The running example, traced

MemberE1 (seq 1)E2 (seq 2)S1 (seq 3)Net
user-asha+60,000−10,000−20,000+30,000 (+₹300)
user-ben−30,000+40,0000+10,000 (+₹100)
user-cara−30,000−30,000+20,000−40,000 (−₹400)
Sum0000

Zero-sum conservation, and how to find the culprit

sqlBecause every commit sums to zero on its own (Component 03), a group-wide violation is always traceable to specific commits
-- group-wide: any row returned is a conservation violation
SELECT currency, SUM(delta_minor) AS total
FROM ledger_events
WHERE group_id = :group_id
GROUP BY currency
HAVING SUM(delta_minor) <> 0;

-- pinpoint: the commit whose own rows do not sum to zero
SELECT group_seq, SUM(delta_minor)
FROM ledger_events
WHERE group_id = :group_id AND currency = :currency
GROUP BY group_seq
HAVING SUM(delta_minor) <> 0;

The group-wide total is the sum of many individually zero commits. A non-zero result is therefore never a rounding tolerance. It is a specific broken write, and the second query names its group_seq, which leads straight to the source record and the code path that produced it.

The cost of the definition

With the index (group_id, currency, user_id), ideally covering delta_minor so the scan is index-only, the query is a range scan over the group's entire history. That is O(rows), about 2,300 rows for an average group after one year. The cost is fine at Stage 0, and it is exactly what Stage 2 removes. At about 3,500 group aggregations per second at peak, it becomes roughly 8 million rows/s in year one and 16 million in year two (Complete Design, Chapter 13).

Key takeaways
  1. 01A net balance is SUM(delta_minor) per user, group and currency; this query defines what every projection must equal
  2. 02After E1, E2 and S1: Asha +₹300, Ben +₹100, Cara −₹400; every commit column sums to zero
  3. 03A group-wide zero-sum violation is traced to a group_seq whose rows do not sum to zero
  4. 04The definition costs O(history) per read, which is the limit Stage 2 removes
Component 09

Pairwise Debts vs Netted Positions

Members ask two different questions: "who owes whom, and for what?" and "how much do I owe overall?" The design answers them from different views of the same data (Complete Design, Chapter 10). This component shows how each view is derived and what each can and cannot explain.

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
After E1 and E2: four raw pairwise debts on the left, two suggested repayments on the right, with identical net positions

Four levels of the same data

ViewAfter E1 + E2Derived fromAnswers
Raw pairwise (per expense)Ben→Asha 300 and Cara→Asha 300 (dinner); Asha→Ben 100 and Cara→Ben 300 (taxi)expense_payers and expense_splits of each active versionWhich expense created this debt?
Netted per pairBen→Asha 200, Cara→Asha 300, Cara→Ben 300Raw pairs, with opposite directions canceledWhat do I owe this particular person?
Net positionAsha +500, Ben +100, Cara −600SUM(delta_minor), or balance_projectionHow much do I owe or am I owed in total?
Suggested repaymentsCara→Asha 500, Cara→Ben 100Net positions (Component 10)What is a short way to settle everything?

Netting per pair reduces four edges to three. The dinner and the taxi created debts in both directions between Asha and Ben, and they cancel to Ben→Asha ₹200. Only simplification over net positions gets down to two transfers. Each step loses information. The netted pair no longer says which expenses it came from, and a suggestion no longer corresponds to any single expense.

Why the distinction matters to the product

A member disputing one expense needs the raw view. The dispute is resolved by correcting or deleting that expense (Component 12), which reverses exactly its rows and leaves every other expense alone. A member disputing the overall number needs the per-expense breakdown behind the net. A UI that only ever shows simplified transfers makes both questions hard to answer, even though its arithmetic is correct.

Settlements in the pairwise view

A settlement is a payer→recipient record, so it reduces the netted pair directly. S1 (Cara→Asha ₹200) turns Cara→Asha 300 into 100. A settlement need not match any expense, because a member may follow a suggestion that crosses pairs. The pairwise view therefore applies settlements to netted pairs, not to individual expenses. Net positions stay correct either way, because both views are sums of the same ledger rows.

Key takeaways
  1. 01Raw pairwise debts carry provenance; netted pairs, net positions and suggestions each discard more of it
  2. 02After E1 + E2: 4 raw edges → 3 netted pairs (Ben→Asha 200) → 2 suggested repayments
  3. 03Disputing one expense needs the raw view; disputing a total needs the breakdown behind the net
  4. 04Settlements reduce netted pairs and never rewrite expense-level obligations
Component 10

Debt Simplification Algorithm

Simplification is a read-only suggestion, computed per currency from the current net positions (Complete Design, Chapter 10). Complete Design states the rule and its non-minimality. This component covers the data structures, the tie-break, the bound, a step-by-step counterexample, and an exact search for small groups.

pseudocodeGreedy matching with two heaps. Each step zeroes at least one member, so with k non-zero members it runs at most k − 1 times, in O(k log k)
function simplifyDebts(nets):                    // map userId -> net_minor for ONE group and ONE currency
    creditors = maxHeap()                        // (amount, userId): larger amount first, ties by ascending userId
    debtors   = maxHeap()
    for (userId, net) in nets:
        if net > 0: creditors.push((net, userId))
        elif net < 0: debtors.push((-net, userId))   // zero nets are already settled

    transfers = []
    while not creditors.empty():                 // debtors empties at the same time, because nets sum to zero
        (credit, to)  = creditors.pop()
        (debt,   frm) = debtors.pop()
        amount = min(credit, debt)
        transfers.append({ from_user_id: frm, to_user_id: to, amount_minor: amount })
        if credit > amount: creditors.push((credit - amount, to))
        if debt   > amount: debtors.push((debt - amount, frm))
    return transfers                             // at most (creditors + debtors - 1) transfers

E1 + E2, traced

The nets are Asha +50,000, Ben +10,000 and Cara −60,000. Step 1 matches Asha (50,000) with Cara (60,000) and transfers 50,000, leaving Cara at 10,000. Step 2 matches Ben (10,000) with Cara (10,000). The result is Cara→Asha ₹500 and Cara→Ben ₹100. The response carries the as_of_seq of the balance snapshot it was computed from, the same snapshot as the sheet shown beside it (Component 15). A suggestion computed before a newer expense is therefore visibly out of date.

Determinism

Ties between equal amounts are broken by ascending user_id, so the same nets always produce the same list. A suggestion that changed on every refresh, with no underlying balance change, would look like a bug to members and would make support conversations impossible.

Greedy is not minimal: a counterexample, step by step

StepLargest creditorLargest debtorTransfer
1M1 400M3 300M3→M1 300
2M2 300M4 200 (ties with M5; lower id wins)M4→M2 200
3M1 100 (ties with M2; lower id wins)M5 200M5→M1 100
4M2 100M5 100M5→M2 100
Nets: M1 +400, M2 +300, M3 −300, M4 −200, M5 −200 (₹)

Greedy produces four transfers. The optimum is three: M3→M2 ₹300, and M4 and M5 each paying M1 ₹200. It exists because the members split into two disjoint zero-sum subsets, {M2, M3} and {M1, M4, M5}. In general the minimum number of transfers is n − k, where n is the number of members with a non-zero net and k is the largest number of disjoint zero-sum subsets they can be partitioned into. Finding k is NP-hard, since it generalizes subset-sum.

An exact search for small groups

pseudocodeBitmask dynamic programming: O(2^n · n) time and O(2^n) memory, so it is only viable for small groups
// n members with non-zero nets (practical up to roughly 15-20); sumOf(mask) = sum of their nets
best[0] = 0                                      // best[mask] = most zero-sum subsets mask can be split into
for mask in 1 .. 2^n - 1:
    best[mask] = max(best[mask without bit i] for i in bits(mask))
                 + (sumOf(mask) == 0 ? 1 : 0)
minTransfers = n - best[2^n - 1]
// backtrack to recover the subsets, then run greedy inside each one (size - 1 transfers each)

Whether to use it is a product decision, not a correctness one. Greedy's occasional extra transfer is a UX cost, and every transfer it proposes settles real net positions exactly. The design claims "few" transfers, never "fewest". An exact mode for small groups is an optional add-on behind the same endpoint.

Key takeaways
  1. 01Two max-heaps, largest creditor against largest debtor, ties by ascending user_id: O(k log k), at most k − 1 transfers
  2. 02E1 + E2 simplify to Cara→Asha ₹500 and Cara→Ben ₹100, returned with the as_of_seq they reflect
  3. 03Counterexample: greedy needs 4 transfers where 3 suffice; minimum = n − (max disjoint zero-sum subsets), which is NP-hard
  4. 04A bitmask DP finds the exact minimum for small groups; the design only claims "few"
  5. 05Simplification runs per currency, is read-only, and is never stored as an obligation
Component 11 · Stage 1

The Write Transaction, Group Sequence and Idempotency

Stage 0 can half-write an expense and can record the same dinner twice when a phone retries (Complete Design, Chapter 11). Stage 1 makes every money-moving request one local transaction that also claims an idempotency key. This component opens that transaction: the order of its statements, what each lock buys, how two racing retries resolve, and why read-committed isolation is enough.

pseudocodeThe create path. The claim, the money rows and the stored response commit together, so a committed record always carries its response
function handleMutation(actor, groupId, operation, key, request):
    hash   = sha256(canonicalPath(request) + canonicalJson(request.body))  // sorted keys, no whitespace
    shares = computeAndValidate(request.body)       // pure split math; 422 before any DB work

    BEGIN                                           // READ COMMITTED
    claimed = INSERT INTO idempotency_records
                (actor_user_id, group_id, operation, idempotency_key, request_hash, created_at, expires_at)
              VALUES (actor, groupId, operation, key, hash, now(), now() + 7 days)
              ON CONFLICT DO NOTHING RETURNING 1    // waits if another transaction holds the same uncommitted key
    if not claimed:
        ROLLBACK
        rec = SELECT request_hash, response_status, response_body FROM idempotency_records WHERE <same 4 columns>
        if rec.request_hash != hash: return 422 IDEMPOTENCY_KEY_CONFLICT
        return replay(rec.response_status, rec.response_body)        // same 201, same group_seq

    requireMembership(actor, groupId)               // 403 FORBIDDEN_NOT_A_MEMBER -> ROLLBACK releases the claim
    seq = UPDATE groups SET last_seq = last_seq + 1 WHERE group_id = groupId RETURNING last_seq
    insert expense head, version, payers, splits
    insert ledger_events (one row per non-zero delta, group_seq = seq); assert they sum to zero
    upsert balance_projection          // Stage 2 (Component 13)
    insert outbox row                  // Stage 3 (Component 14)
    insert audit_entries
    UPDATE idempotency_records SET response_status = 201, response_body = {expense_id, version, group_seq: seq}
    COMMIT                                          // 201 is sent only after this returns
Swipe to pan
ClientIdempotency-KeyExpenseServiceBEGIN — one local transaction on the group1. claim idempotency key (unique per actor, group, op)2. check membership of actor and participants3. group_seq = ++groups.last_seq (locks group row)4. INSERT expenses, expense_versions, payers, splits5. INSERT ledger_events (Σ delta = 0 per currency)6. store 201 response on the idempotency recordCOMMIT → 201 {expense_id, version, group_seq}Retriessame key, same body →stored 201 replayedsame key, other body →422 IDEMPOTENCY_KEY_CONFLICTconcurrent duplicate →waits on the unique keyCrash before COMMITnothing is visible;the retry starts cleanStage 2 adds balance_projection updates and Stage 3 adds the outbox row —inside this same transaction, never as a separate step
Stage 1: idempotency claim, membership check, per-group sequence, expense rows and ledger entries in one commit; a reused key with a different body gets 422

Two racing retries, traced

TimeAttempt 1 (key k1)Attempt 2 (key k1, same body)
t0INSERT claim k1 (uncommitted)
t1Takes the group row lock; group_seq 1INSERT claim k1 blocks on attempt 1’s uncommitted unique key
t2COMMIT; the client’s connection times out before the 201 arrivesUnblocks; DO NOTHING returns no row
t3Reads the record: hashes match, returns the stored 201 with group_seq 1
If attempt 1 had rolled back at t2, attempt 2’s INSERT would succeed and it would run as a fresh request. Either way the expense exists at most once.

A client bug that reuses k1 for the taxi carries a different body, so the hashes differ and the server returns 422 IDEMPOTENCY_KEY_CONFLICT with nothing written. Replaying the dinner's response would silently drop the user's real taxi. The fingerprint covers the canonical path and body only, not volatile headers such as the access token, so a retry after a token refresh still matches. Recurring expenses derive their key from (recurring_id, period), which makes the scheduler's own retries harmless.

Why the group row, and why the sequence is gap-free

UPDATE groups SET last_seq = last_seq + 1 takes a row lock that is held until COMMIT. Every money-moving write in the group therefore runs one at a time, and each later per-group statement (projection upserts, outbox) happens under a lock the transaction already holds, so no two group writes can deadlock. Locks are always taken in the same order: the expense row (for edits) or the settlement row (for confirmations) first, then the group row. Because the increment is part of the transaction, a rollback undoes it. A database SEQUENCE would leave gaps on every rollback. Gap-free numbering is what lets a rebuild prove it has seen every commit, and it lets as_of_seq be compared across views.

Why read committed is enough

Each cross-transaction invariant has a narrow, explicit guard: the unique key for idempotency, the group row lock for ordering and per-group sums, and the version compare-and-set for edits (Component 12). Serializable isolation would add retry storms on hot groups without covering anything new. It also cannot help with a correction that spans two committed transactions, which is exactly what reversals handle. The one rule that matters is that every check that guards a write must run inside the write's transaction. For example, the membership check is SELECT … FOR SHARE, so a concurrent removal waits for this write to commit (Component 19).

Retention

Records expire after 7 days and are purged in batches by expires_at; at roughly 5M writes a day, indefinite retention would be an unbounded table. A key reused after expiry is a new request, so the app asks the user to confirm very old queued entries.

Key takeaways
  1. 01Claim key, check membership, take group_seq, write rows, store response, COMMIT: one local transaction, 201 only after commit
  2. 02Same key and same body replays the stored response; same key and a different body is 422 IDEMPOTENCY_KEY_CONFLICT
  3. 03A concurrent duplicate blocks on the uncommitted unique key, then replays or proceeds; it never double-writes
  4. 04The group row lock serializes a group’s writes and yields a gap-free group_seq; lock order is expense or settlement row, then group row
  5. 05Read committed plus explicit guards inside the transaction is sufficient
Component 12 · Stage 1

Versioned Edits, Reversals and Deletes

The second half of Stage 1 makes corrections safe (Complete Design, Chapter 12). Two members editing the same expense must not silently overwrite each other, and a correction must add history rather than erase it. The mechanism is PUT with If-Match: "<version>", a compare-and-set on expenses.version, and ledger reversal plus replacement.

Swipe to pan
exp-2040 Groceries ₹1,200 — both editors loaded version 4Edit A: PUT If-Match "4"amount ₹1,250Edit B: PUT If-Match "4"split change1 row updated → version 5reversal + new entries · 2000 rows → 409 VERSION_CONFLICTcurrent_version: 5 · reloadcommits first4 is staleUPDATE expenses SET version = version + 1 WHERE expense_id = … AND version = 4 AND status = 'active'
exp-2040 at version 4: two PUT requests with If-Match "4". The first commits version 5; the second gets 409 VERSION_CONFLICT with current_version 5
sqlThe compare-and-set is the whole conflict detector. The head row holds only version and status; content lives in immutable expense_versions
UPDATE expenses
SET    version = version + 1
WHERE  expense_id = :expense_id
  AND  version    = :expected_version     -- from If-Match
  AND  status     = 'active'
RETURNING version;

-- 0 rows: ROLLBACK, re-read (version, status) and return
-- 409 VERSION_CONFLICT {current_version}. Never retry with the same expected version.

The race inside the database

Both requests for exp-2040 reach the UPDATE. The first takes the row lock and moves the version to 5. The second blocks on that lock. When the first commits, PostgreSQL under read committed re-evaluates the second statement's WHERE against the newly committed row. version = 4 no longer matches, so zero rows are updated and the second request returns 409 with current_version: 5. No application lock, and no isolation level above read committed, is involved. A request without If-Match gets 428 PRECONDITION_REQUIRED, because a missing version would silently mean last write wins.

The idempotency key still matters for edits. Without it, a retry of a successful edit would itself get 409, since its own first attempt moved the version. With it, the retry replays the stored response.

Reversal plus replacement

In the same transaction, after the compare-and-set and the group lock, the edit inserts the new version's content, then negates the previous version's stored ledger rows (source_type = 'expense_reversal'), then inserts the new version's rows, all under one new group_seq (Complete Design, Chapter 12 shows the SQL). The reversal copies the stored deltas instead of recomputing the old shares. That way a later change to the rounding rule or a currency table can never alter history.

Rows under the new group_sequser-ashauser-benuser-caraSum
Reversal of version 1−60,000+30,000+30,0000
Version 2 (₹960, equal)+64,000−32,000−32,0000
Net change+4,000−2,000−2,0000
What-if: E1 corrected from ₹900 to ₹960. Both blocks sum to zero on their own.

A cheaper alternative writes only the net-change row per member: three rows instead of six. It loses the clean rule that the ledger rows of version n are exactly that version's effect, and with it the ability to check a reversal against the rows it cancels. Edits are rare compared with creates, so the extra rows are cheap. A delete is the same transaction without the replacement: status = 'deleted' plus reversal rows. An edit after a delete fails the status = 'active' guard. Settlements are never touched, so deleting E1 after S1 leaves Asha −₹300, Ben +₹400 and Cara −₹100.

Serialization scope

The version check is per expense: an edit conflicts only with an edit or delete of the same expense. Every money-moving write still takes the group row lock (Component 11), so writes in one group run one at a time even when they touch different expenses. They wait a few milliseconds, but none fails because of another expense. Lock order is fixed (expense row, then group row), which rules out deadlocks between edits and creates.

Key takeaways
  1. 01PUT + If-Match "<version>"; the compare-and-set also checks status = 'active'; 0 rows means 409 VERSION_CONFLICT with current_version
  2. 02A missing If-Match is 428 PRECONDITION_REQUIRED; idempotency keys make a retried successful edit replay instead of failing
  3. 03Edits negate the stored rows of the old version and append the new version’s rows under one group_seq; deletes append only the reversal
  4. 04Version conflicts are per expense; the group lock serializes, but never fails, writes to different expenses
Component 13 · Stage 2

The Group Balance Projection

After Stage 1 every balance read still runs the aggregation from Component 08. At peak that is about 3,500 group aggregations per second, roughly 8 million ledger rows/s in year one and 16 million in year two, compared with about 17,500 rows/s for stored per-member nets (Complete Design, Chapter 13). Stage 2 adds the table balance_projection and maintains it inside the write transaction itself, not from events.

Swipe to pan
Ledger rows read per group balance request (average group)~6day 1~1,1506 months~2,3001 year~4,6002 yearsSUM on read (Stages 0–1)~3,500 aggregations/s at peak≈ 8M rows/s (year 1)≈ 16M rows/s (year 2)balance_projection (Stage 2)~5 rows per group, any age≈ 17,500 rows/s at peak~5 extra row updates per writered = rows aggregated per read · green = projection rows per read (constant)
Rows read per balance request grow with history; a maintained per-member net stays constant
sqlWrite side and read side of the group balance projection
-- inside the Component 11 transaction, once per ledger row, after the ledger insert
INSERT INTO balance_projection (group_id, currency, user_id, net_minor, last_applied_seq)
VALUES (:group_id, :currency, :user_id, :delta_minor, :group_seq)
ON CONFLICT (group_id, currency, user_id) DO UPDATE
SET net_minor        = balance_projection.net_minor + EXCLUDED.net_minor,
    last_applied_seq = EXCLUDED.last_applied_seq
RETURNING net_minor;            -- becomes net_after_minor in the Stage 3 event

-- read: one statement, so as_of_seq and the nets come from the same snapshot
SELECT g.last_seq AS as_of_seq, b.user_id, b.net_minor
FROM groups g JOIN balance_projection b USING (group_id)
WHERE g.group_id = :group_id AND b.currency = :currency;

Why adding deltas is safe here

Here the upsert adds a delta, while the Stage 3 Projection Consumer writes absolute values (Component 14). The difference is where each runs. This upsert commits or rolls back together with the ledger rows it summarizes, under the group lock, and only after the idempotency claim succeeded. A duplicate request never reaches it, there is no reordering, and a crash leaves neither the rows nor the delta. So on the primary the projection equals SUM(delta_minor) at the same snapshot unless a bug or a manual write bypasses this path, which the drift check below catches, and the writer's next read includes the write by construction.

The cost is about five extra row updates per write, under a lock the transaction already holds. That is roughly 2,900 row writes/s at the 580 writes/s peak, flat over time, in exchange for reads that no longer grow with history. Reading groups.last_seq in the same statement gives an as_of_seq consistent with the nets, because one statement sees one snapshot even under read committed.

Checking and rebuilding the projection

sqlDrift check for one group, as one statement, so both sides are read at the same snapshot
SELECT l.currency, l.user_id, SUM(l.delta_minor) AS ledger_net, b.net_minor AS projected
FROM ledger_events l
LEFT JOIN balance_projection b
       ON b.group_id = l.group_id AND b.currency = l.currency AND b.user_id = l.user_id
WHERE l.group_id = :group_id
GROUP BY l.currency, l.user_id, b.net_minor
HAVING SUM(l.delta_minor) IS DISTINCT FROM b.net_minor;   -- any row is drift

The old aggregation is not thrown away. It becomes the check. A reconciliation job runs this query over a rolling sample of groups, so every group is covered over time. Any row it returns is an alert, then a rebuild of that group under its lock (Component 20), then a root-cause fix. The job never silently patches the value. Expected drift is zero, so a single mismatch means a bug or a manual write that bypassed the transaction.

Key takeaways
  1. 01balance_projection(group_id, currency, user_id, net_minor, last_applied_seq) is updated in the write transaction, never from the bus
  2. 02Peak reads drop from ~8M ledger rows/s (year 1) to ~17,500 projection rows/s, for ~5 extra row writes per expense
  3. 03Delta upserts are safe only because they commit atomically with the ledger rows and behind the idempotency claim
  4. 04The SUM(delta_minor) query becomes the drift check; a mismatch alerts and triggers an investigated rebuild
Component 14 · Stage 3

Outbox, Relay and the Projection Consumer

Notifications, the cross-group dashboard and cache invalidation must react to every commit without joining the write transaction (Complete Design, Chapter 14). Committing the write and then publishing to a bus is a dual write: a crash in between loses the event. The transactional outbox closes the gap. The event is a row in the same transaction, so it exists if and only if the write committed.

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.
One transaction writes the expense, ledger rows, balance_projection and the outbox row; the Outbox Relay publishes afterwards, at least once; consumers apply idempotently

The outbox row and the relay

Each commit inserts one outbox row: outbox_id (which is also the event_id), group_id, group_seq, event_type (expense.created, expense.updated, expense.deleted, settlement.confirmed, and reversal variants), the payload, and published_at = NULL. The payload carries each affected member's absolute net_after_minor, taken from the RETURNING clause of the Stage 2 upsert.

pseudocodeOnly outbox rows are locked here, never the group row, so a slow bus cannot stall expense writes
function outboxRelayLoop():                       // several workers per shard
    loop:
        BEGIN
        batch = SELECT outbox_id, group_id, group_seq, event_type, payload
                FROM outbox WHERE published_at IS NULL
                ORDER BY outbox_id LIMIT 500
                FOR UPDATE SKIP LOCKED            // workers never claim the same row
        if batch is empty: COMMIT; sleep(POLL_INTERVAL); continue
        for row in batch:
            bus.send(key = row.group_id, headers = {event_id: row.outbox_id, group_seq: row.group_seq},
                     value = row.payload)
        bus.flush()                               // wait for replicated acks
        UPDATE outbox SET published_at = now() WHERE outbox_id IN batch.ids
        COMMIT                                    // a crash before this republishes the batch

Two properties follow, and consumers must tolerate both. Duplicates: a crash after flush and before COMMIT republishes the batch, so delivery is at-least-once, not exactly-once. Reordering: within a group, commits are serialized, but two workers can claim adjacent rows of the same group in different batches and publish seq 7 after seq 8. Alerting on the age of the oldest unpublished row (above 30 s) catches a stuck relay. Published rows are purged after 7 days. Change data capture that tails the database log is a valid replacement transport for this loop. The domain event stays the same.

The Projection Consumer: absolute values with a sequence guard

pseudocodeNo dedup table and no reordering buffer: a duplicate or older event matches no row
function onEvent(evt):                            // at-least-once, possibly out of order
    BEGIN                                         // per-user store (Component 18)
    for e in evt.effects:
        INSERT INTO user_balance_summary (user_id, group_id, currency, net_minor, last_applied_seq)
        VALUES (e.user_id, evt.group_id, evt.currency, e.net_after_minor, evt.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
    COMMIT
    cache.delete("balance:" + evt.group_id + ":" + evt.currency)    // idempotent (Component 15)
    bus.commitOffset(evt)                         // only after the effects are durable
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 → User Balance Projection: an absolute net_after_minor written only if its group_seq is newer; older and duplicate events are no-ops
DeliveryEvent (user-asha)Stored beforeOutcome
1seq 2, net_after +50,000noneInserted: +50,000 @ 2
2 (late)seq 1, net_after +60,000+50,000 @ 2Guard 2 < 1 is false: no-op
3 (duplicate)seq 2, net_after +50,000+50,000 @ 2Guard 2 < 2 is false: no-op
Out-of-order and duplicate delivery for E1 and E2. The final value is correct either way

Applying deltas here would double-count every duplicate, and it would need a separate dedup table, strict per-group ordering and gap detection. Absolute values make skipping an intermediate event harmless, because a newer value supersedes it. Each (user, group, currency) row sees only the events that change that member, so gaps in its sequence are normal. Each event therefore has at most one effect, and the bus offset is committed after the effect. The worst case is a redelivery, never a loss.

Failure isolation

If the relay, the bus or this consumer stops, expenses are still accepted and group balances stay correct; only the dashboard and notifications fall behind, showing their as_of_seq. A fixed consumer replays from the bus (7 days) or rebuilds from balance_projection (Component 20).

Key takeaways
  1. 01The outbox row commits with the write; the relay publishes with FOR UPDATE SKIP LOCKED and marks rows published only after acks
  2. 02Delivery is at-least-once and can reorder within a group; this is stated, not hidden
  3. 03The Projection Consumer writes absolute net_after_minor guarded by last_applied_seq < :seq, then deletes the cache key, then commits its offset
  4. 04A relay or bus outage delays the dashboard and notifications only; group balances are unaffected
Component 15 · Stage 3

Versioned Cache and Read Consistency

The group sheet is read up to ~2,315 times a second at peak, concentrated on a few active groups, while it changes a few times an hour (Complete Design, Chapter 15). A plain TTL cache would show a balance from before the latest expense, with no way to tell. The Balance Cache stores the sheet together with the sequence it reflects, so staleness is visible and the writer can always skip it.

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: a cached sheet is returned only if its as_of_seq satisfies min_seq; otherwise the projection is read and stored set-if-newer
pseudocodeA slower reader can never replace a newer entry with an older one
function getGroupBalances(groupId, currency, minSeq = 0):
    key   = "balance:" + groupId + ":" + currency
    entry = cache.get(key)                                   // { sheet, as_of_seq }
    if entry != null and entry.as_of_seq >= minSeq:
        return entry                                         // hit; response carries as_of_seq
    snap = readProjection(groupId, currency)                 // primary, Component 13 query
    cache.setIfNewer(key, snap, ttl = 300s)
    return snap

-- setIfNewer as one atomic cache-side script
local cur = redis.call('HGET', KEYS[1], 'as_of_seq')
if cur and tonumber(cur) >= tonumber(ARGV[1]) then return 0 end
redis.call('HSET', KEYS[1], 'as_of_seq', ARGV[1], 'sheet', ARGV[2])
redis.call('EXPIRE', KEYS[1], 300)
return 1

Two invalidations and a backstop

After COMMIT, the Expense Service deletes the key. This is fast and best effort, and if the process dies here the delete is skipped. The Projection Consumer deletes the key again when the commit's event arrives. That second delete is reliable, because the event comes from the outbox. The 300 s TTL is only a backstop for an invalidation that is lost entirely. It is not the freshness mechanism. One interleaving remains, and it shows why both deletes exist:

TimeReader R (no min_seq)Writer WCache
t0Reads projection at seq 7empty
t1Commits seq 8, returns group_seq 8empty
t2Fast-path deleteempty
t3setIfNewer(seq 7) succeeds; the key is absentsheet @ 7 (stale)
t4Its next read sends min_seq 8: bypass, reads the primarysheet @ 7
t5Projection Consumer deletes on event seq 8empty, then refilled @ 8

Other viewers may see seq 7 between t3 and t5, typically a second or two, always labeled with its as_of_seq. The writer never does, because of min_seq. A refinement would replace the fast-path delete with a tombstone {as_of_seq: 8}. setIfNewer would then reject the stale fill at t3, at the cost of one more cache write per commit. The baseline keeps the simpler delete, because the event-driven delete already bounds the window.

What each surface promises

Writes return group_seq, and the writing device sends it as min_seq on its next read. That gives read-your-writes on that device only: another device of the same user does not know the sequence and may see the previous sheet briefly. Suggested repayments (Component 10) are computed from the same snapshot as the sheet and return its as_of_seq, so they can never contradict the numbers shown beside them. The dashboard reads user_balance_summary, where each row's last_applied_seq is its freshness marker. Its p99 ≤ 2 s freshness is a monitored target, not a guarantee. If the cache is down, reads fall back to the primary projection.

Activity pagination

sqlKeyset pagination: entries appended while a member scrolls cannot shift, duplicate or skip rows, as an OFFSET would
SELECT audit_id, created_at, action, actor_user_id, summary
FROM audit_entries
WHERE group_id = :group_id
  AND (created_at, audit_id) < (:cursor_created_at, :cursor_audit_id)
ORDER BY created_at DESC, audit_id DESC
LIMIT 50;      -- index (group_id, created_at DESC, audit_id DESC); the cursor is opaque to clients
Key takeaways
  1. 01Key balance:{group_id}:{currency} holds {sheet, as_of_seq}; fills are atomic set-if-newer
  2. 02Invalidation: a best-effort delete after commit plus a reliable delete by the Projection Consumer; the 300 s TTL is only a backstop
  3. 03min_seq gives the writing device read-your-writes; other viewers may briefly see the previous sheet, labeled with as_of_seq
  4. 04Activity history uses a (created_at, audit_id) keyset cursor, never an offset
Component 16 · Stage 4

Multi-Currency Handling

Stage 4 adds groups that spend in more than one currency (Complete Design, Chapter 16). The rule is that currency is part of every balance key. ₹1,000 and $20 are two separate facts, and no code path adds them without an explicit, recorded conversion.

Currency as a hard partition

ledger_events, balance_projection and user_balance_summary all carry currency in their key. INR and USD positions in one group are therefore separate rows, each summing to zero across the group, and the Component 08 aggregation already groups by currency. A $20 souvenir paid by Asha is a USD expense with USD minor units (cents). The rounding rule (Component 05) runs with USD's exponent, and the sheet shows a separate USD block. A settlement must be in a currency in which the payer owes the recipient something; otherwise it returns 422 CURRENCY_MISMATCH.

FX rate snapshots are display-only

A "show everything in INR" view is computed at read time from an immutable rate snapshot and labeled as an estimate. It is never stored as a balance.

jsonSnapshots are immutable once used. A wrong rate is fixed by capturing a new snapshot, never by editing this one
{ "rate_id": "fx-2026-10-20-usd-inr",
  "from_currency": "USD", "to_currency": "INR",
  "rate_scaled": 8310000000, "scale": 100000000,      // 83.10 as a fixed-point integer, never a float
  "source": "named rate feed", "captured_at": "2026-10-20T06:00:00Z" }

Converting $20.00 (2,000 cents) gives 2,000 × 8,310,000,000 ÷ 10^8 × 10^(2−2) = 166,200 paise, which is ₹1,662.00. When the division is not exact, the display rounds half-up and shows the rate and its time next to the figure.

Conversion is an explicit, zero-sum record

If members agree to settle Ben's $20 debt to Asha in rupees, a member records a conversion that references the snapshot. One commit, under one group_seq, writes two blocks:

Currencyuser-benuser-ashaSum
USD (closes the dollar positions)+2,000−2,0000
INR (opens the rupee equivalent at 83.10)−166,200+166,2000
Each currency sums to zero independently; nothing is netted implicitly

The conversion record stores from_amount_minor, to_amount_minor, rate_id and initiated_by. Every cross-currency figure therefore traces to one attributable decision. A conversion is corrected like anything else: by a reversal and a new record.

Key takeaways
  1. 01Currency is part of every balance key; each currency sums to zero on its own; mismatches return 422 CURRENCY_MISMATCH
  2. 02Rounding and minor units are per currency (INR 2, JPY 0, KWD 3)
  3. 03FX snapshots are immutable fixed-point integers used for labeled display estimates only
  4. 04Cross-currency settlement is an explicit, member-initiated conversion that is zero-sum per currency
Component 17 · Stage 4

Settlement Lifecycle

A settlement is either a member's assertion that money changed hands outside the system, or a provider payment that counts only once the provider confirms it (Complete Design, Chapter 16). The two never share a single undifferentiated "paid" state, and a balance moves only when a settlement is confirmed.

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
pending → confirmed (ledger rows written) or failed (none); confirmed → reversed on refund, chargeback or dispute. Manual settlements are created confirmed

Manual settlement: an assertion

S1, Cara paying Asha ₹200 in cash, is one transaction shaped exactly like an expense: idempotency claim, membership check, group_seq 3, a settlements row with method = 'manual' and status = 'confirmed', ledger rows user-cara +20,000 and user-asha −20,000, the projection upserts and an outbox row. There is no provider_reference. If Asha disputes it, it moves to reversed and gains settlement_reversal rows. The UI never presents it as a verified payment.

Provider settlement: transitions and guards

TransitionTriggerGuardLedger effect
→ pendingPOST …/settlements, method providerIdempotency claimNone; no group_seq
pending → confirmedVerified webhook, or reconciliation pollWHERE status = 'pending' AND amount and currency matchSettlement rows, projection, outbox, under a new group_seq
pending → failedVerified webhook, or pollWHERE status = 'pending'None
confirmed → reversedRefund, chargeback, disputeWHERE status = 'confirmed'settlement_reversal rows
Anything else (e.g. failed after confirmed)Late or contradictory webhookGuard matches 0 rowsNone; flagged for reconciliation

After pending commits, the Payment Service calls the provider outside any transaction, with settlement_id as the provider's idempotency key. A crash between the commit and the call leaves a pending row with no provider_reference. Reconciliation repeats the call with the same key, which the provider deduplicates, so no second charge is created. The client shows the pending amount separately, and it never reduces anyone's balance.

Webhook handling

pseudocodeVerify first, deduplicate by provider event id, then one guarded, atomic transition
function onProviderWebhook(provider, rawBody, headers):
    if not constantTimeEquals(hmac(SECRET[provider], headers.timestamp + "." + rawBody), headers.signature)
       or abs(now() - headers.timestamp) > 5 min:
        return 401                                     // log; never applied speculatively
    evt = parse(rawBody)
    BEGIN
    if not INSERT INTO provider_events (provider, provider_event_id, settlement_id, payload, received_at)
           ... ON CONFLICT DO NOTHING RETURNING 1:
        ROLLBACK; return 200                           // duplicate delivery; already handled
    s = SELECT ... FROM settlements WHERE settlement_id = evt.settlement_id FOR UPDATE   // settlement row, then group row
    applyTransition(s, evt)                            // guarded UPDATE; 0 rows -> flag, no effect
    COMMIT
    return 200

Reconciliation: webhooks can be lost

pseudocodeA daily provider-report comparison covers the rest; the provider’s record wins, corrected by new ledger rows
function reconcilePendingSettlements():                // every few minutes
    for s in SELECT * FROM settlements
             WHERE status = 'pending' AND created_at < now() - interval '15 minutes':
        if s.provider_reference is null:
            retryProviderCall(s)                       // same idempotency key = settlement_id
            continue
        p = provider.getPayment(s.provider_reference) // authoritative
        if p.status == 'succeeded': applyTransition(s, confirmed)   // same guarded function as the webhook
        elif p.status == 'failed':  applyTransition(s, failed)
        // else still pending at the provider: check again next run
Key takeaways
  1. 01Manual settlements are created confirmed and are disputable assertions; provider settlements start pending with no ledger effect
  2. 02Provider calls run outside the transaction with settlement_id as the idempotency key
  3. 03Webhooks are verified (HMAC and timestamp), deduplicated in provider_events, and applied only through state-guarded UPDATEs
  4. 04Reconciliation polls settlements still pending after 15 min; confirmed → reversed writes settlement_reversal rows
Component 18 · Stage 5

Hot Groups and Partitioning

Two scaling questions remain (Complete Design, Chapter 17). How fast can one group write, given that its writes serialize on the group row? And how is the data split across machines once a single primary is too big to back up, restore and migrate comfortably, at about 3 TB of rows a year?

The hot-group ceiling

The group row lock is held from UPDATE groups until COMMIT. If the transaction takes 5–10 ms, one group tops out at roughly 100–200 writes/s. A 200-member event group writes up to 200 ledger and projection rows per expense, which pushes its ceiling nearer a few dozen writes/s. Ordinary groups write a few times an hour, so the ceiling is the price of a gap-free order, not a practical limit.

Mitigations, in order of preference: keep network calls out of the transaction (already true); batch the multi-row inserts; take the group lock as late as possible, after the inserts that do not need group_seq (an optional refinement that keeps the expense row, then group row lock order); rate-limit writes per group at the gateway with 429 and Retry-After; let the versioned cache absorb read bursts; send notification digests for very large groups. The one thing not to do is drop the group lock for hot groups. The sequence is what makes projections, as_of_seq and replay correct.

Partitioning by group_id

Every money-moving transaction is scoped to one group, so group_id is the partition key. A group's expenses, ledger, settlements, projection, idempotency records, outbox and audit live on one shard, and every write stays a single-shard local transaction. Each shard runs its own Outbox Relay, and the Event Bus is keyed by group_id. Per-user data, meaning users, the user → groups index and user_balance_summary, lives in a separate store keyed by user and fed by events. That is why the dashboard is asynchronous and the group sheet is not. A group directory maps group_id to a shard: hash placement by default, with explicit overrides.

Moving a group between shards

textFreeze, copy, verify, flip. Duplicate publishes during the move are harmless because consumers are sequence-guarded
1. Directory marks the group "moving": new writes get 503 + Retry-After (seconds)
2. Wait for in-flight transactions to finish; record last_seq = N on the source
3. Copy all group-scoped rows, including unpublished outbox rows, to the target
4. Verify on the target: last_seq = N, zero-sum per currency, projection = SUM(delta_minor)
5. Flip the directory entry; writes resume on the target; its relay publishes the copied outbox rows
6. Delete the source rows after a grace period

For a large group, history up to an earlier seq is copied before the freeze, so only the tail is copied while writes pause. Dormant groups are archived: their ledger moves to cheaper storage while their final balance_projection rows stay online.

Key takeaways
  1. 01A group writes at most ~100–200 short transactions/s because of its row lock; per-group 429s, short transactions and the cache keep it healthy
  2. 02Never drop the group lock: the gap-free group_seq underpins projections, as_of_seq and replay
  3. 03Partition by group_id with a group directory; one relay per shard; per-user data lives in a separate, event-fed store
  4. 04Group moves are freeze, copy, verify, flip, protected by the same sequence guards as normal delivery
Component 19 · Stage 5

Membership Authorization and Security

From Stage 5 an API Gateway terminates TLS, validates tokens and rate-limits (Complete Design, Chapter 17, Complete Design, Chapter 18). It authenticates and nothing more. Whether a user may touch a group is checked by the service that owns the group's data, on every request, inside the transaction that uses the answer.

pseudocodeObject-level authorization. Group and expense ids are guessable and never act as access tokens
function requireMembership(actorUserId, groupId, action):
    m = SELECT role, left_at FROM memberships
        WHERE group_id = groupId AND user_id = actorUserId
        FOR SHARE                                    // a concurrent removal waits until this write commits
    if m == null:
        return 403 FORBIDDEN_NOT_A_MEMBER
    if m.left_at != null and action is a write:
        return 403 FORBIDDEN_NOT_A_MEMBER            // former members may read the history they were part of
    if action in (edit, delete) and not (actor created the expense or m.role == 'admin'):
        return 403                                   // default edit policy (Complete Design, Chapter 12)
    return ok

The FOR SHARE lock closes a time-of-check to time-of-use gap. Without it, a member could be removed between the check and the COMMIT, and the write would land after the removal.

Invitations

sqlSingle use is enforced by the guarded UPDATE: of two simultaneous accepts, exactly one matches the row
UPDATE invitations
SET    accepted_at = now(), accepted_by = :user_id
WHERE  invitation_id = :id AND accepted_at IS NULL AND expires_at > now()
  AND  (email IS NULL OR email = :verified_email)
RETURNING group_id;                     -- 0 rows: used, expired or not addressed to this user -> rejected
INSERT INTO memberships (group_id, user_id, role, joined_at) VALUES (:group_id, :user_id, 'member', now())
ON CONFLICT (group_id, user_id) DO UPDATE SET left_at = NULL;      -- re-joining keeps one row

Removal, history and deletion requests

Removing a member sets left_at; the row is never deleted. A removed member cannot be added to new expenses. Expenses and ledger rows that already reference their user_id stay visible to everyone who was part of them, because they are evidence of real financial events. The product can block removal while the member's net in any currency is non-zero, or require a settlement first. A personal-data deletion request is handled by anonymizing, not erasing: profile fields are replaced with a placeholder, receipts containing their data are removed, and the financial rows stay so the other members' balances remain explainable.

Data protection

TLS in transit and encryption at rest cover the database and receipt storage; receipts are served through short-lived signed URLs behind the same membership check. Because ledger_events and audit_entries have no UPDATE or DELETE grant, a compromised account's edits stay visible, and support-tool corrections use the same reversal path with the operator recorded. Per-user and per-group gateway rate limits stop retry storms and floods.

Key takeaways
  1. 01The gateway authenticates; services authorize every request against memberships, inside the write transaction (FOR SHARE)
  2. 02Non-members get 403 FORBIDDEN_NOT_A_MEMBER; former members keep read access to their history
  3. 03Invitations are single-use, expiring and scoped, enforced by one guarded UPDATE
  4. 04Removal sets left_at; deletion requests anonymize identities and keep financial facts
Component 20 · Stage 5

Reconciliation, Repair and Recovery

Every guarantee on this page is only as good as the check that proves it is still true (Complete Design, Chapter 17, Complete Design, Chapter 20). This component covers the continuous checks, the rebuild procedure for every derived view, the signals that page someone, and what disaster recovery can and cannot restore.

Continuous checks

pseudocodeBoth counters must stay at zero. A non-zero value is a finding to investigate before any repair, never something to average away
function reconcileGroup(groupId):                  // rolling: every group is covered over time
    for (currency, total) in SELECT currency, SUM(delta_minor) FROM ledger_events
                             WHERE group_id = groupId GROUP BY currency:
        if total != 0:
            alert("ZERO_SUM_VIOLATION", groupId, currency, total)   // then find the group_seq (Component 08)
    for row in driftQuery(groupId):                 // Component 13
        alert("PROJECTION_DRIFT", groupId, row)    // then rebuild under the lock, below

Rebuilding derived views

sqlRebuilding balance_projection for an ordinary group takes milliseconds under its own lock
BEGIN;
SELECT last_seq FROM groups WHERE group_id = :g FOR UPDATE;      -- pauses this group's writers
DELETE FROM balance_projection WHERE group_id = :g;
INSERT INTO balance_projection (group_id, currency, user_id, net_minor, last_applied_seq)
SELECT group_id, currency, user_id, SUM(delta_minor), :last_seq
FROM ledger_events WHERE group_id = :g
GROUP BY group_id, currency, user_id;
COMMIT;
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, then swap; a redelivered sequence is a no-op

For a very large group, a shadow table is built up to a known seq N without the lock; then, under the lock, only rows with group_seq > N are applied before compare and swap. user_balance_summary is rebuilt by replaying current nets from balance_projection through the same sequence-guarded upsert, safely alongside live events. The cache can always be flushed.

Signals

SignalAlert whenPoints at
Zero-sum violations; projection drift> 0A write-path bug or a manual write
Oldest unpublished outbox row> 30 sRelay or Event Bus
Consumer lag per partitionDashboard p99 > 2 sProjection Consumer or Notification Service
Duplicate and no-op rate per consumerRisingRelay restarts, redelivery
409 VERSION_CONFLICT, 422 IDEMPOTENCY_KEY_CONFLICT, replay rateStep changeClient bugs, retry storms
Cache hit ratio and min_seq bypass rateFalling hit ratioInvalidation storms, cache outage
Pending settlements by age; webhook signature failures> 15 min; any spikeLost webhooks, forgery attempts
Write p99, group read p99> 300 ms, > 100 msHot groups, primary load

Backup and disaster recovery

Each shard has a synchronous in-region standby, so a single node failure loses no acknowledged write and fails over in minutes. It also has an asynchronous cross-region replica and point-in-time backups. Cross-region RPO is therefore seconds, not zero: after a regional failover, the last acknowledged writes may be missing. Because the idempotency record commits with the write, both are lost together. A client that retries with the same key re-executes once, and the effect is still applied at most once. A write whose client already received its 201 and will not retry is genuinely lost. Payment reconciliation re-checks recent provider confirmations, so money that really moved is re-recorded. The bus and the caches are not backed up; they are re-derived from the outbox and the ledger. ledger_events is the one table whose loss is unrecoverable, so it gets the strongest replication and is restored in drills.

Audit evidence

For a disputed expense or settlement, the ledger_events, expense_versions, settlements, provider_events and audit_entries rows for that source_id, in order, are the full story. Because nothing is edited in place, this is a plain ordered read.

Key takeaways
  1. 01Zero-sum and projection-drift checks run continuously; both must stay at 0, and a hit is investigated before repair
  2. 02balance_projection rebuilds under the group lock (shadow plus catch-up for large groups); user_balance_summary replays through the guarded upsert
  3. 03One alert per mechanism: outbox age, consumer lag, conflict rates, cache bypass, pending settlements, latency
  4. 04Cross-region RPO is seconds; unacknowledged requests recover through same-key client retries, while acknowledged writes lost in failover need provider reconciliation or user re-entry; bus and caches are re-derived

The whole design in one table

GuaranteeMechanismComponents
Money is exact and balances are explainableInteger minor units; append-only ledger whose rows sum to zero per commit; balances are sums, not stored facts02, 03, 08
Splits are fair and deterministicOne largest-remainder routine with ties by ascending user_id; separate payer and share sum invariants05, 06, 07
Retries and edits are safeOne local transaction per write with an idempotency claim; If-Match versions; corrections append reversals11, 12
Reads stay cheap and correctTransactionally updated projection, set-if-newer cache fills, as_of_seq and min_seq for consistency13, 15
Side effects never block or corrupt writesOutbox with a relay and idempotent, sequence-guarded consumers; at-least-once delivery stated openly14
Money movement and currencies stay separate and verifiedCurrency inside every balance key; provider settlements pending until a verified, deduplicated webhook, with reconciliation16, 17
It scales and stays checkablePartition by group_id with the group row lock kept; membership authorization on every request; continuous zero-sum and drift checks18, 19, 20
Component numbers refer to the twenty components on this page