Odds API Node.js Tutorial: Streaming Real-Time Odds with WebSockets

Build a reliable Node.js client for real-time odds with the ws package. Snapshots, deltas, sequence-gap detection, resync and reconnects with backoff.

Polling an odds endpoint every few seconds works until it doesn't: you pay for every request, you see changes late, and you still miss moves that happen between polls. A WebSocket odds stream inverts that. You subscribe once, receive the full state, and from then on the server pushes only what changes.

The catch is that a streaming client has to be correct in ways a polling client doesn't. If you miss one message, your local state is silently wrong until something forces a rebuild. This odds API Node.js tutorial builds a client that handles that properly: snapshot plus deltas, sequence-gap detection, resync, a dead-connection watchdog, and reconnects with exponential backoff. Every piece below goes into a single file, stream.mjs, in the order shown.

Prerequisites

The stream endpoint is wss://api.preciseapi.com/v1/stream. It is billed at one credit when the connection opens and one credit per connection-minute while it stays open, regardless of how many messages you receive.

The protocol in one table

The client sends subscribe, resync, unsubscribe and ping. The server sends:

typeWhenHas seq
welcomeOn connect: connection id, plan, heartbeat_ms, remaining creditsNo
subscribedEcho of your normalized subscriptionNo
snapshotFull state for the subscription, same shape as /v1/oddsYes
deltaBatched every 250 ms: changes (full markets) and removedYes
eventStatus, score or clock change for a subscribed eventYes
heartbeatEvery 15 s, carrying the latest seq sentCurrent value
errorInvalid message or subscription; fatal ones are followed by a closeNo

snapshot, delta and event each increment seq by exactly one on a given connection. That single property is what makes gap detection possible. The full reference is in the WebSocket odds API docs.

Step 1: Subscription and local state

Keep state as two maps: events by id, and markets by market id. Market ids are stable for an event, book, market key, period and subject, so an incoming market simply replaces the previous version, including when the line moves.

import WebSocket from 'ws';

const URL = 'wss://api.preciseapi.com/v1/stream';
const SUBSCRIPTION = {
  type: 'subscribe',
  leagues: ['nba', 'nhl'],
  books: ['pinnacle', 'draftkings', 'fanduel'],
  markets: ['moneyline', 'spread', 'total'],
  periods: ['full_game'],
};
const FATAL = new Set([4001, 4002, 4003]); // auth, credits, plan: retrying won't help

const events = new Map(); // event_id -> event (without bookmakers)
const markets = new Map(); // market_id -> { event_id, book, market }

function loadSnapshot(data) {
  events.clear();
  markets.clear();
  for (const { bookmakers, ...event } of data) {
    events.set(event.id, event);
    for (const b of bookmakers) {
      for (const m of b.markets) markets.set(m.id, { event_id: event.id, book: b.id, market: m });
    }
  }
}

function applyDelta(msg) {
  for (const { event_id, book, market } of msg.changes) {
    const prev = markets.get(market.id);
    markets.set(market.id, { event_id, book, market });
    onMarketChange(prev?.market, market, book, event_id);
  }
  for (const { market_id } of msg.removed) markets.delete(market_id);
}

function onMarketChange(prev, next, book, eventId) {
  if (!prev) return;
  const before = prev.outcomes.map((o) => o.price).join('/');
  const after = next.outcomes.map((o) => o.price).join('/');
  if (next.suspended !== prev.suspended) console.log(`${eventId} ${book} ${next.key} ${next.suspended ? 'suspended' : 'reopened'}`);
  else if (before !== after) console.log(`${eventId} ${book} ${next.key} ${before} -> ${after}`);
}

Every field in the subscription except one of leagues or event_ids is optional. markets defaults to moneyline, spread and total, and periods to full_game. Include player_* keys to stream props. Sending a new subscribe replaces the previous one, and each subscribe is followed by a fresh snapshot.

