Skip to content

Subscription Resilience Appendix

Drew edited this page Jun 29, 2026 · 1 revision

Technical companion to Subscription Resilience. Covers the connection lifecycle, the catch-up mechanism, the scoring model, and the specific code changes. Primary file: play/src/hooks/useFetchAndSubscribeGameSession.tsx, with a small supporting query in networking and the rejoin fix in play/src/containers/PregameContainer.tsx.


Architecture overview

The guiding principle: the live subscription is an optimization; getGameSession is the source of truth. When liveness is in doubt we re-fetch the truth and, if we've fallen behind, rebuild the socket ourselves.

The data flow:

triggers (visibility:visible | online | 30s jittered poll)
   └─> resync(reason)
         └─> slim getGameSessionVersion probe  (~150 bytes: just updatedAt)
               ├─ updatedAt ≤ cursor  ->  noop  (socket is keeping up)
               └─ updatedAt >  cursor ->  teardown() + establishSubscriptions()   // proof of a miss

establishSubscriptions()                // also the initial mount path
   ├─ getGameSession            (authoritative)
   ├─ ghost check               (team removed? -> redirect)
   ├─ applyGameSession(g)       (the one ordered gate)
   ├─ subscribeUpdateGameSession  -> applyGameSession(delta)
   └─ subscribeDeleteTeam         -> redirectAsDropped

applyGameSession(g)             // EVERY writer funnels through here
   ├─ ordering gate on updatedAt (newer -> apply; stale -> STALE_SKIP)
   ├─ state-change telemetry + add-time detection + setGameSession
   └─ accrueIfNew(g) + reconcileScore(g)   // scoring, runs in BOTH branches

Five problems were addressed (P1 leaked unsubscribe, P2 catch-up/resync, P3→absolute scoring, P4 rejoin, P5 observability). The sections below map to those.

The apply gate and ordering cursor

Every source of game state — the initial fetch, live subscription deltas, and resync re-fetches — funnels through one function, gated by a monotonic updatedAt cursor. We use updatedAt (not a state/question composite) because every host mutation bumps it — including "add time" (which changes only startTime) and sessionData writes — and it's top-level in both getGameSession and the subscription, and parser-validated non-null.

const applyGameSession = (g: IGameSession, trigger: string) => {
  const incoming = new Date(g.updatedAt).getTime();
  if (incoming <= lastAppliedUpdatedAt) {
    trackEvent(PlayEvent.STALE_SKIP, { /* previousState, newState, trigger, ... */ });
    accrueIfNew(g);
    reconcileScore(g);     // score reconcile runs even on a stale skip (see Scoring)
    return;
  }
  lastAppliedUpdatedAt = incoming;

  if (g.currentState !== previousStateRef.current) {
    trackEvent(PlayEvent.GAME_STATE_CHANGED, { /* ..., trigger */ });
    previousStateRef.current = g.currentState;
  }
  const prevTime = gameSessionRef.current?.startTime ?? 0;
  if (g.startTime > prevTime) setIsAddTime((prev) => !prev);  // host "add time"

  setGameSession((prev) => ({ ...prev, ...g }));
  setCurrentTime(calculateCurrentTime(g));
  accrueIfNew(g);
  reconcileScore(g);
};

This makes application idempotent and order-safe: a slow resync can never clobber newer subscription state, and duplicate deliveries are skipped. lastAppliedUpdatedAt is an effect-closure variable, so it persists across a re-establish (the fresh fetch is newer and applies) but resets cleanly when the effect re-runs.

The version probe (lightweight polling)

The poll and the resync miss-detector don't need the whole game record — only updatedAt. So we added a slim query hitting the same getGameSession resolver with a reduced selection set (~150 bytes). It lives in a hand-maintained file (not the Amplify-generated queries.ts), so codegen won't overwrite it and no amplify push / backend change is required.

