RFC 0002 — Writes While a Member's Home Region Is Down

12 min readReference

Problem

Home regions (see Regions) put each member's own rows on the shard of their home region, zone-sharded on {home_region, user_id}. That is what makes an NA member's writes commit in NA.

It also means that while a region is down, nobody can write its members' rows, wherever the request lands:

  • The app fails over to the other region's API (REGION_API_URLS + GET /region).
  • But mongos still routes the write to the home shard, which has no primary.

The case that must keep working is a Gymmer member logging a workout during the outage, with the workout reaching their home region once it is back.

Where we are (checked 2026-10-18)

Nameniac:

  • Its 7 member collections are sharded on {home_region, user_id} (since 2026-10-17), with zones eu and global and no na range.
  • So an NA-homed row still lands on ifmrs (EU), and an NA outage costs Nameniac nothing today.

Gymmer:

  • Shards now, after gobackend #120/#125, with no chunk moves (Igor, 2026-10-18).
  • Backend registration is OFF and the website is prelaunch, so no NA member can be created. All 4 members are eu.

The gate is NA members existing, on a region with its own range.

  • Nameniac: do not add the na zone range (P4.7) until this ships.
  • Gymmer: do not turn registration on for NA (or open NA sign-up) until this ships.
  • Until then, NA-homed rows either don't exist or commit in EU, and an NA outage costs only latency.

Topology the design relies on (live today)

Replica setMembersWhen a region is down
rs-na (NA shard)yul (priority 2), amer (1), waw (0, voting)NA down → no primary; waw keeps a readable copy in a third failure domain, at about EU latency
ifmrs (EU/global shard)EU voters + amer, yul and waw copiesEU down → no primary; NA members hold readable copies
csrs (config)hel/emea/amer/yul/waw, 1 vote each (priority 2/1/0.5/0/0)either region down → still a majority (EU down: amer/yul/waw = 3 of 5 → amer primary)
Coordinator (redis-fp)three failure domainsevery slot served with any one domain down (drilled 2026-10-17/18)

Principles

  1. Never re-home during an outage. Moving a member would need their home rows, which are unreachable, and would break the uniqueness of {home_region, user_id} singletons when the region returns. The home region only changes through the normal migration path, with both regions up.
  2. Accept only writes that can be replayed exactly. These are parked in the serving region and applied at home later. Every other write fails fast with a typed error (ErrHomeRegionUnavailable): HTTP 503 for clients, a retry for consumers.
  3. Replay is idempotent and ordered per member. Applying a parked write twice, or after a newer write, must not change the result.
  4. Every side effect happens once, at replay: domain events, analytics (ClickHouse), folds. That is when the data is at home. Nothing derived from a spooled write runs at spool time.
  5. Background writers wait; they don't give up. Work that touches an unavailable home is retried until the region returns. It is never dead-lettered because of the outage.

Design

1. Knowing the home region is down — region.HomeAvailable

  • Add a per-region circuit breaker in runtime/region, fed by the errors that owned writes and reads get from mongos: no primary for the shard, shard unreachable, network timeout, FailedToSatisfyReadPreference.
  • Open after N failures within a window. Half-open probe every 5 s with a cheap owned read.
  • Owned operations carry a short deadline (maxTimeMS / client-side operation timeout, around 2 s). mongos otherwise spends its own replica-set-monitor wait on a primary-less shard (15–30 s) before it errors, and every request would pay that before the breaker learns.
  • Local first, shared second.
    • Each replica's own breaker is authoritative.
    • The Coordinator flag only makes the others open sooner.
    • In an Atlantic split, each side trusts its local breaker; the shared flag is advisory.
  • Metrics: region_home_available{region} and region_breaker_transitions_total{region,to}.
  • Alert: a region open for more than 2 minutes.

2. Parking writes — runtime/mongo/spool

A region_spool collection, stamped with the serving region, so it is always writable where the request landed.

text
{ _id: <op_id>,                 // idempotency key — the client's op id
  home_region: "eu",            // where the spool row lives (serving region)
  owner_home: "na",             // the member's home — where it must land
  user_id, seq,                 // per-member order (serving-side counter)
  coll, kind, filter, doc,      // the write, see "spool-safe writes"
  created_at, attempts, last_error }

Two ways to spool:

  1. A crud write kind, from the table below, for simple writes: crud.WithSpool(kinds…).
  2. A registered domain command, for writes whose real path does more than one insert. Example: Gymmer's SyncOps reads the session and the owner's region, does $inc op_seq, inserts, then folds (StartIfPlanned, ApplyFold, ClickHouse analytics).
    • The spool stores {command, payload}.
    • Replay calls the handler registered with spool.Register(command, fn), the same code path the request would have run at home.
    • Replaying a raw insert there would skip the fold and the analytics.

The spool key is the caller's idempotency key, not a bare op id. Gymmer op ids are unique per session (unique index {session_id, op_id}), so the key is hash(collection, session_id, op_id). Generally: hash the fields of the target's unique index. A duplicate on that index at replay means "already applied". That is also why a unique index other than _id is fine when the spool key covers it.

