Skip to content
SeeItFlow
System Design · 20 chapters · ~41 min read

Design Splitwise: Complete System Design of an Expense Sharing App

Splitwise system design: an expense-sharing app where every balance is exact, sums to zero per currency and can be explained from an immutable ledger. This original teaching design starts with one service and one relational database and adds each mechanism only when a requirement or measured limit demands it.

Mangesh MandlikLast updated: How lessons are made
Chapter 01

Problem Definition and Product Boundaries

A group shares costs over days or months: one person pays for dinner, another for the taxi, someone pays a friend back. A shared-expense system has to answer one question precisely and durably: given everything that was paid and by whom, who owes whom, and how much?

An expense is not a payment

This is the most important modeling decision in the system. An expense records a real-world cost and who is responsible for which share of it: dinner cost ₹900 and three people each consumed ₹300. A settlement records money that moved between two members to reduce a debt: Cara paid Asha ₹200. An expense changes who owes what; a settlement changes how much of it is still outstanding. Conflating the two (treating "Ben paid for the taxi" as repayment of an unrelated debt) produces balances nobody can explain. A balance is therefore never stored as an independent fact: it is arithmetic derived from recorded expenses and settlements.

The running example

One small group is used for worked numbers throughout: Weekend Trip (grp-weekend-trip), members Asha, Ben and Cara, currency INR. Amounts are stored in paise (1 rupee = 100 paise), an integer minor unit, because floating-point money is a recurring source of real bugs. Three events are enough to exercise splits, net balances, simplification and settlement; later chapters refer back to them by name (E1, E2, S1) instead of repeating the story.

EventWhat happenedNet after event (Asha / Ben / Cara)
E1 — DinnerAsha pays ₹900, split equally (₹300 each)+₹600 / −₹300 / −₹300
E2 — TaxiBen pays ₹600, exact split ₹100 / ₹200 / ₹300+₹500 / +₹100 / −₹600
S1 — RepaymentCara pays Asha ₹200 (recorded manually)+₹300 / +₹100 / −₹400
The whole running example. In every row the three nets sum to zero.
Swipe to pan
GroupWeekend Trip · INRMembershipAsha · creatorMembershipBen · memberMembershipCara · memberExpensepayers + beneficiaries + split
Weekend Trip: a group, its three memberships, and an expense that references payers, beneficiaries and a split

Who the system serves

Roommates splitting rent and utilities, trip groups, friends splitting a bill — through mobile and web clients. A user creates or joins a group, records expenses as they happen, checks balances, and eventually settles, either by recording a repayment made outside the app or, optionally, through an integrated payment provider. The backend is the system of record; clients display and cache, they never hold financial truth.

What this design is explicitly not

It is not a payment processor: where money moves through a provider, the provider is an external authority this design integrates with (Chapter 16), not something it reimplements. It is not a general-ledger accounting product, though it borrows the discipline that every credit has a matching debit. It is not a budgeting app and not a social network. Keeping these boundaries explicit keeps the design focused on one job: tracking who owes whom, over time, without losing or double-counting a paisa.

Key takeaways
  1. 01An expense (who incurred what cost) and a settlement (money that moved to reduce a debt) are different records and are never conflated.
  2. 02A balance is derived arithmetic over recorded expenses and settlements, not an independently stored fact.
  3. 03Money is stored in integer minor units (paise for INR), never floating point.
  4. 04Running example: Weekend Trip — E1 dinner ₹900 (Asha), E2 taxi ₹600 (Ben), S1 Cara repays Asha ₹200; final nets +₹300 / +₹100 / −₹400.
Interactive

Visual Design Journey

Watch an expense-sharing system evolve from one service and one ledger database into a production design, adding each mechanism only when a correctness or scaling limit demands it.

Chapter 02

Domain Fundamentals

A precise vocabulary prevents most modeling mistakes in this domain. Each term below is defined once and used with exactly this meaning on every page of the module.

Expense

One recorded cost: the group, total amount, currency, one or more payers, and a split that divides the total among beneficiaries. E1: total ₹900, paid by Asha, split equally across all three members.

Payer and beneficiary

A payer contributed money toward the total; a beneficiary is responsible for a share of it. The same person can be both (Asha paid for dinner and ate ₹300 of it), and the roles are tracked separately because a payer who consumes nothing (paying for someone else) is a valid case. An expense can have several payers.

Split

The rule that divides the total among beneficiaries: equal, exact amounts, percentages, or weights (Chapter 09). The shares must sum to exactly the total in minor units. This is a hard invariant enforced on every write, not a best-effort target.

Ledger entry

One signed effect on one participant's balance, produced by an expense, a settlement or a reversal: delta = paid − share for an expense. The entries of one expense always sum to zero. Ledger entries are append-only; they are the authoritative record from which every balance is derived.

Net balance

A participant's position within one group and one currency: what they paid for others, minus their own shares, plus settlements they paid, minus settlements they received. Positive means the group owes them; negative means they owe the group. After E1: Asha +₹600, Ben −₹300, Cara −₹300.

Pairwise debt

A directed obligation between two people — "Ben owes Asha ₹300". Many different sets of pairwise debts are consistent with the same net balances (Chapter 10).

Group balance

Every member's net balance in a group for one currency. Its defining property: the nets sum to exactly zero, because every rupee one member is owed is a rupee others owe. Different currencies are separate balance sets and are never added together.

Settlement

A record that money moved (or is asserted to have moved) between two members. It is a separate record type from an expense, it produces its own ledger entries, and its status — asserted, pending at a provider, confirmed, failed — matters (Chapter 16).

Simplified repayments

A suggested set of transfers that brings every net balance to zero, usually with fewer transfers than the raw pairwise debts. It is a read-only suggestion computed from net balances; it never moves money or changes a stored balance.

Derived view (projection)

Any stored copy of balances computed from the ledger to make reads cheap — the group balance projection (Chapter 13), the user dashboard projection and the cache (Chapters 14–15). Derived views can be rebuilt from the ledger; when they disagree with it, the ledger wins.

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 dinner, equal split across three beneficiaries, ₹300 each
MemberPaidShareNet (paid − share)
Asha₹900₹300+₹600
Ben₹0₹300−₹300
Cara₹0₹300−₹300
E1. +600 − 300 − 300 = 0.
Key takeaways
  1. 01Ledger entries (signed, append-only, zero-sum per expense) are the authoritative record; balances are derived from them.
  2. 02Net balance = paid for others − own shares + settlements paid − settlements received, per group and per currency.
  3. 03A group's nets in one currency always sum to exactly zero.
  4. 04Pairwise debts, simplified repayments and projections are derived views, never the stored source of truth.
Chapter 03

Functional Requirements

Functional requirements describe what the system must do. Separating the essential product from extensions keeps the core design focused on what makes expense sharing correct.

Group and membership management

Users create groups, invite others and join. Members can leave, but a member with a nonzero balance cannot silently disappear: either leaving is blocked until the balance is zero, or the departed member's history stays visible and settleable. Groups have at least two roles — member and admin (rename, remove members, close the group).

Expense recording and correction

Members create an expense with one or more payers, a total, and one of four split types: equal, exact, percentage, weights (Chapter 09). They can edit an expense (amount, split, participants) and delete it. Both are versioned, auditable operations — a correction is recorded as a new fact, never as an erase-and-rewrite of financial history (Chapter 12).

Balances, simplification and settlement

A member can view balances: their own net position, their position against any other member, and the group's balance sheet, plus a dashboard across all their groups. The system offers debt simplification — a suggested, smaller set of repayments (Chapter 10). Members can record a settlement made outside the app, and optionally pay through a payment provider, in which case the settlement counts only once the provider confirms it (Chapter 16).

History, notifications and discovery

Every group has a chronological activity history (expenses created, edited, deleted; settlements recorded). Members are notified when someone else's action affects them. Basic search over a group's expenses and an export of its history are expected.

Extensions beyond the core

Receipt attachments (reference images, not OCR-driven splitting), recurring expenses (a scheduled expense such as monthly rent) and payment-provider integration are valuable but optional; they are described as extensions rather than built into every path.

CapabilityEssential MVPAdvanced extension
Group membershipCreate, invite, join, leave, basic admin roleSub-groups, group-level default currency policy, bulk invites
SplitsEqual, exact, percentage, sharesItemized receipt-line splitting, tax/tip proportional splitting
BalancesNet balance, pairwise balance, group balance sheetHistorical balance-over-time charts
SimplificationGreedy repayment suggestion (few transfers, not guaranteed minimal)User-constrained simplification (e.g. "never suggest I pay X")
SettlementManual "mark as settled"Payment-provider-confirmed settlement, partial settlement scheduling
History & discoveryChronological activity feed, basic searchFull-text search, CSV/PDF export, spend analytics
What this design treats as essential for a credible MVP vs. an explained-but-optional extension.
Key takeaways
  1. 01Core scope: groups and membership, expenses with versioned edits and deletes, balances and simplification, settlement, history and notifications.
  2. 02All four split types (equal, exact, percentage, weights) are core requirements.
  3. 03Edits and deletes are auditable, versioned operations — never silent overwrites.
  4. 04Receipts, recurring expenses and provider payments are explicit extensions.
Chapter 04

Non-Functional Requirements

For a shared-expense system the sharpest non-functional requirements are about financial correctness and about precisely what "up to date" means — not raw throughput. A stale leaderboard rank is harmless; a balance that is silently wrong destroys trust.

Three moments, stated separately

Write acknowledgment is when the client is told the expense was accepted. Durable commit is when the expense and all its ledger entries are atomically persisted in the authoritative database; from then on the fact can only be corrected by a new, audited action. View visibility is when a given read surface reflects it. In this design acknowledgment happens only after durable commit, the group balance is visible to the writer immediately (Chapter 13), and the asynchronous surfaces — dashboard, notifications, search — follow with a small lag that is targeted, measured and shown, but not guaranteed (Chapter 15).

