REST, WebSocket or Webhooks? Choosing How to Receive Odds Data

A decision guide to the three ways PreciseAPI delivers odds data. What polling really costs on each plan, what the WebSocket stream's snapshots, sequence numbers and market versions guarantee, how signed line-move webhooks are retried and de-duplicated, and how to combine all three.

By PreciseAPI Engineering

Published

PreciseAPI delivers the same normalized odds three ways. REST endpoints answer when you ask. A WebSocket stream pushes every change once you subscribe. Webhooks POST a signed event to your server when a price moves past a threshold you set. They are not interchangeable, because each one gives a different guarantee about completeness and ordering, and each is available on different plans.

REST polling vs WebSockets covers freshness and the break-even point for a single polling loop. This guide goes one level deeper. It asks what each path actually promises, what it costs on the plan you're on, and what code you need for that promise to hold. Every limit quoted here comes from the credits, streaming and webhooks docs.

The three delivery paths side by side

RESTWebSocket streamWebhooks
Who starts itYou, one request at a timeYou open it, then the server pushesThe server POSTs to your HTTPS endpoint
What arrivesThe full current state for your queryA snapshot, then changed and removed markets every 250 msOne line.moved event per qualifying price move
CompletenessComplete as of the responseComplete if you apply every message in orderA filtered sample: a threshold and a 10-minute cooldown per market
OrderingEach answer stands alone; meta.versionseq per connection, version per marketNone: events can arrive out of order or twice
BillingPer successful call: 2 credits for /v1/odds, 3 for /v1/props1 credit on open, then 1 per connection-minute1 credit per delivered alert
PlansEvery plan, including the free Sandbox keySyndicate (10 connections)Edge, Sharp and Syndicate

The row that matters most is completeness. REST and the stream can both give you a provably correct board. Webhooks can't, by design, and that decides most architectures.

Start from your plan

The binding constraint is different on each plan, so the same design can be cheap on one and impossible on another. These figures come from the plan definitions behind pricing:

PlanCreditsRequests / minIn-play oddsStreamWebhook endpoints / alert rules
Edge100,000 / month300NoNo2 / 10
SharpUnlimited1,200NoNo10 / 100
SyndicateUnlimited3,000Yes10 connections25 / 500

REST: a budget as much as an interval

Every successful call is billed. Errors, including 429s, are not. There is no conditional request to fall back on: responses carry no ETag, so an unchanged board costs the same as a changed one. On Edge, it pays to write the polling plan down as arithmetic before writing the poller:

// Credits per call, from /docs/credits.
const COST = { '/v1/odds': 2, '/v1/props': 3, '/v1/best-lines': 3, '/v1/events': 1, '/v1/history': 3 };

// Credits a polling loop spends over `days`, polling for `hoursPerDay`.
function pollingCredits({ path, everySec, callsPerCycle = 1, hoursPerDay = 24, days = 30 }) {
  const cycles = Math.floor((hoursPerDay * 3600) / everySec) * days;
  return cycles * callsPerCycle * COST[path];
}

const plan = [
  { label: 'game lines, every 60 s, 6 h a day', path: '/v1/odds', everySec: 60, hoursPerDay: 6 },
  { label: 'props for a 12-game slate, every 120 s, 6 h a day', path: '/v1/props', everySec: 120, hoursPerDay: 6 },
  { label: 'schedule refresh, every 15 min, all day', path: '/v1/events', everySec: 900 },
];
let total = 0;
for (const p of plan) {
  const c = pollingCredits(p);
  total += c;
  console.log(`${p.label.padEnd(52)} ${c.toLocaleString('en-US').padStart(8)}`);
}
console.log(`${'total per 30 days (Edge includes 100,000)'.padEnd(52)} ${total.toLocaleString('en-US').padStart(8)}`);

Running it prints:

game lines, every 60 s, 6 h a day                      21,600
props for a 12-game slate, every 120 s, 6 h a day      16,200
schedule refresh, every 15 min, all day                 2,880
total per 30 days (Edge includes 100,000)              40,680

For comparison, one /v1/odds call every 30 seconds around the clock is 172,800 credits in 30 days, well past Edge's allowance. Every 60 seconds is 86,400, which leaves almost nothing for anything else. Three habits keep REST cheap:

On Sharp and Syndicate, the same arithmetic applies to requests instead of credits. Read X-RateLimit-Remaining from each response, and back off for Retry-After seconds on a 429.

When you diff successive polls, key by market id and pass include_suspended=true. Without that flag, a market whose source stopped reporting disappears from the response and looks the same as one the book removed. Remember that a market id includes its line. When a book moves its main spread from −3 to −3.5, the new line arrives under a new market id and the old id is gone. Matching markets across sportsbooks covers what that means for your keys.

The stream: completeness you have to maintain

The stream is the only path that tells you about every change as it happens. It sends each market that changed, conflated to its latest state within each 250 ms window. The guarantee holds only if your client applies messages exactly as the protocol intends. Four details are easy to miss in the streaming reference:

This board class handles all four, and it can also take a REST answer, which is what makes the hybrid designs later in this post safe:

// A board fed by the stream and, when needed, by REST: seq for gaps, version for order.
export class Board {
  constructor({ onGap }) {
    this.onGap = onGap; // e.g. () => ws.send(JSON.stringify({ type: 'resync' }))
    this.markets = new Map(); // market id -> { version, event_id, book, market } or a removal
    this.seq = null;
    this.building = null; // a snapshot still arriving in snapshot_part frames
    this.waiting = false; // a resync was asked for: deltas wait for its snapshot
  }

  put(eventId, book, market) {
    const held = this.markets.get(market.id);
    if (held && (held.removed ? market.version < held.version : market.version <= held.version)) return; // older copy
    this.markets.set(market.id, { version: market.version, event_id: eventId, book, market });
  }

  remove(r) {
    const held = this.markets.get(r.market_id);
    if (held && r.version !== undefined && held.version > r.version) return;
    this.markets.set(r.market_id, { version: r.version ?? held?.version ?? 0, removed: true });
  }

  // Every server message goes through here.
  onMessage(msg) {
    if ('seq' in msg && msg.type !== 'heartbeat') {
      const gap = this.seq !== null && msg.seq !== this.seq + 1 && msg.type !== 'snapshot';
      this.seq = msg.seq;
      if (gap) return this.lost();
    }
    if (msg.type === 'heartbeat' && this.seq !== null && msg.seq !== this.seq) return this.lost();
    if (msg.type === 'error' && ['rate_limited', 'internal_error'].includes(msg.code) && this.waiting) {
      setTimeout(this.onGap, 1000); // the resync was refused or failed: ask again
      return;
    }
    if (msg.type === 'snapshot' || msg.type === 'snapshot_part') {
      if (msg.type === 'snapshot') [this.building, this.waiting] = [new Map(), false];
      if (!this.building) return; // a part of a snapshot we didn't see start
      for (const e of msg.data) for (const b of e.bookmakers) for (const m of b.markets) this.building.set(m.id, { version: m.version, event_id: e.id, book: b.id, market: m });
      if (msg.last) [this.markets, this.building] = [this.building, null];
    } else if (msg.type === 'delta' && !this.building && !this.waiting) {
      for (const c of msg.changes) this.put(c.event_id, c.book, c.market);
      for (const r of msg.removed) this.remove(r);
    }
  }

  lost() {
    if (this.waiting) return; // one resync at a time (the server allows one a second)
    [this.building, this.waiting] = [null, true];
    this.onGap();
  }

  // A REST answer (/v1/odds) covering the same filters: newer copies win, and a
  // market it leaves out while its meta.version is past ours has been removed.
  mergeRest({ data, meta }, covers) {
    const listed = new Set();
    for (const e of data) for (const b of e.bookmakers) for (const m of b.markets) { listed.add(m.id); this.put(e.id, b.id, m); }
    for (const [id, held] of this.markets) {
      if (!held.removed && !listed.has(id) && covers(held) && meta.version > held.version) this.remove({ market_id: id, version: meta.version });
    }
  }

  live() {
    return [...this.markets.values()].filter((x) => !x.removed);
  }
}

Wire onMessage to your socket's message handler, and onGap to sending {"type":"resync"}. covers(held) tells mergeRest whether a market you hold falls inside the REST query's filters (its league, books, market keys and periods). Without that check, a narrow REST query would delete everything outside it. The connection itself, with backoff, reconnects and a watchdog, is built step by step in the Node.js streaming tutorial. If you'd rather not write any of this, the official SDKs handle reconnects and gap recovery for you.

Operational limits shape the design too. A connection may send one subscribe or resync a second, and the account 12 a minute across all its sockets. The server closes a client with 4000 after 35 seconds without a pong or message, and with 4008 once it falls more than 16 MB behind reading. Before a restart it sends reconnect with retry_after_ms, then closes with 1012. Keep message handling fast and push heavy work onto a queue.

If your logic must never act on an old quote, add max_source_age_ms (1 to 300,000) to the subscription. Quotes the source hasn't confirmed within that window are removed with reason source_expired. Such a subscription can cover at most 100,000 markets.

Webhooks: push without a connection, with gaps by design

Webhooks suit work that should happen when something notable moves, without a process holding a socket open. They have no state to rebuild, which is their strength, and they skip moves on purpose, which is their limit.

What fires. The only rule type is a line move. A rule watches each book's full-game moneyline, spread and total, filtered by leagues, books and markets. It fires when a price moves by at least min_cents, which defaults to 20 and can be set from 1 to 1,000. Cents are measured on the American scale, continuous across ±100, so −105 → +105 is 10 cents. Some moves never alert:

What it costs. Each delivered alert costs 1 credit on Edge, and is skipped silently if the balance is empty. Sharp and Syndicate have unlimited credits.

How it's delivered. Each event is a POST with a JSON body of id, type, created and data. data holds the rule, the event, the book, the full market and a move with outcome_id, outcome, from, to and cents. Three headers come with it:

Your endpoint must answer with a 2xx within 5 seconds. Redirects aren't followed, and endpoints must use HTTPS on the standard port and can't point at private networks. Failed deliveries are retried after 30 seconds, 2 minutes, 10 minutes, 1 hour and 6 hours, then marked failed. After 20 consecutive failures the endpoint is disabled and the account owner is emailed. Each attempt is signed afresh, so a retry six hours later still passes a five-minute timestamp check.

Delivery is at least once, and order isn't guaranteed. This receiver verifies the raw body, acknowledges at once and drops duplicates by event id. It has no dependencies:

import http from 'node:http';
import crypto from 'node:crypto';

const SECRET = process.env.PRECISEAPI_WEBHOOK_SECRET; // whsec_… from Dashboard → Webhooks
const TOLERANCE_SEC = 300;
const seen = new Set(); // delivered event ids; use a table with a unique key in production

function verify(raw, header) {
  const parts = {};
  for (const kv of String(header || '').split(',')) {
    const i = kv.indexOf('=');
    if (i > 0) parts[kv.slice(0, i).trim()] = kv.slice(i + 1).trim();
  }
  const t = Number(parts.t);
  if (!Number.isInteger(t) || Math.abs(Date.now() / 1000 - t) > TOLERANCE_SEC) return false;
  const expected = crypto.createHmac('sha256', SECRET).update(`${t}.`).update(raw).digest('hex');
  const got = Buffer.from(parts.v1 || '', 'utf8');
  return got.length === expected.length && crypto.timingSafeEqual(got, Buffer.from(expected, 'utf8'));
}

const queue = [];
function handle(event) {
  if (event.type !== 'line.moved') return; // test.ping and future types
  const { event: game, book, market, move } = event.data;
  if (!move) return;
  console.log(`${game.away.abbr} @ ${game.home.abbr} ${book.id} ${market.key}: ${move.outcome} ${move.from} -> ${move.to} (${move.cents}c)`);
}

http.createServer((req, res) => {
  if (req.method !== 'POST' || req.url !== '/webhooks/preciseapi') return res.writeHead(404).end();
  const chunks = [];
  req.on('data', (c) => chunks.push(c));
  req.on('end', () => {
    const raw = Buffer.concat(chunks);
    if (!verify(raw, req.headers['preciseapi-signature'])) return res.writeHead(400).end();
    const event = JSON.parse(raw);
    res.writeHead(200).end(); // acknowledge inside 5 s, work afterwards
    if (seen.has(event.id)) return; // a retry or a duplicate: already handled
    seen.add(event.id);
    queue.push(event);
    setImmediate(() => handle(queue.shift()));
  });
}).listen(3000);

We checked the receiver locally by signing a sample body the way the server does. A valid delivery returned 200 and was handled once. The same delivery sent again returned 200 and was skipped. A bad signature returned 400. Put it behind HTTPS, then use "Send test" on the Webhooks page to deliver a signed test.ping.

Two consequences follow from the cooldown and the retries. First, an alert is a trigger, not a record. Several moves within 10 minutes produce one alert, so you can't rebuild a board from webhooks. Second, a late retry describes the past. Compare created and data.market.updated_at with the current time before acting. If you need the current price, fetch it: /v1/events/{id}/odds with a markets filter costs 2 credits.

Which path to use

You're buildingUseWhy
A pre-game odds screen refreshed every minute or twoRESTSimple, stateless, and cheap if you poll around game windows
Alerts or a Discord bot on big movesWebhooksNo connection to keep alive; one credit per alert on Edge
An in-play board or real-time dashboardStream (Syndicate)Every change within 250 ms, with gap detection
A model that needs every recorded main-line price/v1/history plus RESTThe stream conflates within 250 ms and webhooks skip moves
A product serving many browser usersStream or REST on your server, fanned outYour API key never reaches a browser

The live odds API page covers in-play coverage, and the line movement API page covers recorded history.

Combining the paths

Most production systems use two of the three:

Frequently asked questions

Can webhooks keep a full odds board in sync?

No. Alerts fire only for full-game main markets, only when a move passes your threshold, and at most once every 10 minutes per market for each rule. Use them to trigger work, and use REST or the stream for state.

What happens to an alert if my endpoint is down?

It is retried after 30 seconds, 2 minutes, 10 minutes, 1 hour and 6 hours, then marked failed. You can retry any delivery from the dashboard. After 20 consecutive failures the endpoint is disabled and the account owner is emailed.

Does the stream send suspended markets?

Snapshots leave them out, as REST does by default. A market suspended after the snapshot arrives as a change with suspended: true. A market its source stopped listing is first sent as suspended for 150 seconds before it is removed with reason source_dropped.

How do I merge REST answers with the stream safely?

Keep the copy with the highest version for each market id, and ignore older copies after a removal. A market that a REST answer's filters cover but don't list has been removed, provided the answer's meta.version is above the version you hold. The mergeRest method above implements exactly that rule.

Which plan do I need for in-play odds?

Syndicate. It is the only plan with games in progress over REST, the stream and webhooks. Edge and Sharp serve pre-game odds and final scores. See pricing for allowances.

References

Keep reading