Skip to main content
Contentstack MCP profile hub is in general availability!

ETIMEDOUT, 5xx and timeouts from the Delivery API

•
11 min read

Your build dies halfway through prerendering with ETIMEDOUT, or a server-rendered page returns a 500 because a Delivery API call took too long. Run it again and it works. These failures are intermittent by nature, which makes them easy to ignore until they hit a release.

They show up most in static builds that fetch hundreds of pages at once, in server-rendered apps on Azure managed runtimes, and in any app that calls the API right after a large publish. The fix is the same in all three: fetch in a way that expects the network to fail now and then.

What you'll learn

  • How to read the error and tell a network failure from an API error

  • What the TypeScript Delivery SDK already retries, and what it doesn't

  • How to retry 5xx responses, set timeouts and cap concurrency

  • How to fix SNAT port exhaustion on Azure with keep-alive and IPv4

  • How to keep serving the last good content when a fetch fails

Symptoms

From the TypeScript Delivery SDK (@contentstack/delivery-sdk):

APIError: Request failed before a response was received (HTTP status 0).
  { error_code: 'ETIMEDOUT', status: 0 }
Request timeout of 30000ms exceeded. Please try again or increase the timeout value in your configuration.

Other things you see:

  • ETIMEDOUT, ECONNRESET, ECONNREFUSED, ENOTFOUND or EAI_AGAIN in Node.js logs

  • UNKNOWN_ERROR with status: 0

  • 500 Internal Server Error, 502 Bad Gateway, 503 Service Unavailable or 504 Gateway Timeout from the CDA host

  • Error occurred prerendering page "/blog/..." in a Next.js build, with one of the errors above as the cause

  • CF005 on Launch, when a page's server function runs out of time while it waits on the API (see Launch error codes decoded)

Why it happens

The error tells you where to look. Sort it into one of three groups first.

What you see

What it means

Where to look

status: 0, ETIMEDOUT, ECONNRESET, ENOTFOUND

No HTTP response came back. The connection timed out, was reset, or DNS failed.

Your network path: outbound connection limits, DNS, too many sockets at once

502, 503, 504, 500 with a body

The request reached Contentstack and a server or gateway failed to answer.

status.contentstack.com, then your query cost

Request timeout of ...ms exceeded

A response was on its way but took longer than your client allowed.

Heavy queries (deep includes, large pages) and your timeout settings

Contentstack concept: The Content Delivery API sits behind a CDN. A cached response comes straight from the edge. An uncached one goes to the origin, which is slower and rate limited. A publish clears cached responses, so a build that starts right after a large publish sends far more traffic to the origin than the same build an hour later.

Status 0 errors are the most common, and they are usually not about Contentstack at all. A static build that renders 2,000 pages with 8 workers can open hundreds of TLS connections in a few seconds. On a laptop that's fine. On a serverless runtime or a container with limited outbound connections, new connections start to queue and time out.

Azure managed runtimes (App Service, Container Apps, Functions) are the clearest case. They share a pool of outbound SNAT ports across instances. Each new outbound TCP connection holds a port for a few minutes after it closes. Open connections fast enough and the pool runs dry, and new requests fail with ETIMEDOUT even though the API is healthy and has no record of them.

Fix it

Upgrade the SDK and know what it already does

Check what you run first:

npm ls @contentstack/delivery-sdk @contentstack/core

Since @contentstack/delivery-sdk 5.5.1 (with @contentstack/core 1.5.x), the SDK does this by default in Node.js:

  • Timeout: 30,000 ms per request (timeout).

  • Keep-alive: HTTP and HTTPS agents with keepAlive: true, so connections are reused.

  • Retries: retryOnError is on, retryLimit is 5 and retryDelay is 300 ms.

  • What it retries: 429 responses, and network errors with no response: ETIMEDOUT, ECONNRESET, ECONNREFUSED, ENOTFOUND, EAI_AGAIN, ENETUNREACH, EHOSTUNREACH and ENETDOWN. On a 429 it waits for Retry-After or the rate-limit reset header when the response has one.

What it does not do: retry 5xx responses, or back off exponentially. The delay between attempts is fixed. If you are on an older version, upgrade before you add anything else. Versions before 5.5.1 don't retry network errors by default and don't use keep-alive agents.

npm install @contentstack/delivery-sdk@latest

Retry 5xx responses with jitter

Add a retryCondition for gateway errors. The SDK combines it with its built-in network check, so you only list what you want on top. customBackoff replaces the fixed delay. Use it to add jitter, so 8 build workers don't all retry in the same millisecond.

import contentstack from "@contentstack/delivery-sdk";

const RETRYABLE_STATUS = [500, 502, 503, 504];