RequirementTarget (illustrative)Delivered by
Financial correctnessShares and payers sum exactly to the total; every group's ledger sums to zero per currencyServer-side split math and validation (Ch. 09), one write transaction (Ch. 11), continuous zero-sum checks (Ch. 17)
Idempotent writesA retried create, edit, delete or settlement has at most one effect per scoped Idempotency-KeyIdempotency records in the write transaction (Ch. 11)
No lost updatesTwo concurrent edits of one expense cannot both silently succeedOptimistic versions, 409 on mismatch (Ch. 12)
AuditabilityEvery balance is explainable from immutable historyAppend-only ledger; corrections as reversal + replacement (Ch. 07, 12)
AuthorizationEvery object access checks group membership, not just loginMembership check in the Expense Service (Ch. 06, 18)
DurabilityNo acknowledged expense is lost on a single-node failure (in-region RPO ≈ 0); cross-region RPO of secondsSynchronous in-region standby, async cross-region replica, PITR backups (Ch. 17)
Write latencyExpense write p99 < 300 msShort single-database transaction, no external calls inside it (Ch. 11, 14)
Group balance readp99 < 100 ms at peak; read-your-writes for the member who just wroteBalance projection + versioned cache (Ch. 13, 15)
Async freshnessDashboard and notifications reflect a commit within ~2 s at p99 (a target, monitored, not a guarantee)Outbox → event bus → consumers (Ch. 14, 16)
Availability99.9% monthly for expense writes and balance readsStandby failover; writes do not depend on the bus, cache or notifications (Ch. 17)
RecoverabilityAny derived view can be rebuilt from the ledgerReplay/rebuild jobs (Ch. 17)
PrivacyMembers see only their groups; receipts are protected PIIMembership checks on every query, access-controlled storage (Ch. 18)
Every figure is a design assumption for this walkthrough, not a measured benchmark.

Offline tolerance turns idempotency from a nice-to-have into a hard requirement: phones queue expenses while offline and replay them when connectivity returns, often more than once. Observability matters for the same reason: a silent failure on a financial write path is among the worst failure modes this product can have.

Chapter 05

Capacity Estimation

Every number here is a stated assumption for this walkthrough, not a benchmark of any real product. The point is to see which numbers actually shape the architecture.

Assumed workload

AssumptionValue
Registered users / daily active users10 million / 1 million
Groups~4 million (users belong to ~2 groups on average; average group size 5)
Expense writes (creates, edits, deletes)5 million / day
Balance reads20 million / day — about half group balance sheets, half dashboards across a user's groups
Peak multiplier10× the daily average (evenings, weekends, start of month)
Ledger entries per expense~5 (one per participant with a nonzero effect)
Ledger entry size~200 bytes per row (ids, group, user, currency, signed amount, sequence, type, timestamp)

Derived rates and volumes

textBack-of-the-envelope arithmetic used by later chapters.
Writes   5,000,000 / 86,400 s  ≈ 58 /s average  → ~580 /s at peak
Reads   20,000,000 / 86,400 s  ≈ 231 /s average → ~2,315 /s at peak
Read:write ratio               ≈ 4 : 1

Ledger entries   5M × 5        = 25M rows/day  ≈ 9.1B rows/year
Ledger storage   25M × 200 B   ≈ 5 GB/day      ≈ 1.8 TB/year
Expense rows                    ≈ 1.8B/year;  split rows ≈ 9.1B/year
All tables, before indexes      ≈ 3 TB/year and growing

History per group  25M rows/day ÷ 4M groups ≈ 6 rows/day
                   ≈ 2,300 ledger rows per average group after one year
                   (active household and trip groups: several times more)

Notifications  up to 4 other members per expense → ≤ 20M/day, ~2,315 /s at peak

Hot-group skew

Activity is never even. A trip happening this weekend, or a household group on the first of the month, absorbs a disproportionate share of writes and reads while most groups are dormant. Because everything about a balance is scoped to one group, a hot group's own peak rate — not the system-wide average — is what its write path and read path must sustain (Chapter 17).

What these numbers decide

ObservationArchitectural consequence
~580 write transactions/s at peakOne well-provisioned relational primary handles the write rate. Partitioning is needed later for storage growth, blast radius and hot groups — not for day-one write throughput (Ch. 17).
Reads are 4× writes and history grows ~6 rows per group per day, foreverRecomputing balances from the full ledger on every read gets more expensive every day. This is the first scaling limit (Ch. 13).
~1.8 TB/year of ledger, ~3 TB/year totalStorage, not throughput, eventually forces partitioning by group and archiving dormant groups (Ch. 17).
Notification fan-out runs at read-rate scaleNotification delivery must be asynchronous and must never sit in the expense write transaction (Ch. 14, 16).
Key takeaways
  1. 01Peak: ~580 writes/s and ~2,315 balance reads/s (4:1); all figures are illustrative assumptions.
  2. 02Ledger: ~25M rows/day, ~1.8 TB/year; an average group accumulates ~2,300 ledger rows a year.
  3. 03The first real limit is read cost growing with history, not write throughput.
  4. 04Hot-group peaks, not system-wide averages, size the per-group write and read paths.
Chapter 06 · Stage 0

The Simplest Design: One Service, One Relational Database

Start with the smallest design that meets the functional requirements, then let concrete limits justify every addition. Skipping straight to an event-driven diagram hides the reasoning that makes it defensible.

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

Components

Client — mobile and web apps. Expense Service — one deployable that exposes the REST API, validates the session token, checks group membership, computes splits and simplification, and writes and reads the database. Relational database — one PostgreSQL-class primary holding groups, memberships, expenses, splits, settlements and ledger entries. A relational store is chosen because the core write is a multi-row fact (an expense with its payers, splits and ledger entries) that needs constraints and transactions, and because ~580 writes/s at peak fit comfortably on one primary (Chapter 05).

Request flow

Create an expense: the client posts payers, total and split; the service checks membership, computes the shares in integer paise, and inserts the expense, payer, split and ledger rows. Read balances: the service sums the group's ledger entries per member. Edit / delete: the service updates or deletes the rows. Written naively, it looks like this:

sqlStage 0 as most first drafts write it. It works on a whiteboard and in a demo.
-- create: four statements, each auto-committed on its own
INSERT INTO expenses ...;  INSERT INTO expense_payers ...;
INSERT INTO expense_splits ...;  INSERT INTO ledger_events ...;

-- read: aggregate the whole history on every request
SELECT user_id, SUM(delta_minor) AS net_minor
FROM ledger_events
WHERE group_id = :group_id AND currency = :currency
GROUP BY user_id;

-- edit: overwrite in place; delete: remove the rows
UPDATE expense_splits SET share_minor = :new WHERE expense_id = :id AND user_id = :u;
DELETE FROM ledger_events WHERE source_id = :id;

What Stage 0 already gets right

Shares are computed on the server in integer minor units; the ledger is a single source of truth in one place; there is no cache or replica to disagree with; balances are always exactly the sum of history; and membership is checked on every request. For a few thousand users this is a legitimate product.

Where it breaks

Partial writes

Auto-committed statements can stop halfway: a crash after the expense insert but before the ledger insert leaves an expense that affects nobody's balance. → Stage 1, Chapter 11.

Duplicate writes on retry

A phone times out waiting for the response and retries, or an offline queue replays: the same dinner is recorded twice and everyone's balance moves twice. → Stage 1, Chapter 11.

Lost updates

Two members edit the same expense from stale screens; the second write silently overwrites the first. → Stage 1, Chapter 12.

Erased history

In-place UPDATE and DELETE of ledger rows destroy the record of what a balance used to be and why it changed, breaking the auditability requirement. → Stage 1, Chapter 12.

Read cost grows with history

Every balance read scans the group's entire ledger; that cost grows every day while the read rate stays four times the write rate. → Stage 2, Chapter 13.

Side effects in the request

Notifications, feeds and dashboards bolted into the request either slow and couple the write path or get lost when the process dies after commit. → Stage 3–4, Chapters 14–16.

Chapter 07

Data Model and the Source of Truth

The data model separates three things: the immutable record of what happened (expense versions, splits, settlements and ledger entries), derived views that exist only to make reads cheap, and supporting tables that make writes safe. Confusing them is the most common design mistake in this space.

TableKeyRole
groupsgroup_idScope of every expense and balance; holds last_seq, the per-group commit counter
memberships(group_id, user_id)Who may read and write the group; role; left_at kept for history
expensesexpense_idHead row: group, current version, status (active | deleted)
expense_versions(expense_id, version)Immutable content of each version: description, total, currency, split type, author
expense_payers / expense_splits(expense_id, version, user_id)Who paid how much; each beneficiary's exact share
ledger_eventsevent_id; ordered by (group_id, group_seq)Source of truth for balances: one signed delta per participant per committed write; append-only
settlementssettlement_idRepayments: from, to, amount, currency, method (manual | provider), status
audit_entriesaudit_idWho did what and when, with before/after snapshots; append-only
users, invitationsuser_id; invitation_idIdentity and single-use, expiring invitations
Source-of-truth tables. Supporting tables are added by the stage that needs them: idempotency_records (Stage 1), balance_projection (Stage 2), outbox and user_balance_summary (Stage 3), provider_events (Stage 4).
sqlCore DDL (abridged). Every money column is a BIGINT count of minor units with its currency next to it.
CREATE TABLE groups (
  group_id          BIGINT PRIMARY KEY,
  name              TEXT NOT NULL,
  default_currency  CHAR(3) NOT NULL,
  last_seq          BIGINT NOT NULL DEFAULT 0,   -- incremented once per committed money-moving write
  status            TEXT NOT NULL DEFAULT 'active'
);

CREATE TABLE expenses (                          -- head row; content lives in versions
  expense_id  BIGINT PRIMARY KEY,
  group_id    BIGINT NOT NULL REFERENCES groups,
  version     INT    NOT NULL,                   -- current version, used for optimistic concurrency
  status      TEXT   NOT NULL                    -- 'active' | 'deleted'
);

CREATE TABLE expense_versions (
  expense_id   BIGINT, version INT,
  description  TEXT,
  total_minor  BIGINT NOT NULL CHECK (total_minor > 0),
  currency     CHAR(3) NOT NULL,
  split_type   TEXT NOT NULL,                    -- 'equal' | 'exact' | 'percentage' | 'weights'
  created_by   BIGINT NOT NULL, created_at TIMESTAMPTZ NOT NULL,
  PRIMARY KEY (expense_id, version)
);

CREATE TABLE expense_splits (
  expense_id BIGINT, version INT, user_id BIGINT,
  share_minor BIGINT NOT NULL CHECK (share_minor >= 0),
  PRIMARY KEY (expense_id, version, user_id)
);   -- expense_payers is identical with paid_minor > 0

