Francisco Javier Palacios PérezFco. Javier Palacios Pérez
Software Developer
Calling other services: timeouts, retries and errors that don't lie

Calling other services: timeouts, retries and errors that don't lie

Calling other services: timeouts, retries and errors that don't lie

Calling other services: timeouts, retries and errors that don't lie

Your API calls another one. The other one is alive but stuck, and your endpoint sits waiting. No error, no log, no response: the client gives up and you find out through a warning that the service is “running slow”.

The cause fits in one sentence: fetch has no timeout. If you don’t set one, it waits indefinitely — and the backend that only talks to its own database doesn’t exist. We all call someone.

This last lesson is about calling outwards without lying to anybody: not to the user, not to the accounts.

A response is not an error

const ok = await fetch("http://localhost:3411/price");
console.log("price:", ok.status, ok.ok, (await ok.json()).price);
price: 200 true 19.9

And now the thing that breaks the intuition of anyone coming from other libraries:

const missing = await fetch("http://localhost:3411/missing");
console.log("404:", missing.status, missing.ok, (await missing.json()).error);
404: 404 false not_found

It threw nothing. fetch only rejects when the request never completed; a 404 or a 500 are perfectly valid responses your code has to look at. res.ok is the short question — is it 2xx? — and res.status is the long one.

This explains a classic bug: a service starts returning 500, your client treats it as success, and the error surfaces three layers below, disguised as “empty field”.

Four families of failure

And here’s the table worth keeping within reach, because the four behave differently:

What happenedHow it shows up
Time ran outTimeoutError: The operation was aborted due to timeout
Nothing is listeningTypeError: fetch failed with cause.code: 'ECONNREFUSED'
The service answers 4xx or 5xxIt resolves, res.ok === false
The body isn’t JSONSyntaxError when you call .json()

The first two are rejections, but you can’t tell them apart by the message: both say the same thing. The difference is in error.cause:

try {
  await fetch("http://localhost:3999/");
} catch (error) {
  console.log("no service →", error.name + ":", error.message, "· cause:", error.cause?.code);
}
no service → TypeError: fetch failed · cause: ECONNREFUSED

And the fourth, the one that misleads most because it arrives late:

const html = await fetch("http://localhost:3411/html");
console.log("html:", html.status, html.ok);
try {
  await html.json();
} catch (error) {
  console.log("when reading json:", error.name + ": " + error.message);
}
html: 200 true
when reading json: SyntaxError: Unexpected token '<', "<h1>I am a page</h1

200 and ok: true for an HTML page. The error isn’t in the request: it’s in assuming everyone answering 200 speaks your language.

No timeout means nothing

The proof, with a server that accepts the connection and never answers:

const pending = fetch("http://localhost:3402/").then(() => "answered");
const result = await Promise.race([pending, new Promise((r) => setTimeout(() => r("still pending"), 2000))]);
no timeout at 2085 ms: still pending

Two seconds and it’s still there. In production it isn’t two seconds: it’s until the client gives up, and meanwhile your process holds an open connection for every request coming in. The cure is the AbortSignal from the async lesson, applied to an HTTP request:

try {
  await fetch("http://localhost:3411/slow", { signal: AbortSignal.timeout(100) });
} catch (error) {
  console.log("timeout →", error.name + ":", error.message);
}
timeout → TimeoutError: The operation was aborted due to timeout

A hundred milliseconds and an error with its own name. AbortSignal.timeout() is the short form of what you built by hand with Promise.race in lesson 6: the race is no longer needed, because the runtime knows how to abort.

Retries that don’t make things worse

A badly built retry turns one failure into two. There are four rules, and all of them matter:

  • Only idempotent calls get retried. A GET can be repeated; a POST for a payment can’t: if the first attempt arrived and the response was lost, the retry charges twice.
  • Only failures that waiting can fix. 5xx, timeout and network errors. A 400 or a 404 won’t improve by repeating the same bad request.
  • With growing waits. Retrying instantly is attacking a service that’s already down.
  • With a limit. Three attempts and give up, with an error that says it gave up.