Anything not spoolable returns ErrHomeRegionUnavailable.

KindExampleWhy replay is exact
insert with a client-supplied _id / op idworkout op log, events, check-insduplicate key on replay = already applied
upsert with $setOnInsert onlycreate-if-absent singletonssecond apply is a no-op
set guarded by a version / updated_atpreferences, profile fieldsapplied only if newer than the stored version (LWW)

Not spool-safe (rejected during the outage): plain $inc, array pushes without an op id, deletes, and anything that reads-then-writes across documents or sits under a unique index the spool key doesn't cover. Rejecting these is correct; the client retries after Retry-After. A registered command may do any of these, because it runs the full domain path at home.

Nameniac example: favourite add is an upsert under a unique {home_region, user_id, domain}, unfavourite is a delete, and prefs have no version. So all Nameniac member writes get the 503, which is right for its volume. A deterministic _id = hash(user, domain) would make favourite-add spool-safe later if wanted.

3. Background writers — consumers and jobs

Consumers and scheduled jobs write members' rows too (Nameniac's worker: site_radar_hits, site_alert_log; Gymmer has its own).

The risk: since go-events v0.7.0, a handler that keeps failing is dead-lettered after EVENTS_MAX_DELIVERIES (~9 minutes). An outage longer than that would move real work to <topic>.dlq.

The rule:

  • ErrHomeRegionUnavailable is a retry that doesn't count a delivery.
    • go-events classifies it (errors.Is) and redelivers with the normal backoff, capped at the breaker's probe interval.
    • It does not increment the delivery count, so the message never reaches the DLQ because of an outage.
    • The bus must not loop hot on a long outage.
  • Optional, per consumer: use the spool instead, for consumer writes that are spool-safe by the table above. The handler then acks at once.
  • Scheduled jobs that touch owned rows treat the error as "skip this member, retry next run", never as a job failure.
  • Pausing whole consumer groups while the breaker is open was considered. Rejected: one group usually serves members of both regions.

