Skip to navigation

Follow many games

Follow a whole slate on one connection, start a stream from a snapshot, or poll instead.

The Quickstart follows one game. A scoreboard for a whole day needs every game that’s on. This page shows how many streams a plan can hold, how to start a stream from a snapshot, and how to follow a slate. It ends with two ways to poll instead.

One stream per game

league:<alias> carries the data a league’s games share. That’s teams, players, venues, seasons and weeks, plus rosters, injuries, transactions and depth charts. It carries no games, live states or plays. A live score comes only from the game’s own stream, so each game you show live needs a game:<id> subscription.

Your plan caps subscriptions per account, across all its connections and keys:

PlanConnectionsSubscriptions
DeveloperNoneNone
Pro trial210
Pro520
Business10150

One connection holds at most 100 subscriptions. A stream past your plan’s cap, or past 100 on one connection, gets too_many_subscriptions for that stream. The connection stays open, and the other streams in the message still subscribe.

One subscribe message names 1 to 100 streams. A message with more gets bad_request for the whole message, with no stream set, and none of its streams subscribe.

If a day has more games than your plan’s cap, follow the games you show live and poll the schedule for the rest.

Start from a snapshot

A subscribe without resume starts from a snapshot. This is the way to start a league stream, which has no REST read to resume from. It also starts a game stream in one request, instead of the game, roster and box score reads.

The server sends:

  1. subscribed with mode: "snapshot" and a seq.
  2. One or more snapshot messages, all with that seq. Each holds up to 500 entities. The last one has last: true.
  3. changes, starting at seq + 1.

Buffer the entities until last arrives. Then replace your state for the stream with them, and record the seq. After that, apply changes as usual.

A league snapshot holds the league’s seasons, weeks, venues and teams, every player who has appeared in its games, rosters or injury reports, and its open injuries. A game snapshot holds the game, its live state, drives, plays, game roster and player stats. It also holds the teams, venue and players the game references.

A snapshot subscribe counts as one request against your allowance, whatever the snapshot’s size. It also takes one token from your snapshot bucket, which holds as many tokens as your plan has subscriptions. Resume subscribes, such as after a reconnect, don’t use the bucket. Rate limits has the details.

This module keeps one state map per stream. Game roster entries and stat lines use the player’s id as entity_id, so separate maps keep two games’ entries apart:

streams.mts
import type { Change } from "@statpad/sdk";
type Entity = Pick<Change, "entity_type" | "entity_id" | "payload">;
export const states = new Map<string, Map<string, Change["payload"]>>();
export const lastSeq = new Map<string, number>();
const pending = new Map<string, Entity[]>();
export function onMessage(msg: any) {
if (msg.type === "subscribed") pending.set(msg.stream, []);
if (msg.type === "snapshot") {
const entities: Entity[] = [...(pending.get(msg.stream) ?? []), ...msg.entities];
pending.set(msg.stream, entities);
if (!msg.last) return;
states.set(msg.stream, new Map(entities.map((e) => [`${e.entity_type}:${e.entity_id}`, e.payload])));
lastSeq.set(msg.stream, msg.seq);
}
if (msg.type === "changes") {
const state = states.get(msg.stream) ?? new Map();
states.set(msg.stream, state);
for (const { seq, op, entity_type, entity_id, payload } of msg.changes as Change[]) {
const key = `${entity_type}:${entity_id}`;
if (op === "delete") state.delete(key);
else state.set(key, payload);
lastSeq.set(msg.stream, seq);
}
}
}

league.mts follows league:nfl. The first time it connects, it has no seq, so it subscribes for a snapshot. After a disconnect, it resumes from the last seq it applied:

league.mts
import WebSocket from "ws";
import { lastSeq, onMessage, states } from "./streams.mts";
const stream = "league:nfl";
function connect() {
const ws = new WebSocket("wss://stream.statpad.dev/v1/stream", {
headers: { Authorization: `Bearer ${process.env.STATPAD_API_KEY}` },
});
ws.on("message", (raw) => {
const msg = JSON.parse(raw.toString());
if (msg.type === "welcome") {
const seq = lastSeq.get(stream);
const resume = seq === undefined ? undefined : { [stream]: seq };
ws.send(JSON.stringify({ type: "subscribe", streams: [stream], resume }));
}
onMessage(msg);
if (msg.type === "subscribed") console.log(`subscribed ${msg.stream}, mode ${msg.mode}, seq ${msg.seq}`);
if (msg.type === "snapshot") console.log(`snapshot: ${msg.entities.length} entities at seq ${msg.seq}${msg.last ? ", last" : ""}`);
if (msg.type === "snapshot" && msg.last) {
const counts: Record<string, number> = {};
for (const key of states.get(stream)!.keys()) {
const type = key.split(":")[0];
counts[type] = (counts[type] ?? 0) + 1;
}
console.log(counts);
}
if (msg.type === "changes") console.log(`changes: up to seq ${lastSeq.get(stream)}`);
});
ws.on("error", (err) => console.error(err.message));
ws.on("close", (code) => {
console.log(`Disconnected (${code}), resuming from seq ${lastSeq.get(stream)}`);
setTimeout(connect, 1000);
});
}
connect();

A real league:nfl snapshot spans several messages. This run is against a test server that sends 1,200 players in three messages, then two changes, then closes the connection:

subscribed league:nfl, mode snapshot, seq 40
snapshot: 500 entities at seq 40
snapshot: 500 entities at seq 40
snapshot: 200 entities at seq 40, last
{ player: 1200 }
changes: up to seq 42
Disconnected (1012), resuming from seq 42
subscribed league:nfl, mode resume, seq 42
changes: up to seq 43

The second subscribe carried "resume": { "league:nfl": 42 }, so the server sent only seq 43. For production, add the backoff and error handling from Live updates.

Follow a slate

To follow a day of games:

  1. Read the day’s schedule.
  2. Subscribe to each game that’s live or starts within 30 minutes.
  3. Unsubscribe from each game when it ends.
  4. Read the schedule again every few minutes, to catch games as they start.

slate.mts does this for NCAAF on one connection. It uses streams.mts, so each game starts from a snapshot. Set maxSubscriptions to your plan’s cap:

slate.mts
import { Statpad, type Game } from "@statpad/sdk";
import WebSocket from "ws";
import { onMessage, states } from "./streams.mts";
const apiKey = process.env.STATPAD_API_KEY!;
const league = "ncaaf";
const maxSubscriptions = 20;
const statpad = new Statpad({ apiKey });
const ws = new WebSocket("wss://stream.statpad.dev/v1/stream", { headers: { Authorization: `Bearer ${apiKey}` } });
const following = new Set<string>();
let timer: NodeJS.Timeout | undefined;
async function refresh() {
try {
const today = new Date().toLocaleDateString("en-CA", { timeZone: "America/New_York" });
const { data: schedule } = await statpad.games.listGames({ path: { league }, query: { date: today, limit: 500 } });
const soon = Date.now() + 30 * 60_000;
const streams = schedule.data
.filter((g) => ["inprogress", "halftime", "delayed"].includes(g.status) || (g.status === "scheduled" && Date.parse(g.scheduled_at) < soon))
.map((g) => `game:${g.id}`)
.filter((stream) => !following.has(stream))
.slice(0, maxSubscriptions - following.size);
if (streams.length > 0) ws.send(JSON.stringify({ type: "subscribe", streams }));
} catch (err) {
console.error(`Schedule read failed: ${(err as Error).message}`);
}
}
ws.on("message", (raw) => {
const msg = JSON.parse(raw.toString());
onMessage(msg);
if (msg.type === "welcome") {
refresh();
timer = setInterval(refresh, 5 * 60_000);
}
if (msg.type === "subscribed") {
following.add(msg.stream);
console.log(`subscribed ${msg.stream}, mode ${msg.mode}, seq ${msg.seq}`);
}
if (msg.type === "unsubscribed") {
following.delete(msg.stream);
console.log(`unsubscribed ${msg.stream}`);
}
if (msg.type === "error") {
following.delete(msg.stream);
console.error(`${msg.code}: ${msg.message}`);
}
if (msg.type === "changes") {
const game = states.get(msg.stream)?.get(`game:${msg.stream.slice(5)}`) as Game | undefined;
if (game && ["complete", "closed"].includes(game.status)) {
ws.send(JSON.stringify({ type: "unsubscribe", streams: [msg.stream] }));
}
}
});
ws.on("error", (err) => console.error(err.message));
ws.on("close", (code) => {
clearInterval(timer);
console.error(`Disconnected (${code})`);
});

