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.
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).
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.
- 01Group is the ownership, ordering and partition boundary. The expense version is the atomic boundary for one financial event. Nothing is netted across groups
- 02Payer and beneficiary are roles on (expense, version, user), and the two routinely overlap
- 03Membership is a stored fact in memberships, never inferred from a user_id appearing in an expense
- 04Each expense carries its own currency; the group default currency is only a UI default
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.
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.
- 01Every amount is an integer count of minor units, from the API edge to the ledger
- 02The minor-unit exponent comes from a currency table (INR 2, JPY 0, KWD 3) and is never hardcoded as ×100
- 03BIGINT leaves enormous headroom; per-currency input bounds keep split-math intermediates in range
- 04A float in the money path is a correctness defect, not a style choice
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.
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_seq | user_id | delta_minor | source_type | source_id / version |
|---|---|---|---|---|
| 1 | user-asha | +60,000 | expense | exp-1001 / 1 |
| 1 | user-ben | −30,000 | expense | exp-1001 / 1 |
| 1 | user-cara | −30,000 | expense | exp-1001 / 1 |
| 4 | user-asha | −60,000 | expense_reversal | exp-1001 / 1 |
| 4 | user-ben | +30,000 | expense_reversal | exp-1001 / 1 |
| 4 | user-cara | +30,000 | expense_reversal | exp-1001 / 1 |
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).
- 01Every financial fact is an INSERT. UPDATE and DELETE are not granted on ledger_events
- 02The rows of one committed write sum to zero, and the service asserts this before COMMIT
- 03source_type, source_id and source_version tie every row to the record and version that produced it
- 04A delete or correction appends negated rows under a new group_seq, and the history stays readable
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.
| Table | Key | Constraint or enforcement | Stage |
|---|---|---|---|
| groups | group_id | last_seq is incremented once per money-moving commit; that row lock serializes the group’s writes | 0 / 1 |
| memberships | (group_id, user_id) | role; left_at IS NULL means a current member; rows are never deleted | 0 |
| expenses | expense_id | version is the If-Match compare-and-set target; status is active or deleted | 0 / 1 |
| expense_versions | (expense_id, version) | Immutable; total_minor > 0, currency, split_type | 1 |
| 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 transaction | 0 |
| ledger_events | event_id; index (group_id, currency, user_id) | INSERT-only grant; the rows of one group_seq sum to zero | 0 |
| settlements | settlement_id | method manual or provider; status pending, confirmed, failed or reversed; amount_minor > 0 | 0 / 4 |
| idempotency_records | UNIQUE (actor_user_id, group_id, operation, idempotency_key) | request_hash, stored response, expires_at = +7 days | 1 |
| balance_projection | (group_id, currency, user_id) | net_minor, last_applied_seq; updated inside the write transaction | 2 |
| outbox | outbox_id (= event_id) | group_id, group_seq, event_type, payload, published_at | 3 |
| user_balance_summary | (user_id, group_id, currency) | Lives in a separate per-user store; sequence-guarded upserts | 3 |
| provider_events | UNIQUE (provider, provider_event_id) | Webhook deduplication | 4 |
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).
- 01Keys, FKs, CHECKs and unique indexes enforce identity, scoping, sign and deduplication
- 02Multi-row sum invariants are enforced by the service inside the transaction and verified by reconciliation jobs
- 03Only expenses.version is mutable for an edit; content versions and ledger rows are append-only
- 04Each stage adds named tables: idempotency_records (1), balance_projection (2), outbox and user_balance_summary (3), provider_events (4)
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.
// 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 constructionTraced
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).
- 01One routine, largest remainder in integers, serves equal, percentage and weighted splits
- 02Leftover minor units go to the largest remainders, ties by ascending user_id; each share is within one minor unit of exact
- 03₹100 over three gives 3,334 / 3,333 / 3,333; E1 divides evenly at 30,000 each
- 04The allocation sums to the total by construction, so no separate fix-up step exists
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.
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 rowsExample: 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.
- 01Payer contributions have their own sum invariant: positive amounts that sum exactly to total_minor (422 PAYER_SUM_MISMATCH)
- 02Each member's ledger delta is paid − share; zero deltas produce no row; single-payer is the one-element case
- 03Both sides are checked against the stored total, never only against each other
- 04Pairwise attribution across several payers reuses largest remainder, weighted by paid_minor
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).
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
| Member | E1 (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,000 | 0 | +10,000 (+₹100) |
| user-cara | −30,000 | −30,000 | +20,000 | −40,000 (−₹400) |
| Sum | 0 | 0 | 0 | 0 |
Zero-sum conservation, and how to find the culprit
-- 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).
- 01A net balance is SUM(delta_minor) per user, group and currency; this query defines what every projection must equal
- 02After E1, E2 and S1: Asha +₹300, Ben +₹100, Cara −₹400; every commit column sums to zero
- 03A group-wide zero-sum violation is traced to a group_seq whose rows do not sum to zero
- 04The definition costs O(history) per read, which is the limit Stage 2 removes
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.
Four levels of the same data
| View | After E1 + E2 | Derived from | Answers |
|---|---|---|---|
| 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 version | Which expense created this debt? |
| Netted per pair | Ben→Asha 200, Cara→Asha 300, Cara→Ben 300 | Raw pairs, with opposite directions canceled | What do I owe this particular person? |
| Net position | Asha +500, Ben +100, Cara −600 | SUM(delta_minor), or balance_projection | How much do I owe or am I owed in total? |
| Suggested repayments | Cara→Asha 500, Cara→Ben 100 | Net 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.
- 01Raw pairwise debts carry provenance; netted pairs, net positions and suggestions each discard more of it
- 02After E1 + E2: 4 raw edges → 3 netted pairs (Ben→Asha 200) → 2 suggested repayments
- 03Disputing one expense needs the raw view; disputing a total needs the breakdown behind the net
- 04Settlements reduce netted pairs and never rewrite expense-level obligations
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.
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) transfersE1 + 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
| Step | Largest creditor | Largest debtor | Transfer |
|---|---|---|---|
| 1 | M1 400 | M3 300 | M3→M1 300 |
| 2 | M2 300 | M4 200 (ties with M5; lower id wins) | M4→M2 200 |
| 3 | M1 100 (ties with M2; lower id wins) | M5 200 | M5→M1 100 |
| 4 | M2 100 | M5 100 | M5→M2 100 |
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
// 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.
- 01Two max-heaps, largest creditor against largest debtor, ties by ascending user_id: O(k log k), at most k − 1 transfers
- 02E1 + E2 simplify to Cara→Asha ₹500 and Cara→Ben ₹100, returned with the as_of_seq they reflect
- 03Counterexample: greedy needs 4 transfers where 3 suffice; minimum = n − (max disjoint zero-sum subsets), which is NP-hard
- 04A bitmask DP finds the exact minimum for small groups; the design only claims "few"
- 05Simplification runs per currency, is read-only, and is never stored as an obligation
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.
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 returnsTwo racing retries, traced
| Time | Attempt 1 (key k1) | Attempt 2 (key k1, same body) |
|---|---|---|
| t0 | INSERT claim k1 (uncommitted) | |
| t1 | Takes the group row lock; group_seq 1 | INSERT claim k1 blocks on attempt 1’s uncommitted unique key |
| t2 | COMMIT; the client’s connection times out before the 201 arrives | Unblocks; DO NOTHING returns no row |
| t3 | Reads the record: hashes match, returns the stored 201 with group_seq 1 |
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.
- 01Claim key, check membership, take group_seq, write rows, store response, COMMIT: one local transaction, 201 only after commit
- 02Same key and same body replays the stored response; same key and a different body is 422 IDEMPOTENCY_KEY_CONFLICT
- 03A concurrent duplicate blocks on the uncommitted unique key, then replays or proceeds; it never double-writes
- 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
- 05Read committed plus explicit guards inside the transaction is sufficient
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.
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_seq | user-asha | user-ben | user-cara | Sum |
|---|---|---|---|---|
| Reversal of version 1 | −60,000 | +30,000 | +30,000 | 0 |
| Version 2 (₹960, equal) | +64,000 | −32,000 | −32,000 | 0 |
| Net change | +4,000 | −2,000 | −2,000 | 0 |
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.
- 01PUT + If-Match "<version>"; the compare-and-set also checks status = 'active'; 0 rows means 409 VERSION_CONFLICT with current_version
- 02A missing If-Match is 428 PRECONDITION_REQUIRED; idempotency keys make a retried successful edit replay instead of failing
- 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
- 04Version conflicts are per expense; the group lock serializes, but never fails, writes to different expenses
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.
-- 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
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 driftThe 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.
- 01balance_projection(group_id, currency, user_id, net_minor, last_applied_seq) is updated in the write transaction, never from the bus
- 02Peak reads drop from ~8M ledger rows/s (year 1) to ~17,500 projection rows/s, for ~5 extra row writes per expense
- 03Delta upserts are safe only because they commit atomically with the ledger rows and behind the idempotency claim
- 04The SUM(delta_minor) query becomes the drift check; a mismatch alerts and triggers an investigated rebuild
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.
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.
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 batchTwo 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
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| Delivery | Event (user-asha) | Stored before | Outcome |
|---|---|---|---|
| 1 | seq 2, net_after +50,000 | none | Inserted: +50,000 @ 2 |
| 2 (late) | seq 1, net_after +60,000 | +50,000 @ 2 | Guard 2 < 1 is false: no-op |
| 3 (duplicate) | seq 2, net_after +50,000 | +50,000 @ 2 | Guard 2 < 2 is false: no-op |
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).
- 01The outbox row commits with the write; the relay publishes with FOR UPDATE SKIP LOCKED and marks rows published only after acks
- 02Delivery is at-least-once and can reorder within a group; this is stated, not hidden
- 03The Projection Consumer writes absolute net_after_minor guarded by last_applied_seq < :seq, then deletes the cache key, then commits its offset
- 04A relay or bus outage delays the dashboard and notifications only; group balances are unaffected
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.
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 1Two 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:
| Time | Reader R (no min_seq) | Writer W | Cache |
|---|---|---|---|
| t0 | Reads projection at seq 7 | empty | |
| t1 | Commits seq 8, returns group_seq 8 | empty | |
| t2 | Fast-path delete | empty | |
| t3 | setIfNewer(seq 7) succeeds; the key is absent | sheet @ 7 (stale) | |
| t4 | Its next read sends min_seq 8: bypass, reads the primary | sheet @ 7 | |
| t5 | Projection Consumer deletes on event seq 8 | empty, 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
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- 01Key balance:{group_id}:{currency} holds {sheet, as_of_seq}; fills are atomic set-if-newer
- 02Invalidation: a best-effort delete after commit plus a reliable delete by the Projection Consumer; the 300 s TTL is only a backstop
- 03min_seq gives the writing device read-your-writes; other viewers may briefly see the previous sheet, labeled with as_of_seq
- 04Activity history uses a (created_at, audit_id) keyset cursor, never an offset
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.
{ "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:
| Currency | user-ben | user-asha | Sum |
|---|---|---|---|
| USD (closes the dollar positions) | +2,000 | −2,000 | 0 |
| INR (opens the rupee equivalent at 83.10) | −166,200 | +166,200 | 0 |
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.
- 01Currency is part of every balance key; each currency sums to zero on its own; mismatches return 422 CURRENCY_MISMATCH
- 02Rounding and minor units are per currency (INR 2, JPY 0, KWD 3)
- 03FX snapshots are immutable fixed-point integers used for labeled display estimates only
- 04Cross-currency settlement is an explicit, member-initiated conversion that is zero-sum per currency
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.
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
| Transition | Trigger | Guard | Ledger effect |
|---|---|---|---|
| → pending | POST …/settlements, method provider | Idempotency claim | None; no group_seq |
| pending → confirmed | Verified webhook, or reconciliation poll | WHERE status = 'pending' AND amount and currency match | Settlement rows, projection, outbox, under a new group_seq |
| pending → failed | Verified webhook, or poll | WHERE status = 'pending' | None |
| confirmed → reversed | Refund, chargeback, dispute | WHERE status = 'confirmed' | settlement_reversal rows |
| Anything else (e.g. failed after confirmed) | Late or contradictory webhook | Guard matches 0 rows | None; 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
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 200Reconciliation: webhooks can be lost
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- 01Manual settlements are created confirmed and are disputable assertions; provider settlements start pending with no ledger effect
- 02Provider calls run outside the transaction with settlement_id as the idempotency key
- 03Webhooks are verified (HMAC and timestamp), deduplicated in provider_events, and applied only through state-guarded UPDATEs
- 04Reconciliation polls settlements still pending after 15 min; confirmed → reversed writes settlement_reversal rows
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
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 periodFor 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.
- 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
- 02Never drop the group lock: the gap-free group_seq underpins projections, as_of_seq and replay
- 03Partition by group_id with a group directory; one relay per shard; per-user data lives in a separate, event-fed store
- 04Group moves are freeze, copy, verify, flip, protected by the same sequence guards as normal delivery
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.
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 okThe 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
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 rowRemoval, 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.
- 01The gateway authenticates; services authorize every request against memberships, inside the write transaction (FOR SHARE)
- 02Non-members get 403 FORBIDDEN_NOT_A_MEMBER; former members keep read access to their history
- 03Invitations are single-use, expiring and scoped, enforced by one guarded UPDATE
- 04Removal sets left_at; deletion requests anonymize identities and keep financial facts
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
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, belowRebuilding derived views
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;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
| Signal | Alert when | Points at |
|---|---|---|
| Zero-sum violations; projection drift | > 0 | A write-path bug or a manual write |
| Oldest unpublished outbox row | > 30 s | Relay or Event Bus |
| Consumer lag per partition | Dashboard p99 > 2 s | Projection Consumer or Notification Service |
| Duplicate and no-op rate per consumer | Rising | Relay restarts, redelivery |
| 409 VERSION_CONFLICT, 422 IDEMPOTENCY_KEY_CONFLICT, replay rate | Step change | Client bugs, retry storms |
| Cache hit ratio and min_seq bypass rate | Falling hit ratio | Invalidation storms, cache outage |
| Pending settlements by age; webhook signature failures | > 15 min; any spike | Lost webhooks, forgery attempts |
| Write p99, group read p99 | > 300 ms, > 100 ms | Hot 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.
- 01Zero-sum and projection-drift checks run continuously; both must stay at 0, and a hit is investigated before repair
- 02balance_projection rebuilds under the group lock (shadow plus catch-up for large groups); user_balance_summary replays through the guarded upsert
- 03One alert per mechanism: outbox age, consumer lag, conflict rates, cache bypass, pending settlements, latency
- 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
| Guarantee | Mechanism | Components |
|---|---|---|
| Money is exact and balances are explainable | Integer minor units; append-only ledger whose rows sum to zero per commit; balances are sums, not stored facts | 02, 03, 08 |
| Splits are fair and deterministic | One largest-remainder routine with ties by ascending user_id; separate payer and share sum invariants | 05, 06, 07 |
| Retries and edits are safe | One local transaction per write with an idempotency claim; If-Match versions; corrections append reversals | 11, 12 |
| Reads stay cheap and correct | Transactionally updated projection, set-if-newer cache fills, as_of_seq and min_seq for consistency | 13, 15 |
| Side effects never block or corrupt writes | Outbox with a relay and idempotent, sequence-guarded consumers; at-least-once delivery stated openly | 14 |
| Money movement and currencies stay separate and verified | Currency inside every balance key; provider settlements pending until a verified, deduplicated webhook, with reconciliation | 16, 17 |
| It scales and stays checkable | Partition by group_id with the group row lock kept; membership authorization on every request; continuous zero-sum and drift checks | 18, 19, 20 |