Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
260 changes: 260 additions & 0 deletions doc/2026-11-16_design_id5827.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,260 @@
# Design record — id5827: Stage C — TigerBeetle adapter + B→C cutover

- Issue: #5827 (design, from #5676 decomposition item 5)
- Parent: #5676 — Currency scaling: autoscaling service, Redis → multi-Turso → TigerBeetle path
- Inputs (all landed): #5823 — currency backend port + invariant test-suite contract
(`doc/2026-11-14_design_id5823.md`); #5824 — Stage A: Redis hot store + regular-store
system of record (`doc/2026-11-08_design_id5824.md`); #5826 — Stage B: multi-Turso sharding
by currency (`doc/2026-11-16_design_id5826.md`); #5828 — conversion & RateAuthorisation
across stages (`doc/2026-11-05_design_id5828.md`); #5829 — load & correctness verification
programme (`doc/2026-11-08_design_id5829.md`); #5825 — autoscaling
(`doc/2026-11-16_design_id5825.md`)
- Programme: epic #2056; conversion #2063; RateAuthorisation #2290; TB backend investigation
#2040 (`doc/2026-10-28T23-34-15Z_investigation_tigerbeetle_currency_backend`,
`doc/2026-10-29T11-57-00Z_investigation_tigerbeetle_cluster_topology`);
ledger binding `doc/2026-11-03T20-36-00Z_design_tigerbeetle_ledger_binding`
- Status: decision recorded (queue task 13037, 2026-11-16). Implementation timing is a
separate decision, as the parent issue states.

## 0. Gate note

