POSTMORTEM

Moving my first product's AI call out of a web request that kept timing out

JUNE 11, 2026 · 6 MIN · RISKSCANAI
TL;DR

When a model call can take longer than your platform lets a web request run, answer the user at once and let the model finish in a separate job.

  • RiskScanAI waited on Claude inside a web request, and the model took 25 to 35 seconds while the project's paid hosting plan stopped requests at 26 seconds.
  • For six days I tried fixes that assumed the call could be made to fit, and the separate-job design I ended with was built on March 15, dropped on March 18 and brought back on March 19.
  • The finished version saves a stand-in summary written without the AI, returns it right away and lets the page check back until the AI summary replaces it, though no automated check enforces the design.

RiskScanAI was my first product: a small business answers a questionnaire about its security posture, and Claude writes it an assessment. On March 19 the assessment page crashed with Unexpected token '<', which is what JavaScript says when it tries to read HTML as JSON (the structured data format the page expected). The HTML was Netlify's 504 page, which the gateway (the platform layer in front of each function) returns when a function runs out of time, and my first timeout fix had gone in six days earlier.

Why the AI call took longer than a web request was allowed to run

The assessment is a five-section JSON document of two to three thousand tokens (the units a model reads and writes), and the commit that diagnosed the crash, the diagnosis commit from here on, put Claude Sonnet (Anthropic's mid-size model) at 25 to 35 seconds to write it. RiskScanAI's server code ran as Netlify Functions (small handlers the platform runs on demand), which the project's commits say stop at 10 seconds on the free plan and 26 on Pro. That limit works like a parking meter you can't feed: when it runs out the car gets towed whether or not your errand is done, and the tow notice here was an HTML page.

The fixes that assumed the call would fit

Neither number was settled at the time. The commits treat the plan as free on March 13, Pro on March 15, free again on March 18 and Pro five minutes later, and they guess the call at 10 to 20 seconds, 20 to 30-plus and 12 to 15. Every fix I tried in that stretch still waited on the model inside the request:

  • I pinned the function timeout in netlify.toml (the site's config file) and removed a recursive retry (code that called itself again after a failure).
  • I raced the Claude call against a timer (ran both and took whichever finished first), set to 7 seconds and then 22.
  • I added an assistant prefill, which writes the first characters of the model's reply so it starts inside the JSON.
  • I switched to Haiku, Anthropic's smaller and faster model.

None of them held, and the final commit, later on March 19, recorded the result: every model tried ("Sonnet 4, Sonnet 4.6, Haiku") either timed out or wrote a summary of insufficient quality within the limit.

The background design was in the repo four days before it stuck

On March 15 I moved the call into a background function (a Netlify function whose name ends in -background, which the platform answers at once with 202, the status code for "accepted, not finished yet", then lets run for up to 15 minutes), and made the manual regenerate endpoint (the URL that asks for a fresh summary) a thin trigger that only starts it.

On March 18 one commit delegated to the background function again, citing the free plan's limit, and the next, five minutes later, switched regenerate back to calling Sonnet directly. The final commit brought the background function back for good, under the message "Don't wait for Claude in the HTTP request."

How the background version answers right away

Finishing the questionnaire now stores a deterministic fallback summary (built without the model, so the same answers always give the same text) and fires the background function, both inside one Promise.all (which runs them together and waits for both). Questionnaire finish returns HTTP 200 (success) with the fallback; only the manual regenerate endpoint returns 202.

The background function calls Claude and writes the result to the database. If the reply was cut off at the token limit or isn't valid JSON, it writes nothing and the fallback stays, a fail-safe default in security terms. The page polls (asks the server whether the result is ready) every 3 seconds, first at 300 milliseconds, and the diagnosis commit's crash fix, a check of the Content-Type header (where the server says what format it is sending) before parsing, is in the last block below.

questionnaire finish · where the Claude call lives
before: waits in the requestconst summary = await claude(…)
after: stores and triggersstore(fallback); fire(jobBackground); return 200 + fallback

what changedThe Claude call moved out of the request the user waits on.

Reuse: answer at once and finish the model call in the background

These blocks are simplified and are not the product's code. db, buildFallback and callModel stand in for your own storage, fallback builder and model call, and /api/status is an endpoint you write that returns the stored record as JSON.

start.js is the handler the user's request hits:

export async function handler(event) {
  const { id, answers } = JSON.parse(event.body);
  const fallback = buildFallback(answers); // no model call
  await Promise.all([
    db.save(id, { status: 'pending', result: fallback }),
    fetch(`${process.env.URL}/.netlify/functions/job-background`, {
      method: 'POST',
      body: JSON.stringify({ id, answers }),
    }),
  ]);
  return { statusCode: 200, body: JSON.stringify({ id, result: fallback }) };
}

Use this whenever the work behind a request can take longer than your platform lets a request run.

job-background.js does the slow work:

export async function handler(event) {
  const { id, answers } = JSON.parse(event.body);
  const result = await callModel(answers); // null if cut off or not valid JSON
  if (!result) return; // the fallback stays
  await db.save(id, { status: 'done', result });
}

Use this for the model call itself; returning without a write keeps the fallback when the reply is unusable.

The page polls for the result:

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

async function pollForResult(id, { firstMs = 300, everyMs = 3000, maxPolls = 20 } = {}) {
  await sleep(firstMs);
  for (let i = 0; i < maxPolls; i++) {
    const res = await fetch(`/api/status?id=${encodeURIComponent(id)}`);
    const type = res.headers.get('content-type') || '';
    if (res.ok && type.includes('application/json')) {
      const job = await res.json();
      if (job.status === 'done') return job.result;
    }
    await sleep(everyMs);
  }
  return null; // keep showing the fallback
}

Use the content-type check in any client that calls a function behind a gateway, since the gateway's HTML error page replaces your function's JSON when the function times out. Set everyMs and maxPolls so the total wait is longer than your slowest model call.

Check the request limit before you write the handler

Nothing was automated afterwards: no check of any kind in the RiskScanAI repo stops a request handler from waiting on a model, and the product that came after it documented the limit and also had another function return a gateway error while it waited on Claude. Find your platform's real request limit and time your model call before writing the handler, and if the call comes anywhere near the limit, put it in a background job from the first version.

Trust belongs in the schema, not the application.
The operating principle behind every project here. A rule the database enforces can't be forgotten in a hurry. Constraints, denied-by-default access, append-only logs — the controls that hold are the ones the system won't run without.