CREATE TABLE ledger_events (
  event_id       BIGINT PRIMARY KEY,
  group_id       BIGINT NOT NULL,
  group_seq      BIGINT NOT NULL,                 -- the commit that produced this row
  user_id        BIGINT NOT NULL,
  currency       CHAR(3) NOT NULL,
  delta_minor    BIGINT NOT NULL,                 -- signed: + the group owes this user more
  source_type    TEXT NOT NULL,   -- 'expense' | 'expense_reversal' | 'settlement' | 'settlement_reversal'
  source_id      BIGINT NOT NULL,
  source_version INT,
  created_at     TIMESTAMPTZ NOT NULL
);
CREATE INDEX ledger_by_group ON ledger_events (group_id, currency, user_id);

CREATE TABLE settlements (
  settlement_id      BIGINT PRIMARY KEY,
  group_id           BIGINT NOT NULL,
  from_user_id       BIGINT NOT NULL, to_user_id BIGINT NOT NULL,
  amount_minor       BIGINT NOT NULL CHECK (amount_minor > 0),
  currency           CHAR(3) NOT NULL,
  method             TEXT NOT NULL,             -- 'manual' | 'provider'
  status             TEXT NOT NULL,             -- 'pending' | 'confirmed' | 'failed' | 'reversed'
  provider_reference TEXT,
  created_at TIMESTAMPTZ NOT NULL, confirmed_at TIMESTAMPTZ
);

Invariants the schema and the write path enforce

(1) Payers sum to the total and shares sum to the total, exactly, for every expense version. (2) The ledger entries of one committed write sum to zero. (3) Therefore, for every group and currency, all ledger entries sum to zero — and any nonzero sum is a bug to investigate, never a rounding tolerance. (4) Ledger rows and old expense versions are never updated or deleted; a correction appends new rows. (5) Money amounts are integers in the currency's minor unit; amounts in different currencies are never added together.

E1 as stored rows

jsonE1 as rows (ids shown in their public string form, user ids shortened). 90000 paise = ₹900.00; 60000 − 30000 − 30000 = 0.
expenses:          { "expense_id": "exp-1001", "group_id": "grp-weekend-trip", "version": 1, "status": "active" }
expense_versions:  { "expense_id": "exp-1001", "version": 1, "description": "Dinner",
                     "total_minor": 90000, "currency": "INR", "split_type": "equal" }
expense_payers:    [ { "user_id": "asha", "paid_minor": 90000 } ]
expense_splits:    [ { "user_id": "asha", "share_minor": 30000 },
                     { "user_id": "ben",  "share_minor": 30000 },
                     { "user_id": "cara", "share_minor": 30000 } ]
ledger_events (group_seq 1):
                   [ { "user_id": "asha", "delta_minor":  60000, "source_type": "expense" },
                     { "user_id": "ben",  "delta_minor": -30000, "source_type": "expense" },
                     { "user_id": "cara", "delta_minor": -30000, "source_type": "expense" } ]
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's ledger effect: Asha +60,000 paise, Ben and Cara −30,000 each, net zero
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)
Entity relationships: groups, memberships, expense head and versions, payers, splits, ledger events, settlements, and the derived/supporting tables added in later stages

Keys, ordering and ownership

group_seq is monotonic per group, not global: each committed write that moves money takes the next value from groups.last_seq, and all ledger rows of that write share it. It gives a total order of a group's history (for replay and for freshness markers such as as_of_seq) without any global coordination. Every money-bearing table carries group_id, which later becomes the partition key (Chapter 17), and every query filters by a group the caller is a member of — ownership is enforced in the query, not assumed from a valid session.

Chapter 08

API Surface

The API separates group management, expense writes, balance reads and settlement, each with its own idempotency and consistency contract. Headers introduced by later stages are shown here once so the whole surface is in one place.

Method and pathPurposeContract
POST /v1/groupsCreate a groupCreator becomes admin
POST /v1/groups/{group_id}/invitations, POST /v1/invitations/{id}/acceptInvite and joinSingle-use, expiring token scoped to one group
POST /v1/groups/{group_id}/expensesCreate an expenseIdempotency-Key required (Ch. 11)
PUT /v1/groups/{group_id}/expenses/{expense_id}Edit (reversal + replacement)If-Match: "<version>" and Idempotency-Key (Ch. 12)
DELETE /v1/groups/{group_id}/expenses/{expense_id}Delete (reversal only)If-Match and Idempotency-Key (Ch. 12)
GET /v1/groups/{group_id}/balances?currency=&min_seq=Group balance sheetReturns as_of_seq; min_seq requests read-your-writes (Ch. 15)
GET /v1/groups/{group_id}/simplify?currency=Suggested repaymentsRead-only; returns the as_of_seq it was computed from
POST /v1/groups/{group_id}/settlementsRecord (manual) or initiate (provider) a settlementIdempotency-Key required (Ch. 16)
GET /v1/groups/{group_id}/activity?cursor=Activity historyOpaque cursor pagination
GET /v1/users/me/balancesDashboard across groupsEventually consistent; per-group as_of_seq (Ch. 14)
POST /v1/payments/webhooks/{provider}Provider status callbacksSignature-verified, deduplicated (Ch. 16)

Creating an expense (E1)

httpThe server computes equal, percentage and weighted shares itself and returns them. `group_seq` lets the client ask for read-your-writes on its next balance read.
POST /v1/groups/grp-weekend-trip/expenses
Authorization: Bearer <access-token>
Idempotency-Key: 6f1d2c9e-0b7a-4c55-9a51-3c2f8e7d1a40

{
  "description": "Dinner",
  "total_minor": 90000,
  "currency": "INR",
  "split_type": "equal",
  "payers": [ { "user_id": "user-asha", "paid_minor": 90000 } ],
  "beneficiaries": ["user-asha", "user-ben", "user-cara"]
}

201 Created
{
  "expense_id": "exp-1001",
  "version": 1,
  "group_seq": 1,
  "splits": [
    { "user_id": "user-asha", "share_minor": 30000 },
    { "user_id": "user-ben",  "share_minor": 30000 },
    { "user_id": "user-cara", "share_minor": 30000 }
  ]
}

Split validation

httpAn exact split that is ₹50 short is rejected before anything is written. The corrected request (Cara 30000) becomes E2.
POST /v1/groups/grp-weekend-trip/expenses
Idempotency-Key: 0c4b7e21-5d8f-4a1e-b3c6-9f2a7d6e5b14

{ "description": "Taxi", "total_minor": 60000, "currency": "INR", "split_type": "exact",
  "payers": [ { "user_id": "user-ben", "paid_minor": 60000 } ],
  "splits": [ { "user_id": "user-asha", "share_minor": 10000 },
              { "user_id": "user-ben",  "share_minor": 20000 },
              { "user_id": "user-cara", "share_minor": 25000 } ] }

422 Unprocessable Entity
{ "error": "SPLIT_SUM_MISMATCH", "expected_total_minor": 60000, "actual_split_sum_minor": 55000 }

Reading balances and suggestions

httpAfter E1 and E2. `as_of_seq` states exactly which commit the numbers reflect; the suggestion moves no money.
GET /v1/groups/grp-weekend-trip/balances?currency=INR&min_seq=2

200 OK
{ "currency": "INR", "as_of_seq": 2,
  "balances": [ { "user_id": "user-asha", "net_minor":  50000 },
                { "user_id": "user-ben",  "net_minor":  10000 },
                { "user_id": "user-cara", "net_minor": -60000 } ] }

GET /v1/groups/grp-weekend-trip/simplify?currency=INR

200 OK
{ "as_of_seq": 2,
  "suggested_repayments": [
    { "from_user_id": "user-cara", "to_user_id": "user-asha", "amount_minor": 50000 },
    { "from_user_id": "user-cara", "to_user_id": "user-ben",  "amount_minor": 10000 } ] }

Recording a settlement (S1)

httpA manual settlement is a member's assertion and is confirmed on creation. A provider settlement starts `pending` (Chapter 16).
POST /v1/groups/grp-weekend-trip/settlements
Idempotency-Key: 9a7e3f10-2b6c-4d8e-a1f5-7c0b9e4d2a63

{ "from_user_id": "user-cara", "to_user_id": "user-asha",
  "amount_minor": 20000, "currency": "INR", "method": "manual" }

201 Created
{ "settlement_id": "set-77", "status": "confirmed", "group_seq": 3 }

Errors and pagination

ErrorHTTPMeaning and client reaction
SPLIT_SUM_MISMATCH / PAYER_SUM_MISMATCH422Input is inconsistent; fix and resubmit
VERSION_CONFLICT409Expense changed since it was loaded; reload, reapply the change, resubmit with the new version
PRECONDITION_REQUIRED428Edit or delete sent without If-Match
IDEMPOTENCY_KEY_CONFLICT422The key was already used for a different request body; a client bug — never retried with the same key
FORBIDDEN_NOT_A_MEMBER403Authenticated, but not a member of this group
CURRENCY_MISMATCH422e.g. a settlement in a currency in which the payer owes nothing in this group

List endpoints (activity, groups) use opaque cursors derived from (created_at, id) rather than numeric offsets, because new rows are appended during pagination and an offset would skip or repeat entries. Recurring expenses (an extension) are created by a scheduler through the same create endpoint, with an idempotency key derived from (recurring_id, period) so a scheduler retry cannot charge a month twice.

Chapter 09

Core Algorithms I: Splits, Rounding and Net Balances

All balance arithmetic happens inside the Expense Service, in integers, with one documented rounding rule. This chapter works the exact numbers; the same functions are reused unchanged by every later stage.

The ledger effect of an expense

For every participant: delta = paid − share. Summed over one expense this equals total paid − total shares, and because validation forces both sums to equal the total, it is exactly zero. That is the mechanism behind the zero-sum invariant — arithmetic forced by two sum checks on every write, not a coincidence.

Split typeInputHow shares are computedValidation
equalBeneficiariestotal ÷ n, remainder by the rounding rulen ≥ 1
exactOne amount per beneficiaryTaken as givenShares sum exactly to the total
percentageBasis points per beneficiary (1% = 100 bps)total × bps ÷ 10,000, remainder by the rounding rulebps sum to exactly 10,000
weightsPositive integer weight per beneficiarytotal × weight ÷ Σweights, remainder by the rounding ruleEvery weight > 0
Payers are validated the same way: contributions are positive and sum exactly to the total.

The rounding rule (largest remainder, deterministic tie-break)