4. Replaying — the spool relay

  • One generic relay primitive in runtime/ (leader lock, batch, per-key order, attempts, last_error, pending/oldest gauges), shared by runtime/outbox's regional relays and the spool relay. Not a second hand-rolled loop.
  • When HomeAvailable(owner_home) closes, the relay drains that home's rows: per member, in seq order.
  • Each row is applied through the same path the request would have taken:
    • a crud kind goes through crud (OwnFilter, the owner's home);
    • a command goes through its registered handler.
  • Where that path writes data and outbox events together, it is a single-shard transaction on the home shard. The outbox collection is keyed {home_region, …} like member data, so the outbox row sits on the same shard.
  • Where the domain deliberately emits after the write, outside a transaction (Gymmer's session.completed), replay keeps that behaviour.
  • The spool row is deleted right after that commits, in its own write on the serving shard. Deleting it inside the transaction would make it a cross-Atlantic two-phase commit. A crash between the two is harmless: duplicates are a no-op by construction.
  • Dependencies replay in order. Per-member seq order covers a spooled session start replaying before its ops. While both are spooled, the serving region's own reads must see the spooled start (the overlay, §5), or ops loop on "awaiting session".
  • Terminal outcomes are not retried. If by replay time the target refuses the write for a business reason (Gymmer: the session was finished elsewhere → 409, or access was revoked → 403), the row moves to region_spool_failed with the reason, and the member/admin is told. Only transient errors retry.
  • A row failing transiently after K attempts stays put with last_error.
  • Metrics: region_spool_pending{owner_home}, region_spool_oldest_seconds, region_spool_failed_total.
  • Alert: the oldest row is older than 15 minutes after the breaker closes.

5. Reads during the outage

  • Read fallback is already in the topology (see the table above).
    • NA down: rs-na keeps a voting, priority-0 copy on waw. rtmongo.Nearest / secondary reads of NA members' rows are served from waw, slightly stale.
    • EU down: ifmrs has copies on amer and yul.
    • Decision for Igor: accept waw (OVH Warsaw, a third failure domain) rather than hel/emea as rs-na's off-region copy. Recommended: yes.
  • Read-your-writes overlay: for spool-enabled collections, owned list and get reads merge the member's spooled rows (union by _id), so the next screen shows the set the member just logged.

6. The symmetric case — EU down

EU is home to most members, so this is the bigger outage.

EU down (NA serving)NA down (EU serving)
Members of the down regionspool-safe writes spooled on rs-na (serving region na); the rest get 503spool-safe writes spooled on ifmrs; the rest get 503
Members of the serving regionnormalnormal
Global-zone writes (catalogue, identity, anything unsharded on ifmrs)all fail: ifmrs has no primary in NAnormal
Readsfrom amer/yul copies of ifmrsfrom waw's copy of rs-na
Sign-in / token refreshfails if identity writes are required (identity stays unsharded on ifmrs)normal

Gymmer screens that degrade while EU is down (the Gymmer session to confirm):

  • sign-up and sign-in (identity is global);
  • catalogue edits (admin);
  • anything that writes global collections.

Today Gymmer's workout sync stops about 30 minutes into an EU outage:

  • Every op append reads the global users collection for the owner's region.
  • Access tokens last 30 minutes, and refresh is single-use (a write to identity on ifmrs).

To keep logging through an EU outage:

  1. Take the owner's region from somewhere the serving region can read: the session document (ops are already stamped with it) or a token claim, not a global lookup per append.
  2. Decide refresh during an EU outage separately: a longer access-token TTL for NA-served requests, or a regional refresh path. This RFC doesn't settle it.

7. Migrations during an outage

  • runModuleMigrations failing means boot fails. So during an outage, any replica that restarts with a pending migration touching the down region's rows can't boot. That includes deferred rechecks (go-framework#11), which become runnable at a later boot.
  • Rule (Nameniac's follow-up to #11, before v0.35.1 is consumed): at boot, a migration failing with ErrHomeRegionUnavailable / no primary is deferred (not recorded, logged), not fatal.
  • MIGRATE_ONLY jobs still fail, so deploys stay fail-closed.
  • Until the typed error exists, a classifier on mongo error codes.

8. What the client sees

  • Spooled write: 202 Accepted with {"spooled": true, "until": "home_region"}.
  • Rejected write: 503 with code home_region_unavailable and Retry-After.

Clients must handle both explicitly. Gymmer's journal today does not:

  • A 202 without a seq resets its failure counters, and sinceSeq = Math.max(sinceSeq, res.seq) becomes NaN, which the server reads as 0, forcing a full resync.
  • It retries a 503 at 3/6/8 s and ignores Retry-After.

Required client changes (the Gymmer session):

  • on spooled, leave sinceSeq alone and keep the ops unsent;
  • persist the spooled ids;
  • don't count a spooled answer as a failure;
  • show "saved, syncing to your region";
  • retry at Retry-After or the next heartbeat;
  • treat home_region_unavailable like a network error, so an offline session start kicks in.

Gymmer specifics (from the Gymmer session):

  • The workout journal is an op log with idempotent op ids, and ops are stamped with the session owner's region, never the request's. Op inserts are therefore the insert-by-op-id kind, so spooling is exact.
  • seq acknowledges an op for the sync indicator. A spooled op must not get a home seq; the fold recomputes at replay. /complete also checks op presence (Ops.Has), so completion waits until the ops replay. The client already holds its finish marker, and /complete gets a 503 during the outage.
  • What can spool, from Gymmer's review:
    • offline session start: insert with the client's _id, duplicate → existing;
    • op sync, as a registered SyncOps command.
  • What gets a 503: from-program/ad-hoc start (read-then-write), complete, pause/resume, preferences and ratings.
  • Biometrics are ClickHouse, so they're unaffected.
  • The idempotency middleware doesn't store 5xx, so a retry after a 503 is safe.
  • Prerequisite, being fixed now: SyncOps answered unchanged for a re-send of already-known ops after a lost response. The client then moved sinceSeq past ops that never got a seq, and the finish gate never opened. A spool replay would hit it every time. Fix: answer unchanged only when the request carried no ops.

Phases

  1. Review this RFC: Nameniac done (revision 2), Gymmer pending. Decide the waw copy question (§5).
  2. go-framework:
    • HomeAvailable breaker with short owned deadlines;
    • the generic relay primitive, with outbox migrated onto it;
    • spool + relay and crud.WithSpool;
    • ErrHomeRegionUnavailable;
    • the boot-migration deferral (§7).
  3. go-events: ErrHomeRegionUnavailable = retry without counting a delivery (§3).
  4. Tests on the sharded fixture with one shard stopped, both directions:
    • writes spool; non-safe writes 503; consumers retry without reaching the DLQ; reads fall back;
    • restart → replay in order, events once, duplicate replay a no-op;
    • boot with a pending migration defers.
    • Controls: replay without dedupe; out-of-order replay; an event at spool time; a consumer counting deliveries.
  5. Gymmer adopts:
    • offline start (crud kind) and SyncOps (registered command);
    • the client contract (§8);
    • owner region without a global lookup (§6);
    • the unchanged fix;
    • a check of its background writers.
  6. Game day on a staging copy, NA first, then EU: stop the shard, log a full workout through the other region, restart, verify replay, events and the client's sync state.
  7. Only then: allow NA members. Nameniac adds the na zone range (P4.7); Gymmer turns on NA registration. Gymmer's sharding itself goes ahead now, because no NA member exists.

Alternatives considered

  • Client-only queueing. Reject every write with 503 and let the offline-first app hold everything. It is simplest, but background writers, web clients and other modules get nothing, and a second device can't see what was logged. The 503 path stays for non-spool-safe writes.
  • Temporary re-home. Rejected (principle 1).
  • Regional shards with off-region voters, so the other region can elect a primary. This undoes regional write latency, the reason for sharding, and in an Atlantic split both sides would want the primary.
  • Pausing consumer groups while the breaker is open. Rejected (§3): groups serve members of both regions.
Was this page helpful?