// networking/src/graphql-custom/customQueries.ts
export const getGameSessionVersion = /* GraphQL */ `
  query GetGameSession($id: ID!) {
    getGameSession(id: $id) {
      id
      updatedAt
      currentState
      currentQuestionIndex
      startTime
      __typename
    }
  }
`;
// networking/.../GameSessionAPIClient.ts
async getGameSessionVersion(id: string): Promise<IGameSessionVersion | null> {
  const result = await this.callGraphQL(
    getGameSessionVersionQuery, { id } as unknown as GraphQLOptions
  ) as { data: any };
  const gs = result?.data?.getGameSession;
  if (isNullOrUndefined(gs)) return null;
  return {
    id: gs.id, updatedAt: gs.updatedAt, currentState: gs.currentState,
    currentQuestionIndex: gs.currentQuestionIndex ?? null,
    startTime: gs.startTime ?? null,
  };
}

IGameSessionVersion is a dedicated slim type (id, updatedAt, currentState, currentQuestionIndex, startTime) — intentionally not IGameSession, so it can't be mistaken for a full record.

Conditional self-managed re-establish

We trust AppSync while a socket is healthy, but never trust it to resurrect a dead one. resync runs the slim probe and only rebuilds the connection when it can prove a message was missed (the backend updatedAt is ahead of what we've applied):

const resync = async (reason: string) => {
  if (resyncing || establishing || ignore) return;   // serialize; don't race the initial establish
  resyncing = true;
  try {
    await sleep(Math.random() * 2000);                // jitter the re-establish herd
    if (ignore) return;
    const v = await apiClients.gameSession.getGameSessionVersion(gameSessionId);
    if (!v || ignore) return;
    const incoming = new Date(v.updatedAt).getTime();
    if (incoming > lastAppliedUpdatedAt) {            // proof the live socket missed something
      trackEvent(PlayEvent.SUBSCRIPTION_RESYNC, { reason, action: 'reestablish', ... });
      teardown();
      await establishSubscriptions('resync_reestablish');
    } else {
      trackEvent(PlayEvent.SUBSCRIPTION_RESYNC, { reason, action: 'noop', ... });
    }
  } catch (e) {
    trackError(PlayEvent.SUBSCRIPTION_RESYNC, e, { reason, action: 'error', ... });
  } finally {
    resyncing = false;
  }
};

establishSubscriptions is the single fetch-and-subscribe path (used by both the initial mount and every resync rebuild). Two latches — resyncing and establishing — prevent overlapping rebuilds and the initial-vs-resync race that would otherwise leak a duplicate subscription. The rebuild is silent: it never flips isLoading, so there's no loading flash on recovery.

const establishSubscriptions = async (trigger: string = 'initial_fetch') => {
  if (establishing) return;
  establishing = true;
  try {
    const fetchedGame = await apiClients.gameSession.getGameSession(gameSessionId);
    if (!fetchedGame || !fetchedGame.id) { setError(...); setIsLoading(false); return; }
    if (ignore) return;
    // ghost check (see below) ...
    setIsLoading(false);
    applyGameSession(fetchedGame, trigger);

    const gameSub = await apiClients.gameSession.subscribeUpdateGameSession(
      fetchedGame.id,
      (response) => {
        if (!response) { /* SUBSCRIPTION_ERROR */ return; }
        if (!firstDataReceived) { /* SUBSCRIPTION_FIRST_DATA + msToFirstData */ }
        if (!ignore) setHasRejoined(false);
        applyGameSession(response, 'subscription_update');
      }
    );
    if (ignore) { gameSub.unsubscribe(); return; }   // cleanup ran during the await -> don't leak
    gameSessionSubscription = gameSub;

    const teamSub = await apiClients.team.subscribeDeleteTeam(gameSessionId, (deletedTeam) => {
      if (deletedTeam.id === teamId) { setHasRejoined(false); redirectAsDropped(fetchedGame, 'team_deleted_by_teacher'); }
    });
    if (ignore) { teamSub.unsubscribe(); return; }
    teamsSubscription = teamSub;

    trackEvent(PlayEvent.SUBSCRIPTION_ESTABLISHED, { ... });
  } finally {
    establishing = false;
  }
};

const teardown = () => {
  gameSessionSubscription?.unsubscribe?.();
  teamsSubscription?.unsubscribe?.();
  gameSessionSubscription = undefined;
  teamsSubscription = undefined;
};

Resync triggers

Three triggers call resync, registered and torn down with the effect:

const onVisible = () => { if (!document.hidden) resync('foreground'); };
const onOnline  = () => resync('online');
document.addEventListener('visibilitychange', onVisible);
window.addEventListener('online', onOnline);

// jittered 30s poll: random initial phase so 30 iPads don't align on one access point
let pollId: any;
const pollStart = setTimeout(() => { pollId = setInterval(() => resync('poll'), 30000); },
                             Math.random() * 30000);

return () => {                                  // cleanup
  ignore = true;
  document.removeEventListener('visibilitychange', onVisible);
  window.removeEventListener('online', onOnline);
  clearTimeout(pollStart); clearInterval(pollId);
  teardown();
};
  • visibility:visible — the must-have. Backgrounding suspends the page and freezes Amplify's own dead-socket detector, so connection-state events are silent in exactly that case; foreground is the only reliable "the student is back" signal.
  • online — network recovery.
  • 30s jittered poll — covers foregrounded-dead sockets (captive portal, AP roaming, NAT idle-timeout, auth expiry, AppSync-side closes) that fire no browser event. Because re-establish is conditional, the steady-state cost is just the ~150-byte probe.

Connection-state is deliberately not a trigger: our own re-establish causes reconnect transitions, which would feed back into a connection-state trigger and loop; the poll covers that case more simply.

Absolute, self-healing scoring

Additive scoring (score = prev + delta) is unsafe once retries/resync exist — a re-applied delta can double-count, and a failed write on a backgrounded device used to be lost permanently (the scored-key was marked before the write, with no retry → "correct answer, zero points"). Scoring is now absolute and max-guarded, split into two responsibilities:

// per-earn delta for the "+X" UI; fires once per (question, discuss-phase)
const accrueIfNew = (g: IGameSession) => {
  if (g.currentState !== PHASE_1_DISCUSS && g.currentState !== PHASE_2_DISCUSS) return;
  const key = `${g.currentQuestionIndex ?? 0}:${g.currentState}`;
  const scored = loadScored();
  if (scored.has(key)) return;
  const team = g.teams?.find((t) => t.id === teamId);
  if (!team) { console.error('Team not found'); return; }
  const delta = ModelHelper.calculateBasicModeScoreForQuestion(g, g.questions[g.currentQuestionIndex ?? 0], team, false);
  scored.add(key); saveScored(scored);
  saveTotal(loadTotal() + delta);   // accumulate persisted absolute total
  setNewPoints(delta);              // UI animation
};

// durable backend write; runs on EVERY apply (outside the updatedAt gate)
const reconcileScore = async (g: IGameSession) => {
  const team = g.teams?.find((t) => t.id === teamId);
  if (!team) return;
  const backend = team.score ?? 0;
  const target = Math.max(loadTotal(), backend);   // monotonic — scores never decrease
  saveTotal(target);
  if (target > backend) {
    try { await apiClients.team.updateTeam({ id: teamId, score: target }); }
    catch (e) { /* next reconcile retries */ }
  }
};

Key properties:

  • reconcileScore runs even on a stale STALE_SKIP — team-score writes don't bump GameSession.updatedAt, so score freshness must not be gated by the cursor.
  • Idempotent + self-healing: a failed write leaves localTotal > backend, so the next apply/resync re-writes it. Re-applying is safe because the write is absolute, not additive.
  • max(localTotal, backend) guards against a localStorage-evicted device writing a stale-low total over a correct backend score. Valid because scores are monotonic (correct = 10, trickiest = a 0–100 share, never negative).
  • The running total is persisted (scoreTotal:${gameSessionId}:${teamId}); the once-per-phase guard is scoredKeys:${gameSessionId}:${teamId}. 1:1 devices mean a single writer per team, so there's no concurrent-writer race.

Ghost-team guard

If a team is removed while the student's socket is alive, the subscribeDeleteTeam handler redirects. If the socket is dead (the Morgan case), that message is missed — so the authoritative resync fetch also checks for it. The check runs only on the getGameSession result (not subscription deltas, whose nested teams can be partial — and the delta path adds no coverage, since a dead socket delivers no deltas):

// inside establishSubscriptions, after the authoritative fetch:
if (
  fetchedGame.currentQuestionIndex != null &&                 // game has started
  !fetchedGame.teams?.some((tm) => tm.id === teamId)          // my team is gone
) {
  redirectAsDropped(fetchedGame, 'team_missing_on_fetch');
  return;
}
const redirectAsDropped = (g: IGameSession, trigger: string) => {
  trackEvent(PlayEvent.STUDENT_DROPPED, { gameSessionId, teamId, trigger, ... });
  window.localStorage.removeItem(StorageKey);
  window.localStorage.removeItem(StorageKeyAnswer);
  window.localStorage.removeItem(StorageKeyEduDataStudentId);
  gameSessionSubscription?.unsubscribe?.();
  teamsSubscription?.unsubscribe?.();
  flushAndRedirect('https://play.rightoneducation.com');
};

Gating on currentQuestionIndex != null (game started) avoids a false positive in the just-joined window, where a brand-new team can be briefly absent from a read due to eventual consistency.

Observability events

Added to the PlayEvent enum (play/src/lib/analytics.ts); the connection_state_change / tab_visibility_change trackers were already wired globally from App.tsx:

  • SUBSCRIPTION_FIRST_DATA — first received message (vs the optimistic SUBSCRIPTION_ESTABLISHED); carries msToFirstData.
  • SUBSCRIPTION_RESYNC — action: 'reestablish' | 'noop' | 'error' with the trigger reason.
  • STALE_SKIP — a payload rejected by the ordering cursor.

These let us measure, in production: how often resyncs fire and how often they actually rebuild, how often stale/out-of-order payloads arrive, and — via connection_state_change with visibility: 'visible' + isOnline: true — the rate of foregrounded-dead sockets that justify the poll.

Rejoin / duplicate-name fix

Root cause (June 23 lockouts): clicking "No" on the rejoin prompt deleted the student's own identity from localStorage, then the fresh-join path collided with their own still-present team and hard-blocked them. The fix (PregameContainer.tsx) keeps identity intact and reattaches by teamId:

// "No" no longer deletes StorageKey — just dismisses the modal
const handleDontRejoinSession = () => { setRejoinGameObject(null); };

// identity is the teamId, never the display name
const ownsLiveTeam = (gs: IGameSession, stored: LocalModel | null): stored is LocalModel =>
  !!stored && stored.gameSessionId === gs.id && gs.teams.some((t) => t.id === stored.teamId);

const classifyEntry = (gs, stored): EntryDecision => {
  if (ownsLiveTeam(gs, stored)) return { kind: 'recover', model: stored };  // reattach
  if (gs.currentState !== GameSessionState.TEAMS_JOINING) return { kind: 'reject_state' };
  return { kind: 'join' };
};

Three layers prevent a double-join: (1) classifyEntry → one switch where exactly one branch acts; (2) an ownsLiveTeam guard at the team-creation site; (3) an isSubmittingRef in-flight latch against rapid re-taps. The genuine duplicate-name guard (a different student taking a taken name) is preserved, and now sets the error flag correctly so the message actually renders.

Leaked-subscription fix (P1)

subscribeGraphQL is async (returns a Promise<Subscription>); the old code stored the Promise and called .unsubscribe() on it (a no-op), so every rejoin/refresh stacked a live subscription. Fixed by await-ing the subscribe calls to get the real handles, storing those, unsubscribing them in cleanup/teardown, and guarding the async race with the ignore flag (if (ignore) { sub.unsubscribe(); return; } after each await). This is what makes the self-managed re-establish in P2 safe to do repeatedly.

Clone this wiki locally