diff --git a/doc/2026-11-08_design_id5824.md b/doc/2026-11-08_design_id5824.md new file mode 100644 index 0000000000..b699ed2528 --- /dev/null +++ b/doc/2026-11-08_design_id5824.md @@ -0,0 +1,162 @@ +# Design record — id5824: Stage A — Redis hot store + regular-store system of record + +- Issue: #5824 (design, from #5676 decomposition item 2) +- Parent: #5676 — Currency scaling: autoscaling service, Redis → multi-Turso → TigerBeetle path +- Prerequisite: #5823 — currency backend port + invariant test-suite contract (see §7, dependency) +- Programme: epic #2056; conversion #2063; RateAuthorisation #2290 +- Status: decision recorded (queue task 13798, 2026-11-08). Implementation timing is a + separate decision, as the parent issue states. + +## 1. Decision in one paragraph + +Stage A runs two stores with exactly one authority. The **regular store** — the +persistence path the rest of ID already uses — is the **system of record**: currency +definitions, metadata, and the append-only transfer journal live there, and a transfer +is *committed* if and only if its journal entry is durable there. **Redis is a hot +operational layer only**: a replayable projection of balances plus idempotency +fast-path and contention striping. Redis holds no decision-relevant state that the +journal cannot rebuild. This answers the parent's open question 1 for Stage A: +Redis is the system of record for *nothing*. + +## 2. Chosen shape + +### 2.1 Commit protocol (write-through, journal-first) + +1. Validate the request and run the #2290 RateAuthorisation check **before** posting; + the authorisation record is stored with the transfer (parent rule, unchanged). +2. Append the transfer to the regular-store journal in **one transaction**: both + balanced legs, the idempotency key (unique), authorisation reference, metadata, + and a monotonically increasing journal sequence number. This append is the + **commit point**. If it fails, the transfer does not exist. +3. Apply the committed entry to Redis with a Lua script that is a pure function of + the journal entry: it checks the entry's sequence/idempotency key against the + projection watermark, applies both legs atomically, and advances the watermark. + Re-applying an entry is a no-op. +4. Acknowledge to the caller once the journal append is durable. Redis application + is normally synchronous-fast-path, but the ack does **not** depend on it (§2.2). + +Ordering note: this is write-through with the journal *first*, not a dual write. +There is no interleaving in which Redis reflects a transfer the journal lacks, +and none in which a committed transfer is missing from the journal. + +### 2.2 Failure semantics + +- **Journal append fails** → no commit, no Redis change, caller gets the error; + retry with the same idempotency key is safe. +- **Redis unavailable at posting time** → the transfer still commits (journal is + sufficient); the projection lags and catches up by replay (§3). The posting + path never blocks on the hot layer's health. +- **Crash between journal append and Redis apply** → the entry is committed and + will be projected by replay from the watermark. This is the normal recovery + path, not an edge case. +- **Duplicate submission / retry** → the journal's unique idempotency key returns + the original outcome; the Lua apply dedupes by key + sequence. + +### 2.3 Reads + +- **Balance reads** serve from the Redis projection **plus** any committed journal + tail beyond the projection watermark, so a read never reports a balance older + than the last committed transfer the caller has seen acknowledged + (read-your-committed-writes). Pure-projection reads with a stated staleness + bound are allowed only for explicitly approximate consumers (dashboards), never + for posting decisions. +- **History and definitions** read from the regular store only. +- Posting decisions (funds checks) evaluate against journal + projection under + the journal transaction, never against the projection alone. + +### 2.4 Contention + +Redis Lua execution serialises applies per projection; per-account striping may +be used to reduce contention on hot accounts. Striping and locks are performance +devices only — correctness rests on the journal transaction and the idempotent +apply, never on a Redis lock being held. + +## 3. Crash recovery + +- **Redis partial loss / restart**: replay journal entries after the projection + watermark persisted with the last snapshot (below). Replay is the same Lua + apply as the live path — one code path for live and recovery application. +- **Redis total loss**: rebuild from the latest **balance snapshot** — a periodic + snapshot of journal-derived balances plus its journal sequence watermark, + stored in the regular store — then replay the journal tail after the + watermark. Snapshots are an optimisation; correctness needs only the journal. +- **Guarantee**: a committed transfer is never lost by any Redis failure, + including total loss (RPO for committed transfers = 0; projection RPO = replay + lag, which is measured and alerted, §4). +- Redis persistence settings (AOF/RDB) are therefore an availability/latency + choice, explicitly **not** a durability requirement, and must not be cited as + one in ops docs. + +## 4. Reconciliation + +- A continuous reconciliation job compares Redis projection balances against + journal-derived balances per account/currency. +- Divergence beyond projection lag (watermark age above a configured bound, or + any balance mismatch after the lag window) raises an alert; the repair + procedure is always the same: replay from the journal. There is no manual + Redis-side repair — the journal wins every dispute by definition. +- Reconciliation also verifies the idempotency index: every Redis idempotency + entry must correspond to a journal entry. + +## 5. Invariants implementation must hold + +Inherited from the parent (principle 3) and restated for Stage A; each must be +covered by the invariant test suite (#5823 contract, §7): + +1. Every transfer is balanced (sum of legs = 0 per currency) and atomic. +2. No account balance goes negative where the currency's rules forbid it. +3. Transfers are idempotent under retry with the same idempotency key. +4. A committed transfer survives Redis total loss (journal replay restores it). +5. Redis never reflects an uncommitted transfer. +6. Balance reads honour read-your-committed-writes (§2.3). +7. The ledger is auditable/replayable end-to-end from the journal alone. +8. No backend concept (Redis, journal internals) leaks into the user-facing + transfer API (parent principle 1): create-transfer (idempotency key, from, + to, amount, currency, metadata), balance, history — unchanged from the + parent's interface list. + +## 6. Alternatives rejected + +- **Redis as system of record** (AOF/RDB durability): rejected. It forks the + parent's Stage A framing, puts durability on the layer with the weakest + operational story in our fleet, and makes Redis loss a data-loss event + instead of a replay event. +- **Write-behind** (Redis first, journal asynchronously): rejected. A Redis + crash then loses acknowledged transfers — a direct violation of parent + principle 3 and of this record's §3 guarantee. +- **Synchronous dual-write / 2PC across Redis and the regular store**: + rejected. Adds a distributed-transaction failure matrix to buy atomicity + the journal-first ordering already provides, and couples posting + availability to Redis health. +- **No Redis — journal-only reads/writes**: rejected for Stage A. It is the + correct fallback posture (§2.2 degrades toward it) but does not meet the + parent's hot-path goals (atomic fast postings, hot-account handling) that + Stage A exists to provide. + +## 7. Dependency on #5823 (recorded, not invented) + +#5823 (backend port + invariant test-suite contract) is **not yet recorded**: +at the time of this record the issue is open and its design task is in flight. +This record therefore: + +- uses the parent #5676 vocabulary (port, adapter, invariant test suite) and + makes only semantic decisions that are independent of the port's concrete + method names and test identifiers; +- does **not** invent port signatures or test-suite IDs; +- states the binding rule for the seam: when #5823's record lands, its port + vocabulary and invariant-test identifiers supersede any naming in this + record, and any conflict is resolved in #5823's favour **without** + re-opening the Stage A decisions in §1–§4 (authority, commit ordering, + recovery, reconciliation). If #5823 lands a decision that genuinely + contradicts one of those, that is a parent-decision change and must be + recorded on #5676, not silently forked here. + +## 8. Parent-decision changes + +**None.** This record decides only what #5676 delegated to Stage A (the +write-through/reconciliation protocol and the system-of-record question, +parent open question 1) and stays inside the parent's staged path, +interfaces-that-must-not-change list, and invariant set. Stage B (multi-Turso +sharding) and Stage C (TigerBeetle) are untouched; the currency_poc +LedgerBackend seam in `pkgs/id/src/currency_poc/` remains a proof of concept +under the #2056 programme rule and is not promoted by this record.