When a share is not a whole number of paise: give every beneficiary the floor of their exact share; the leftover r paise (always fewer than the number of beneficiaries) go one each to the r beneficiaries with the largest fractional remainders; ties are broken by ascending user_id. The result sums exactly to the total, depends only on the inputs (not on request order or map iteration order), and is never off by more than one paisa from the exact share. Percentages are accepted as integer basis points, so no floating-point value ever enters the computation. For an equal split every remainder is the same, so the rule reduces to "the first r members in user_id order get one extra paisa".

ExampleExact shares (paise)FloorsLeftoverFinal shares
₹100.00 equal over 33,333.33 each3,333 × 3 = 9,9991 → asha (first by id)3,334 / 3,333 / 3,333
₹125.50 at 33.33% / 33.33% / 33.34%4,182.915 / 4,182.915 / 4,184.174,182 + 4,182 + 4,184 = 12,5482 → asha, ben (largest remainders .915)4,183 / 4,183 / 4,184
₹1,000 weights 1 : 2 : 220,000 / 40,000 / 40,000exact020,000 / 40,000 / 40,000
Standalone arithmetic for the rule (not part of the running example). Every final row sums exactly to the total: 10,000; 12,550; 100,000.

Net balances across expenses: E1 + E2

A member's group net is simply the sum of their deltas across every expense and settlement — addition, nothing more. E2 (taxi ₹600 paid by Ben, exact shares ₹100 / ₹200 / ₹300) contributes Asha −10,000, Ben +40,000, Cara −30,000.

MemberE1 dinnerE2 taxiNet (paise)
Asha+60,000−10,000+50,000 (+₹500)
Ben−30,000+40,000+10,000 (+₹100)
Cara−30,000−30,000−60,000 (−₹600)
50,000 + 10,000 − 60,000 = 0. Conservation holds across any number of expenses.

A settlement is another zero-sum ledger effect: S1

When Cara pays Asha ₹200, the payer's debt shrinks and the recipient is owed less: Cara +20,000, Asha −20,000. A settlement uses exactly the same ledger mechanism as an expense; only its source record differs.

MemberBefore S1S1After
Asha+50,000−20,000+30,000 (+₹300)
Ben+10,0000+10,000 (+₹100)
Cara−60,000+20,000−40,000 (−₹400)
30,000 + 10,000 − 40,000 = 0.
Key takeaways
  1. 01Each participant's ledger effect is paid − share; validated sums force every expense's effects to total zero.
  2. 02Rounding: floor every share, give leftover minor units to the largest fractional remainders, ties by ascending user_id; percentages are integer basis points.
  3. 03A member's net in a group is the running sum of their ledger deltas; a settlement is just another zero-sum effect.
  4. 04Running example after E1, E2, S1: Asha +₹300, Ben +₹100, Cara −₹400.
Chapter 10

Core Algorithms II: Pairwise Debts, Simplification and the Settlement Record

Raw pairwise debts and simplified repayments are two different, equally valid views of the same net balances. Simplification is a read-only suggestion computed from nets; only a recorded settlement changes a balance.

Raw pairwise debts after E1 and E2

Tracking each expense's obligations pair by pair gives four debts among three people:

FromToAmountSource expense
BenAsha₹300Dinner
CaraAsha₹300Dinner
AshaBen₹100Taxi
CaraBen₹300Taxi
Four raw pairwise debts from two expenses, before simplification.

From net positions to simplified repayments

Netting those four debts gives the positions already computed in Chapter 09: Asha +₹500, Ben +₹100, Cara −₹600. Simplification starts from the net positions, not the pair history, and finds a small set of transfers that zeroes every position: Cara → Asha ₹500 and Cara → Ben ₹100. Four raw debts become two.

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
E1 + E2: four raw pairwise debts collapse to two suggested repayments with the same net effect

Greedy creditor/debtor matching

Split members into creditors (positive net) and debtors (negative net). Repeatedly match the largest creditor with the largest debtor (ties by user_id), transfer the smaller of the two amounts, and repeat until everyone is at zero. Each step zeroes at least one member, so the result has at most (creditors + debtors − 1) transfers and runs in O(n log n) with two heaps. Here: Cara (−600) with Asha (+500) → ₹500; then Cara (−100) with Ben (+100) → ₹100.

Greedy is small, not guaranteed minimal

The true minimum number of transfers equals n − k, where k is the largest number of disjoint subgroups whose nets each sum to zero; finding that partition is NP-hard in general. Greedy can miss it. Five members with nets M1 +₹400, M2 +₹300, M3 −₹300, M4 −₹200, M5 −₹200: greedy pays M3→M1 ₹300, M4→M2 ₹200, M5→M1 ₹100, M5→M2 ₹100 — four transfers. The optimum pairs M3→M2 ₹300 and lets M4 and M5 each pay M1 ₹200 — three transfers. For typical groups (3–20 members) greedy is fast, explainable and usually optimal or one transfer away; an exact search is possible for very small groups if the product wants it. This design only ever claims "few", never "fewest".

Simplification preserves net positions, not provenance

Simplification may suggest that Cara pays Ben even though Ben's taxi debt and Asha's dinner debt arose separately. That is allowed: the invariant it preserves is every member's net position, not who originally owed whom. Members can follow a suggestion, ignore it, or settle differently; balances update correctly from whatever settlement is actually recorded. Suggestions are computed per currency from the current balances and returned with the as_of_seq they reflect, so a suggestion computed before a newer expense is recognisably out of date.

The settlement record

A repayment is its own record (settlements), never an edit to an expense. Recording one writes ledger entries +amount for the payer and −amount for the recipient in the same transaction (S1 in Chapter 09). A manual settlement is a member's assertion and takes effect on creation; a provider-backed settlement takes effect only when the provider confirms it (Chapter 16). Either way the settlement is permanent history: a mistaken or refunded settlement is undone by a reversal, not deleted.

Key takeaways
  1. 01Raw pairwise debts and simplified repayments are consistent views of the same net balances.
  2. 02Greedy largest-creditor/largest-debtor matching yields at most (creditors + debtors − 1) transfers — few, but not guaranteed minimal; the exact minimum is NP-hard in general.
  3. 03Simplification preserves net positions, not who originally owed whom, and never changes a stored balance.
  4. 04A settlement is its own record with its own zero-sum ledger entries; mistakes are reversed, never deleted.
Chapter 11 · Stage 1

Correct Writes I: One Transaction and Idempotency Keys

Stage 0 can leave half-written expenses and records the same dinner twice when a phone retries. Both are permanent errors in everyone's history, so they are fixed before anything is scaled.

Problem 1: a write must be all or nothing

An expense is several rows — head, version, payers, splits, ledger entries, audit entry. If they are committed separately, a crash in between leaves an expense with no balance effect, or ledger entries with no expense. No compensation logic is needed to fix this: everything lives in one relational database, so one local transaction does it. A saga or distributed transaction would add failure modes without adding safety.

Problem 2: clients retry

Mobile networks time out after the server has committed; offline queues replay on reconnect; users double-tap. Retrying is correct client behavior, so the server must make a retry harmless. Alternatives considered: duplicate heuristics (same payer, amount and description within a minute) are wrong both ways — two genuine ₹150 coffees are not duplicates, and a retry an hour later after reconnecting is. Client-generated expense ids dedupe creates but not edits or settlements, and cannot tell a retry from a different request reusing the id. An idempotency key with a request fingerprint, recorded in the same transaction as the write handles every money-moving endpoint and distinguishes "same request again" from "different request, same key".

The Stage 1 write transaction

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, the expense rows and their ledger entries commit together; only then is 201 returned
sqlStage 1 create path. Membership and validation failures roll back everything, including the key claim.
BEGIN;
-- 1. claim the key; UNIQUE (actor_user_id, group_id, operation, idempotency_key)
INSERT INTO idempotency_records
  (actor_user_id, group_id, operation, idempotency_key, request_hash, created_at, expires_at)
VALUES (:actor, :group, 'create_expense', :key, :sha256_of_canonical_body, now(), now() + interval '7 days');
-- unique violation → ROLLBACK and resolve against the existing record (table below)

-- 2. authorize, then serialize this group's money-moving writes and take the next sequence
SELECT 1 FROM memberships WHERE group_id = :group AND user_id = :actor AND left_at IS NULL;
UPDATE groups SET last_seq = last_seq + 1 WHERE group_id = :group RETURNING last_seq;   -- :seq

-- 3. the fact (shares computed and validated in the service before this point)
INSERT INTO expenses ...; INSERT INTO expense_versions ...;
INSERT INTO expense_payers ...; INSERT INTO expense_splits ...;

-- 4. its balance effect: one row per participant, all tagged group_seq = :seq
INSERT INTO ledger_events (...) VALUES (... 'expense', :seq ...), (...), (...);
INSERT INTO audit_entries ...;

-- 5. remember the outcome for replays
UPDATE idempotency_records SET response_status = 201, response_body = :json, resource_id = :expense_id
WHERE actor_user_id = :actor AND group_id = :group AND operation = 'create_expense' AND idempotency_key = :key;
COMMIT;   -- the 201 is sent only after this succeeds

How a retry is resolved

SituationWhat the server does
First requestClaims the key, commits the expense and the stored response, returns 201
Retry after commit, same bodyUnique violation on the key → loads the record, hashes match → returns the stored 201 unchanged. No new rows, no second ledger effect, no second activity entry
Retry while the first is still runningThe second INSERT waits on the first transaction's uncommitted key. If the first commits, the second replays its response; if the first rolls back, the second proceeds as a fresh request
First attempt crashed before COMMITNothing was written, not even the key, so the retry executes normally
Same key, different body422 IDEMPOTENCY_KEY_CONFLICT; nothing is written. A silent replay would hide a client bug and drop the user's real change
Same key after the 7-day retentionTreated as a new request. Clients must not hold unsent writes longer than the window; the app surfaces very old queued entries for the user to confirm
The key is scoped to (actor, group, operation): the same raw key from another user or for another group is a different request. The fingerprint is a SHA-256 of the canonicalised path and body.

Why the group row is locked

UPDATE groups SET last_seq = last_seq + 1 does two jobs. It gives every money-moving commit in a group a gap-free sequence number, group_seq, which later stages use for freshness markers (as_of_seq), ordering and replay. And it serializes concurrent writes in the same group, so every later per-group update in the transaction happens under one lock and cannot deadlock against another write in the group. The cost is that writes within one group run one at a time — a few milliseconds each, while ordinary groups write a few times an hour. Hot groups are the exception and are handled in Chapter 17. Alternatives such as a global sequence or timestamps either need cross-group coordination or give ties and gaps under clock skew.

What changes in the request flow, and what remains