en-CA formats the date as YYYY-MM-DD, the format date takes. A date with the default tz is a day in US Eastern time.

refresh subscribes to no more games than your free slots. If more games are on, poll the schedule for the rest. A failed schedule read logs the error, and the next refresh tries again.

The script doesn’t reconnect. When the connection closes, it stops reading the schedule and logs the close code. Stay connected shows how to reconnect and resume.

This run used a test server, with league set to "nfl" and a fixed date. A recorded NFL game replayed from the middle of the game to the final, and then the test server stopped:

subscribed game:01a1f1d5-8bb4-7dc8-8df2-3ed7a3293a49, mode snapshot, seq 389
unsubscribed game:01a1f1d5-8bb4-7dc8-8df2-3ed7a3293a49
Disconnected (1006)

The script frees each slot when the game is final, but corrections keep arriving for up to 3 hours after the final. If you store stats and have slots to spare, stay subscribed for that time. Otherwise, read the box score again later.

A game:<id> stream opens when the league publishes the game, which can be months before it starts. A subscription to an early game holds one of your slots until you unsubscribe.

Poll the schedule

If your screen shows only statuses and scores, you don’t need the stream. GET /v1/{league}/games returns each game’s status, away_score and home_score, with the teams. Each page counts as one request:

poll-schedule.mts
import { Statpad } from "@statpad/sdk";
import { setTimeout as sleep } from "node:timers/promises";
const statpad = new Statpad({ apiKey: process.env.STATPAD_API_KEY! });
const today = new Date().toLocaleDateString("en-CA", { timeZone: "America/New_York" });
const over = ["complete", "closed", "suspended", "postponed", "cancelled"];
while (true) {
const { data: schedule } = await statpad.games.listGames({ path: { league: "ncaaf" }, query: { date: today, limit: 500 } });
for (const game of schedule.data) console.log(game.id, game.status, game.away_score, game.home_score);
if (schedule.data.every((game) => over.includes(game.status))) break;
await sleep(30_000);
}

The loop stops once every game of the day is complete, closed, suspended, postponed or cancelled. At one page every 30 seconds, a 4-hour window costs 480 requests. This works on every plan, including Developer. The schedule has no period or clock, so read the game, or follow it, where you need them.

Poll the changes window

GET /v1/{league}/changes lists which entities changed in a time window, for clients that refetch rather than stream. Each entry names its entity_type, entity_id, game_id and latest version. Refetch what changed, then ask for the next window from window_end:

changed.mts
import { Statpad, paginate } from "@statpad/sdk";
import { setTimeout as sleep } from "node:timers/promises";
const statpad = new Statpad({ apiKey: process.env.STATPAD_API_KEY! });
const path = { league: "nfl" };
let from = new Date(Date.now() - 60 * 60_000).toISOString();
while (true) {
const games = new Set<string>();
for await (const page of paginate(statpad.changes.listChangedEntities, { path, query: { from } })) {
for (const entity of page.data) if (entity.game_id) games.add(entity.game_id);
from = page.window_end;
}
for (const game_id of games) {
const { data: detail } = await statpad.games.getGame({ path: { ...path, game_id } });
console.log(`${detail.away_team.alias} ${detail.game.away_score}, ${detail.home_team.alias} ${detail.game.home_score}, ${detail.game.status}`);
}
console.log(`next window from ${from}`);
await sleep(60_000);
}

Against a test server that had just replayed a recorded game, the first pass printed:

BUF 23, MIN 6, complete
next window from 2026-11-19T02:53:49.393451Z

The window rules:

  • A window ends no later than 60 seconds ago, so a change shows up here at least a minute after it happens.
  • A window spans at most 24 hours. With an older from, page through one window at a time.
  • window_end is where this window stopped. Pass it as the next from, and you miss no change.
  • Each entity appears once per game it changed in, with its latest version.
  • A page holds 1,000 entities by default and 5,000 at most. Every page of one window shares its window_end.

For anything faster than a minute, use the stream, or poll one game’s GET /v1/{league}/games/{id}/changes as in Live updates.