Fix
Vercel function timeout scraping sports stats: fix
Short answer: a serverless function ends when it passes its maximum duration, and a scraper that walks many pages with delays and retries will pass it. Raising the limit hides the problem. Replace the walk with one or two API calls that return whole tables in a fraction of a second.
The symptoms
You wrote a route that fetches a stats page for each team, parses the tables and returns a combined result. Locally it takes forty seconds and nobody minds. Deployed, you see one of these:
- A 504 from the platform with a timeout error code, after exactly the same number of seconds every time.
- A function log that stops in the middle of the loop, with no error from your code.
- A request that succeeds on a quiet afternoon and times out on a game night, when the remote site is slower.
- A cold first request that fails while the second one works because half the pages were fetched before the cut-off.
- A bill that grows even though most of the invocations return nothing, because each one waits on the network until it is ended.
All of these are the same shape. The function is spending its whole life waiting.
Why it happens
Serverless functions are built for short request and response work. The platform gives each invocation a maximum duration and ends it when that is reached. On Vercel the default is 300 seconds with fluid compute, which is on by default. The maximum is 300 seconds on the Hobby plan and 800 seconds on Pro and Enterprise, and an extended beta allows up to 1,800 seconds on supported runtimes. These numbers come from the platform's own documentation as of this page's verification date, so check the current page before you rely on them. In the App Router you set the limit with an exported maxDuration constant, and in other setups through the functions block in vercel.json.
A scraper meets that limit for reasons that have little to do with your code:
- Serial page walks. Thirty teams times one page each is thirty round trips. If you wait politely between them, as you should, the loop is slow by design.
- Slow origins. A page built for browsers carries scripts, images and tracking. The server may take seconds to answer, and it is slowest on the nights you care about most.
- Retries. Good clients back off after a 429 or 5xx. Each retry multiplies the time, so a flaky origin turns a one-minute job into a ten-minute one.
- Parsing. Pulling a table out of markup and matching its columns to your schema costs CPU, and a layout change breaks it.
- Unbounded waits. A fetch with no timeout can sit for as long as the origin allows. Without a deadline, one dead connection uses the whole budget.
The platform is doing its job. A request path is the wrong place for a job whose runtime is set by someone else's server.
Fixes that stay honest
Before you reach for the API, there are plain engineering steps that help with any slow dependency:
- Set your own deadline on every fetch. Use an abort signal so a single slow call fails fast instead of eating the budget.
- Move the work off the request path. Run the job on a schedule, store the result, and let user requests read the stored copy. A visitor should never wait on a scrape.
- Cache with a revalidation window. If the data changes nightly, serve it for hours.
- Fetch in parallel only where the origin allows it. Respect robots rules, the site's terms and any stated rate limits. Parallel load on a site that did not invite it is not a fix.
- Right-size the limit. Set
maxDurationfor what the job needs, not the largest value the plan allows.
These help, but they leave the root cause in place. The data comes from a place that was not built to serve a program, so every run depends on its speed and its permission.
The fix: replace the loop with an API call
An API returns the whole table in one request, in a stable shape, from a server built for programs. The loop disappears, so there is nothing to time out. Here is a route handler that fetches standings and the next two days of games in parallel, with an eight-second deadline on each call. In a Next.js App Router file you would add export const maxDuration = 15; above GET. The code below is plain JavaScript that runs under Node, so you can try it without a deploy.
const BASE = "https://mcp.puckapi.com/v1";
async function tool(name, body, ms = 8000) {
const res = await fetch(`${BASE}/${name}`, {
method: "POST",
headers: { "content-type": "application/json", "x-api-key": process.env.SDHQ_KEY },
body: JSON.stringify(body),
signal: AbortSignal.timeout(ms), // fail fast instead of running to the platform limit
});
if (!res.ok) throw new Error(`${name} -> HTTP ${res.status}`);
return (await res.json()).data;
}
// In a Next.js app router file this would be: export const maxDuration = 15;
export async function GET() {
const started = Date.now();
const [standings, schedule] = await Promise.all([
tool("get_standings", {}),
tool("get_schedule", { days: 2 }),
]);
return Response.json({
teams: standings.standings.length,
games_next_2_days: schedule.upcoming_games.length,
elapsed_ms: Date.now() - started,
});
}
const res = await GET();
console.log(res.status, await res.json());On the verified run this printed 200 { teams: 32, games_next_2_days: 20, elapsed_ms: 368 }. Two requests, 368 milliseconds in total, 4 credits. A loop over 32 team pages would need 32 requests and the polite delays between them.
Go further: precompute, then serve
If many visitors need the same table, do not call the API on each request. Run one scheduled job that calls the API, writes the result to your storage, and let the route read it. The API call then costs the same 2 credits once an hour, not once per visitor. You can also let the platform cache the response with a revalidation window, so the first request after expiry refreshes it and the rest read the cached copy.
A simple check from a terminal shows what the loop would have been replaced by:
curl -s -X POST https://mcp.puckapi.com/v1/get_games \
-H "x-api-key: $KEY" \
-H "Content-Type: application/json" \
-d '{"date": "2026-12-05", "limit": 3}'That returned HTTP 200 with three finished games, each with its season, date, teams, score and endedIn value, for 5 credits. One request gave a whole date.
Sizing the budget
A useful habit is to write the time budget down before you write the code. A route that answers a visitor should finish in a second or two. If a call can take eight seconds at worst, then two sequential calls can take sixteen, and your maxDuration must be larger than that plus overhead. Parallel calls take as long as the slowest one. When the numbers do not fit, that is the signal to move the work to a schedule, not to raise the limit.
When not to use this
- You are rebuilding history. A season of box scores is thousands of games. A data package is one download and avoids both the loop and the credit cost.
- You need a field the API does not hold. Check the tool list before you commit.
- Your job really is long. If you must process many seasons, use a queue or a durable workflow, which are built for steps that outlast one request.
- You want a pick. Prices come back as information about the market. No tool recommends a wager.
Try it
- Get a free key: 1,000 credits a month, no card.
- Skip the API and download a data package if you want a full season in a file.
FAQ
Why does my Vercel function time out when it scrapes sports stats?
A scrape walks many pages one after another, each with its own delay, retries and backoff. The sum passes the function's maximum duration and the platform ends the invocation. The slow part is waiting on the remote site, not your code.
Should I just raise maxDuration?
It buys time but does not fix the cause. A longer limit lets a slow loop run longer and bills for the wait. It is better to shrink the work to one or two fast calls, or move the job off the request path into a scheduled run that stores its result.
How fast is one SportsDataHQ call?
On the verification run a standings call and a schedule call ran in parallel and the whole handler finished in 368 ms. Each call cost 2 credits. A single request returns a whole table, so there is no page loop to time out.
Checked against the live API on 2026-12-06. Questions: hello@sportsdatahq.com.