How to Build an Odds Screen in Real Time (Architecture and Code)
A production architecture for a live odds screen with a REST snapshot, WebSocket deltas, best-line highlighting in React and handling of stale prices.
An odds screen is a grid: events down the side, books across the top, a price in every cell, and the best price per outcome highlighted. It is the first thing most people build with an odds feed, and it looks simple. Once you work out how to build an odds screen properly, though, the interesting problems are all about time: getting a consistent starting state, applying changes in order, and knowing when a number on screen is no longer true.
This post lays out an odds screen architecture that holds up in production and sketches the code for each layer, using the PreciseAPI REST endpoints and WebSocket stream.
How to build an odds screen: the architecture
PreciseAPI ──REST snapshot──▶ your backend ──JSON + SSE/WS──▶ browsers
──WebSocket deltas─▶ (state store)
Three rules drive this shape:
- Your API key stays on the server. Calling the API from the browser exposes the key to anyone who opens dev tools.
- One upstream connection, many viewers. The backend holds a single stream subscription and fans updates out to every user, so your cost does not grow with traffic.
- Snapshot, then deltas. You start from a full picture of the board and apply only what changes. Polling a full board every few seconds is both slower and more expensive.
Step 1: Load a snapshot
There are two good starting points.
/v1/odds returns every book's markets for many events at once, grouped by source. It is the raw material for a full grid:
curl "https://api.preciseapi.com/v1/odds?league=nba&markets=moneyline,spread,total&books=pinnacle,draftkings,fanduel,betmgm,caesars" \
-H "Authorization: Bearer $PRECISEAPI_KEY"
Each event carries id, league, start_time, status, home, away and a bookmakers array. Each bookmaker has id, name, type, updated_at and markets, and each market has id, key, period, line, outcomes (with side, point and price), suspended and updated_at.
/v1/best-lines does the aggregation for you: for each comparable market it returns best_price and best_books (all books tied at that price) per outcome, plus books_quoting, the number of books posting the market. If you are building an odds comparison screen that shows only the best price rather than a full grid, it can be the only call you need. The odds comparison API page summarizes it.
In practice, the WebSocket stream also sends a snapshot message immediately after you subscribe, in the same shape as /v1/odds. A REST call is still useful for server-side rendering, for a cold cache on deploy, or for plans without streaming.
Step 2: Apply WebSocket deltas
Open one connection to wss://api.preciseapi.com/v1/stream, subscribe, and keep a state store keyed by market id:
import WebSocket from 'ws';
const state = new Map(); // event_id -> { event, books: Map<book_id, Map<market_id, market>> }
let lastSeq = 0;
function eventEntry(event) {
let e = state.get(event.id);
if (!e) state.set(event.id, (e = { event, books: new Map() }));
else e.event = { ...e.event, ...event };
return e;
}
function loadSnapshot(events) {
state.clear();
for (const ev of events) {
const { bookmakers, ...event } = ev;
const entry = eventEntry(event);
for (const b of bookmakers) entry.books.set(b.id, new Map(b.markets.map((m) => [m.id, m])));
}
}
function applyDelta({ changes, removed }) {
for (const { event_id, book, market } of changes) {
const entry = state.get(event_id);
if (!entry) continue; // unknown event: fetch /v1/events/{id} or wait for the next snapshot
if (!entry.books.has(book)) entry.books.set(book, new Map());
entry.books.get(book).set(market.id, market);
}
for (const { event_id, book, market_id } of removed) state.get(event_id)?.books.get(book)?.delete(market_id);
}
const ws = new WebSocket('wss://api.preciseapi.com/v1/stream', {
headers: { Authorization: `Bearer ${process.env.PRECISEAPI_KEY}` },
});
ws.on('open', () => {
ws.send(JSON.stringify({
type: 'subscribe',
leagues: ['nba'],
books: ['pinnacle', 'draftkings', 'fanduel', 'betmgm', 'caesars'],
markets: ['moneyline', 'spread', 'total'],
}));
});
let resyncing = false;
ws.on('message', (raw) => {
const msg = JSON.parse(raw);
if (msg.type === 'snapshot') {
loadSnapshot(msg.data);
lastSeq = msg.seq;
resyncing = false;
} else if (msg.type === 'delta' || msg.type === 'event') {
if (resyncing) return; // ignore until the fresh snapshot arrives
if (msg.seq !== lastSeq + 1) {
resyncing = true; // missed a message: rebuild from a new snapshot
return ws.send(JSON.stringify({ type: 'resync' }));
}
lastSeq = msg.seq;
if (msg.type === 'delta') applyDelta(msg);
else eventEntry(msg.data); // status, score or clock change
}
broadcast(); // push to your browsers (debounced)
});
A few protocol details matter here:
- The market id is stable for a given event, book, market key, period and subject. When a spread moves from -3 to -3.5, the same market id arrives with a new
line, so an upsert by id is correct. - Deltas are batched every 250 ms. Each
deltacontainschanges(full market objects) andremoved(market ids that were pulled). - Every
snapshot,deltaandeventmessage incrementsseqby exactly one. A gap means you missed a message, and the fix is to sendresyncand rebuild from the fresh snapshot. The server allows one subscribe or resync per second.
The Node.js WebSocket tutorial covers reconnects, heartbeats and gap handling in depth; this sketch keeps them short so the shape of the state store is clear.
Step 3: Serve the board to browsers
Your backend now has the whole real-time odds board in memory. Expose it two ways:
GET /boardreturns the current state as JSON for the initial page load.- A Server-Sent Events or WebSocket endpoint pushes changes. Debounce to a few updates per second per client. Humans can't read faster than that, and it keeps CPU and bandwidth flat during busy periods.
Send only what the page needs. A browser rendering one league doesn't need every book's alternate lines.
Step 4: Highlight the best line
For moneylines, "best" is simple: the highest decimal price for each outcome. For spreads and totals you have to decide what you are comparing, because books may be on different lines. Home -3 at -110 and home -3.5 at +100 are different markets.
The standard approach is to group by line first: compare prices only between books offering the same point, then show the main line from a reference book (often the sharp book you trust most) and flag books offering a better number. Here is a React sketch that handles moneylines and same-line comparisons:
const toDecimal = (a) => (a > 0 ? 1 + a / 100 : 1 + 100 / -a);
const STALE_MS = 60_000;
function cellsFor(event, bookIds, key, side) {
return bookIds.map((bookId) => {
const market = [...(event.books[bookId] ?? [])].find((m) => m.key === key && m.period === 'full_game');
const outcome = market?.outcomes.find((o) => o.side === side);
if (!outcome) return { bookId };
const stale = market.suspended || Date.now() - Date.parse(market.updated_at) > STALE_MS;
return { bookId, price: outcome.price, point: outcome.point, stale };
});
}
function markBest(cells) {
const live = cells.filter((c) => c.price !== undefined && !c.stale);
const byPoint = new Map();
for (const c of live) {
const k = c.point ?? 'ml';
if (!byPoint.has(k) || toDecimal(c.price) > toDecimal(byPoint.get(k))) byPoint.set(k, c.price);
}
return cells.map((c) => ({ ...c, best: !c.stale && c.price !== undefined && c.price === byPoint.get(c.point ?? 'ml') }));
}
export function OddsRow({ event, bookIds, marketKey, side, label }) {
const cells = markBest(cellsFor(event, bookIds, marketKey, side));
return (
<tr>
<th scope="row">{label}</th>
{cells.map((c) => (
<td key={c.bookId} className={[c.best && 'best', c.stale && 'stale'].filter(Boolean).join(' ')}>
{c.price === undefined ? '–' : `${c.point !== undefined ? `${c.point > 0 ? '+' : ''}${c.point} ` : ''}${c.price > 0 ? '+' : ''}${c.price}`}
</td>
))}
</tr>
);
}
Here event.books is a plain object of bookId -> markets[] that your backend sends to the browser. Ties are all highlighted, which matches how /v1/best-lines reports best_books.
Step 5: Handle stale and suspended prices
A stale price is worse than a missing one, because users rely on it. Of everything in how to build an odds screen, this is the step to get right. Defend in layers:
- Suspended markets. When a source stops reporting, its markets are marked
suspended: true. In the stream they arrive as normal deltas with that flag set. Grey them out and exclude them from best-line calculations. REST endpoints exclude suspended markets unless you passinclude_suspended=true. - Per-market age. Every market has
updated_at. A pre-game moneyline that hasn't changed in a minute is usually fine; a live-game price that hasn't changed in 20 seconds usually isn't. Use different thresholds forscheduledandliveevents. - Connection health. The server sends a
heartbeatevery 15 seconds. If you stop receiving anything for well over that interval, assume the connection is dead, mark the whole board stale and reconnect. Don't silently keep displaying the last state. - Event status. When an
eventmessage moves a game tolive, the same event id and market ids carry on, but the prices are now in-play prices, and a player prop stays only while its source keeps posting it. Show the status clearly, and switch to your tighter live staleness threshold. When it goesfinal, drop the row.
Cost and plan notes
Streaming is billed at one credit when a connection opens and one per connection-minute, regardless of how many events you follow, so a single connection running all month costs about 43,200 credits. Polling /v1/odds (2 credits per call) every 10 seconds costs about 17,280 credits per day for the same coverage, and is slower. Streaming, and the in-play prices of the live odds API, are on Syndicate, whose credits are unlimited; see pricing for limits.
This post covers how to build an odds screen in code. If you are scoping a product rather than a weekend project, the real-time odds screen use case covers the full feature set, and the line shopping glossary entry is a good primer for users. When you're ready to write code, the quickstart gets a key and a first request working in a few minutes.