Architecture · 2026-11-26 · 7 min read

Caching NFL REST API Responses on Cloudflare Workers with Rate-Limit Headers

Build a Cloudflare Workers caching layer for OpenPigskin's NFL REST API using Cache API TTLs, X-Quota-Remaining headers, and Retry-After backoff.

Why edge caching multiplies your OpenPigskin quota by 100x

Every OpenPigskin plan enforces both a per-minute rate limit and a monthly hard cap with zero automatic overage fees: Starter (1,000 req/month, 10 req/min), Developer (250,000 req/month, 100 req/min), Pro (2,000,000 req/month, 300 req/min) and Scale (10,000,000 req/month, 600 req/min).

Without a shared cache in front of your users, 500 concurrent visitors refreshing a Sunday scoreboard or checking a playoff box score will hit OpenPigskin 500 times for identical JSON. Placing a lightweight Cloudflare Worker proxy between your frontend and https://openpigskinapi.com collapses thousands of identical edge requests into a single authenticated upstream call — keeping latency under 20 ms while preserving your API key strictly server-side.

Match your Worker TTLs to OpenPigskin's response headers and data freshness

OpenPigskin sends explicit caching and quota headers on every response (all exposed via Access-Control-Expose-Headers): X-Plan, X-Quota-Limit, X-Quota-Remaining and X-Request-Id. Archive routes return Cache-Control: private, max-age=60, while /v1/live, /v1/live/{id} and /v1/schedule return Cache-Control: private, max-age=10 (backed by ~20-second upstream refreshes for live games and 300-second caching for date-range schedules). Error responses return Cache-Control: no-store.

Here is the Cloudflare Workers gotcha that trips up most developers: caches.default.put() refuses to store responses marked Cache-Control: private. Because OpenPigskin marks authenticated responses private by default, your Worker must strip or override Cache-Control to public, max-age=<ttl> on the cached copy (while never storing your Authorization header or non-200 error payloads) and pick TTLs by route class:

Use 20 seconds for /v1/live and /v1/live/{id}, 300 seconds for /v1/schedule, 3,600 seconds (1 hour) for /v1/seasons, standings, leaders, teams, venues and player profiles, and 86,400 seconds (24 hours) for finalized historical /v1/games/{id}, /boxscore, /plays, /drives and /win-probability documents.

Implement an edge-caching Worker with single-flight coalescing and 429 handling

When a cache entry expires at 1:05 PM ET on Sunday, dozens of simultaneous requests inside the same Cloudflare isolate can stampede the origin at once. Combining caches.default with an in-memory inflight Map guarantees only one upstream fetch runs per cache key per isolate, while inspecting Retry-After (sent as 60 seconds on HTTP 429 rate_limited) and X-Quota-Remaining protects your app from cascading failures.

typescript
export interface Env {
  OPENPIGSKIN_KEY: string;
}

const ORIGIN = "https://openpigskinapi.com";
const inflight = new Map<string, Promise<Response>>();

function ttlForPath(pathname: string): number {
  if (pathname === "/v1/live" || pathname.startsWith("/v1/live/")) return 20;
  if (pathname === "/v1/schedule") return 300;
  if (/^\/v1\/games\/game_nfl_\d{4}_/.test(pathname)) return 86_400;
  return 3_600;
}

function buildCacheKey(url: URL): Request {
  // Normalize query parameter order so ?team=SEA&season=2025 and ?season=2025&team=SEA share one cache entry
  const sorted = new URL(url.toString());
  const entries = [...sorted.searchParams.entries()].sort(([a], [b]) => a.localeCompare(b));
  sorted.search = new URLSearchParams(entries).toString();
  return new Request(sorted.toString(), { method: "GET" });
}

