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
199 changes: 199 additions & 0 deletions doc/2026-11-16_design_id5826.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,199 @@
# Design record — id5826: Stage B — multi-Turso sharding by currency

- Issue: #5826 (design, from #5676 decomposition item 4)
- 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`); #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
- Status: decision recorded (queue task 17435, 2026-11-16). Implementation timing is a
separate decision, as the parent issue states.

## 0. Gate note

Both gates named by the task packet are closed fresh (2026-11-16): #5823 (port/invariant
contract) and #5824 (Stage A design) have landed records, and their decisions are consumed
below, not re-decided. #5676 is the umbrella and does not need to close first: its decisions
are its governing principles and staged path, already recorded in its body. #5828 §3.2
already decided the cross-DB conversion mechanism; this record adopts it and answers only what
the parent delegated to the Stage B design (shard key, directory, schema versioning,
rebalancing, cross-DB ordering and failure recovery).

## 1. Decision in one paragraph

Stage B shards the **regular store by currency**: one currency lives wholly in **exactly one
Turso database**, and a database holds one or more whole currencies (a currency group is a
co-location choice, never a split). Every same-currency transfer therefore stays inside one
DB and keeps Stage A's local atomicity; the only cross-DB operation is a currency conversion,
which is the **#5828 saga with a durable coordinator intent** — adopted unchanged, because this
record claims no cross-database atomicity. Routing is done by a **versioned currency→DB
directory** in the metadata store, owned and operated by the ID platform as an audited admin
surface, never by per-front-end configuration. Rebalancing a currency to another DB is a
reviewed migration with a **bounded per-currency write freeze**, saga drain, pre/post invariant
checks, and an **epoch flip** that fences the old DB, with directory rollback available only
before the flip accepts writes.

## 2. Chosen shape

### 2.1 Shard key

- Shard key is **currency**. A currency is never split across DBs, at any tenant size.
- A DB may host several whole currencies; grouping is a capacity/latency choice made in the
directory, invisible to callers and to the port.
- Account-range sharding is not used: it would split a single currency's ledger, break the
per-currency conservation and balance-rule facts the port enforces, and turn every plain
same-currency transfer into a cross-shard operation.

### 2.2 The currency→DB directory

- One table in the existing metadata store: `currency_id → database_id, schema_version,
directory_epoch, state (active | migrating | retired)`. The metadata store is the
**only** authority for routing; application configuration may cache it read-through but may
not override it.
- Resolution is by currency ID (the caller's currency is on every port operation), plus a
shard identifier on cross-DB saga legs. No backend concept (database URL, shard number)
appears above the port.
- Writes to the directory are reviewed admin operations, audited with actor, reason, PR and
epoch; a currency's entry changes only through the migration procedure (§3) or initial
provisioning.
- The directory is not auto-scaled, not sharded, and holds no balances: it is a small,
strongly consistent routing table. Its availability is on the posting critical path, so it is
cached with an explicit staleness bound (a cached entry is valid only for the epoch it was
read at; migrations bump the epoch).

### 2.3 Same-currency operations (the overwhelming majority)

Resolve currency → DB, then run the unchanged #5823 port against that DB: one local
transaction for the balanced legs, idempotency key, authorisation reference and journal
sequence. Stage A's commit rule applies **per DB**: committed iff the journal entry is durable
in that currency's DB. Custody, holds and caps are per-DB facts enforced locally, exactly as
#5828 §3.2 states.

### 2.4 Cross-currency conversions

Adopted from #5828 §3.2 without modification: coordinator = source currency's DB, durable
intent + source hold at admission, destination pending leg fenced by the saga epoch, one
durable `COMMIT`, compensation only before commit, forward-only recovery after commit, refund
conversion as the only post-commit reversal, saga timeout an operator parameter (5 minutes),
outcomes `POSTED` / `FAILED_COMPENSATED` / `COMPENSATING` declared per #5823 §3.6, and the
user-visible pending settlement state. When both legs resolve to the same DB the operation is
locally atomic, and the saga machinery is not used — the outcome is Stage A's.

### 2.5 Schema versioning across the DB fleet

- One schema version per release; the directory records each DB's `schema_version`.
- A front-end writes only to DBs at its own schema version and rejects a currency whose DB is
mid-upgrade with a typed maintenance error (never a silent fallback to another version).
- Upgrade is rolling per DB: expand (additive), deploy, backfill, contract — with the prior
version's reads still correct during the window. A DB in `migrating` state is frozen for
writes anyway (§3), so schema and data moves share one maintenance story.
- No cross-DB schema transaction is claimed; a fleet-wide version is a release fact verified by
the directory census (every active DB at the release's version).

## 3. Rebalancing migration (currency moves DB)

Per currency, coordinated by the directory entry, not by ad-hoc scripts:

1. **Freeze.** Set `state = migrating` and bump the epoch. New conversions for the currency are
rejected with a typed maintenance error (#5828 §"Explicitly deferred" rule, now exercised);
plain transfers may continue only until step 2 starts.
2. **Drain.** Wait for in-flight sagas on the currency to reach a terminal state, bounded by the
saga timeout; `COMPENSATING` sagas are allowed to finish, never force-closed.
3. **Fence.** Set `state = migrating-write-frozen`. The old DB rejects new writes for the
currency, identified by the new epoch; the write freeze is per currency, not per database, so
co-located currencies keep serving.
4. **Copy.** Snapshot the currency's accounts and journal at a sequence watermark, restore into
the destination DB, and replay the journal tail to that watermark.
5. **Verify.** Run the #5823 invariant suite cases for the copied currency against the
destination, plus a **per-account balance census** and journal-sequence equality against the
source at the watermark; any mismatch aborts the migration with the source still authoritative.
6. **Flip.** One directory transaction moves the currency to `active` on the destination at a new
epoch. The old DB's fence makes a late write a typed rejection, not a lost update.
7. **Retire.** After a quiet period the old DB's copy of the currency is archived read-only
(journal retained for audit); deletion follows the existing backup/restore requirements.
8. **Rollback.** Permitted any time before step 6: clear the fence, restore `active` on the
source, keep the destination's partial copy as garbage. After step 6 the only reversal is a
new migration back — never an unaudited epoch rewind.

The freeze is a maintenance window the size of steps 3–6 (copy + verify + flip), bounded and
measured; it is not "zero-downtime" in the absolute sense, and the record says so instead of
claiming it.

## 4. Failure recovery and ordering

- **Coordinator crash** (cross-DB conversion): resume from the intent's recorded step and
commit/no-commit state; the intent is in the system of record, so recovery is replay, not
memory. Idempotent at every step.
- **Destination DB unavailable during a saga**: the hold stays, the pending leg stays pending,
and the saga either completes forward within the timeout or compensates. Funds are never
half-spendable in either direction.
- **Directory unavailable**: posting fails closed with a typed unavailable error while cached
entries remain valid at their epoch; no request is routed by a guessed or defaulted database.
- **Split brain between directory and DB fence**: the DB fence (epoch) always wins; a write the
directory would allow but the DB rejects is a safe rejection, surfaced as maintenance, and the
directory is advanced by the migration procedure, never by retrying around the fence.
- **Ordering**: local per-DB per-account ordering, no global cross-DB order claimed, and none
needed — caps and balances are per-DB facts enforced at the hold or posting step (#5828 §3.2,
adopted).
- **Partial legs matching no saga state** are quarantined and alerted as an invariant violation
(#5828 §2 rule, unchanged).

## 5. Invariants implementation must hold

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

1. I1–I8 hold unchanged, per currency and per DB, including across a migration.
2. Every posted same-currency transfer's legs live in exactly one DB; a currency is never split.
3. Every cross-DB operation exists as a durable coordinator intent before any leg is posted.
4. The directory is the sole routing authority: one currency has exactly one active DB at a
given epoch, and no write for an older epoch is accepted.
5. A posting decision never reads a balance, hold or cap across DBs; cross-DB facts are
materialised by the saga, not read live from another DB.
6. Rebalancing preserves per-account balances, journal order and the sequence watermark; the
pre/post census is equal at the flip.
7. Saga-epoch fencing makes a compensated conversion unreachable by a late post, and a
post-commit saga completes forward or by posted refund, never by release.
8. No backend concept (database ID, epoch, shard) appears above the port; maintenance and
saga-pending states are the only new port-visible vocabulary, declared per #5823 §3.6.

## 6. Alternatives rejected

- **Account-range sharding**: rejected. It splits one currency's ledger, defeats the per-currency
conservation and balance rules of the port, and makes ordinary same-currency transfers
cross-shard — the exact cost Stage B exists to avoid for the common path.
- **Currency as the strict per-DB unit (one DB per currency)**: rejected as a rule, kept as a
possible deployment. It multiplies DBs and connection/schema surface for small currencies;
whole-currency co-location gets the same invariants with fewer moving parts.
- **Two-phase commit / XA across Turso DBs**: rejected, following #5828: no concrete mechanism
exists in the store stack, and claiming cross-DB atomicity without one would be dishonest.
- **A single coordinator DB holding all conversion legs**: rejected (#5828): it re-centralises
the hot path Stage B shards.
- **Routing from front-end configuration**: rejected. Two sources of truth for where money
lives is how shards split-brain; the directory table, audited and versioned, is the only one.
- **Hot migration without a write freeze**: rejected. It cannot prove the per-account census at
the flip; a bounded maintenance window per currency is cheaper than reconciling a moving
ledger.
- **Independent per-DB schema evolution**: rejected. It makes the fleet's correctness a matrix
of adapter versions; one release version with a rolling window keeps the suite meaningful.

## 7. Parent-decision changes

**None.** This record answers exactly what #5676 delegated to Stage B: the shard key is
currency (open question 3), the directory is an ID-platform-operated metadata table (same), the
cross-currency atomicity answer is #5828's saga (open question 4, adopted), and TigerBeetle
timing is untouched (open question 5). Cross-currency legs remain same-ledger legs under one
correlation stamp (#5823 I7); RateAuthorisation and the #2063 contract stay above the port
unchanged. Stage A's Redis decision and Stage C are not revisited.

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

1. Directory table, admin tooling and epoch/fence enforcement in the port adapter.
2. Migration tool: snapshot/copy/replay, census and flip, with the §3 procedure as its spec.
3. Per-DB connection management, pool limits and per-shard health/alerting.
4. Schema rolling-upgrade procedure and directory census check for the fleet.
5. Stage B legs of the #5829 programme: saga crash-injection, migration interrupted at each
step, and the per-account census oracle.