Skip to content

TutorialsLesson 10 of 15Media and prices9 min read

Live odds: polling /v1/odds/{raceId} responsibly

Read bookmaker prices with /v1/odds/{raceId}, join them to runners by horse ID, and poll only active races within the five-second shared cache window.

  • Join prices to runners correctly
  • Poll only races that matter
  • Explain what the odds feed does not promise

What the odds endpoint returns

GET/v1/odds/{raceId}All live plans

Latest supplied UK and Irish bookmaker prices for the declared runners in one race.

Data holds raceId and runners; each runner has horseId and odds. A price row includes bookmaker, bookmakerId, price, fractional and eachWay. The source quote ID oddId is optional: treat it as opaque, never as a timestamp. Price preserves source text without format conversion; fractional and eachWay can be empty. An empty odds array or an SP marker is not a numeric quote and must not be used in a returns calculation.

async function getOdds(raceId, date) {
  const url = new URL("/v1/odds/" + encodeURIComponent(raceId), "https://racingapi.net");
  url.searchParams.set("region", "uk");
  if (date) url.searchParams.set("date", date);
  const res = await fetch(url, {
    headers: { "X-API-Key": process.env.RACINGAPI_KEY },
    signal: AbortSignal.timeout(15000),
  });
  const body = await res.json();
  if (!res.ok) throw Object.assign(new Error(body.code), { status: res.status, retryAfter: res.headers.get("Retry-After") });
  return body;
}

// race is an object from your cached racecards; keep its selected feed date.
// Set RACE_DATE for non-current feeds. Join by horse ID, never by position.
const { data, meta } = await getOdds(race.id, process.env.RACE_DATE);
const byHorse = new Map(data.runners.map(r => [r.horseId, r.odds]));
for (const runner of race.runners) {
  const prices = byHorse.get(runner.id) || [];
  const shown = prices.map(p => p.bookmaker + " " + (p.fractional || p.price));
  console.log(runner.name, shown.join(", ") || "no prices", "as of", meta.retrievedAt);
}

The five-second shared cache

Current-day odds come from a shared server snapshot cached for up to five seconds. Every customer asking for the same feed in that window gets the same validated snapshot, and meta.cached tells you when that happened. Polling faster than every five seconds therefore spends allowance without returning newer prices. The five-second window is a cache ceiling, not a promise that prices change that often.

Active-only, bounded polling

DiagramWhich races to poll
Which races to poll: step 1, Upcoming soon; step 2, Visible to someone; step 3, Poll at 5s or slower; step 4, Stop after the off.1 YOUR SERVERUpcoming soon2 VISITORVisible to someone3 CACHEPoll at 5s or slower4 STOPStop after the off
  1. 1Upcoming soon. Races starting within your window, for example the next 30 minutes.
  2. 2Visible to someone. Only races a visitor currently has open, or that your page shows.
  3. 3Poll at 5s or slower. One shared poller per race, results fanned out from your cache.
  4. 4Stop after the off. When offAt is set or finishers appear, stop polling that race.
Poll a small, time-bounded set; stop once the race is off or resulted.
// Reuse getOdds above. One background poller per race/date, not per visitor.
// This Map is process-local: multiple servers need a shared job/lock.
const pollers = new Map();

function watchRace(raceId, date, onPrices, shouldStop = () => false, maxMs = 20 * 60_000, onError = console.error) {
  if (!Number.isFinite(maxMs) || maxMs <= 0) throw new Error("Set a finite polling window");
  const key = raceId + ":" + (date || "today");
  if (pollers.has(key)) return pollers.get(key).stop;
  const deadline = Date.now() + maxMs;
  let stopped = false;
  let failures = 0;
  const job = { timer: undefined, stop };
  function stop() {
    stopped = true;
    clearTimeout(job.timer);
    if (pollers.get(key) === job) pollers.delete(key);
  }
  const tick = async () => {
    if (stopped || Date.now() >= deadline) { stop(); return; }
    let delay = 5000;
    try {
      if (shouldStop()) { stop(); return; }
      const body = await getOdds(raceId, date);
      if (stopped || Date.now() >= deadline || shouldStop()) { stop(); return; }
      onPrices(body);
      failures = 0;
    } catch (err) {
      onError(err);
      const transient = [429, 500, 502, 503, 504].includes(err.status);
      if (!transient || ++failures >= 3) { stop(); return; }
      const retry = Number(err.retryAfter);
      if (Number.isFinite(retry) && retry > 60) { stop(); return; }
      delay = Number.isFinite(retry) && retry > 0 ? Math.max(5000, retry * 1000) : 30000;
    }
    if (stopped || Date.now() + delay >= deadline) { stop(); return; }
    job.timer = setTimeout(tick, delay);
  };
  pollers.set(key, job);
  job.timer = setTimeout(tick, 0);
  return stop;
}

Pass the selected YYYY-MM-DD, a callback that publishes prices to your cache, and a shouldStop callback reading your refreshed race status, offAt or finishers. A missing offAt is not proof a race is still pre-race: set maxMs no longer than your intended pre-race window. The returned stop function also cancels a job when nobody needs it. Fatal responses stop immediately; transient HTTP failures stop after three consecutive failures. Report onError to your logs or monitoring rather than silently hiding failures. Coordinate all race pollers through the account-wide rate limiter: many races polling together can otherwise exceed your plan's per-second limit.

More on budgets in Saving requests. Field definitions are in the API reference.

Reference material

Exact schemas: API reference. First call: Quickstart. Copy-ready helpers: Code examples. Plans: Pricing.