The only gate this design waited on was Stage B #5826 (the B→C cutover is meaningless
until the shape it migrates FROM is settled — 2026-11-05 and 2026-11-08 triages, and the
2026-11-16 re-triage that narrowed the gates to exactly #5826). Fresh 2026-11-16: #5826
is **closed** with its record merged (PR #10769): shard key is currency, the versioned
audited currency→DB directory is the sole routing authority, rebalancing is
freeze → drain → fence → copy/verify → epoch flip, rollback only before the flip. #5823
(port + suite contract), #5824 (Stage A), #5828 (conversion), #5829 (verification) and
#5825 (autoscaling) have all landed and are consumed below, not re-decided. #5676 is the
umbrella and does not close first: its decisions are its governing principles and staged
path, already recorded in its body. #5828 §3.3 already decided the Stage C atomicity
mechanism (the #2063 linked batch, unchanged); this record adopts it and answers only
what the parent delegated to the Stage C design: the adapter mapping and the B→C
migration/cutover plan — plus the parent's open question 5 (TigerBeetle timing), which
belongs to this ticket.

## 1. Decision in one paragraph

Stage C runs the currency ledger on **one TigerBeetle cluster behind the unchanged #5823
port**: one currency is one `ledger: u32`, TB accounts/transfers/pending-post-void are the
port's accounts/transfers/pending lifecycle with no new semantics invented, and
conversions post as #2063 linked batches with `FAILED_ATOMIC` semantics exactly as #5828
§3.3 states. The B→C cutover migrates **one currency at a time** through
readiness → shadow dual-run with a zero-divergence ledger comparison → the Stage B
migration procedure reused verbatim (freeze, saga drain, fence, copy/verify, directory
flip) → retirement of the Stage B copy as read-only audit. There is exactly one system
of record per currency at every moment; the cutover never dual-writes authority. This
answers the parent's open question 5: **Stage C is the committed terminal stage**, not an
option — and Stages A/B already carry everything that keeps it reachable (§7).

## 2. Chosen shape

### 2.1 Adapter mapping (port → TigerBeetle)

The mapping is the as-built `tb_ledger` binding generalised from the PoC module into the
production port contract; the binding record's decisions stand, restated here as adapter
obligations:

- **Currency is a `ledger: u32` (non-zero).** One currency lives wholly in one TB ledger;
currency groups (Stage B co-location) dissolve — each currency gets its own ledger ID
at cutover. No cross-ledger transfer primitive exists at the port, permanently: a
conversion's legs are composed same-ledger pairs under one correlation stamp
(#5823 §3.1, #5828 §2).
- **Accounts**: caller-chosen `u128` ID (zero and int-max reserved and rejected ahead of
any TB call), application chart-of-accounts `code: u16`, balance-rule flags mapping to
TB's `debits_must_not_exceed_credits` / `credits_must_not_exceed_debits`. TB rejects
`code = 0`; the adapter applies the binding's bijective wire shift (`wire = c + 1`)
and restores original codes on lookup, with the original-code registry updated only
after TB accepts creation — a rejected retry must never overwrite it.
- **Transfers**: caller-generated `u128` ID persisted write-ahead by the caller (#5823
§3.1); linked chains post atomically or not at all; the Exists-in-chain, failed-ID
(`IdAlreadyFailed`), and result-length (#4669) rules are the port's, and the adapter
emulates them exactly where TB's wire breaks chains on non-created statuses (the
binding's `Exists`-then-`LinkedEventFailed` translation).
- **Pending lifecycle is native**: a hold is a TB pending transfer, `post_pending` /
`void_pending` are TB post/void, timeouts are TB timeouts. The four-figure balance
(§3.1 of #5823) is derived from TB posted + pending figures exactly as the PoC derives
spendable from the posted pair.
- **Correlation**: `user_data_128` carries the conversion ID; lookups page and post-filter
on exact equality for every value including zero (TB treats a zero filter field as "no
filter"). History and events come from the TB journal in commit order per account, with
one event per posting in history order — the #5823 §3.4 fidelity rule, against TB's own
ordering.
- **Error vocabulary**: the port's closed typed set; unmodelled TB statuses surface as
typed `UnmodelledStatus` / `BackendFailure`, never as success and never as panic in
production paths (the binding's panic stance was a PoC convenience and does not carry
over). The vocabulary changes only by amendment to the #5823 record.

### 2.2 What Stage C drops

The Stage B saga machinery retires with Stage B: no coordinator intents, no saga epochs,
no pending-settlement user-visible state. A conversion whose legs live in different
ledgers is still two same-ledger linked batches under one correlation stamp (port rule),
but each batch is now natively atomic — the saga existed to compensate for Turso having
no cross-DB atomicity, and TB's per-batch atomicity plus the port's composition rule make
it unnecessary. Receipts stay stage-blind (#5828 §2): a reader cannot tell which stage
posted a conversion except from the recorded adapter name.

### 2.3 The directory during and after cutover

The #5826 currency→DB directory remains the sole routing authority through the cutover,
extended by one column: `tigerbeetle_ledger`. During cutover a currency's entry carries
both its Stage B database and its target TB ledger; after the flip the DB columns become
historical audit and the entry is `active` on the ledger. When every currency has flipped,
the directory is a small static currency→ledger map with the same audited-admin,
epoch-fenced discipline — it is not deleted, because ledger assignment must stay a
reviewed fact, not a convention callers reconstruct. No backend concept (ledger ID,
cluster) appears above the port at any point.

### 2.4 Reads at Stage C

TB is strongly consistent, so reads serve from TB directly: posting decisions evaluate
posted + pending together; caller-facing balances follow read-your-committed-writes
(#5824 §2.3, generalised). Cached reads with a stated staleness bound remain available
only to explicitly approximate consumers (dashboards), never as posting inputs — the
#5825 A5 rule, unchanged. Parent open question 6 (balance-read staleness) is therefore
answered for Stage C the same way as for A/B: stale only where declared approximate,
inside the stage's published bound.

## 3. B→C cutover (per currency)

The procedure reuses the #5826 §3 migration shape deliberately — one migration story,
not two — with the Stage B DB as source and the TB ledger as destination:

1. **Readiness.** The TB adapter has a published conformance statement (#5823 §4.4:
adapter build, suite version, §3.6 declarations, per-case results, environment) with
leg 0 green, and the shadow-comparison harness (§4) is deployed. No currency cutover
starts without both.
2. **Shadow dual-run.** Stage B remains the sole system of record. Every committed
posting is also submitted to the TB shadow ledger with identical IDs; the ledger
comparison job continuously checks per-account balances and history against the
source. Admission, idempotency, and receipts all still come from Stage B — the shadow
decides nothing.
3. **Freeze.** Directory entry to `migrating` with an epoch bump; new conversions for
the currency rejected with the typed maintenance error; plain transfers continue only
until step 4.
4. **Drain + fence.** Wait for in-flight sagas to reach terminal states (bounded by the
saga timeout); then the Stage B write fence engages for the currency at the new epoch.
Shadow submission stops at the same watermark: the shadow ledger must equal the
source journal tail exactly at the fence point.
5. **Copy/verify.** Snapshot the currency's accounts and journal at the watermark (already
substantially present via shadow posting — this step closes the tail and proves it),
replay any tail after the watermark, and run the #5823 suite cases for the currency
against TB plus a per-account balance census and history-order comparison against the
source. Any mismatch aborts with the source still authoritative.
6. **Flip.** One directory transaction moves the currency to `active` on the TB ledger at
a new epoch. Posting now goes to TB; the Stage B fence makes a late write a typed
rejection, not a lost update.
7. **Soak + retire.** A quiet period with the comparison job still running (now TB as
primary against the frozen source copy); then the Stage B copy is archived read-only,
journal retained for audit, deletion per the backup/restore requirements.
8. **Rollback.** Permitted any time before step 6: clear the fence, restore `active` on
the source, discard the shadow as garbage. After step 6 the only reversal is a new
migration back (TB → Stage B via the same procedure), never an unaudited epoch rewind.

Currencies cut over one at a time, ordered by operational convenience (quiet currencies
first); there is no requirement to cut all currencies in one window, and no flag day.
The freeze is a bounded per-currency maintenance window (steps 3–6), stated honestly as
in #5826 — not zero-downtime.

## 4. Failure recovery and ordering

- **Adapter crash between TB commit and local recording**: recovery probes the exact
pre-generated IDs (`try_lookup_transfer` / correlation stamp); all present and
matching → `POSTED`, none present → resubmit identically, partial/mismatched →
quarantine and alert (#5828 §2 rule, unchanged).
- **TB cluster fault (replica loss)**: TB's own replication is the durability story;
posting blocks or fails closed per the client contract, never half-posts a linked
chain. Recovery ceiling is the #5829 envelope line (≤ 15 min replica failover).
- **Shadow divergence during dual-run**: any non-zero divergence halts that currency's
cutover (no flip) and files a finding against the adapter — divergence is a failed
campaign, never a threshold to tune away (#5829 P2/P3).
- **Cutover aborted mid-currency**: the currency stays on its pre-cutover store (source
still authoritative before the flip; reverse migration after). Partial TB state from an
aborted cutover is garbage collected by ID, never merged.
- **Directory unavailable**: posting fails closed on cached entries valid at their epoch;
no request is routed by guess. The TB-side has no independent routing — the adapter
posts only to the ledger the directory names.
- **Ordering**: TB commit order per account, same guarantee the port's history surface
already states; cross-account order unspecified, as in the parent. The Stage A
admission-sequence discipline (#5828 §3.1) is subsumed: TB linked batches are the
atomic unit, and credits are spendable exactly when posted — no pending-until-durable
overlay is needed or kept.

## 5. Invariants implementation must hold

Inherited from the parent (principle 3), #5823 (I1–I8), #5828 (intent-before-legs,
recovery by leg ID, stage-blind receipts), restated for Stage C; each covered by the
#5823 suite plus the #5829 verification programme:

1. I1–I8 hold unchanged, per currency and per ledger, before, during, and after cutover.
2. Every posted transfer's legs live in exactly one TB ledger; cross-ledger movement
appears only as composed same-ledger pairs under one correlation stamp.
3. One system of record per currency at every moment: before the flip it is the Stage B
DB, after the flip it is TB — never both, never neither.
4. The directory is the sole routing authority: one currency has exactly one active
store at a given epoch, and no write for an older epoch is accepted.
5. Shadow divergence is zero at the flip; any divergence aborts the cutover.
6. A posting decision never reads a balance across ledgers; pending amounts are never
spendable by a second transfer (I2/I6 via TB flags + four-figure balances).
7. Linked batches are all-or-nothing (`POSTED` / `FAILED_ATOMIC`); no partial legs are
ever observable outside declared pending states.
8. No backend concept (ledger ID, wire code, cluster, epoch) appears above the port;
receipts are stage-blind.

## 6. Alternatives rejected

- **Big-bang cutover (all currencies in one window)**: rejected. It couples every
currency's risk into one flip, needs a fleet-wide freeze, and makes a rollback a
fleet-wide event. Per-currency cutover gets the same end state with bounded blast
radius; the directory already supports per-currency states.
- **One TigerBeetle cluster per currency**: rejected. It multiplies cluster operations,
connection surface, and upgrade coordination for no invariant gain — TB ledgers
already isolate currencies inside one cluster, the way whole-currency co-location
isolated them inside one DB in Stage B.
- **Dual-write authority (Stage B and TB both accept writes during cutover)**:
rejected. Two authorities with no shared transaction is the ambiguous-crash matrix
#5824 §6 refused for Redis/journal; shadow-then-flip keeps exactly one decider at all
times.
- **Async replication instead of shadow comparison**: rejected. Replication without the
zero-divergence comparison proves movement, not correctness; the comparison job *is*
the cutover's evidence (#5829 leg for §4.2), not an optional extra.
- **Keeping the Stage B saga for cross-ledger conversions**: rejected. The saga
compensated for missing cross-DB atomicity; TB batches are natively atomic per ledger
pair, and the port forbids cross-ledger primitives anyway. Keeping the saga would
preserve pending-settlement UX and operator machinery for a limitation that no longer
exists.
- **Retiring the directory after cutover**: rejected. Two sources of truth for where a
currency lives is how shards split-brain (#5826 §6); ledger assignment stays a
reviewed, audited fact in the directory.
- **Deferring Stage C indefinitely ("TB as an option")**: rejected — see §7. An
uncommitted destination lets stage-specific dialects accrete around the port until
migration needs a rewrite, violating parent principle 4.

## 7. Parent-decision changes

**None.** This record answers exactly what #5676 delegated to Stage C, including its
open question 5: **Stage C (TigerBeetle) is the committed terminal stage** of the staged
path. What Stages A/B had to avoid to keep it reachable — per-stage port dialects,
cross-ledger primitives, optional holds, backend concepts above the port, codes/IDs TB
cannot represent — they already avoid via the #5823 contract (required pending
lifecycle, reserved-ID rejection, closed error vocabulary, ledger-scoped transfers) and
the #5828 stage-blind receipt rule. The binding record proves the mapping is real
(`tb_ledger` runs the #2063 scenarios against a live TB cluster today). Conversion and
RateAuthorisation stay above the port unchanged; Stage A/B decisions are not revisited;
the user-facing API and the invariant set are untouched.

## 8. Follow-ons (named, filed when implementation is scheduled)

1. Production TB adapter crate: move the mapping out of `currency_poc` into its
production home with the §2.1 error-vocabulary and registry discipline, plus its
conformance statement (§4.4 of #5823).
2. Shadow dual-run harness + ledger-comparison job: ID-preserving shadow submission,
per-account census and history-order comparison, divergence alerting, soak-window
publication — the #5829 Stage C campaign extension (§10.4 of #5829).
3. Per-currency cutover tooling: freeze/drain/fence/copy/verify/flip orchestration per
§3 with the directory epoch discipline, cutover rehearsals (including abort
mid-currency and divergence injection), and TB→Stage B reverse-migration drills.
4. Production cluster topology: replica layout, failover runbook, and the #5829 §5.3
Stage C envelope campaign (20,000 tps sustained / 60,000 burst, posting p99 ≤ 20 ms)
on the staging twin — the evidence #5825's transition review consumes.