async function get(url, { attempts = 3, wait = 50 } = {}) {
  for (let i = 1; i <= attempts; i++) {
    try {
      const res = await fetch(url, { signal: AbortSignal.timeout(1000) });
      if (res.ok) return { data: await res.json(), attempt: i };
      if (res.status < 500) throw new Error(`HTTP ${res.status} is not retried`);
      console.log(`attempt ${i}: ${res.status} from the server`);
    } catch (error) {
      if (error.name !== "TimeoutError" && error.cause?.code !== "ECONNREFUSED") throw error;
      console.log(`attempt ${i}: ${error.name}`);
    }
    if (i < attempts) await new Promise((r) => setTimeout(r, wait * i));
  }
  throw new Error("the service did not answer after retries");
}
const t0 = Date.now();
const { data, attempt } = await get("http://localhost:3411/flaky");
console.log("recovered on attempt", attempt, "→", data, "·", Date.now() - t0, "ms");
attempt 1: 503 from the server
attempt 2: 503 from the server
recovered on attempt 3 → { ok: true, attempts: 3 } · 233 ms

Not two minutes: 233 milliseconds, because we waited 50 and then 100. The growing wait keeps the retry cheap when the service recovers fast and stops the hammering when it doesn’t.

And a warning you learn late: retrying doesn’t fix a slow service. If the dependency takes 3 seconds and your timeout is 2, every retry adds two more seconds to the user’s wait and eats their connection. Retries are for transient failures, not chronic slowness.

When the dependency is down

Three possible answers, and choosing wrong is a product bug:

  • Fail fast: return a 503 with a clear message. Right when the data is essential and the user would rather know now.
  • Degrade: answer with what you have — a cache, a default, the part of the page that doesn’t depend on the service. Right for the expendable.
  • Queue: accept the work and do it when the service returns. Right for the asynchronous, and dangerous if the user believes it’s already done.

The line you don’t cross: don’t lie. Serving stale data as if it were fresh, or accepting a payment you never recorded, is worse than an honest error. A 503 with Retry-After is information; an invented response is debt.

And the detail that makes this work in a team: the error you return to your client has to say what happened without telling them your architecture. {"error":"service_unavailable","retry_in":30} works; TypeError: fetch failed at get (/srv/lib/client.js:42) doesn’t.

Testing it without a network

A test that calls the internet isn’t a test: it’s a lottery with the office wifi. The right way is to start a local server inside the test, on port 0, so the operating system picks a free one.

// client.test.js
import { test, before, after } from "node:test";
import assert from "node:assert/strict";
import { createServer } from "node:http";

let server;
let base;

before(async () => {
  server = createServer((req, res) => {
    if (req.url === "/price") {
      res.writeHead(200, { "Content-Type": "application/json" });
      res.end(JSON.stringify({ price: 19.9 }));
      return;
    }
    res.writeHead(404, { "Content-Type": "application/json" });
    res.end(JSON.stringify({ error: "not_found" }));
  });
  await new Promise((r) => server.listen(0, "127.0.0.1", r));
  base = `http://127.0.0.1:${server.address().port}`;
});

after(() => server.close());

test("reads the price from the service", async () => {
  const res = await fetch(`${base}/price`);
  assert.equal(res.ok, true);
  assert.equal((await res.json()).price, 19.9);
});

test("a 404 doesn't throw, it's checked with ok", async () => {
  const res = await fetch(`${base}/nothing`);
  assert.equal(res.status, 404);
  assert.equal(res.ok, false);
});
node --test client.test.js
✔ reads the price from the service (49.192998ms)
✔ a 404 doesn't throw, it's checked with ok (7.70034ms)
ℹ tests 2
ℹ pass 2
ℹ fail 0

No mocks, no nock, no network. The server is the runtime, the port is chosen by the system and the test cleans up after itself with after. And for the error paths a server can’t fake — a deliberate timeout, a corrupted response — node:test ships mock, which replaces fetch with whatever you need inside one specific test.

What you take from this lesson

  • fetch only rejects when the request didn’t complete: a 404 or 500 are values, and res.ok is your job.
  • Four families of failure: timeout, network, HTTP and JSON. Only the first two reject, and error.cause tells them apart.
  • fetch has no default timeout; AbortSignal.timeout() sets one in a line.
  • Retry only idempotent calls, only 5xx/network/timeout, with growing waits and a limit.
  • Retrying doesn’t fix chronic slowness: it multiplies it.
  • When the dependency falls: fail fast, degrade or queue. Never lie.
  • The test starts its own server on port 0 and needs no internet.

The course closes here. You started asking why Node exists and you finish with two services talking to each other: an API that validates, logs, shuts down without dropping requests, knows which parts of the runtime it doesn’t need to install, and calls others without hanging. What lies ahead — database, authentication, integration tests, deployment — has its own path, and now you can read what’s underneath every layer.

Thanks for making it this far.

Never stop coding!