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.
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.
| Event | What happened | Net after event (Asha / Ben / Cara) |
|---|---|---|
| E1 — Dinner | Asha pays ₹900, split equally (₹300 each) | +₹600 / −₹300 / −₹300 |
| E2 — Taxi | Ben pays ₹600, exact split ₹100 / ₹200 / ₹300 | +₹500 / +₹100 / −₹600 |
| S1 — Repayment | Cara pays Asha ₹200 (recorded manually) | +₹300 / +₹100 / −₹400 |
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.
- 01An expense (who incurred what cost) and a settlement (money that moved to reduce a debt) are different records and are never conflated.
- 02A balance is derived arithmetic over recorded expenses and settlements, not an independently stored fact.
- 03Money is stored in integer minor units (paise for INR), never floating point.
- 04Running example: Weekend Trip — E1 dinner ₹900 (Asha), E2 taxi ₹600 (Ben), S1 Cara repays Asha ₹200; final nets +₹300 / +₹100 / −₹400.
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.
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.
| Member | Paid | Share | Net (paid − share) |
|---|---|---|---|
| Asha | ₹900 | ₹300 | +₹600 |
| Ben | ₹0 | ₹300 | −₹300 |
| Cara | ₹0 | ₹300 | −₹300 |
- 01Ledger entries (signed, append-only, zero-sum per expense) are the authoritative record; balances are derived from them.
- 02Net balance = paid for others − own shares + settlements paid − settlements received, per group and per currency.
- 03A group's nets in one currency always sum to exactly zero.
- 04Pairwise debts, simplified repayments and projections are derived views, never the stored source of truth.
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.
| Capability | Essential MVP | Advanced extension |
|---|---|---|
| Group membership | Create, invite, join, leave, basic admin role | Sub-groups, group-level default currency policy, bulk invites |
| Splits | Equal, exact, percentage, shares | Itemized receipt-line splitting, tax/tip proportional splitting |
| Balances | Net balance, pairwise balance, group balance sheet | Historical balance-over-time charts |
| Simplification | Greedy repayment suggestion (few transfers, not guaranteed minimal) | User-constrained simplification (e.g. "never suggest I pay X") |
| Settlement | Manual "mark as settled" | Payment-provider-confirmed settlement, partial settlement scheduling |
| History & discovery | Chronological activity feed, basic search | Full-text search, CSV/PDF export, spend analytics |
- 01Core scope: groups and membership, expenses with versioned edits and deletes, balances and simplification, settlement, history and notifications.
- 02All four split types (equal, exact, percentage, weights) are core requirements.
- 03Edits and deletes are auditable, versioned operations — never silent overwrites.
- 04Receipts, recurring expenses and provider payments are explicit extensions.
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).
| Requirement | Target (illustrative) | Delivered by |
|---|---|---|
| Financial correctness | Shares and payers sum exactly to the total; every group's ledger sums to zero per currency | Server-side split math and validation (Ch. 09), one write transaction (Ch. 11), continuous zero-sum checks (Ch. 17) |
| Idempotent writes | A retried create, edit, delete or settlement has at most one effect per scoped Idempotency-Key | Idempotency records in the write transaction (Ch. 11) |
| No lost updates | Two concurrent edits of one expense cannot both silently succeed | Optimistic versions, 409 on mismatch (Ch. 12) |
| Auditability | Every balance is explainable from immutable history | Append-only ledger; corrections as reversal + replacement (Ch. 07, 12) |
| Authorization | Every object access checks group membership, not just login | Membership check in the Expense Service (Ch. 06, 18) |
| Durability | No acknowledged expense is lost on a single-node failure (in-region RPO ≈ 0); cross-region RPO of seconds | Synchronous in-region standby, async cross-region replica, PITR backups (Ch. 17) |
| Write latency | Expense write p99 < 300 ms | Short single-database transaction, no external calls inside it (Ch. 11, 14) |
| Group balance read | p99 < 100 ms at peak; read-your-writes for the member who just wrote | Balance projection + versioned cache (Ch. 13, 15) |
| Async freshness | Dashboard and notifications reflect a commit within ~2 s at p99 (a target, monitored, not a guarantee) | Outbox → event bus → consumers (Ch. 14, 16) |
| Availability | 99.9% monthly for expense writes and balance reads | Standby failover; writes do not depend on the bus, cache or notifications (Ch. 17) |
| Recoverability | Any derived view can be rebuilt from the ledger | Replay/rebuild jobs (Ch. 17) |
| Privacy | Members see only their groups; receipts are protected PII | Membership checks on every query, access-controlled storage (Ch. 18) |
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.
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
| Assumption | Value |
|---|---|
| Registered users / daily active users | 10 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 reads | 20 million / day — about half group balance sheets, half dashboards across a user's groups |
| Peak multiplier | 10× 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
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 peakHot-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
| Observation | Architectural consequence |
|---|---|
| ~580 write transactions/s at peak | One 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, forever | Recomputing 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 total | Storage, not throughput, eventually forces partitioning by group and archiving dormant groups (Ch. 17). |
| Notification fan-out runs at read-rate scale | Notification delivery must be asynchronous and must never sit in the expense write transaction (Ch. 14, 16). |
- 01Peak: ~580 writes/s and ~2,315 balance reads/s (4:1); all figures are illustrative assumptions.
- 02Ledger: ~25M rows/day, ~1.8 TB/year; an average group accumulates ~2,300 ledger rows a year.
- 03The first real limit is read cost growing with history, not write throughput.
- 04Hot-group peaks, not system-wide averages, size the per-group write and read paths.
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.
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:
-- 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.
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.
| Table | Key | Role |
|---|---|---|
| groups | group_id | Scope 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 |
| expenses | expense_id | Head 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_events | event_id; ordered by (group_id, group_seq) | Source of truth for balances: one signed delta per participant per committed write; append-only |
| settlements | settlement_id | Repayments: from, to, amount, currency, method (manual | provider), status |
| audit_entries | audit_id | Who did what and when, with before/after snapshots; append-only |
| users, invitations | user_id; invitation_id | Identity and single-use, expiring invitations |
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
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" } ]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.
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 path | Purpose | Contract |
|---|---|---|
| POST /v1/groups | Create a group | Creator becomes admin |
| POST /v1/groups/{group_id}/invitations, POST /v1/invitations/{id}/accept | Invite and join | Single-use, expiring token scoped to one group |
| POST /v1/groups/{group_id}/expenses | Create an expense | Idempotency-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 sheet | Returns as_of_seq; min_seq requests read-your-writes (Ch. 15) |
| GET /v1/groups/{group_id}/simplify?currency= | Suggested repayments | Read-only; returns the as_of_seq it was computed from |
| POST /v1/groups/{group_id}/settlements | Record (manual) or initiate (provider) a settlement | Idempotency-Key required (Ch. 16) |
| GET /v1/groups/{group_id}/activity?cursor= | Activity history | Opaque cursor pagination |
| GET /v1/users/me/balances | Dashboard across groups | Eventually consistent; per-group as_of_seq (Ch. 14) |
| POST /v1/payments/webhooks/{provider} | Provider status callbacks | Signature-verified, deduplicated (Ch. 16) |
Creating an expense (E1)
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
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
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)
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
| Error | HTTP | Meaning and client reaction |
|---|---|---|
| SPLIT_SUM_MISMATCH / PAYER_SUM_MISMATCH | 422 | Input is inconsistent; fix and resubmit |
| VERSION_CONFLICT | 409 | Expense changed since it was loaded; reload, reapply the change, resubmit with the new version |
| PRECONDITION_REQUIRED | 428 | Edit or delete sent without If-Match |
| IDEMPOTENCY_KEY_CONFLICT | 422 | The key was already used for a different request body; a client bug — never retried with the same key |
| FORBIDDEN_NOT_A_MEMBER | 403 | Authenticated, but not a member of this group |
| CURRENCY_MISMATCH | 422 | e.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.
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 type | Input | How shares are computed | Validation |
|---|---|---|---|
| equal | Beneficiaries | total ÷ n, remainder by the rounding rule | n ≥ 1 |
| exact | One amount per beneficiary | Taken as given | Shares sum exactly to the total |
| percentage | Basis points per beneficiary (1% = 100 bps) | total × bps ÷ 10,000, remainder by the rounding rule | bps sum to exactly 10,000 |
| weights | Positive integer weight per beneficiary | total × weight ÷ Σweights, remainder by the rounding rule | Every weight > 0 |
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".
| Example | Exact shares (paise) | Floors | Leftover | Final shares |
|---|---|---|---|---|
| ₹100.00 equal over 3 | 3,333.33 each | 3,333 × 3 = 9,999 | 1 → 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.17 | 4,182 + 4,182 + 4,184 = 12,548 | 2 → asha, ben (largest remainders .915) | 4,183 / 4,183 / 4,184 |
| ₹1,000 weights 1 : 2 : 2 | 20,000 / 40,000 / 40,000 | exact | 0 | 20,000 / 40,000 / 40,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.
| Member | E1 dinner | E2 taxi | Net (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) |
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.
| Member | Before S1 | S1 | After |
|---|---|---|---|
| Asha | +50,000 | −20,000 | +30,000 (+₹300) |
| Ben | +10,000 | 0 | +10,000 (+₹100) |
| Cara | −60,000 | +20,000 | −40,000 (−₹400) |
- 01Each participant's ledger effect is paid − share; validated sums force every expense's effects to total zero.
- 02Rounding: floor every share, give leftover minor units to the largest fractional remainders, ties by ascending user_id; percentages are integer basis points.
- 03A member's net in a group is the running sum of their ledger deltas; a settlement is just another zero-sum effect.
- 04Running example after E1, E2, S1: Asha +₹300, Ben +₹100, Cara −₹400.
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:
| From | To | Amount | Source expense |
|---|---|---|---|
| Ben | Asha | ₹300 | Dinner |
| Cara | Asha | ₹300 | Dinner |
| Asha | Ben | ₹100 | Taxi |
| Cara | Ben | ₹300 | Taxi |
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.
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.
- 01Raw pairwise debts and simplified repayments are consistent views of the same net balances.
- 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.
- 03Simplification preserves net positions, not who originally owed whom, and never changes a stored balance.
- 04A settlement is its own record with its own zero-sum ledger entries; mistakes are reversed, never deleted.
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
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 succeedsHow a retry is resolved
| Situation | What the server does |
|---|---|
| First request | Claims the key, commits the expense and the stored response, returns 201 |
| Retry after commit, same body | Unique 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 running | The 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 COMMIT | Nothing was written, not even the key, so the retry executes normally |
| Same key, different body | 422 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 retention | Treated 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 |
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).
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:
| Time | Client A | Client B | Stored result with a plain UPDATE |
|---|---|---|---|
| t0 | Loads version 4 | Loads version 4 | ₹1,200, "Groceries" |
| t1 | Saves total ₹1,250 | ₹1,250 | |
| t2 | Saves 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
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 }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.
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;| Member | Version 1 entries | Reversal | Version 2 entries | Net 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 |
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).
- 01Edits and deletes require If-Match: "<version>"; a stale version gets 409 VERSION_CONFLICT, never a silent overwrite.
- 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.
- 03A delete is a reversal without a replacement; existing settlements stay and may flip a balance's direction.
- 04Idempotency keys apply to edits too, so a retried successful edit replays instead of failing with 409.
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
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 historyWrites 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
| Option | What it fixes | Where it falls short |
|---|---|---|
| Covering index on (group_id, currency, user_id) including delta_minor | Index-only scans, fewer page reads | Still O(history) per read; buys months, not a different growth curve |
| Read replicas | Moves scans off the primary | Still O(history); replica lag silently breaks read-your-writes; more hardware for the same wasted work |
| Cache in front of the aggregation | Hot groups hit the cache | Every 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 rows | A snapshot job with its own correctness problems; read cost still varies |
| Balance projection updated in the write transaction | O(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 events | Removes even that write cost | The 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.
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;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.
- 01Aggregating the ledger per read costs O(history): ~8M rows/s at peak after one year, doubling the next — while writes stay flat.
- 02Indexes, replicas, caches and snapshots slow the growth but keep the O(history) read.
- 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.
- 04The old aggregation query becomes a reconciliation check; the projection stays rebuildable from the ledger.
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
| Approach | Failure |
|---|---|
| Call the notifier and update the dashboard inside the transaction | A 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 COMMIT | A crash between commit and publish loses the event forever; a bus outage either fails acknowledged writes or drops events |
| Distributed transaction across database and bus | Poorly 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 outbox | Chosen: 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.
{
"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:
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 nothingSkipping 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.
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.
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.
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
| View | Served from | Guarantee | Freshness shown as |
|---|---|---|---|
| Ledger, expense detail, settlement status | Primary | Strongly consistent; authoritative | — |
| Writer's group balance after a write | Cache if as_of_seq ≥ min_seq, else primary projection | Read-your-writes on the device that wrote | as_of_seq |
| Group balance for other members and devices | Versioned cache | Normally ~1–2 s behind a commit; worst case the 300 s safety TTL if an invalidation is lost | as_of_seq / "updated … ago" |
| Suggested repayments | Computed from one balance snapshot | Consistent with the as_of_seq returned | as_of_seq |
| Dashboard across groups | User Balance Projection | Eventually consistent; target p99 ≤ 2 s | Per-group as_of_seq |
| Notifications (Stage 4) | Notification Service | Processed effectively once; delivery best-effort | — |
- 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.
- 02Writes return group_seq; reads with min_seq bypass any older cache entry — read-your-writes for the writer.
- 03Other viewers may briefly see the previous sheet, always labeled with as_of_seq; the bound is a monitored target, not a guarantee.
- 04Each view states where it is served from and how fresh it is; the ledger is always the authority.
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.
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:
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.
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).
- 01Notifications consume events and deduplicate on (event_id, recipient); a push outage never touches the write path.
- 02Every balance is keyed by currency; currencies are never netted; FX is display-only and labeled; conversion is an explicit, zero-sum record.
- 03Provider settlements: pending → confirmed | failed, confirmed → reversed. Balances move only on a verified, deduplicated, state-guarded confirmation.
- 04The provider is authoritative for money movement; a reconciliation job covers lost or late webhooks.
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
| Mechanism | Failure | System response | Recovery and what to monitor |
|---|---|---|---|
| Outbox Relay | Crashes or the Event Bus is down | Writes still commit and group balances stay correct; unpublished outbox rows accumulate; dashboard and notifications fall behind | Relay resumes from the oldest unpublished row. Alert on the age of the oldest unpublished row (e.g. > 30 s) |
| Relay / bus | An event is published twice or out of order | Consumers deduplicate by event_id or guard on group_seq; older events are no-ops | Duplicate rate per consumer; a rising rate points at relay restarts |
| Projection Consumer | Lags, or a bug writes wrong values | Dashboard is stale (as_of_seq shows it) or wrong | Fix, then replay from the bus (7 days) or rebuild from balance_projection. Consumer lag per partition |
| balance_projection | Drifts 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 |
| Ledger | A group's entries do not sum to zero in a currency | Zero-sum check alerts; writes continue | Investigate before any repair; corrections are new entries. Zero-sum violations must be 0 |
| Cache | Invalidation lost, or the cache is down | Safety TTL bounds staleness; on outage reads fall back to the primary | Hit ratio; cache-bypass rate; primary read load |
| Payment webhooks | Lost, duplicated, late or forged | Signature check, provider_events dedupe, state guards | Pending settlements older than 15 min; signature failures |
| Database primary | Node failure | Synchronous in-region standby is promoted (RTO minutes); no acknowledged write is lost on a single failure | Replication 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.
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:
| Data | Where it lives |
|---|---|
| groups, memberships, expenses and versions, payers, splits, ledger_events, settlements, balance_projection, idempotency_records, outbox, audit_entries | The group's shard. Every write is a single-shard local transaction; each shard has its own relay |
| users, the user → groups index, user_balance_summary | Keyed by user in a separate store; maintained from events, which is why the dashboard is asynchronous |
| provider_events | Looked 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.
- 01Writes depend only on the database: relay, bus, cache or consumer outages delay derived views but never lose or corrupt balances.
- 02balance_projection, user_balance_summary and the cache are rebuildable from the ledger; zero-sum and projection-drift checks must stay at 0.
- 03A hot group is bounded by its group lock (~100–200 short writes/s); rate limits, short transactions and the cache keep it healthy.
- 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.
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.
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.
| Component | Responsibility | Stage |
|---|---|---|
| Client (mobile, web) | Records expenses with idempotency keys, sends If-Match on edits and min_seq on reads; displays as_of freshness | 0 |
| Expense Service | Membership checks, split math, the single write transaction (ledger, balance_projection, outbox, idempotency), balance and simplify reads | 0–3 |
| Ledger DB (relational, sharded by group_id) | Source of truth: expenses and versions, splits, ledger_events, settlements, audit; plus balance_projection, idempotency_records, outbox | 0, 1, 2, 3, 5 |
| Balance Cache | Group balance sheets keyed by group and currency, versioned by as_of_seq; safety TTL 300 s | 3 |
| Outbox Relay | Publishes outbox rows to the Event Bus at least once | 3 |
| Event Bus | Partitioned log keyed by group_id; 7-day retention | 3 |
| Projection Consumer + User Balance Projection | Per-user dashboard rows via sequence-guarded upserts; cache invalidation | 3 |
| Notification Service | Per-recipient notifications deduplicated by (event_id, recipient); push delivery | 4 |
| Payment Service | Provider calls with settlement_id as idempotency key; verified, deduplicated webhooks; settlement transitions | 4 |
| Payment Provider (external) | Authoritative for whether money moved | 4 |
| FX rate snapshots | Display-only conversions, labeled with rate, time and source | 4 |
| Reconciliation and rebuild jobs | Zero-sum and projection-drift checks, projection rebuilds, provider reconciliation | 2, 4, 5 |
| API Gateway | TLS, token validation, per-user and per-group rate limits; no group authorization | 5 |
| Standby and replicas | In-region synchronous standby; cross-region asynchronous replica | 5 |
Request flows
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
| Stage | Adds | Limit 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 corrections | Partial writes, duplicates on retry, lost updates, erased history |
| 2 — Read bottleneck (Ch. 13) | balance_projection maintained in the write transaction | Balance reads that cost O(history) |
| 3 — Evolution (Ch. 14–15) | Outbox, relay, event bus, User Balance Projection, versioned cache, explicit consistency contract | Lost 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 settlement | Unserved 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 policy | Operational failure, growth, abuse |
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.
| Guarantee | Mechanism | Boundary |
|---|---|---|
| Every expense's shares and payers sum exactly to its total | Integer minor units, server-side computation, validation inside the write transaction | Per currency; rounding moves at most one minor unit per member, by a fixed rule |
| Each group's ledger sums to zero per currency | Zero-sum per write, enforced by the same validation; continuous check | A violation means a bug; it is detected and investigated, not silently tolerated |
| A write is all or nothing | One local transaction on the group's shard | Holds because no write ever spans groups or shards |
| A retried write has at most one effect | Idempotency record (actor, group, operation, key) with request fingerprint, in the same transaction | Within the 7-day retention window; a reused key with a different body is rejected, not replayed |
| No silent lost update on an expense | If-Match compare-and-set on expenses.version | The loser must reload and reapply; the system does not merge |
| Every balance is explainable | Append-only ledger, reversal-plus-replacement corrections, audit entries | Personal data may be anonymized; financial facts are kept |
| The writer sees their own write in the group balance | Projection in the write transaction; min_seq bypasses older cache entries | On the device that wrote; other viewers may briefly see the previous sheet |
| Settlements move balances only when confirmed | pending / confirmed / failed / reversed, verified and deduplicated webhooks, state guards | Manual 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.
- 01The relational ledger is the single source of truth at every stage; every other store is derived and rebuildable.
- 02Correctness guarantees come from one local transaction per write, scoped idempotency, versioned edits and an append-only ledger.
- 03Freshness of derived views is an explicit, monitored budget shown to users, not a promise.
- 04The honest limits — non-minimal simplification, per-group write ceiling, cross-region RPO, key retention — are design choices, stated up front.