Splitwise System Design Trade-offs and Architectural Decisions
Splitwise system design trade-offs: for each decision, the constraint, realistic options, selection criteria and when another option wins, sized for 10M users, ~580 expense writes/s and ~2,315 balance reads/s at peak. Includes ledger versus mutable balances, projections versus compute-on-read and outbox versus direct publish.
Decision Map: What Is Load-Bearing and What Is Situational
Not every decision carries the same weight. A load-bearing decision protects an invariant — exact shares, zero-sum per currency, at most one effect per retried write, no lost update, explainable history, balances that move only on confirmed money — and getting it wrong produces a permanent error in someone's balance. A situational decision is a sound choice for this workload that a different scale or product could reasonably flip.
| # | Decision | Choice | Weight | Stage |
|---|---|---|---|---|
| 01 | Starting shape and storage engine | One service over one relational database | Situational (storage: load-bearing) | Stage 0 |
| 02 | Source of truth | Append-only ledger; balances derived | Load-bearing | Data model |
| 03 | Money arithmetic and rounding | Integer minor units, largest remainder | Load-bearing | Algorithms |
| 04 | What a balance is | Per-member net deltas; pairwise view derived | Situational | Algorithms |
| 05 | Debt simplification | Greedy, on demand, a suggestion | Situational | Algorithms |
| 06 | Retry safety | Scoped idempotency key + fingerprint | Load-bearing | Stage 1 |
| 07 | Concurrency control | If-Match versions + per-group row lock | Load-bearing | Stage 1 |
| 08 | Corrections and deletes | Reversal + replacement; delete = reversal | Load-bearing | Stage 1 |
| 09 | Balance reads | Projection updated in the write transaction | Load-bearing at scale | Stage 2 |
| 10 | Event publication and delivery | Outbox, at-least-once, idempotent consumers | Load-bearing | Stage 3 |
| 11 | Read caching and consistency | Versioned cache, min_seq read-your-writes | Situational | Stage 3 |
| 12 | Cross-group dashboard | Event-fed per-user view; no cross-group netting | Situational | Stage 3 |
| 13 | Currency isolation | Separate balances per currency; FX display-only | Load-bearing | Stage 4 |
| 14 | Settlement | Manual assertion + provider-confirmed state machine | Load-bearing | Stage 4 |
| 15 | Partitioning | By group_id via a group directory | Load-bearing at scale | Stage 5 |
| 16 | Audit retention vs privacy | Anonymize, do not erase | Situational (policy) | Stage 5 |
| 17 | Secondary decisions | Push + refresh, object storage, build on double-entry principles | Secondary | Stages 4–5 |
Closely related choices are discussed together rather than as separate decisions: storage engine with service topology, rounding with money representation, simplification timing with the algorithm, identifier generation with idempotency, deletes with corrections, write-path timing with balance reads, delivery guarantee with event publication, read consistency with caching, and manual recording with the settlement state machine. Each has its own sub-heading.
Starting Shape: One Service over One Relational Database
Stage 0 (Complete Design, Chapter 06) needs a shape that can already enforce "shares sum to the total" and "each write sums to zero". Both span several rows — expense head, version, payers, splits, ledger entries — so the first question is where a multi-row write can be atomic.
| Option | Benefits | Limits |
|---|---|---|
| Modular monolith (one Expense Service with internal modules) over one relational database | Every money-moving write is one local transaction; constraints and integer types enforce invariants in the database; extraction later follows existing seams | Module boundaries hold only by discipline; the whole service scales as one unit |
| Microservices per concept (expense, ledger, balance, settlement) from day one | Independent deployment and scaling | An expense must update ledger and balance across network calls — the dual-write problem before any scale demands it |
| Document store for the financial core | Flexible schema; horizontal scaling built in | Multi-document transactions are weaker or costlier, yet every write is a multi-row invariant |
| Relational core + document store for side data | Flexible storage for data with no money invariant | A second system to operate, for data that fits fine in the first |
Selection criteria. Whether the core write fits in one local transaction; whether load actually requires separate scaling (~580 writes/s at peak fits one primary); how many systems the team operates.
Choice for this workload. One Expense Service over one PostgreSQL-class database. Later stages add components only where a measured limit demands them — the Notification Service as an event consumer and the Payment Service as the provider adapter (Stage 4), and an API Gateway at Stage 5 that terminates TLS, validates tokens and rate-limits, but does not authorize: group membership is still checked by the service that owns the data.
When another option wins. A separate service is worth its network boundary when its load or failure profile diverges — the Payment Service isolates provider calls and webhooks, the Notification Service isolates slow push providers. A document store is fine for non-financial side data (preferences, receipt metadata) that never enters a balance.
Remaining risk. One primary holds all groups until storage and blast radius justify partitioning (Decision 15).
Why relational is the load-bearing half
Topology is situational; the storage engine is not. The invariants are cross-row by definition — an expense's splits must equal its total, and its ledger entries must sum to zero — so the engine must commit several rows atomically and reject partial writes. A product with no cross-row money invariant does not exist in this space, so there is no realistic workload that flips this half.
Built in: Complete Design, Chapter 06 for Stage 0 and Complete Design, Chapter 19 for which component was added at which stage.
Source of Truth: Append-Only Ledger vs Mutable Balances
Every later decision depends on what the system treats as authoritative after a dispute, a correction or a crash. Members need to see why a balance is what it is, and derived views must be rebuildable (Complete Design, Chapter 07).
| Option | Benefits | Limits |
|---|---|---|
| Mutable balance rows, incremented in place | Reads are a row lookup | No record of how a balance got there; a correction means guessing the inverse; a bug leaves a number nothing can explain or rebuild |
| Mutable balances plus a separate audit log | Looks auditable | The log and the balance can drift, because the balance is never derived from the log |
| Append-only ledger_events (one signed delta per participant per committed write), balances derived | Replayable and auditable; corrections are new rows; every projection can be rebuilt from scratch | A balance needs aggregation or a maintained projection (Decision 09); history grows forever |
Selection criteria. Can every balance be explained and rebuilt from stored facts? Can a correction be expressed without destroying the old state?
Choice for this workload. ledger_events is the only source of truth, ordered per group by a gap-free group_seq. balance_projection, user_balance_summary and the Balance Cache are derived and disposable; when any of them disagrees with the ledger, the view is wrong.
When another option wins. Nothing in this product class. What legitimately varies is how old history is stored — dormant groups can move their ledger to cheaper storage while their final projection rows stay online — not whether the ledger remains the truth.
Remaining risk. Growth: ~25M ledger rows (~5 GB) a day. Reads must not aggregate it (Decision 09), and archival and partitioning handle the storage (Decision 15).
Built in: Complete Design, Chapter 07 (schema and invariants) and Complete Design, Chapter 17 (rebuild and repair).
Money Arithmetic: Integer Minor Units and a Deterministic Rounding Rule
Shares must sum to the total exactly, and recomputing a stored expense must give the same shares. That needs an exact number type and one rule for leftover minor units (Complete Design, Chapter 09).
| Option | Benefits | Limits |
|---|---|---|
| Binary floating point | Native everywhere | Most decimal fractions are inexact; shares can fail to sum to the total, and errors compound |
| Arbitrary-precision decimal | Exact base-10 arithmetic | Slower, and still needs a remainder rule: ₹100 ÷ 3 does not terminate |
| Integer minor units (paise; JPY 0 decimals, KWD 3) in BIGINT columns | Exact integer arithmetic; a remainder is an integer a rule can assign | Every layer must stay in minor units; converting to major units happens only for display |
Selection criteria. Exactness, determinism under replay, and whether the rule is simple enough to test with hand-computed outputs.
Choice for this workload. Integer minor units everywhere money is stored, computed or sent over the API (total_minor, share_minor, net_minor), with percentages as integer basis points summing to 10,000.
When another option wins. Nothing for the ledger. Major-unit decimals belong only in the display layer.
Remaining risk. A client or service that silently converts to floats reintroduces the bug; the server computes and validates shares itself and never trusts client-computed shares.
The remainder rule
Options: largest remainder (floor every share, give the leftover r units one each to the largest fractional remainders, ties by ascending user_id); let the payer or user choose who absorbs the extra paise; random assignment; last member absorbs the remainder. User choice adds a UI step for at most a few paise and still needs a default for API-created and recurring expenses; random assignment breaks replay; last-member-absorbs depends on list order and can move more than one unit onto one person.
Choice: largest remainder with the user_id tie-break. It depends only on the inputs, never moves a share more than one minor unit from its exact value, and reduces to "the first r members by user_id get one extra unit" for an equal split: ₹100 over three → 3,334 / 3,333 / 3,333; ₹125.50 at 3333/3333/3334 bps → 4,183 / 4,183 / 4,184. A "who gets the extra paisa" picker can sit on top as UX, never as the mechanism.
Built in: Complete Design, Chapter 09, with the worked rounding table.
What a Balance Is: Per-Member Net Positions vs Stored Pairwise Debts
Members ask two questions: "what is my position in this group?" and "who owes whom, and why?". The ledger has to answer both without storing the same fact twice (Complete Design, Chapter 10).
| Option | Benefits | Limits |
|---|---|---|
| Ledger rows as per-member signed deltas (paid − share); net = sum per member and currency | Zero-sum is checkable per write; one projection row per member; simplification needs exactly these nets | Who-owed-whom is not in the ledger rows themselves |
| Stored pairwise debts per ordered pair, updated on every expense | "Who owes whom" is a direct read | Up to n(n−1) rows per group, many touched per expense; a second structure that must agree with the nets |
| Both, maintained in the write transaction | Both questions are direct reads | Twice the derived state to keep consistent and rebuild |
Selection criteria. Which question is asked on the hot path, and whether provenance is lost by not storing pairs.
Choice for this workload. Per-member deltas in ledger_events and per-member nets in balance_projection. Provenance is not lost: expense_payers and expense_splits record who paid and who benefited per expense version, so a pairwise "why" view is derived from them on demand. After E1 and E2 that view shows four raw debts (Ben→Asha ₹300, Cara→Asha ₹300, Asha→Ben ₹100, Cara→Ben ₹300) netting to Asha +₹500, Ben +₹100, Cara −₹600.
When another option wins. A product whose main screen is a per-pair ledger ("you and Ben") across many groups may maintain a pairwise projection — derived from the same splits, never a second source of truth.
Remaining risk. Users can confuse the derived pairwise view with what they must pay; the settle-up screen therefore shows suggestions computed from nets (Decision 05).
Built in: Complete Design, Chapter 09 (net balances) and Complete Design, Chapter 10 (pairwise vs net).
Debt Simplification: Greedy Matching vs Exact Minimum Transfers
Settle-up should suggest few transfers. Simplification preserves every member's net position, not who originally owed whom, and it is a suggestion — it moves no money and changes no stored balance (Complete Design, Chapter 10).
| Option | Benefits | Limits |
|---|---|---|
| Greedy: match the largest creditor with the largest debtor (ties by user_id), transfer the smaller amount, repeat | O(n log n) with two heaps; deterministic; at most (creditors + debtors − 1) transfers; easy to explain | Not guaranteed minimal |
| Exact minimum: maximize the number of disjoint zero-sum subgroups k; transfers = n − k | Provably fewest transfers | NP-hard in general; exponential search, practical only for very small groups |
| Greedy plus a bounded exact search under a size threshold | Optimal for small groups, greedy above | Two code paths to test; the gain is usually one transfer |
Selection criteria. Group size (typically 3–20), whether the product promises "fewest" or just "few", and determinism of the output.
Choice for this workload. Greedy, documented as "few, not fewest". After E1 and E2 it turns the four raw debts into Cara→Asha ₹500 and Cara→Ben ₹100.
When another option wins. A product that promises the minimum for small groups can add the bounded exact search. The honest counterexample: 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), while the optimum is M3→M2 300, M4→M1 200, M5→M1 200 (three).
Remaining risk. A suggestion computed before a newer expense is out of date; it is returned with the as_of_seq it was computed from so the client can tell.
When to compute it: on demand, not persisted
Persisting suggestions after every write saves a computation that costs microseconds for a 5-member group, and adds an invalidation path that can silently serve a suggestion that no longer matches the balances. The design computes greedy on demand from one balance_projection snapshot (or a cached sheet) and returns its as_of_seq. Persist a suggestion only if a surface shows it continuously, and then version it by as_of_seq.
Built in: Complete Design, Chapter 10, including the counterexample.
Retry Safety: Scoped Idempotency Keys vs Dedup Heuristics vs Client IDs
Phones time out after the server has committed, offline queues replay, users double-tap. Retrying is correct client behavior, so a retried write must have at most one effect — on creates, edits, deletes and settlements alike (Complete Design, Chapter 11).
| Option | Benefits | Limits |
|---|---|---|
| No dedup | Nothing to build | Every ambiguous timeout risks a double-counted expense in everyone's history |
| Heuristic: same payer, amount and description within a window | No client change | Wrong both ways: two genuine ₹150 coffees are suppressed, and a retry after an hour offline is not caught |
| Client-generated expense id as primary key | Dedupes creates; optimistic UI knows the id | Does not cover edits or settlements, and cannot tell a retry from a different request reusing the id |
| Idempotency-Key scoped to (actor, group, operation, key), stored with a SHA-256 request fingerprint in the same transaction as the write | Exact; covers every money-moving endpoint; distinguishes "same request again" from "different request, same key" | Clients must keep the key across retries; the server keeps a record per write for 7 days |
Selection criteria. Exactness (no false positives or negatives), coverage of every mutation, and behavior while the first attempt is still running.
Choice for this workload. Scoped keys with fingerprints, claimed as the first statement of the write transaction. Same key and same body → the stored response is replayed (no new rows, no second ledger effect); same key and different body → 422 IDEMPOTENCY_KEY_CONFLICT, never a silent replay; a retry racing the first attempt waits on the uncommitted key; a crash before commit leaves no key, so the retry runs normally. Recurring expenses use (recurring_id, period) as the key.
When another option wins. Nothing for money-moving writes. Heuristics may still warn a user ("this looks like an expense you added a minute ago") as UX, never as dedup.
Remaining risk. Keys expire after 7 days, so a client must not hold unsent writes longer; old queued entries are surfaced for the user to confirm. Downstream, the event pipeline redelivers independently of client retries, so consumers deduplicate too (Decision 10).
Who generates identifiers
The retry key and the record's identity are separate concerns. The client generates the Idempotency-Key; the server generates expense_id, settlement_id and group_seq. A server-only id leaves a timed-out client unable to tell whether its write committed — the key resolves that. A client-generated primary key lets a buggy client collide with or spoof an existing record's id. Optimistic UI can show a local placeholder until the server's id returns.
Built in: Complete Design, Chapter 11 (transaction, retry table) and Complete Design, Chapter 08 (headers and errors).
Concurrency Control: Versioned Edits and a Per-Group Write Order
Two concurrency problems look alike but differ. Across requests, two members edit the same expense from stale screens and the second save silently overwrites the first (the lost update). Within the database, concurrent writes to one group must apply in one order so later stages can tag freshness and replay history (Complete Design, Chapter 11, Complete Design, Chapter 12).
| Option | Benefits | Limits |
|---|---|---|
| Last write wins | Nothing to build | Exactly the lost update: one member's correction disappears with no signal |
| Pessimistic edit lock held while the form is open | No conflicts | A lock across human think time; abandoned screens need timeouts and stall everyone else |
SELECT … FOR UPDATE inside one request | Simple | Protects one server request, not the client's read-then-write across two requests |
| Field-level merge | Fewer conflicts | Fine for descriptions, dangerous for amounts and splits |
| Optimistic concurrency: PUT with If-Match: "<version>", compare-and-set on expenses.version | Nothing held between requests; conflicts are surfaced, not hidden | The losing client must reload and reapply |
Selection criteria. How often conflicts happen (rarely, in groups of 3–20), whether the client's read and write span two requests (they do), and what the loser sees.
Choice for this workload. UPDATE expenses SET version = version + 1 WHERE expense_id = :id AND version = :expected AND status = 'active'; zero rows → 409 VERSION_CONFLICT with current_version; a missing If-Match → 428 PRECONDITION_REQUIRED. Inside the transaction, UPDATE groups SET last_seq = last_seq + 1 … RETURNING takes the next group_seq and serializes the group's money-moving writes; locks are always taken expense row first, then group row, so two writes cannot deadlock.
When another option wins. A truly collaborative, long-running joint edit would justify an explicit edit lock or merge. A global sequence or timestamps would avoid the per-group serialization but need cross-group coordination or give ties and gaps under clock skew.
Remaining risk. The group row lock caps one group at roughly 100–200 short writes/s (a few dozen for a 200-member group). That is far above real groups, and per-group rate limits (429 + Retry-After) protect it; dropping the lock for hot groups would break the gap-free order that projections, as_of_seq and replay rely on.
Built in: Complete Design, Chapter 12 (If-Match, the exp-2040 timeline) and Complete Design, Chapter 17 (hot-group ceiling).
Corrections and Deletes: Reversal Plus Replacement vs In-Place Change
Members correct expenses constantly, and a balance must stay explainable afterwards: "Dinner ₹900, corrected to ₹960" is exactly what a dispute needs (Complete Design, Chapter 12).
| Option | Benefits | Limits |
|---|---|---|
| Update the expense and its ledger rows in place | Current state is just the latest values | The previous state is gone; balances can no longer be explained or replayed |
| Hard delete and recreate | End state looks right | The original record itself disappears from history |
| New expense_versions row; reversal entries negating the previous version's ledger rows; entries for the new version — all under one new group_seq | Balance ends as if the corrected amount had been entered originally; the full story stays in the ledger | Every edit writes roughly twice the ledger rows of a create |
Selection criteria. Auditability, replay, and one mechanism for every kind of change.
Choice for this workload. Reversal plus replacement in the same transaction as the If-Match check. Correcting E1 from ₹900 to ₹960 nets +4,000 / −2,000 / −2,000 paise; every column of the correction sums to zero.
When another option wins. Nothing for the mechanism. A product can choose how much of the reversal detail to show in the activity feed versus keep as audit history.
Remaining risk. More ledger volume, absorbed by projections (Decision 09) and archival. Operator and support fixes must use the same path — a direct "fix" to a derived balance breaks auditability for good.
Deletes are reversals without a replacement
A hard delete breaks replay; a soft-delete flag without a compensating entry relies on every balance query filtering the flag, and one forgotten filter resurrects the expense. The design marks expenses.status = 'deleted' and appends reversal entries — the same transaction as an edit, without the new version. Settlements already recorded are separate facts and stay: if E1 were deleted after S1, the nets would become Asha −₹300, Ben +₹400, Cara −₹100. The system never silently forgives or drops a settlement because the expense behind it was removed.
Built in: Complete Design, Chapter 12 (edit transaction SQL and worked table).
Balance Reads: Aggregate on Read vs a Projection Updated in the Write Transaction
After Stage 1 the design is correct, but every balance read sums the group's whole ledger. At peak that is ≈ 3,500 group aggregations/s over ~2,300 rows per average group after one year — about 8M rows/s, about 16M in year two — while writes stay flat at ~580/s (Complete Design, Chapter 13).
| Option | Benefits | Limits |
|---|---|---|
| Covering index on (group_id, currency, user_id) | Index-only scans | Still O(history) per read; buys months |
| Read replicas | Moves scans off the primary | Still O(history); replica lag silently breaks read-your-writes |
| Cache in front of the aggregation | Hot groups hit the cache | Every write invalidates it; misses still pay O(history) |
| Periodic snapshot + recent delta | Bounds the scan | A snapshot job with its own correctness problems |
| balance_projection updated inside the write transaction | O(members) reads (~17,500 rows/s at peak); never ahead of or behind the ledger on the primary; read-your-writes by construction | ~5 extra row updates per write, under the group lock the transaction already holds |
| Projection updated asynchronously from events | Removes even that write cost | The writer's own group balance becomes eventually consistent — the view users check right after writing |
Selection criteria. Read cost as history grows, whether the writer sees their own write, and extra write cost under a lock already held.
Choice for this workload. The synchronous group projection. 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 maintaining them in the Stage 1 transaction is the cheapest correct option. The old aggregation query becomes the reconciliation check.
When another option wins. Compute-on-read is right for small deployments, admin and audit tooling, and reconciliation. An asynchronous group projection wins only if the ledger and projection ever live in different datastores, and then the product must accept and label a staleness window on its most-checked view.
Remaining risk. A bug or manual edit can make the projection drift; a reconciliation job compares it with SUM(delta_minor) (mismatches must stay at 0) and a rebuild recomputes a group's rows under its lock.
What is synchronous and what is not
This is the write-path timing decision, and it is split by view rather than made once. Synchronous, in the write transaction: ledger entries, balance_projection, the idempotency record and (from Stage 3) the outbox row — the 201 is sent only after they commit. Asynchronous, driven by the Event Bus: the per-user user_balance_summary (Decision 12), the event-driven cache delete (Decision 11) and notifications. A relay or bus outage therefore delays the dashboard and notifications but never the group balance.
Built in: Complete Design, Chapter 13 (numbers, alternatives, SQL) and Complete Design, Chapter 17 (rebuild).
Event Publication: Transactional Outbox vs Publishing After Commit
Notifications, the cross-group dashboard and cache invalidation must react to every committed write without slowing it down or disagreeing with the database (Complete Design, Chapter 14).
| Option | Benefits | Limits |
|---|---|---|
| Side effects inside the transaction | Simple | A slow push provider holds the group lock; a rollback after the push has already notified |
| Publish to the bus after COMMIT | No new table | The dual write: a crash between commit and publish loses the event; a bus outage fails or drops acknowledged writes |
| Distributed transaction across database and bus | One atomic unit in theory | Poorly supported by brokers; writes become unavailable whenever the bus is |
| Change data capture on the database log | No outbox table | Events are row changes tied to the schema; a good relay transport, not a replacement for explicit domain events |
| Transactional outbox: one outbox row per commit (event_id, group_id, group_seq, event_type, payload) in the write transaction | The event exists if and only if the write committed; the write path depends only on the database | A relay to run, rows to purge, and duplicates to absorb downstream |
Selection criteria. Atomicity between the write and its event, write-path availability when the bus is down, and control of the event shape.
Choice for this workload. Outbox. The Outbox Relay claims unpublished rows with FOR UPDATE SKIP LOCKED, publishes to the Event Bus keyed by group_id (7-day retention), then marks them; published rows are purged after 7 days. Events carry each member's absolute net_after_minor from the projection update in the same transaction.
When another option wins. CDC as the relay's transport when outbox polling load matters or many tables need a uniform stream — still reading explicit outbox rows, not raw table changes.
Remaining risk. Relay lag delays derived views; alert when the oldest unpublished row is older than ~30 s. A relay crash after publishing but before marking republishes the row, so duplicates are normal.
Delivery: at-least-once with idempotent consumers
At-most-once delivery silently loses dashboard updates and notifications. Exactly-once delivery across a database and an external broker is not something this pipeline can provide, and approximating it with distributed transactions costs availability. So delivery is at-least-once, not exactly-once, and the guarantee comes from the consumers: each event has at most one effect because every consumer applies it idempotently and commits its bus offset only after its own local write.
The Projection Consumer writes the absolute value with a sequence guard — … SET net_minor = EXCLUDED.net_minor, last_applied_seq = EXCLUDED.last_applied_seq WHERE user_balance_summary.last_applied_seq < EXCLUDED.last_applied_seq — so a duplicate or older event matches no row and needs no reordering buffer. The Notification Service has a unique constraint on (event_id, recipient_user_id). A consumer added later without such a guard is the recurring risk; review every new consumer for it.
Built in: Complete Design, Chapter 14 (outbox, relay, bus, consumer contract).
Read Caching: Versioned Cache vs Plain TTL
balance_projection makes a group read cheap, but up to ~2,315 reads/s at peak — concentrated on a few hot groups during a trip — still share the primary with writes (Complete Design, Chapter 15).
| Option | Benefits | Limits |
|---|---|---|
| No cache | Simplest; the projection read is already cheap | Hot-group bursts land on the primary |
| Read replicas | Offloads the primary | Lag the caller cannot see; breaks read-your-writes |
| Cache-aside with a plain TTL | Easy to add | Shows a balance from before the latest expense for up to the TTL, with no way to tell |
| Versioned cache: balance:{group_id}:{currency} → {sheet, as_of_seq} | High hit rate; staleness is visible and bounded; the writer can demand freshness | Set-if-newer fills and two invalidation paths to implement |
Selection criteria. Whether staleness is visible to the caller, whether the writer sees their own write, and the worst case after a lost invalidation.
Choice for this workload. Versioned cache. Read: return the entry only if its as_of_seq ≥ the caller's min_seq; otherwise read balance_projection and store the sheet only if no newer entry exists (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 event arrives (reliable, outbox-driven). Safety TTL 300 s is a backstop for a lost invalidation, not the freshness mechanism. The version is group_seq — not the expense's edit version.
When another option wins. No cache while the primary has read headroom. Plain TTL is fine for non-financial data (group names, member lists).
Remaining risk. A reader that loaded the projection just before a commit can repopulate the key just after the fast-path delete; the event-driven delete removes it, typically within a second or two, and the TTL bounds the worst case. The writer is unaffected because it reads with min_seq.
The consistency contract per view
Strong consistency for every read wastes the cache; eventual consistency for every read hides the writer's own expense. The design states a guarantee per surface instead: ledger, expense detail and settlement status are read from the primary and authoritative; the writer's group balance is read-your-writes on the device that wrote (writes return group_seq, the next read sends it as min_seq); other members and devices see the versioned cache, normally ~1–2 s behind, at worst the 300 s TTL; the dashboard is eventually consistent with a p99 ≤ 2 s target. Every lagging surface shows its as_of_seq, and every "~" is a monitored target, not a guarantee.
Built in: Complete Design, Chapter 15 (read path and consistency contract).
Cross-Group Dashboard: Event-Fed Per-User View, No Cross-Group Netting
A member of a trip group, a flat and a club wants one screen showing where they stand everywhere. Group data is group-scoped (and, at Stage 5, sharded by group), so "all my groups" is the one read that crosses that boundary (Complete Design, Chapter 14).
| Option | Benefits | Limits |
|---|---|---|
Query every group's balance_projection at read time | Always current; no new table | A fan-out over every group, and later every shard, on each dashboard open |
| Update a per-user table inside the write transaction | Fresh dashboard | Every write touches one row per member; once groups and users are sharded differently, a cross-shard write |
| Net balances across groups ("you owe Ben ₹50 overall") | Fewest apparent debts | Silently merges contexts members keep separate; a forced transformation, not a suggestion |
| User Balance Projection (user_balance_summary, keyed by user) maintained by the Projection Consumer from events; one row per group and currency, summed only for display | Single-key dashboard read wherever group data lives; no extra cost on the write path | Eventually consistent — target p99 ≤ 2 s after commit |
Selection criteria. Read cost of the dashboard, coupling of the write path to other partitions, and whether group boundaries stay intact.
Choice for this workload. The event-fed per-user projection, with each group's row carrying its as_of_seq; the dashboard is labeled as possibly a few seconds behind, and the client may overlay its own just-committed write as pending. Totals are display sums of group-local nets, never a settleable cross-group debt.
When another option wins. Read-time fan-out is fine while everything lives on one database and users belong to few groups. A cross-group settlement is legitimate only as an explicit, member-initiated action that writes ordinary settlement rows in each group.
Remaining risk. The dashboard lags whenever the relay, bus or consumer lags; the group sheet does not. Monitor consumer lag per partition; replay from the bus (7 days) or rebuild from balance_projection with the same sequence-guarded upsert.
Built in: Complete Design, Chapter 14 (Projection Consumer) and Complete Design, Chapter 15 (consistency per surface).
Currency Isolation: Separate Balances per Currency vs Converting at Entry
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 (Complete Design, Chapter 16).
| Option | Benefits | Limits |
|---|---|---|
| Convert every expense to the group currency at entry | One number per member | Bakes a rate and date into permanent history; balances change meaning when rates move; cannot be undone cleanly |
| Separate balances, no converted view | Exact and zero-sum per currency | No at-a-glance total for the member |
| Currency in every balance key; FX only as a labeled display estimate; conversion only as an explicit record | Ledger never depends on a rate; members still get an orientation total | A display-rate dependency (FX Rate Snapshots) and careful labeling |
Selection criteria. Whether a rate ever enters the system of record, whether each currency stays zero-sum, and who decides on a conversion.
Choice for this workload. ledger_events, balance_projection and user_balance_summary are keyed by currency; the sheet shows one block per currency and simplification runs per currency, so a $20 souvenir stays in USD. A settlement must be in a currency in which the payer owes the recipient (otherwise 422 CURRENCY_MISMATCH). A "show in INR" total uses an FX Rate Snapshot (rate, as-of time, source) and is labeled as an estimate. Settling a USD debt in rupees is a member-initiated conversion record that closes USD positions and opens INR ones, each currency zero-sum.
When another option wins. Nothing for the ledger. A regulated context may drop even the display estimate.
Remaining risk. Members may read the estimate as a payable amount; the UI must label it, and the server never accepts it as one.
Built in: Complete Design, Chapter 16.
Settlement: Manual Assertion plus Provider-Confirmed State Machine
A repayment must reduce balances only when money actually moved. Members settle by cash and bank transfer outside the app, and optionally through an in-app Payment Provider whose confirmation arrives later, may fail, and can be reversed by a refund or chargeback (Complete Design, Chapter 16).
| Option | Benefits | Limits |
|---|---|---|
| Boolean "settled" set when the payment is initiated | Instant feedback | A failed or reversed payment leaves a wrong balance that must be visibly undone |
| Confirmation only, no visible pending state | Balances always trustworthy | Members see nothing until confirmation and retry, risking a second charge |
| Provider-only settlements | Every settlement verified | Cash and outside transfers — the common case — cannot be recorded |
| Manual settlements recorded as confirmed assertions; provider settlements pending → confirmed | failed, confirmed → reversed | Every real method is supported; balances move only on confirmed money; the source of each settlement is visible | A state machine, webhook handling and reconciliation to run |
Selection criteria. Who is authoritative for money movement (the provider, for provider settlements), and whether any intermediate state can touch a balance.
Choice for this workload. A manual settlement writes a confirmed settlement and its ledger rows in one transaction, like an expense; it is a member's assertion, visible to both parties and reversible like any record. A provider settlement commits as pending with no ledger rows and no group_seq; the Payment Service calls the provider outside the transaction with settlement_id as the provider idempotency key. A webhook is untrusted until its signature and timestamp verify; it is deduplicated in provider_events and applied with WHERE status = 'pending', writing the ledger rows, projection and outbox in the same transaction. failed writes nothing; a refund or chargeback moves confirmed → reversed with settlement_reversal rows. Late or contradictory webhooks match no row and are flagged, not applied.
When another option wins. An enterprise or compliance context may require provider-confirmed settlements only and drop the manual path.
Remaining risk. Webhooks can be lost: reconciliation asks the provider about settlements still pending after 15 minutes and compares the daily provider report; on disagreement the provider's record wins and the correction is new ledger entries.
Recording paths: manual and provider, distinguished
Manual-only treats every settlement as an unverified claim; provider-only blocks the most common real payments. Keeping both, tagged by method (manual | provider), lets the activity history say whether a repayment was asserted by a member or confirmed by a provider, while both use the same ledger mechanics once confirmed.
Built in: Complete Design, Chapter 16 (state machine, webhook transaction, reconciliation).
Partitioning: By Group via a Group Directory
One primary eventually becomes too large a blast radius and storage unit (~5 GB of ledger rows a day). The partition key must keep each money-moving write inside one local transaction (Complete Design, Chapter 17).
| Option | Benefits | Limits |
|---|---|---|
| By group_id, through a group directory (hash by default, explicit overrides) | Every write and group read stays on one shard; no cross-shard transaction; a hot group can be moved | A single very hot group is still bounded by its group lock |
| By user | "All my balances" on one node | An expense touches several members, so every write becomes cross-shard |
| By expense id hash | Even write spread | A group's balance scatters across every shard |
| Splitting a hot group across shards | Higher per-group write ceiling | Breaks the per-group order and the zero-sum transaction; never for real groups |
Selection criteria. Whether the common write stays local, the read pattern of the hot path, and how hot groups are handled.
Choice for this workload. Partition by group_id. Per-user data (user_balance_summary, notifications) lives in a separate store keyed by user and fed by events — the reason the dashboard is asynchronous. Each shard runs its own Outbox Relay; provider events resolve to their shard through the group directory; dormant groups are archived to cheaper storage while their final projection rows stay online.
When another option wins. A product without a dominant group-scoped access pattern (e.g. a per-user personal ledger) would partition by user.
Remaining risk. The hot-group ceiling (~100–200 short writes/s per group) is handled by per-group rate limits (429 + Retry-After), short transactions, the cache and notification digests — never by dropping the group lock. Each shard keeps a synchronous in-region standby and an asynchronous cross-region replica, so cross-region RPO is seconds, not zero; clients retry with the same idempotency keys after failover.
Built in: Complete Design, Chapter 17 (partitioning, hot groups, DR).
Audit Retention vs Deletion Requests: Anonymize, Do Not Erase
The append-only ledger that makes balances explainable conflicts with a member's request — sometimes a legal right — to have their personal data deleted (Complete Design, Chapter 18).
| Option | Benefits | Limits |
|---|---|---|
| Keep everything forever | Maximal auditability | Ignores privacy obligations; a compliance risk |
| Delete the user's expenses and ledger rows | Literal erasure | Every other member's balances become wrong and unexplainable; zero-sum breaks |
| Anonymize: keep expense, split and ledger rows; replace identifying profile fields with a placeholder; remove receipts with personal data | Other members' history stays correct; the person is no longer identifiable | Needs a defined line between personal data and financial facts, reviewed legally |
Selection criteria. Correctness for the other members, the substance of the privacy request, and jurisdictional retention minimums.
Choice for this workload. Anonymize, decided and documented before the first request arrives. Members can export their data; receipts live in object storage behind the group-membership check and are served through short-lived signed URLs.
When another option wins. Jurisdictions with minimum retention periods may override deletion for financial records; the boundary is set per jurisdiction. This is design guidance, not legal advice; see the scope note in Complete Design, Chapter 18.
Remaining risk. Free text in descriptions and notes can still identify someone; the anonymization job must cover it.
Built in: Complete Design, Chapter 18.
Secondary Decisions: Update Delivery, Receipt Storage, Build vs Adopt
These choices are real but do not protect a money invariant; each has a standard answer for this workload and a clear condition that flips it.
| Decision | Options | Choice | When another option wins |
|---|---|---|---|
| Update delivery | Polling; push + refresh; persistent WebSockets | Push notifications from the Notification Service, then an on-demand refresh of the group sheet (versioned cache) | A live, simultaneous feature (everyone itemizing one bill at the table) justifies a WebSocket channel for that interaction only |
| Receipt storage | Database blob; object storage reference; inline thumbnail + object original | Object storage, referenced from the expense, upload first then reference; signed URLs behind the membership check | Thumbnail hybrid only if receipt-heavy browsing proves slow |
| Build vs adopt | Custom engine; general-purpose ledger platform; custom engine on double-entry principles | Build, on double-entry principles: balanced, append-only postings, reversals instead of edits | Adopt a ledger platform when the product grows into multi-party accounting with regulatory reporting |
Update delivery: push plus refresh
Expense apps are checked in bursts — after a dinner, before settling up — not watched continuously. Polling either wastes requests or lags and adds directly to the ~2,315 reads/s peak; a WebSocket fleet for 10M users means heartbeats, reconnects and connection state for a screen nobody keeps open. A push from the Notification Service (deduplicated per (event_id, recipient_user_id)) followed by a cheap cached read covers the need; a member with the app already open may need a pull-to-refresh.
Receipt storage: object storage reference
Receipt photos are large, rarely read binaries that would bloat the transactional database and its backups. Object storage holds the file; the expense stores a reference written after the upload succeeds, so a missing object is detectable and orphaned uploads are swept. Receipts can contain personal data, so they are encrypted at rest and never served from public links.
Build vs adopt: a custom engine on double-entry principles
Groups, splits, simplification suggestions and per-currency isolation map awkwardly onto a general ledger platform's accounts and postings, so a translation layer would add complexity without adding correctness. The design already borrows the part that matters — every write is a balanced, append-only set of postings, and corrections are reversals — and owns the implementation and tests. The calculus flips once the product needs regulated accounting and reporting, where a platform's compliance-tested abstractions outweigh the domain-fit cost.
Architecture Decision Record: The Load-Bearing Choices
Most decisions above are tied to the stated workload and could reasonably flip. The ones below are load-bearing: get them wrong and a balance becomes wrong permanently, regardless of scale.
| Decision | Choice | Why | Reconsider when |
|---|---|---|---|
| Source of truth | Append-only ledger_events; every balance, summary and cache is derived and rebuildable | Corrections, audit, recovery and disputes all need one replayable history | Never for this product class; only the storage tier of old history varies |
| Money arithmetic | Integer minor units; largest remainder, ties by ascending user_id; percentages in basis points | Shares sum to the total exactly and replay gives the same shares | Never for the ledger |
| Retry safety | Idempotency-Key scoped to (actor, group, operation, key) with a request fingerprint, in the write transaction | A retried write has at most one effect; a reused key with a different body gets 422 | Never for money-moving writes |
| Concurrency | PUT + If-Match compare-and-set (409 VERSION_CONFLICT, 428 without the header); per-group group_seq under the group row lock | No silent lost update; one gap-free order per group | A long-running collaborative edit flow, where an explicit lock or merge is more honest |
| Corrections and deletes | Reversal + replacement; delete = status deleted + reversal | Every balance stays explainable and replayable | Never; only how much reversal detail the feed shows |
| Group balance reads | balance_projection updated in the write transaction | O(members) reads; read-your-writes by construction | Ledger and projection split across datastores — then accept and label staleness |
| Event publication | Transactional outbox; at-least-once delivery; consumers apply absolute values with a sequence guard | No dual write; writes never depend on the bus | CDC can become the relay transport; the outbox rows stay |
| Currency isolation | Currency in every balance key; FX display-only; conversion is an explicit record | No rate ever enters the ledger; each currency stays zero-sum | Never for the ledger |
| Settlement | Manual = confirmed assertion; provider = pending → confirmed | failed, confirmed → reversed | Balances move only on confirmed money; the provider is authoritative for provider payments | Compliance contexts may drop the manual path |
- 01The append-only ledger is upstream of almost every other decision: projections, summaries and caches are disposable because they can be rebuilt from it.
- 02Correctness comes from one local transaction per write — idempotency record, version check,
group_seq, ledger rows, group projection and outbox row together — not from the event pipeline. - 03Delivery is at-least-once, not exactly-once; idempotent, sequence-guarded consumers make each event have at most one effect.
- 04Freshness of the dashboard, notifications and other viewers' cached sheets is a monitored target shown to users through
as_of_seq, not a guarantee. - 05Situational choices — topology, caching, partition key, transport, receipts, build vs adopt — should move when the workload does.