Note the suspended check. When a source stops reporting, its markets arrive as ordinary deltas with suspended: true. Your application should stop treating those prices as live offers.

Step 2: Connect and authenticate

Authenticate with the Authorization header. (Browsers can't set headers on WebSockets, so the server also accepts {"type":"auth","api_key":"…"} as the first message, but your key belongs on a server: odds API JavaScript that ships to a browser exposes it. Keys in the URL are refused.)

let ws;
let attempt = 0;
let lastSeq = 0;
let resyncing = false;
let lastResyncAt = 0;
let watchdog;
let resyncTimer;
let heartbeatMs = 15_000;
let stopping = false;

function connect() {
  ws = new WebSocket(URL, { headers: { Authorization: `Bearer ${process.env.PRECISEAPI_KEY}` } });

  ws.on('open', () => {
    lastSeq = 0; // seq is per connection
    resyncing = true; // nothing is trustworthy until the first snapshot
    ws.send(JSON.stringify(SUBSCRIPTION));
    lastResyncAt = Date.now(); // subscribe counts toward the one-per-second limit
    armWatchdog();
  });

  ws.on('message', (raw) => {
    armWatchdog();
    let msg;
    try {
      msg = JSON.parse(raw);
    } catch {
      return;
    }
    handle(msg);
  });

  ws.on('close', (code, reason) => {
    clearTimeout(watchdog);
    clearTimeout(resyncTimer);
    if (stopping) return;
    if (FATAL.has(code)) {
      console.error(`stream closed with ${code} ${reason}; not reconnecting`);
      process.exitCode = 1;
      return;
    }
    scheduleReconnect(code === 4029 ? 10_000 : 0);
  });

  ws.on('error', (err) => console.warn('socket error:', err.message)); // 'close' follows
}

The close codes are worth handling explicitly. 4001 (authentication failed), 4002 (out of credits) and 4003 (streaming not in your plan) will fail the same way on every retry, so stop and alert a human. 4029 means too many concurrent connections for your plan, which often happens when a previous process hasn't released its socket yet, so wait a little longer and retry. Anything else, including network drops and 1013 during maintenance, gets a normal backoff.

Step 3: Handle messages and detect gaps

function handle(msg) {
  switch (msg.type) {
    case 'welcome':
      heartbeatMs = msg.heartbeat_ms || heartbeatMs;
      console.log(`connected ${msg.connection_id}, credits remaining: ${msg.credits_remaining}`);
      return;
    case 'subscribed':
      return;
    case 'snapshot':
      loadSnapshot(msg.data);
      lastSeq = msg.seq;
      resyncing = false;
      attempt = 0; // healthy again: reset backoff
      console.log(`snapshot seq=${msg.seq}: ${events.size} events, ${markets.size} markets`);
      return;
    case 'delta':
    case 'event':
      if (resyncing) return;
      if (msg.seq !== lastSeq + 1) return requestResync(`expected seq ${lastSeq + 1}, got ${msg.seq}`);
      lastSeq = msg.seq;
      if (msg.type === 'delta') applyDelta(msg);
      else events.set(msg.data.id, { ...events.get(msg.data.id), ...msg.data });
      return;
    case 'heartbeat':
      // Heartbeats carry the latest seq the server has sent. If it is ahead of us, we missed something.
      if (!resyncing && msg.seq > lastSeq) requestResync(`heartbeat seq ${msg.seq} > ${lastSeq}`);
      return;
    case 'error':
      console.warn(`server error ${msg.code}: ${msg.message}`);
      if (msg.code === 'rate_limited' && resyncing) sendResync(); // throttled retry
      return;
    default:
      return; // pong, unsubscribed and future message types
  }
}

Three details here are easy to get wrong:

  1. A heartbeat does not increment seq. It reports the current value. Treating it as the next message in the sequence (a common bug) triggers a resync every 15 seconds. Comparing it with your last seen value instead gives you a second, independent gap check that catches a lost final message during a quiet period.
  2. While a resync is in flight, ignore deltas. They describe changes relative to state you have already decided not to trust, and the incoming snapshot supersedes them.
  3. The default branch ignores unknown types. New message types can be added without a version bump, so a client that throws on unknown input will break on a backwards-compatible change.

Step 4: Resync without tripping the rate limit

The server accepts at most one subscribe or resync per second per connection and answers extra requests with an error whose code is rate_limited. Throttle on the client so you rarely see that error, and retry if you do:

function requestResync(why) {
  console.warn(`gap detected (${why}), resyncing`);
  resyncing = true;
  sendResync();
}

function sendResync() {
  clearTimeout(resyncTimer);
  const wait = 1050 - (Date.now() - lastResyncAt); // server allows one per second
  if (wait > 0) {
    resyncTimer = setTimeout(sendResync, wait);
    return;
  }
  lastResyncAt = Date.now();
  if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify({ type: 'resync' }));
}