export const stack = contentstack.stack({
  apiKey: process.env.CONTENTSTACK_API_KEY!,
  deliveryToken: process.env.CONTENTSTACK_DELIVERY_TOKEN!,
  environment: process.env.CONTENTSTACK_ENVIRONMENT!,
  region: process.env.CONTENTSTACK_REGION,
  timeout: 10_000,
  retryLimit: 3,
  retryCondition: (error) => RETRYABLE_STATUS.includes(error?.response?.status),
  retryDelayOptions: {
    // Used instead of the fixed delay: 0.5 to 1.5 seconds per attempt
    customBackoff: () => 500 + Math.floor(Math.random() * 1000),
  },
});

customBackoff gets no arguments, so it can't grow the delay per attempt. For true exponential backoff, wrap the call yourself (the 429 guide has a helper). Don't retry other 4xx responses. A 412 or 422 means the request itself is wrong, and it will fail the same way every time.

Set timeouts that fit your time budget

Retries multiply your timeout. With the defaults, one stuck request can take 30 seconds times 6 attempts. That is fine in a build. It is not fine inside a server function with its own limit. On Launch, a Cloud Function or SSR request times out after 30 seconds by default.

Use two configurations:

Where

timeout

retryLimit

Worst case

Static build or script

15,000 to 30,000 ms

3 to 5

Minutes, which a build can afford

SSR page or API route

5,000 ms

1 to 2

Under 20 seconds, inside the function limit

If a query regularly needs more than a few seconds, shorten the query instead of raising the timeout. Deep include_all_depth values and large reference trees are the usual cause. Nested references empty or error 141 covers how to slim them down.

Cap concurrency in builds

A static build that fires every page request at once is the most common source of ETIMEDOUT. Fetch the list once, then fetch details with a fixed number of requests in flight:

export async function mapWithConcurrency<T, R>(
  items: T[],
  limit: number,
  fn: (item: T) => Promise<R>
): Promise<R[]> {
  const results: R[] = new Array(items.length);
  let next = 0;

  async function worker() {
    while (next < items.length) {
      const index = next++;
      results[index] = await fn(items[index]);
    }
  }

  await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
  return results;
}

const { entries } = await stack.contentType("blogpost").entry().only(["uid", "url"]).query().find();

const posts = await mapWithConcurrency(entries ?? [], 5, (e) =>
  stack.contentType("blogpost").entry(e.uid).fetch()
);

Two more changes cut the connection count further:

  • Fetch shared data once. Header, footer and navigation entries are the same on every page. Load them once per build and pass them down, instead of once per page.

  • Fetch fewer, bigger pages. One list query that returns the fields every page needs replaces hundreds of single-entry calls. Use only() to keep the payload small.

On Azure managed runtimes: keep-alive and IPv4

If your app runs on Azure App Service, Container Apps or Functions, including Launch projects on Azure, apply the two changes from the Launch troubleshooting guide for Azure: reuse connections and resolve DNS to IPv4. Put both in one agent, so the IPv4 setting doesn't replace your keep-alive agent:

import contentstack from "@contentstack/delivery-sdk";
import http from "node:http";
import https from "node:https";

const agentOptions = {
  keepAlive: true,
  keepAliveMsecs: 180_000,
  maxSockets: 50,
  maxFreeSockets: 20,
  family: 4, // resolve and connect over IPv4 only
};

export const stack = contentstack.stack({
  apiKey: process.env.CONTENTSTACK_API_KEY!,
  deliveryToken: process.env.CONTENTSTACK_DELIVERY_TOKEN!,
  environment: process.env.CONTENTSTACK_ENVIRONMENT!,
  region: process.env.CONTENTSTACK_REGION,
  httpAgent: new http.Agent(agentOptions),
  httpsAgent: new https.Agent(agentOptions),
});

maxSockets is the important number. It caps how many connections the process opens to one host, and anything above it waits for a free socket instead of claiming a new SNAT port. The same pressure applies to every outbound call your app makes, so give your other HTTP clients a keep-alive agent too.

Fail the build, or serve the last good data

When the API really is unavailable, you have two good options and one bad one. The bad one is shipping a build with empty pages because a fetch returned nothing.

Fail the build. On Launch and most hosts, a failed deployment doesn't replace the live one. For a fully static site, letting the build fail and retrying later is often the right call. Make sure errors propagate instead of being caught and turned into empty arrays.

Serve a snapshot. For data that rarely changes (navigation, settings, redirects), or for server-rendered routes where no previous build covers you, keep the last good response and fall back to it:

import { mkdir, readFile, writeFile } from "node:fs/promises";
import path from "node:path";

const SNAPSHOT_DIR = path.join(process.cwd(), ".content-snapshot");