export default {
  async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
    if (request.method !== "GET") {
      return new Response("Method Not Allowed", { status: 405 });
    }
    const url = new URL(request.url);
    if (!url.pathname.startsWith("/v1/")) {
      return new Response("Not Found", { status: 404 });
    }

    const cache = caches.default;
    const cacheKey = buildCacheKey(url);
    const cached = await cache.match(cacheKey);
    if (cached) {
      const hit = new Response(cached.body, cached);
      hit.headers.set("X-Edge-Cache", "HIT");
      return hit;
    }

    const keyStr = cacheKey.url;
    let pending = inflight.get(keyStr);
    if (!pending) {
      pending = (async () => {
        const upstreamUrl = `${ORIGIN}${url.pathname}${url.search}`;
        const upstream = await fetch(upstreamUrl, {
          headers: { Authorization: `Bearer ${env.OPENPIGSKIN_KEY}` },
        });

        // Log quota headroom from OpenPigskin response headers
        const plan = upstream.headers.get("X-Plan") ?? "unknown";
        const limit = Number(upstream.headers.get("X-Quota-Limit") ?? "0");
        const remaining = Number(upstream.headers.get("X-Quota-Remaining") ?? "0");
        if (limit > 0 && remaining / limit < 0.15) {
          console.warn(`OpenPigskin quota low (${plan}): ${remaining}/${limit} remaining`);
        }

        // Never cache 429, 4xx or 5xx responses
        if (!upstream.ok) {
          const retryAfter = upstream.headers.get("Retry-After");
          const headers = new Headers({
            "Content-Type": "application/json",
            "Cache-Control": "no-store",
            "X-Edge-Cache": "BYPASS",
          });
          if (retryAfter) headers.set("Retry-After", retryAfter);
          return new Response(await upstream.text(), { status: upstream.status, headers });
        }

        const body = await upstream.text();
        const ttl = ttlForPath(url.pathname);
        const cacheable = new Response(body, {
          status: 200,
          headers: {
            "Content-Type": "application/json; charset=utf-8",
            "Cache-Control": `public, max-age=${ttl}`,
            "X-Edge-Cache": "MISS",
            "X-Request-Id": upstream.headers.get("X-Request-Id") ?? "",
          },
        });
        ctx.waitUntil(cache.put(cacheKey, cacheable.clone()));
        return cacheable;
      })().finally(() => inflight.delete(keyStr));

      inflight.set(keyStr, pending);
    }

    return (await pending).clone();
  },
};

Keep secrets safe and handle rate_limited vs. monthly_quota_exceeded

OpenPigskin rejects API keys passed in query strings (such as ?api_key= or ?token=), requiring Authorization: Bearer op_live_... or X-API-Key. Store OPENPIGSKIN_KEY as a Cloudflare Workers secret (wrangler secret put OPENPIGSKIN_KEY) rather than hardcoding it in wrangler.jsonc or browser bundles.

When your Worker receives HTTP 429, inspect error.code in the JSON payload to distinguish a temporary 60-second per-minute burst (error.code: rate_limited with Retry-After: 60) from an exhausted monthly pool (error.code: monthly_quota_exceeded with X-Quota-Remaining: 0). For rate_limited, back off and serve stale KV snapshots if available; for monthly_quota_exceeded, alert ops immediately rather than retrying in a tight loop.

bash
# Store your API key securely as a Worker secret
npx wrangler secret put OPENPIGSKIN_KEY

# Inspect upstream headers directly during staging tests
curl -i "https://openpigskinapi.com/v1/seasons/2025/standings?division=NFC%20West" \
  -H "Authorization: Bearer op_live_YOUR_KEY" | head -n 20

Preserve source attribution through your cache layer

Because the Worker caches the full JSON payload verbatim, every cached response retains OpenPigskin's meta block intact — meta.source: nflverse and meta.licence: CC BY 4.0 on archive routes, and meta.source: ESPN with meta.licence: null on /v1/live and /v1/schedule.

If your frontend renders multiple cached widgets on the same page (for example a live Sunday banner beside a historical team EPA card), read meta.source from each cached payload so you never misattribute live ESPN scores as CC BY 4.0 nflverse data.

Get a free API key →← All guides