The architecture is unchanged — still Client → Expense Service → one database — but every money-moving request now carries Idempotency-Key and is answered only after one atomic commit. Still open: concurrent edits can overwrite each other, and edits and deletes still rewrite history (Chapter 12). Reads still aggregate the whole ledger (Chapter 13).

Chapter 12 · Stage 1

Correct Writes II: Versioned Edits, Reversals and Deletes

Members correct expenses all the time, often two at once. Stage 1 makes a correction safe under concurrency and turns it into new history instead of erased history.

Problem: the lost update

Two members open the same expense, a ₹1,200 grocery bill currently at version 4. Each edits a different field and saves the whole form:

TimeClient AClient BStored result with a plain UPDATE
t0Loads version 4Loads version 4₹1,200, "Groceries"
t1Saves total ₹1,250₹1,250
t2Saves description "Groceries + soap" with the form's old total ₹1,200₹1,200 — A's correction is silently lost

Alternatives considered: last write wins is exactly the bug above. A pessimistic edit lock held while a member has the form open spans human think time and needs timeouts for abandoned screens. `SELECT … FOR UPDATE` inside the request only protects one server request, not the client's read-then-write across two requests. Field-level merging works for descriptions but is dangerous for amounts and splits. Optimistic concurrency fits: conflicts are rare, nothing is held between requests, and a conflict is surfaced instead of hidden.

Optimistic concurrency with an expected version

httpClient B's save after A committed version 5. B reloads version 5, reapplies its description change and resubmits with If-Match: "5".
PUT /v1/groups/grp-weekend-trip/expenses/exp-2040
If-Match: "4"
Idempotency-Key: 3b9f0e62-8c1d-4f7a-9e25-b6d4a0c7f318

{ "description": "Groceries + soap", "total_minor": 120000, "split_type": "equal", ... }

409 Conflict
{ "error": "VERSION_CONFLICT", "current_version": 5 }
Swipe to pan
exp-2040 Groceries ₹1,200 — both editors loaded version 4Edit A: PUT If-Match "4"amount ₹1,250Edit B: PUT If-Match "4"split change1 row updated → version 5reversal + new entries · 2000 rows → 409 VERSION_CONFLICTcurrent_version: 5 · reloadcommits first4 is staleUPDATE expenses SET version = version + 1 WHERE expense_id = … AND version = 4 AND status = 'active'
Two edits based on version 4: the first commits version 5, the second gets 409 VERSION_CONFLICT instead of overwriting it

The check is a compare-and-set inside the transaction: UPDATE expenses SET version = version + 1 WHERE expense_id = :id AND version = :expected AND status = 'active'. Zero rows updated means someone else committed first (or the expense was deleted), so the transaction rolls back and returns 409 with the current version. The idempotency key still matters for edits: without it, a retry of a successful edit would itself get 409, because its own first attempt moved the version.

Corrections are reversal plus replacement

An edit never updates ledger rows or old versions. In the same transaction as the version check, it appends a new expense_versions row with its payers and splits, appends reversal ledger entries that exactly negate the previous version's entries, and appends the new version's entries — all under a new group_seq. The balance ends up exactly as if the corrected amount had been entered originally, and the full story — original, reversal, replacement — stays in the ledger.

sqlEdit transaction. Locks are always taken in the same order — expense row, then group row — so two writes cannot deadlock.
BEGIN;
-- idempotency claim as in Chapter 11, then:
UPDATE expenses SET version = version + 1
WHERE expense_id = :id AND version = :expected AND status = 'active';   -- 0 rows → ROLLBACK, 409
UPDATE groups SET last_seq = last_seq + 1 WHERE group_id = :group RETURNING last_seq;   -- :seq
INSERT INTO expense_versions / expense_payers / expense_splits ... (version = :expected + 1);

-- reversal: the exact negation of the previous version's entries
INSERT INTO ledger_events (event_id, group_id, group_seq, user_id, currency, delta_minor,
                           source_type, source_id, source_version, created_at)
SELECT next_event_id(), group_id, :seq, user_id, currency, -delta_minor,
       'expense_reversal', source_id, source_version, now()
FROM ledger_events
WHERE source_type = 'expense' AND source_id = :id AND source_version = :expected;

-- replacement: the new version's entries
INSERT INTO ledger_events (...) VALUES (... 'expense', :id, :expected + 1, :seq ...);
INSERT INTO audit_entries ...;
COMMIT;
MemberVersion 1 entriesReversalVersion 2 entriesNet change
Asha+60,000−60,000+64,000+4,000
Ben−30,000+30,000−32,000−2,000
Cara−30,000+30,000−32,000−2,000
What-if: E1 corrected from ₹900 to ₹960 (equal split). Every column sums to zero. The running example keeps ₹900.

Deleting an expense

A delete is the same transaction without a replacement: version check, status = 'deleted', reversal entries, audit entry. Nothing is erased. Settlements already recorded are separate facts and are left untouched, so the arithmetic may now point the other way. If E1 were deleted after S1, the nets would become Asha −₹300 (she still owes her ₹100 taxi share and received ₹200 she was no longer owed), Ben +₹400, Cara −₹100. The system never silently "forgives" or drops a settlement because the expense that motivated it was removed.

Who may edit

By default an expense's creator and the group's admins may edit or delete it. That is an explicit authorization check against memberships before the transaction starts, not a client-side rule. A product can relax it for small trusted groups.

What changes, and what remains

Edits and deletes now carry If-Match and Idempotency-Key; the ledger is strictly append-only; the activity feed can show "Dinner ₹900" followed by "corrected to ₹960", which is exactly what members want in a dispute. Every Stage 0 correctness gap is closed. What remains is cost: every balance read still aggregates the group's whole history (Chapter 13).

Key takeaways
  1. 01Edits and deletes require If-Match: "<version>"; a stale version gets 409 VERSION_CONFLICT, never a silent overwrite.
  2. 02A correction appends reversal entries for the old version and entries for the new one under a new group_seq; ledger rows are never updated or deleted.
  3. 03A delete is a reversal without a replacement; existing settlements stay and may flip a balance's direction.
  4. 04Idempotency keys apply to edits too, so a retried successful edit replays instead of failing with 409.
Chapter 13 · Stage 2

The Read Bottleneck: Aggregating the Ledger on Every Read

After Stage 1 the design is correct, but every balance read still sums the group's entire ledger. The capacity numbers from Chapter 05 show why that cost cannot stay on the read path.

What the numbers say

textIllustrative arithmetic from the Chapter 05 assumptions.
Peak balance reads              ~2,315 /s  (≈ 1,160 group sheets + 1,160 dashboards)
Dashboard fan-out               ~2 groups per user → ~2,320 group aggregations /s
Group aggregations at peak      ≈ 3,500 /s

Ledger rows per average group   ≈ 2,300 after 1 year, ≈ 4,600 after 2 (+~6 /day, forever)
Rows scanned at peak, year 1    ≈ 3,500 × 2,300 ≈ 8 million /s
Rows scanned at peak, year 2    ≈ 16 million /s — and the most-read groups are the longest

Reading stored per-member nets  ≈ 3,500 × 5 rows ≈ 17,500 rows /s, independent of history
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)
Aggregation cost grows with every day of history; a maintained per-member balance is read in constant time

Writes stay flat at ~580/s, but read cost grows linearly with history and multiplies with the 4:1 read ratio. The busiest groups are also the longest-lived (households) and the most-read, so the average understates it. Latency degrades first: a long household group's sheet or a dashboard over several groups starts missing the 100 ms p99 read target, and the scans compete with writes for the same primary.

Alternatives considered

OptionWhat it fixesWhere it falls short
Covering index on (group_id, currency, user_id) including delta_minorIndex-only scans, fewer page readsStill O(history) per read; buys months, not a different growth curve
Read replicasMoves scans off the primaryStill O(history); replica lag silently breaks read-your-writes; more hardware for the same wasted work
Cache in front of the aggregationHot groups hit the cacheEvery write invalidates it; misses and cold dashboards still pay O(history)
Periodic snapshot + delta (store nets as of seq N, sum newer rows)Bounds the scan to recent rowsA snapshot job with its own correctness problems; read cost still varies
Balance projection updated in the write transactionO(members) reads; always equal to the ledger; read-your-writes by construction~5 extra row updates per write, under the group lock the transaction already holds
Balance projection updated asynchronously from eventsRemoves even that write costThe writer's own balance becomes eventually consistent — the one view users check right after writing

Decision: a balance projection maintained in the same transaction

Group balances are group-scoped, live in the same database as the ledger, and change only when the group's ledger changes — under a lock the write already holds. So the cheapest correct option is to maintain them inside the Stage 1 transaction. The read becomes a lookup of one row per member, and because the projection commits atomically with the ledger it can never be ahead of or behind it on the primary.

sqlStage 2. Applying deltas is safe here because the deltas commit or roll back together with the ledger entries they summarize, and idempotency (Chapter 11) prevents a retried request from producing a second transaction.
CREATE TABLE balance_projection (
  group_id BIGINT, user_id BIGINT, currency CHAR(3),
  net_minor        BIGINT NOT NULL,
  last_applied_seq BIGINT NOT NULL,
  PRIMARY KEY (group_id, currency, user_id)
);