export async function withSnapshot<T>(key: string, load: () => Promise<T>): Promise<T> {
  const file = path.join(SNAPSHOT_DIR, `${key}.json`);
  try {
    const data = await load();
    await mkdir(SNAPSHOT_DIR, { recursive: true });
    await writeFile(file, JSON.stringify(data));
    return data;
  } catch (error) {
    try {
      const cached = JSON.parse(await readFile(file, "utf8")) as T;
      console.warn(`[content] ${key}: serving snapshot after error`, error);
      return cached;
    } catch {
      throw error; // no snapshot yet: fail loudly
    }
  }
}

const nav = await withSnapshot("navigation", () =>
  stack.contentType("navigation").entry().query().find()
);

A file snapshot only survives between builds if your CI caches the directory. At runtime, an in-memory copy per server instance works the same way. For server-rendered pages on Launch, a Cache-Control header with stale-while-revalidate lets the CDN keep serving the last good page while the origin struggles. The caching chapter shows the headers.

Check the status page

Before you change code, open status.contentstack.com and check your region for the time window of the errors. If there is an incident, retries and fallbacks are what carry you through it. If there isn't, and your errors are status 0, the cause is almost always on your side of the connection.

Check that it worked

Measure a single request from the machine that fails. time_connect tells you how long the TCP connection took, which is where SNAT and DNS problems show up:

curl -sS -o /dev/null \
  -w "status=%{http_code} dns=%{time_namelookup}s connect=%{time_connect}s total=%{time_total}s\n" \
  -H "api_key: $CONTENTSTACK_API_KEY" \
  -H "access_token: $CONTENTSTACK_DELIVERY_TOKEN" \
  "https://cdn.contentstack.io/v3/content_types/blogpost/entries?environment=production&limit=1"

Use your region's CDA host if you are not on AWS North America. A connect time of several seconds, or a timeout here while the same request is fast from your laptop, points at the network path.

Then log what the SDK does. Pass a logHandler with debug: true and count failed attempts in a build:

export const stack = contentstack.stack({
  // ...credentials and retry settings
  debug: true,
  logHandler: (level, data) => {
    if (data?.type === "response_error") {
      console.warn(`[cda] ${data.status} ${data.method} ${data.url} ${data.error}`);
    }
  },
});

After the fixes, a build should show a few retried errors at most, and no failed pages. In Analytics, the Delivery API status codes for your organization should show the 5xx and 429 counts drop.

Prevent it

  • Keep @contentstack/delivery-sdk current. Retry and keep-alive behavior improved a lot during 5.x.

  • Give every build a concurrency cap, and fetch shared entries once.

  • Keep SSR timeouts and retry counts below your hosting function's own limit.

  • Don't start a full rebuild in the same minute as a large bulk publish. Let the publish finish first, or prime the pages you need most.

  • Load test with the hosting provider in the loop. On Launch, coordinate load tests with Contentstack first, as the Launch load testing docs describe.

  • If the errors are 429s rather than timeouts, read Fix 429 rate limit errors in builds, imports and bulk publish. The limits that apply are listed in Contentstack limits on one page.

Key takeaways

  • status: 0 and ETIMEDOUT mean no response came back. Look at your network path and concurrency before you look at Contentstack.

  • The Delivery SDK retries 429s and network errors 5 times by default, 300 ms apart. Add a retryCondition for 500, 502, 503 and 504.

  • Keep timeout times retryLimit inside the time budget of where the code runs: long in builds, short in SSR.

  • Cap concurrent requests in builds with a small worker pool, and fetch shared data once.

  • On Azure managed runtimes, use one keep-alive agent with maxSockets and family: 4.

  • Decide up front whether a failed fetch fails the build or serves the last good data. Never ship empty pages.

  • Check status.contentstack.com before you change code.

Frequently asked questions

  • What is the default timeout of the TypeScript Delivery SDK?

    30 seconds per request. Set the timeout option on contentstack.stack() to change it.

  • Does the Delivery SDK retry failed requests?

    Yes. Current versions retry 429 responses and network errors such as ETIMEDOUT, ECONNRESET and ENOTFOUND up to 5 times, 300 ms apart. They do not retry 5xx responses unless you add a retryCondition.

  • What does "Request failed before a response was received (HTTP status 0)" mean?

    The request never got an HTTP response. The connection timed out, was reset or could not be opened, so the cause is on the network path between your server and the API, not in your query.

  • Why do I only see ETIMEDOUT on Azure?

    Azure managed runtimes share a limited pool of outbound SNAT ports. Under many concurrent new connections the pool runs out and new connections time out. Keep-alive and IPv4 resolution fix most of it.

  • Where do I check whether Contentstack has an incident?

    On status.contentstack.com. If it shows no incident for your region and time window, look at your own network path and concurrency first.