The timer is cleared on close, so a resync scheduled for a dead connection can't fire on its replacement.

Step 5: Watchdog and reconnect with backoff

TCP connections can die without either side noticing for minutes. The server sends a heartbeat every 15 seconds, so if nothing at all arrives for two and a half intervals, assume the connection is gone and replace it:

function armWatchdog() {
  clearTimeout(watchdog);
  watchdog = setTimeout(() => {
    console.warn('no traffic for 2.5 heartbeats, dropping connection');
    ws.terminate(); // triggers 'close' -> reconnect
  }, heartbeatMs * 2.5);
}

function scheduleReconnect(minDelay) {
  const base = Math.min(30_000, 500 * 2 ** attempt);
  const delay = Math.max(minDelay, base / 2 + Math.random() * (base / 2)); // jitter
  attempt++;
  console.log(`reconnecting in ${Math.round(delay)} ms (attempt ${attempt})`);
  setTimeout(connect, delay);
}

process.on('SIGINT', () => {
  stopping = true;
  ws?.close(1000, 'client shutdown');
});

connect();

The backoff starts at about half a second, doubles each attempt and caps at 30 seconds. Jitter matters if you run several workers: without it they all reconnect at the same instant after an outage. The attempt counter resets only after a snapshot arrives, not when the socket opens, so a connection that opens and immediately fails still backs off.

On reconnect, seq starts again from zero and you resubscribe, so the first message you act on is always a fresh snapshot. Treat every snapshot as the complete state, not a patch.

Testing the failure paths

Most bugs in a streaming odds API Node.js client live in code that only runs when something goes wrong, so test it deliberately. A small local ws server that sends a snapshot, skips a sequence number, sends a heartbeat ahead of the last delta, goes silent, and finally closes with 4001 exercises every branch above in a few seconds.

Or use the odds API Node.js SDK

If you'd rather not own this code, the official Node.js odds client, @preciseapi/node, implements the same behaviour: reconnects with jittered backoff, automatic resync on gaps (throttled to the server limit), a watchdog at 2.5 heartbeat intervals, and no reconnect after 4001, 4002 or 4003.

import { PreciseAPI } from '@preciseapi/node';

const client = new PreciseAPI({ apiKey: process.env.PRECISEAPI_KEY });
const stream = client.stream({ leagues: ['nba'], markets: ['moneyline', 'spread'] });

stream.on('snapshot', (events) => console.log('full state:', events.length, 'events'));
stream.on('market', ({ event_id, book, market }) => console.log(event_id, book, market.key));
stream.on('gap', ({ expected, received }) => console.warn('gap', expected, received));
stream.on('error', (err) => console.error(err.code, err.message));

Where to go next

With a reliable odds API Node.js client in place, the obvious next projects are an odds screen that fans this state out to browsers, or a steam move detector that watches deltas across books. Both reuse the state store above unchanged. The live odds API page lists which leagues and sources are covered in-play, and the streaming reference has the full message schemas.

Keep reading