Skip to navigation

Live updates

Keep state from the stream, reconnect after drops and errors, or poll the changes feed instead.

The Quickstart client follows a game in two short files. This page adds what a production client needs. It shows how to keep a game’s current state, then gives four rules for staying connected. Each rule is a small change to the quickstart’s follow.mts, and the last section has the whole client with all four. The Developer plan has no stream, so on Developer, skip to Without the stream.

How the stream works

Each stream is a journal of changes. There are two kinds:

  • game:<game id> carries one game. That covers the game, its live state, plays, drives, game roster and player stats.
  • league:<alias> carries what the league’s games share. That covers teams, players, venues, seasons and weeks, plus rosters, injuries, transactions and depth charts.

Every change has a seq. Within a stream, seqs have no gaps and arrive in order, so a client that has applied seq N has applied everything before it. Every change also carries the entity’s full current state. An upsert replaces what you hold under entity_type and entity_id, and a delete removes it.

A subscription starts in one of three ways:

StartSendWhat arrives
Resumeresume: { "<stream>": <seq> }Every change after that seq, then live changes. Use the seq from a REST read or the last one you applied.
SnapshotNo resume, the defaultA snapshot of every live entity as of a seq, then every change after it.
Livesnapshot: false and no resumeOnly changes from now on.

The quickstart resumes from a REST read. One request returns the game’s current state and the seq to stream from. This works for game streams. For a league stream, subscribe with a snapshot.

Keep state

Every change carries the entity’s full state, so a map keyed by type and id holds everything a client needs. Use this onChange in place of the quickstart’s, and read from state when you render:

on-change.mts
import type { Change } from "@statpad/sdk";
export const state = new Map<string, Change["payload"]>();
export function onChange({ op, entity_type, entity_id, payload }: Change) {
const key = `${entity_type}:${entity_id}`;
if (op === "delete") state.delete(key);
else state.set(key, payload);
}

Fill the map from the REST read before you subscribe. The game read returns the game, its live state and both teams. The plays, drives, roster and box score endpoints return the rest. Build a scoreboard shows which entity_id each one uses.

Applying the same change twice leaves the same state, so a repeated change after a reconnect is harmless.

Stay connected

Connections drop during deploys, on mobile networks and when laptops sleep. The quickstart already resumes from the last seq it applied. These four rules cover the remaining failures.

Back off between reconnects

During an outage, a client that reconnects every second sends a failed attempt every second until the outage ends. Wait about a second after the first failure and double the wait after each failure, up to 30 seconds. Add random jitter so that many clients don’t reconnect at the same moment. Reset the count when a subscription succeeds:

let attempt = 0;
// in the message handler
if (msg.type === "subscribed") attempt = 0;
// in place of the quickstart's close handler
ws.on("close", (code) => {
const delay = Math.min(30_000, 1000 * 2 ** attempt++) * (0.5 + Math.random() / 2);
setTimeout(connect, delay);
});

Notice a dead connection

A connection can stop delivering messages without the socket closing, for example when a laptop sleeps or a router drops the route. The server sends heartbeat every 5 seconds, and can pause it for up to 10 seconds while it waits for a ping reply. If 20 seconds pass with no message, close the socket yourself, and the close handler reconnects and resumes:

let silence: NodeJS.Timeout | undefined;
const heard = () => {
clearTimeout(silence);
silence = setTimeout(() => ws.terminate(), 20_000);
};
ws.on("open", heard);
ws.on("message", heard);
ws.on("close", () => clearTimeout(silence));

With this rule in place, you can test reconnects by turning off Wi-Fi for 30 seconds during a game. The client closes the silent connection, retries with backoff until the network returns, then resumes from its last seq.

Handle stream errors

An error message that names a stream ends that subscription. The connection stays open, so for most codes you subscribe again:

CodeWhyWhat to do
slow_consumerYour client fell behind its send buffer.Subscribe again from your last seq.
internalThe subscription failed on Statpad’s side.Subscribe again from your last seq.
unavailableStatpad couldn’t check your allowance or capacity.Wait a few seconds, then subscribe again.
rate_limitedYou subscribed to streams too fast.Wait retry_after seconds, then subscribe again.
resync_requiredYour seq is older than the stream still holds. A game stream keeps at least 7 days after the game ends.Read the game over REST, replace your state with it, and resume from its seq.
quota_exhaustedThe account used this period’s allowance.Stop until the period resets or you upgrade the plan.
too_many_subscriptionsThe account is at its plan’s subscription cap, or this connection holds 100.Unsubscribe from streams you’ve finished with, or open another connection.
forbidden, unknown_stream, invalid_resume, bad_requestThe request is malformed, or the plan doesn’t allow it.Stop. Retrying won’t help.

In code, move the subscribe into a function so the handler can call it again:

