Almost every real back end talks to other services: a payment provider, an email service, a maps API, an AI model, a government database. Those services are outside your control. They are sometimes slow, sometimes down, and sometimes send you data you did not expect. A server that assumes they always work will fail in the worst possible moment. This lesson has two halves: calling other APIs defensively, and receiving webhooks, where another service calls you.
Calling an API: three habits
Node 18 and later has fetch built in, so you need no extra package for simple calls. Raw fetch has no timeout, though, so a service that never answers can leave your request waiting forever and use up your server. Build one small wrapper function that every call goes through, and put these habits in it.
- A timeout.
AbortSignal.timeout(2000)cancels the request after two seconds. - Retries for temporary failures. Network errors, 5xx replies and 429 (too many requests) are often gone a moment later, so try again.
- No retry for your own mistakes. A 400, 401, 403 or 404 will fail the same way every time, so retrying only wastes time.
- Exponential backoff. Wait a little, then longer, for example 50, 100, 200 milliseconds, so you do not hammer a service that is already struggling.
- A limit on attempts, then a clear error that the rest of your app can handle.
- Make a folder and open it in a terminal. Run
npm init -y, then openpackage.jsonand add"type": "module"so thatimportworks. - Save the code as
client.js. The test uses only Node, with no extra packages.
import crypto from 'node:crypto';
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
// Call another service safely: a time limit, a few retries on temporary errors, and clear failures.
export async function fetchJson(url, { retries = 2, timeoutMs = 2000, baseDelayMs = 50, headers } = {}) {
let lastError;
for (let attempt = 0; attempt <= retries; attempt++) {
try {
const res = await fetch(url, { signal: AbortSignal.timeout(timeoutMs), headers });
if (res.ok) return await res.json();
// 4xx means we did something wrong: retrying will not help, except for 429 (slow down).
if (res.status < 500 && res.status !== 429) throw Object.assign(new Error(`HTTP ${res.status}`), { fatal: true });
lastError = new Error(`HTTP ${res.status}`);
} catch (error) {
if (error.fatal) throw error;
lastError = error;
}
if (attempt < retries) await sleep(baseDelayMs * 2 ** attempt); // 50, 100, 200 ...
}
throw new Error(`Failed after ${retries + 1} attempts: ${lastError.message}`);
}
// Webhooks: the other service signs the body with a shared secret. Check it before you trust it.
export function sign(rawBody, secret) {
return crypto.createHmac('sha256', secret).update(rawBody).digest('hex');
}
export function verifySignature(rawBody, signature, secret) {
const expected = Buffer.from(sign(rawBody, secret));
const given = Buffer.from(String(signature ?? ''));
return expected.length === given.length && crypto.timingSafeEqual(expected, given); // constant-time compare
}
In fetchJson, a loop runs up to retries + 1 times. Inside it, the fetch call carries the timeout signal. A 4xx reply other than 429 is thrown straight away. A network error, a timeout or a 5xx makes the loop sleep for baseDelayMs * 2 ** attempt and try again. The test starts a small fake server that fails twice and then answers, one that always returns 404, and one that is too slow, and checks that the wrapper behaves correctly in each case.
Receiving webhooks
A webhook is a request that a service sends to your server when something happens, for example "payment succeeded" or "new commit pushed". Instead of asking again and again, you give them a URL and they call it. The risk is obvious: anyone on the internet can send a request to that URL and claim that a payment succeeded. You must check that the request really came from the provider.
The usual method is an HMAC signature. You and the provider share a secret. For each webhook the provider calculates a hash of the exact body using the secret and sends it in a header. You calculate the same hash and compare. An attacker who does not know the secret cannot produce a matching signature. Three details matter. First, hash the raw bytes of the body, before express.json() changes them, or the hash will not match. Second, compare with crypto.timingSafeEqual, because an ordinary === stops at the first different character and can leak information through timing. Third, reject requests with a missing or wrong-length signature before comparing.
In Express, use express.raw({ type: 'application/json' }) on the webhook route only, so the body arrives as a Buffer, verify it, and then JSON.parse it yourself. Always answer quickly with a 200 after you have verified and saved the event, and do slow work later in a queue, because providers resend if you take too long. Since they can resend, store the event id and ignore ids you have already handled.
Your task
- Add jitter, a small random amount, to the backoff delay, and explain why it helps when many clients retry together.
- Make the wrapper read the
Retry-Afterheader on a 429. - Write an Express route that receives a webhook, verifies the signature and answers 401 for a bad one.
How to check it worked
- All four tests pass.
- A 404 is tried once, not three times.
- You can say why the raw body is needed for the signature.