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
| REST | WebSocket stream | Webhooks | |
|---|---|---|---|
| Who starts it | You, one request at a time | You open it, then the server pushes | The server POSTs to your HTTPS endpoint |
| What arrives | The full current state for your query | A snapshot, then changed and removed markets every 250 ms | One line.moved event per qualifying price move |
| Completeness | Complete as of the response | Complete if you apply every message in order | A filtered sample: a threshold and a 10-minute cooldown per market |
| Ordering | Each answer stands alone; meta.version | seq per connection, version per market | None: events can arrive out of order or twice |
| Billing | Per successful call: 2 credits for /v1/odds, 3 for /v1/props | 1 credit on open, then 1 per connection-minute | 1 credit per delivered alert |
| Plans | Every plan, including the free Sandbox key | Syndicate (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:
| Plan | Credits | Requests / min | In-play odds | Stream | Webhook endpoints / alert rules |
|---|---|---|---|---|---|
| Edge | 100,000 / month | 300 | No | No | 2 / 10 |
| Sharp | Unlimited | 1,200 | No | No | 10 / 100 |
| Syndicate | Unlimited | 3,000 | Yes | 10 connections | 25 / 500 |
- Edge: credits run out first. Your polling interval is a budget decision.
- Sharp: credits are unlimited, so the limit is 1,200 requests a minute, shared by every key on the account. There is no stream, so REST plus webhooks is the whole toolkit, for pre-game odds.
- Syndicate: the stream's per-minute meter doesn't draw down a balance, because credits are unlimited. The limits are 10 concurrent connections and the subscription rules covered below. Only Syndicate gets games in progress over any path. On other plans, REST leaves live games out (asking for
status=livereturns 403), and in-play moves never trigger an alert.
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:
- Poll around game windows, not around the clock. Most of the plan above is spent during six hours a day.
- Batch.
league=nba,nhlcovers several leagues in one call, up to 200 events of game lines. Requests that include player props are served 25 events at a time, so a slate larger than that needs one call per 25 events. - Free endpoints stay free.
/v1/leagues,/v1/sportsbooks,/v1/markets,/v1/statusand/v1/usagecost nothing, so refreshing them never touches your balance.
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:
- Snapshots can span several frames. A large
snapshotcontinues insnapshot_partframes of about 5,000 markets each, sharing asnapshot_id. The last frame haslast: true, and nodeltais sent before it. Each frame carries its ownseq. - Two counters, two jobs.
seqrises by exactly one persnapshot,snapshot_part,deltaandeventmessage on one connection, so it detects gaps.heartbeat(every 15 seconds) carries the currentseqwithout raising it.event_removedcarries noseqat all.versionbelongs to a market, and it is the same number on REST, in snapshots and in deltas for the same state, so it orders copies across paths. - Snapshots leave suspended markets out, as REST does by default. A suspension after the snapshot arrives as an ordinary change with
suspended: true. - Removals carry a reason:
source_dropped,line_moved,expired,closed,settled,event_merged(withmerged_into),player_merged,promotion_expired, andsource_expiredwhen you subscribed withmax_source_age_ms.
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:
- An update to a suspended market.
- A second move on the same market within 10 minutes for the same rule.
- A move in a game in progress, unless the account is on Syndicate.
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:
PreciseAPI-Event: the event type.PreciseAPI-Delivery: the event id.PreciseAPI-Signature: t=<unix seconds>,v1=<hex>, wherev1is HMAC-SHA256 of<t>.<raw body>keyed with your endpoint'swhsec_secret.
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 building | Use | Why |
|---|---|---|
| A pre-game odds screen refreshed every minute or two | REST | Simple, stateless, and cheap if you poll around game windows |
| Alerts or a Discord bot on big moves | Webhooks | No connection to keep alive; one credit per alert on Edge |
| An in-play board or real-time dashboard | Stream (Syndicate) | Every change within 250 ms, with gap detection |
| A model that needs every recorded main-line price | /v1/history plus REST | The stream conflates within 250 ms and webhooks skip moves |
| A product serving many browser users | Stream or REST on your server, fanned out | Your 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:
- Webhook triggers a REST read. An alert names the event and market. Fetch the event's current odds, then act on that rather than on the alert body. This is the cheapest way on Edge to react to moves without polling a whole league.
- Stream with a REST bootstrap or bridge. Load the board from
/v1/odds, or bridge a long reconnect with a slow poll, and merge withmergeRestabove. Because both paths carry the sameversionper market, an older REST copy never overwrites a newer streamed one. - History for backfill. After an outage,
/v1/historyreturns the recorded changes for main full-game markets, which a REST snapshot can't. Replaying historical lines explains what those points do and don't tell you.
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
- I. Fette and A. Melnikov, RFC 6455: The WebSocket Protocol, IETF, 2011.
- H. Krawczyk, M. Bellare and R. Canetti, RFC 2104: HMAC: Keyed-Hashing for Message Authentication, IETF, 1997.
- NIST, FIPS 180-4: Secure Hash Standard (SHA-256).
- M. Nottingham and R. Fielding, RFC 6585: Additional HTTP Status Codes (429 Too Many Requests), IETF, 2012.
- R. Fielding, M. Nottingham and J. Reschke, RFC 9110: HTTP Semantics, section 10.2.3, Retry-After, IETF, 2022.
- Node.js documentation, crypto.timingSafeEqual.
- PreciseAPI docs: streaming, webhooks and alerts, credits, rate limits and the data model.