-- inside the Chapter 11/12 transaction, once per participant, after the ledger insert
INSERT INTO balance_projection (group_id, currency, user_id, net_minor, last_applied_seq)
VALUES (:group, :currency, :user, :delta, :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;                     -- the member's new net, reused by Stage 3 events

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

The aggregation query is not deleted: it becomes the reconciliation check. A background job periodically recomputes SUM(delta_minor) per member for a sample of groups (and every group over time) and compares it with balance_projection, and checks that each group's ledger sums to zero per currency (Chapter 17). The projection is derived and can always be rebuilt from the ledger.

What remains

Three limits are left, none of them about the group sheet itself. Side effects — notifications, activity, the dashboard — still have no reliable trigger: doing them inside the transaction couples the write to slow systems, and doing them after commit loses them on a crash. The dashboard fans out to every group a user belongs to, and once groups are spread across partitions (Chapter 17) that fan-out becomes cross-partition. All reads still hit the primary, and hot groups produce bursts. Stage 3 addresses all three.

Key takeaways
  1. 01Aggregating the ledger per read costs O(history): ~8M rows/s at peak after one year, doubling the next — while writes stay flat.
  2. 02Indexes, replicas, caches and snapshots slow the growth but keep the O(history) read.
  3. 03balance_projection is updated inside the write transaction: O(members) reads, never out of step with the ledger on the primary, read-your-writes by construction.
  4. 04The old aggregation query becomes a reconciliation check; the projection stays rebuildable from the ledger.
Chapter 14 · Stage 3

Transactional Outbox, Event Bus and Derived Views

Notifications, activity and the cross-group dashboard must react to every committed write, reliably and without slowing it down. That needs a way to publish "this commit happened" that cannot disagree with the database.

Problem: the dual write

ApproachFailure
Call the notifier and update the dashboard inside the transactionA slow push provider holds the group lock and stretches write latency; if the transaction then rolls back, the notification has already gone out
Publish to a message bus after COMMITA crash between commit and publish loses the event forever; a bus outage either fails acknowledged writes or drops events
Distributed transaction across database and busPoorly supported by brokers, slow, and makes writes unavailable whenever the bus is
Change data capture (tail the database log)Valid; but events are row changes tied to the schema. It is a good transport for the relay below, not a replacement for explicit domain events
Transactional outboxChosen: the event is a row in the same transaction, so it exists if and only if the write committed

How the outbox works

The write transaction inserts one outbox row per commit: outbox_id (also the event id), group_id, group_seq, event_type (expense.created, expense.updated, expense.deleted, settlement.confirmed, …), the payload, and published_at = NULL. The Outbox Relay repeatedly claims a batch of unpublished rows (FOR UPDATE SKIP LOCKED, so several relay workers can run), publishes each to the Event Bus with key group_id, and then sets published_at. If the relay crashes after publishing but before marking, the row is published again on restart. Delivery is therefore at-least-once — duplicates are normal, and several relay workers can also publish a group's events out of order. Published rows are purged after 7 days.

Swipe to pan
one write transactionexpense rows + ledger_eventsbalance_projectionoutbox row (event_id, group_seq)Outbox RelayFOR UPDATE SKIP LOCKEDEvent Buskey group_idConsumersdedupe event_id / seq guardpollat least onceCrash after publish, before marking published → the row is sent again. Duplicates and reordering areexpected; consumers make them harmless. Published rows are purged after 7 days.
The expense rows and the outbox row commit in one transaction; the relay publishes afterwards, retriably and at least once
jsonE2's event. `net_after_minor` comes from the RETURNING clause of the Stage 2 projection update in the same transaction.
{
  "event_id": "ob-90412",
  "event_type": "expense.created",
  "group_id": "grp-weekend-trip",
  "group_seq": 2,
  "source": { "expense_id": "exp-1002", "version": 1 },
  "currency": "INR",
  "effects": [
    { "user_id": "user-asha", "delta_minor": -10000, "net_after_minor":  50000 },
    { "user_id": "user-ben",  "delta_minor":  40000, "net_after_minor":  10000 },
    { "user_id": "user-cara", "delta_minor": -30000, "net_after_minor": -60000 }
  ]
}

The Event Bus

A partitioned, replicated log (Kafka-class). Keying by group_id keeps a group's events in one partition, in the order the relay published them, and lets consumers scale by partition. Retention of 7 days lets a consumer replay recent history after a bug fix; anything older is rebuilt from the ledger, which remains the only permanent record.

The consumer contract

Every consumer assumes duplicates and reordering, and makes each update idempotent: it deduplicates by event_id or guards on group_seq, writes its effect and its progress in one local transaction, and commits its bus offset only after that. Processing is therefore effectively once — at-least-once delivery plus idempotent application — which is the only honest claim for a distributed pipeline.

The User Balance Projection (dashboard)

The dashboard needs every group's net for one user. A Projection Consumer maintains user_balance_summary, keyed by user so a dashboard is a single-key read wherever the group data lives. Because each event carries the member's absolute net_after_minor with its group_seq, the consumer can apply events idempotently and in any order:

sqlIdempotent and order-tolerant. Applying deltas instead would double-count duplicates and need strict ordering and gap handling.
INSERT INTO user_balance_summary (user_id, group_id, currency, net_minor, last_applied_seq)
VALUES (:user, :group, :currency, :net_after, :group_seq)
ON CONFLICT (user_id, group_id, currency) DO UPDATE
SET net_minor = EXCLUDED.net_minor, last_applied_seq = EXCLUDED.last_applied_seq
WHERE user_balance_summary.last_applied_seq < EXCLUDED.last_applied_seq;
-- a duplicate or an older event matches no row and changes nothing
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 (sequence guard) → User Balance Projection; an older or duplicate event is a no-op

Skipping an intermediate state is harmless because a newer absolute value supersedes it. An event cannot be lost permanently, because the outbox row stays until it is published. The dashboard target is p99 ≤ 2 s from commit, measured as relay lag plus consumer lag; each group on the dashboard carries its as_of_seq so the client can tell how fresh it is.

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

What was deliberately not added

No separate simplification service — simplification is a stateless computation over current balances. No microservice per split type — split math is a library inside the Expense Service. No distributed transaction for an expense write — the single local transaction plus the outbox is the whole unit of work, and everything downstream is asynchronous and idempotent. The write path still depends only on the database: if the relay, bus or consumers are down, expenses are still accepted and group balances are still correct.

What remains

The group balance sheet is still read from the primary at up to ~2,315 reads/s with hot-group bursts, and the system now has views with different freshness. Chapter 15 adds the cache and states the consistency contract for every view.

Chapter 15 · Stage 3

Versioned Cache, Read Paths and Consistency Guarantees

Once a cache and asynchronous views exist, every read needs an explicit answer to two questions: how stale can this be, and how does the caller know?

Problem: hot reads on the primary

A group's balance sheet changes a few times an hour but is read constantly while a trip is under way, and peaks concentrate on a few hot groups. The projection read is cheap, yet thousands of them per second still share the primary with writes. Read replicas add lag the caller cannot see. A plain TTL cache shows a balance from before the latest expense for up to the TTL, with no way to tell. A versioned cache keeps the hit rate and makes staleness visible and bounded.

How the versioned cache works

Key balance:{group_id}:{currency} holds the balance sheet together with its as_of_seq. Read: if an entry exists and its as_of_seq is at least the caller's min_seq (when one is sent), return it; otherwise read balance_projection from the primary and store the result only if no newer entry is present (an atomic set-if-newer on as_of_seq). Invalidate: the Expense Service deletes the key right after commit (fast, best effort), and the Projection Consumer deletes it again when the commit's event arrives (reliable, because it is driven by the outbox). Safety TTL: 300 s, so a lost invalidation cannot serve old data indefinitely.

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

One race remains and is worth stating: a reader that loaded the projection just before a commit can repopulate the key just after the fast-path delete with the older sheet. The event-driven delete then removes it — typically within a second or two — and the safety TTL bounds the worst case. The writer is never affected, because it reads with min_seq.

Read-your-writes for the writer

Every write response returns group_seq. The client sends it as min_seq on its next balance read, and any cached sheet older than that is bypassed in favor of the primary projection, which already includes the write. Other members, and the writer's other devices, may see the previous sheet for that short window, always labeled with its as_of_seq. The client can also merge its own just-committed effect into the dashboard optimistically, marked as pending until the dashboard's as_of_seq catches up — a display aid, never a stored balance.

Activity history

Activity history (GET /activity, Chapter 08) is paginated with an opaque cursor derived from (created_at, audit_id) rather than a raw numeric offset, because new activity is always being appended and a numeric offset would skip or duplicate entries as the underlying set grows during pagination — a classic, avoidable bug in any append-heavy, offset-paginated feed.

The consistency contract

ViewServed fromGuaranteeFreshness shown as
Ledger, expense detail, settlement statusPrimaryStrongly consistent; authoritative—
Writer's group balance after a writeCache if as_of_seq ≥ min_seq, else primary projectionRead-your-writes on the device that wroteas_of_seq
Group balance for other members and devicesVersioned cacheNormally ~1–2 s behind a commit; worst case the 300 s safety TTL if an invalidation is lostas_of_seq / "updated … ago"
Suggested repaymentsComputed from one balance snapshotConsistent with the as_of_seq returnedas_of_seq
Dashboard across groupsUser Balance ProjectionEventually consistent; target p99 ≤ 2 sPer-group as_of_seq
Notifications (Stage 4)Notification ServiceProcessed effectively once; delivery best-effort—
Every "~" is a monitored target, not a guarantee. The ledger stays authoritative: when any view disagrees with it, the view is wrong.
Key takeaways
  1. 01Cache key balance:{group_id}:{currency} stores the sheet with its as_of_seq; fills are set-if-newer; invalidation is fast-path delete plus event-driven delete; safety TTL 300 s.
  2. 02Writes return group_seq; reads with min_seq bypass any older cache entry — read-your-writes for the writer.
  3. 03Other viewers may briefly see the previous sheet, always labeled with as_of_seq; the bound is a monitored target, not a guarantee.
  4. 04Each view states where it is served from and how fresh it is; the ledger is always the authority.
Chapter 16 · Stage 4

Notifications, Multi-Currency and Provider-Confirmed Settlement

Three requirements from Chapter 03 are still unserved: telling members when something affects them, groups that spend in more than one currency, and paying inside the app. Each plugs into the Stage 3 architecture without changing the write transaction's shape.

Notifications as an event consumer

Problem: members must hear about expenses and settlements that affect them, at up to ~2,315 notifications/s at peak (Chapter 05), through push providers that are slow and sometimes down. Approach: a Notification Service consumes the Event Bus. For each event it creates one notification per affected member other than the actor, with a unique constraint on (event_id, recipient_user_id) so a redelivered event cannot notify twice, then sends pushes with retries and backoff. Per-user preferences and digests for very busy groups are applied here. What changes: nothing on the write path — a push outage delays notifications only. The group's activity history needs no consumer: it is read directly from audit_entries in the group's own database, so it is never behind the ledger.

Multi-currency: separate ledgers that share a group

Problem: a trip spends in INR at home and USD abroad. ₹1,000 and $20 cannot be added without a rate, and any rate is a policy choice that changes daily. Simplest approach and where it breaks: convert everything to the group's default currency at entry time. This silently picks a rate and a date for every member, makes balances change meaning when the rate is revised, and cannot be undone cleanly. Chosen: every expense and settlement keeps its own currency, and currency is part of every balance key.

balance_projection and user_balance_summary are keyed by currency, so INR and USD positions are separate rows that each sum to zero across the group. The balance sheet shows one block per currency; simplification runs per currency; a settlement must be in a currency in which the payer owes the recipient something (otherwise 422 CURRENCY_MISMATCH). Each currency's minor unit comes from a currency table (INR and USD have 2 decimals, JPY 0, KWD 3), and the Chapter 09 rounding rule applies per currency.

A "show everything in INR" view is computed at display time from a CurrencyRateSnapshot (rate, as-of time, source) and labeled as a converted estimate; it is never stored as a balance. If members agree to settle a USD debt in rupees, that is an explicit, member-initiated conversion record: it writes USD entries that close the USD positions and INR entries that open the equivalent INR positions at the recorded rate — zero-sum in each currency, never automatic.

Provider-confirmed settlement

Problem: paying in the app means a third party moves the money. The provider — not this system and not the client — is the authority on whether money moved, and its answer arrives later, asynchronously, possibly more than once and out of order. Rule: a balance moves only when the provider has confirmed the payment. A pending payment is shown separately and never reduces anyone's balance; a failed payment never counts as settled.

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

Initiation. POST /settlements with method: provider commits a pending settlement (with its idempotency record) and nothing else — no ledger entries, no sequence number. A Payment Service then calls the provider outside any database transaction, using the settlement_id as the provider's idempotency key, so a retried call cannot create a second charge. The client receives 201 {status: "pending"} plus whatever the provider needs for the payer to approve.

Confirmation. The provider calls POST /v1/payments/webhooks/{provider}. Webhooks are untrusted input until verified: the Payment Service checks the signature and timestamp, then processes the event in one transaction:

sqlWebhook handling: deduplicated by provider event id, guarded on the current state, and atomic with the balance effect.
BEGIN;
INSERT INTO provider_events (provider, provider_event_id, settlement_id, payload, received_at)
VALUES (...);                         -- UNIQUE (provider, provider_event_id); duplicate → ROLLBACK, reply 200

UPDATE settlements SET status = 'confirmed', confirmed_at = now()
WHERE settlement_id = :sid AND status = 'pending'
  AND amount_minor = :amount AND currency = :currency;   -- 0 rows → already final or mismatched → flag, no effect

UPDATE groups SET last_seq = last_seq + 1 WHERE group_id = :group RETURNING last_seq;
INSERT INTO ledger_events (... 'settlement' ...);         -- payer +amount, recipient −amount
-- balance_projection upserts and the outbox row, exactly as for an expense
COMMIT;

A failed webhook moves pending → failed with the same guard and writes no entries. A late or out-of-order webhook (failed arriving after confirmed) matches no row and is flagged for reconciliation rather than applied. A refund or chargeback after confirmation moves confirmed → reversed and writes settlement_reversal entries, exactly like an expense reversal. Because webhooks can be lost, a reconciliation job asks the provider about every settlement still pending after 15 minutes and compares the provider's daily report with confirmed settlements; on any disagreement the provider's record of money movement wins, and the correction is written as new ledger entries.

Manual settlement is an assertion

A manual settlement (S1) is confirmed when it is recorded, because it records something that happened outside the system — cash or a bank transfer. It is a member's assertion, not a verified payment: it is visible to both parties in the activity history and can be disputed, in which case it is reversed. The UI never presents it as equivalent to a provider-confirmed payment.

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

What remains

The design is now feature-complete. What is left is running it: relay and consumer failures, rebuilding derived views, hot groups, storage growth, disaster recovery, abuse and privacy (Chapters 17–18).

Key takeaways
  1. 01Notifications consume events and deduplicate on (event_id, recipient); a push outage never touches the write path.
  2. 02Every balance is keyed by currency; currencies are never netted; FX is display-only and labeled; conversion is an explicit, zero-sum record.
  3. 03Provider settlements: pending → confirmed | failed, confirmed → reversed. Balances move only on a verified, deduplicated, state-guarded confirmation.
  4. 04The provider is authoritative for money movement; a reconciliation job covers lost or late webhooks.
Chapter 17 · Stage 5

Production Readiness: Failures, Rebuilds, Hot Groups and Partitioning

Every mechanism added so far has a failure mode. Production readiness means knowing, for each one, what the system does on its own, how it recovers, and what to watch.

Failure handling

MechanismFailureSystem responseRecovery and what to monitor
Outbox RelayCrashes or the Event Bus is downWrites still commit and group balances stay correct; unpublished outbox rows accumulate; dashboard and notifications fall behindRelay resumes from the oldest unpublished row. Alert on the age of the oldest unpublished row (e.g. > 30 s)
Relay / busAn event is published twice or out of orderConsumers deduplicate by event_id or guard on group_seq; older events are no-opsDuplicate rate per consumer; a rising rate points at relay restarts
Projection ConsumerLags, or a bug writes wrong valuesDashboard is stale (as_of_seq shows it) or wrongFix, then replay from the bus (7 days) or rebuild from balance_projection. Consumer lag per partition
balance_projectionDrifts from the ledger (a bug, a manual edit)Reconciliation job finds a mismatch with SUM(delta_minor)Rebuild the group's rows under its lock. Mismatch count must be 0
LedgerA group's entries do not sum to zero in a currencyZero-sum check alerts; writes continueInvestigate before any repair; corrections are new entries. Zero-sum violations must be 0
CacheInvalidation lost, or the cache is downSafety TTL bounds staleness; on outage reads fall back to the primaryHit ratio; cache-bypass rate; primary read load
Payment webhooksLost, duplicated, late or forgedSignature check, provider_events dedupe, state guardsPending settlements older than 15 min; signature failures
Database primaryNode failureSynchronous in-region standby is promoted (RTO minutes); no acknowledged write is lost on a single failureReplication lag; failover drills

Rebuild and repair

Every derived view can be rebuilt from the ledger, which is why the ledger is append-only and group_seq is gap-free per group. `balance_projection`: for one group, take the group lock, recompute SUM(delta_minor) per member and currency, replace the rows and set last_applied_seq to groups.last_seq. For a very large group, build into a shadow table up to a known sequence, then apply the newer entries under the lock and swap. `user_balance_summary`: replay current nets from balance_projection through the same sequence-guarded upsert; it is idempotent, so it can run while live events continue. Cache: flushing it is always safe.

Swipe to pan
ledger_eventsgroup_seq 1 … NRebuild Jobreplay in seq ordershadow tablenets as of seq Ncompare → swapapply seq > N, then cut overLive events while the rebuild runsseq 40seq 41seq 42seq 41 againlast_applied_seq = 42→ duplicate is a no-opSequence-guarded, absolute-value upserts make replay and redelivery idempotent:applying the same history twice gives the same balances, never doubled ones
Repair: replay the ledger in group_seq order into a shadow projection, compare, swap; redelivered events are no-ops

Hot groups

Writes in one group serialize on the group row (Chapter 11). With transactions of a few milliseconds, 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, so its ceiling is nearer a few dozen writes/s. That is the price of a gap-free per-group order, and it is far above what real groups do. Mitigations: keep the transaction short (no network calls inside it — already true), insert ledger and projection rows in batches, rate-limit writes per group at the gateway (429 with Retry-After), let the versioned cache absorb read bursts, and 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, freshness markers and replay correct.

Partitioning by group

Throughput did not force partitioning; storage and blast radius do. At ~3 TB a year of rows plus indexes, backups, restores and maintenance on one primary get slow, and one bad migration or hot spot affects everyone. The partition key is group_id, because every money-moving transaction is scoped to a single group:

DataWhere it lives
groups, memberships, expenses and versions, payers, splits, ledger_events, settlements, balance_projection, idempotency_records, outbox, audit_entriesThe group's shard. Every write is a single-shard local transaction; each shard has its own relay
users, the user → groups index, user_balance_summaryKeyed by user in a separate store; maintained from events, which is why the dashboard is asynchronous
provider_eventsLooked up by settlement id, which resolves to its group's shard through the group directory

A group directory maps group_id to a shard (hash-based by default, with explicit overrides so a hot group can be moved). New groups are placed by the directory; nothing in the write path ever spans two groups, so no cross-shard transaction is needed. Closed or long-dormant groups are archived: their ledger moves to cheaper storage and their final balance_projection rows stay online.

Disaster recovery

Each shard has a synchronous in-region standby (no acknowledged write lost on a single-node failure, failover in minutes) and an asynchronous cross-region replica. Cross-region RPO is therefore not zero: after a regional failover the last seconds of acknowledged writes may be missing. Clients retry queued writes with the same idempotency keys, and the payment reconciliation job re-checks recent provider confirmations. Point-in-time backups are restored in regular drills. The bus and caches are not backed up; they are re-derived from the outbox and the ledger.

API Gateway

There are now several services behind one public surface — Expense Service, Payment Service webhooks, dashboard reads — and per-user and per-group rate limits are needed against retry storms and abuse. An API Gateway takes over TLS termination, access-token validation, request size limits and rate limiting. It authenticates; it does not authorize. Whether a user may touch a group is still checked by the service that owns the group's data, on every request.

Observability

Golden signals per endpoint (write p99 < 300 ms, group balance read p99 < 100 ms), plus the signals specific to this domain: 409 VERSION_CONFLICT and 422 IDEMPOTENCY_KEY_CONFLICT rates, idempotent replay rate, oldest unpublished outbox row, consumer lag per partition, cache hit ratio and bypass rate, projection-vs-ledger mismatches and zero-sum violations (both must stay at 0), pending settlements by age, and webhook signature failures. Each gets its own alert; a generic "errors elevated" alarm hides which mechanism is failing.

Key takeaways
  1. 01Writes depend only on the database: relay, bus, cache or consumer outages delay derived views but never lose or corrupt balances.
  2. 02balance_projection, user_balance_summary and the cache are rebuildable from the ledger; zero-sum and projection-drift checks must stay at 0.
  3. 03A hot group is bounded by its group lock (~100–200 short writes/s); rate limits, short transactions and the cache keep it healthy.
  4. 04Partition by group_id for storage and blast radius; per-user data lives in a separate store fed by events. Cross-region RPO is seconds, not zero.
Chapter 18 · Stage 5

Security, Privacy and Data Retention

A shared-expense app holds other people's money obligations and their spending patterns. Authorization, auditability and deletion policy are design requirements, not launch-week additions.

Membership authorization on every object access

Every request that reads or writes an expense, settlement or balance checks that the authenticated user is a current member of that group — or a former member, for read access to the history they were part of. Being authenticated proves identity, not entitlement. The check runs on the server for every request; group and expense ids are never treated as access tokens, because ids are often guessable.

Invitations

Invitation tokens are single-use, expire, and are scoped to one group and, for email invites, one address. An expired or already-used token is rejected, never silently honoured, and accepting one grants access to that group only.

Abuse prevention

The gateway rate-limits expense creation, invitations and settlements per user and per group, which stops both runaway client retry loops (already harmless thanks to idempotency, but still costly) and deliberate floods. Patterns such as rapidly joining and leaving groups, or creating and reversing many expenses, feed an abuse-detection pipeline that sits outside the ledger logic.

Encryption and receipts

TLS everywhere in transit; encryption at rest for the database and receipt storage. Receipts can contain personal data (card digits, medical purchases), so they are stored in object storage behind the same group-membership check as the expense and served through short-lived signed URLs, never public links.

Audit trail as a security property

Because audit_entries and the ledger are append-only, a compromised account's edits and reversals remain visible after the fact and cannot be erased by whoever made them. Support-tool corrections go through the same reversal-plus-replacement path, with the operator's identity recorded.

Deletion requests and financial-record retention

A user's request to delete personal data collides with the other members' right to an explainable history: their balances depend on that user's expenses and settlements. The practical resolution is to anonymize, not erase: keep the expense, split and ledger rows, replace the user's identifying profile fields with a placeholder, and remove receipts containing their personal data. This is a deliberate, documented policy decision — made before the first request arrives.

Scope note: this is engineering design guidance, not legal advice. Whether anonymization satisfies a particular erasure request, and how long financial records must be retained, depends on jurisdiction and needs legal review. For example, Regulation (EU) 2016/679 (GDPR) provides a right to erasure in Article 17 but also exceptions, including for compliance with a legal obligation.

Export

A group's export is generated from the same authoritative tables the application uses, so it can never drift from what the app shows.

Chapter 19

Final Architecture and Request Flows

Every component in the final design was added at a specific stage to remove a specific limit. The diagram is the Stage 0 whiteboard with those additions in place.

Swipe to pan
Final Architecture — Group-Partitioned Ledger, Derived and Rebuildable ViewsThe gateway authenticates; services authorize; every money write is one local transaction on its group shardLedger DB shardsby group_idgroups · membershipsexpenses · splitsledger_eventssettlements · auditidempotency_recordsbalance_projectionoutboxprovider_eventsClientmobile · webAPI Gatewayauthn · rate limitsNEWExpense Servicetxn + outbox · readsBalance Cacheas_of_seq · TTL 300 sUser Balance Projectionper user · asyncProjection Consumerseq guard · cache DELNotification Servicededupe event_idOutbox Relayat least onceEvent Buskey group_id · 7 dPayment Providerexternal · authorityPayment Serviceverified webhooksFX Rate Snapshotsdisplay onlyReconciliationzero-sum · providerRebuild Jobsledger → viewsNEWStandby + Replicassync · cross-regionNEWset-if-newer · DELpay · webhookScaleLedger DB sharded by group_id, sync standby + async cross-region replica, rebuild and reconciliation jobs.RuleThe ledger is the source of truth; projections, cache, dashboard and notifications are derived.
Final architecture: gateway, Expense Service and Payment Service over group-partitioned Ledger DB shards; outbox relay, event bus, projections, cache, notifications and reconciliation around them
ComponentResponsibilityStage
Client (mobile, web)Records expenses with idempotency keys, sends If-Match on edits and min_seq on reads; displays as_of freshness0
Expense ServiceMembership checks, split math, the single write transaction (ledger, balance_projection, outbox, idempotency), balance and simplify reads0–3
Ledger DB (relational, sharded by group_id)Source of truth: expenses and versions, splits, ledger_events, settlements, audit; plus balance_projection, idempotency_records, outbox0, 1, 2, 3, 5
Balance CacheGroup balance sheets keyed by group and currency, versioned by as_of_seq; safety TTL 300 s3
Outbox RelayPublishes outbox rows to the Event Bus at least once3
Event BusPartitioned log keyed by group_id; 7-day retention3
Projection Consumer + User Balance ProjectionPer-user dashboard rows via sequence-guarded upserts; cache invalidation3
Notification ServicePer-recipient notifications deduplicated by (event_id, recipient); push delivery4
Payment ServiceProvider calls with settlement_id as idempotency key; verified, deduplicated webhooks; settlement transitions4
Payment Provider (external)Authoritative for whether money moved4
FX rate snapshotsDisplay-only conversions, labeled with rate, time and source4
Reconciliation and rebuild jobsZero-sum and projection-drift checks, projection rebuilds, provider reconciliation2, 4, 5
API GatewayTLS, token validation, per-user and per-group rate limits; no group authorization5
Standby and replicasIn-region synchronous standby; cross-region asynchronous replica5

Request flows

Swipe to pan
ClientIdempotency-KeyAPI Gatewaytoken · rate limitExpense Servicecompute sharesLedger DB · one transaction1. idempotency claim · membership2. group_seq = last_seq + 13. expense, version, payers, splits4. ledger_events (Σ = 0)5. balance_projection upserts6. outbox row · stored responseCOMMIT → 201 {group_seq}After commit (never inside the transaction)• best-effort DEL of balance:{group_id}:{currency} in the Balance Cache• Outbox Relay → Event Bus → Projection Consumer (dashboard, cache DEL) and Notification Service — at least once• a retry with the same key replays the stored 201; a crash before COMMIT leaves nothing behind
Create-expense write path: one transaction commits the expense, ledger entries, balance projection, outbox row and idempotency record before 201

Create expense. Client → API Gateway (token, rate limit) → Expense Service: compute and validate shares → one transaction on the group's shard: claim the idempotency key, check membership, take the next group_seq, insert expense, version, payers, splits and ledger entries, update balance_projection, insert the outbox row and the stored response → commit → 201 with group_seq → best-effort cache delete. Asynchronously: relay → bus → Projection Consumer (dashboard row, cache delete) and Notification Service. A retry with the same key replays the stored 201.

Edit or delete. The same transaction, plus the If-Match compare-and-set on expenses.version (409 on mismatch), reversal entries for the previous version and, for an edit, entries for the new one.

Read group balances. Gateway → Expense Service → Balance Cache; hit only if as_of_seq ≥ min_seq, otherwise balance_projection on the primary and set-if-newer into the cache. Simplify runs greedy matching on that same snapshot and returns its as_of_seq. Dashboard reads user_balance_summary for the user, one row per group and currency.

Settle. Manual: one transaction writes a confirmed settlement and its ledger entries, like an expense. Provider: a pending settlement is committed; the Payment Service calls the provider; the verified webhook confirms it in one transaction that writes the ledger entries, projection and outbox row — or marks it failed with no entries. Reconciliation resolves anything still pending after 15 minutes.

Repair. Reconciliation jobs compare projections with ledger sums and check zero-sum per group and currency; rebuild jobs regenerate any derived view from the ledger.

How the architecture evolved

StageAddsLimit it removes
0 — Simplest design (Ch. 06)Client → Expense Service → one relational DB; balances summed on read—
1 — Correct writes (Ch. 11–12)One transaction per write, idempotency keys with fingerprints, per-group sequence, If-Match versions, reversal-based correctionsPartial writes, duplicates on retry, lost updates, erased history
2 — Read bottleneck (Ch. 13)balance_projection maintained in the write transactionBalance reads that cost O(history)
3 — Evolution (Ch. 14–15)Outbox, relay, event bus, User Balance Projection, versioned cache, explicit consistency contractLost or coupled side effects, cross-group dashboard, hot reads on the primary
4 — Capabilities (Ch. 16)Notification Service, per-currency balances, Payment Service with provider-confirmed settlementUnserved notification, multi-currency and in-app payment requirements
5 — Production (Ch. 17–18)Rebuild and reconciliation jobs, hot-group limits, partitioning by group, standby and DR, API Gateway, security and privacy policyOperational failure, growth, abuse
Chapter 20

Guarantees and Honest Limits

A precise boundary is a stronger answer than a broad claim. This is what the design guarantees, what it only targets, and where it deliberately stops.

GuaranteeMechanismBoundary
Every expense's shares and payers sum exactly to its totalInteger minor units, server-side computation, validation inside the write transactionPer currency; rounding moves at most one minor unit per member, by a fixed rule
Each group's ledger sums to zero per currencyZero-sum per write, enforced by the same validation; continuous checkA violation means a bug; it is detected and investigated, not silently tolerated
A write is all or nothingOne local transaction on the group's shardHolds because no write ever spans groups or shards
A retried write has at most one effectIdempotency record (actor, group, operation, key) with request fingerprint, in the same transactionWithin the 7-day retention window; a reused key with a different body is rejected, not replayed
No silent lost update on an expenseIf-Match compare-and-set on expenses.versionThe loser must reload and reapply; the system does not merge
Every balance is explainableAppend-only ledger, reversal-plus-replacement corrections, audit entriesPersonal data may be anonymized; financial facts are kept
The writer sees their own write in the group balanceProjection in the write transaction; min_seq bypasses older cache entriesOn the device that wrote; other viewers may briefly see the previous sheet
Settlements move balances only when confirmedpending / confirmed / failed / reversed, verified and deduplicated webhooks, state guardsManual settlements are assertions, confirmed when recorded and disputable

What the design only targets

Dashboard and notification freshness (~2 s at p99), cache staleness for other viewers (~1–2 s, at worst the 300 s safety TTL), read and write latency, and availability are monitored targets, not guarantees. Every surface that can lag says how fresh it is (as_of_seq).

Where this design stops

Simplification is not minimal: greedy gives few transfers, not provably the fewest. One group's write rate is bounded by its group lock — the price of a gap-free order. Cross-region failover can lose the last seconds of acknowledged writes (RPO > 0); recovery relies on client retries with the same keys and payment reconciliation. Idempotency keys expire after 7 days. Event delivery is at-least-once; correctness comes from idempotent consumers, not from the pipeline. Manual settlements are not verified by anyone but the members. No cross-currency netting happens unless members record an explicit conversion. And the product is not a payment processor, a bank or a general ledger.

Key takeaways
  1. 01The relational ledger is the single source of truth at every stage; every other store is derived and rebuildable.
  2. 02Correctness guarantees come from one local transaction per write, scoped idempotency, versioned edits and an append-only ledger.
  3. 03Freshness of derived views is an explicit, monitored budget shown to users, not a promise.
  4. 04The honest limits — non-minimal simplification, per-group write ceiling, cross-region RPO, key retention — are design choices, stated up front.