const subscribe = () => ws.send(JSON.stringify({ type: "subscribe", streams: [stream], resume: { [stream]: lastSeq } }));
if (msg.type === "error") {
switch (msg.code) {
case "slow_consumer":
case "internal":
subscribe();
break;
case "unavailable":
setTimeout(subscribe, 5_000);
break;
case "rate_limited":
setTimeout(subscribe, msg.retry_after * 1000);
break;
case "resync_required":
try {
lastSeq = (await readGame()).seq;
subscribe();
} catch {
ws.close();
}
break;
default:
process.exit(1);
}
}

Errors describes every code.

Stop on close codes that won’t recover

When the server closes the connection, the close code says whether reconnecting can help. For almost every code, back off, reconnect and resume. The exception is 1008, which means the key is invalid or revoked, or the account has no streaming access. Reconnecting won’t help until the key or plan changes:

ws.on("close", (code) => {
if (code === 1008) process.exit(1);
// otherwise back off and reconnect
});

4008 means the account already has as many connections as its plan allows. Backoff handles it, but if it keeps happening, close connections you don’t need. Errors lists every close code.

The whole client

follow.mts
import { Statpad } from "@statpad/sdk";
import WebSocket from "ws";
import { onChange } from "./on-change.mts";
const apiKey = process.env.STATPAD_API_KEY!;
const gameId = process.argv[2];
const stream = `game:${gameId}`;
const statpad = new Statpad({ apiKey });
const readGame = async () => (await statpad.games.getGame({ path: { league: "nfl", game_id: gameId } })).data;
let lastSeq = (await readGame()).seq;
let attempt = 0;
function connect() {
const ws = new WebSocket("wss://stream.statpad.dev/v1/stream", {
headers: { Authorization: `Bearer ${apiKey}` },
});
const subscribe = () => ws.send(JSON.stringify({ type: "subscribe", streams: [stream], resume: { [stream]: lastSeq } }));
let silence: NodeJS.Timeout | undefined;
const heard = () => {
clearTimeout(silence);
silence = setTimeout(() => ws.terminate(), 20_000);
};
ws.on("open", heard);
ws.on("message", async (raw) => {
heard();
const msg = JSON.parse(raw.toString());
if (msg.type === "welcome") subscribe();
if (msg.type === "subscribed") attempt = 0;
if (msg.type === "changes") {
for (const change of msg.changes) {
onChange(change);
lastSeq = change.seq;
}
}
if (msg.type === "error") {
console.error(`${msg.code}: ${msg.message}`);
switch (msg.code) {
case "slow_consumer":
case "internal":
subscribe();
break;
case "unavailable":
setTimeout(subscribe, 5_000);
break;
case "rate_limited":
setTimeout(subscribe, msg.retry_after * 1000);
break;
case "resync_required":
try {
lastSeq = (await readGame()).seq;
subscribe();
} catch {
ws.close();
}
break;
default:
process.exit(1);
}
}
});
ws.on("error", (err) => console.error(err.message));
ws.on("close", (code) => {
clearTimeout(silence);
if (code === 1008) {
console.error("The key was rejected or the plan has no streaming access.");
process.exit(1);
}
const delay = Math.min(30_000, 1000 * 2 ** attempt++) * (0.5 + Math.random() / 2);
console.error(`Disconnected (${code}), resuming from seq ${lastSeq} in ${Math.round(delay / 1000)}s`);
setTimeout(connect, delay);
});
}
connect();

Without the stream

On Developer, or anywhere you can’t keep a WebSocket open, poll the changes feed. GET /v1/{league}/games/{id}/changes returns the same changes the stream sends, starting after the seq you pass, so the quickstart’s onChange works as is:

poll.mts
import { Statpad, StatpadError } from "@statpad/sdk";
import { setTimeout as sleep } from "node:timers/promises";
import { onChange } from "./on-change.mts";
const statpad = new Statpad({ apiKey: process.env.STATPAD_API_KEY! });
const path = { league: "nfl", game_id: process.argv[2] };
let lastSeq = (await statpad.games.getGame({ path })).data.seq;
while (true) {
try {
const { data: page } = await statpad.changes.listGameChanges({ path, query: { after_seq: lastSeq } });
for (const change of page.data) {
onChange(change);
lastSeq = change.seq;
}
if (lastSeq < page.head_seq) continue;
} catch (err) {
if (!(err instanceof StatpadError && err.code === "resync_required")) throw err;
lastSeq = (await statpad.games.getGame({ path })).data.seq;
}
await sleep(5_000);
}

When lastSeq is behind head_seq, the loop requests the next page at once. Otherwise it waits five seconds. Each poll counts as one request against your allowance, so polling every five seconds uses about 720 requests per hour. The SDK retries rate_limited, internal and unavailable responses itself.

Replay a game

Subscribe with resume set to 0 and the stream sends the game’s whole journal from the first change. If the game is still going, live changes follow. Each replayed change counts as one request against your allowance, about 1,300 for a whole NFL game. To try a replay without a key, Sample responses feeds a recorded game through the same onChange.