My API key allows 20 bulk requests a minute. I sent 25 at once. Twenty came back fine. Five came back as 429 Too Many Requests, and my script carried on as if nothing had happened. No exception, no warning, just five missing results.
The fix is an old one: retry with exponential backoff. In this how-to we'll write a small fetchWithRetry() wrapper in plain JavaScript. It retries the errors worth retrying, waits a bit longer each time, and listens when the server says exactly how long to wait. The example is a domain availability API, the WhoisFreaks Domain Availability API v2, which answers AVAILABLE, UNAVAILABLE or UNKNOWN for one name or up to 100 at a time.
You need Node.js 20.6 or newer and no npm packages. Every output below comes from a real run.
A. The Problem: Five Requests Lost Without an Error
Here is the burst with plain fetch:
const statuses = await Promise.all(
Array.from({ length: total }, async () => {
const res = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ domainNames: names }),
});
if (res.status === 429) console.log("429:", (await res.json()).message);
return res.status;
}),
);
Output of plain-burst.js

Two things went wrong. The key allows 20 bulk requests per minute, so five were turned away. And Promise.all resolved normally, because fetch only rejects when a request can't complete at all. A 429 is a valid HTTP response, so it lands in res just like a 200.
fetch() rejects only on network failures and aborts. A 429 or 503 resolves normally, so you have to check res.status yourself.
B. Setup
Sign up on the product page to get an API key, then put it in a .env file next to your scripts:
WHOISFREAKS_API_KEY=your_api_key_here
Since version 20.6, Node can load that file itself with the --env-file flag, so you don't need the dotenv package:
node --env-file=.env check.js
These scripts run in Node, so the key never reaches a browser. Don't paste it into front-end code, and add .env to .gitignore.
The code lives in three files: retry.js (the wrapper), whoisfreaks.js (the API calls) and check.js (a command line checker). Two short burst scripts drive the tests in sections A and E.
C. Build fetchWithRetry Step by Step
1. Decide What Is Worth Retrying
Some failures fix themselves. Others never will, however long you wait.
// Status codes that usually mean "try again later"
const RETRY_ON = [408, 429, 500, 502, 503, 504];
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
- Retry:
408 (timeout), 429 (rate limited), 500, 502, 503 and 504 (server trouble), plus network errors and timeouts.
- Don't retry:
400 (bad input), 401 (invalid or inactive key) and 413 (more than 100 names, or out of credits). Waiting won't fix any of these.
2. Wait a Bit Longer Each Time
// Wait roughly 1s, 2s, 4s, 8s... (capped at maxDelay).
// Half of each wait is random ("jitter"), so clients that failed
// together don't all retry at the same moment.
function backoffDelay(attempt, baseDelay, maxDelay) {
const delay = Math.min(maxDelay, baseDelay * 2 ** attempt);
return Math.round(delay / 2 + Math.random() * (delay / 2));
}
With baseDelay at 1 second, the wait doubles each time: up to 1, 2, 4 and 8 seconds. Half of each wait is random. That randomness is called jitter: if a hundred clients fail at the same moment, jitter spreads their retries out instead of sending them all back together. AWS calls this version "equal jitter" and compares it with other options in its write-up on backoff.
Real waits from backoffDelay(), 40 per retry

maxDelay caps the growth, so a long retry chain never waits minutes between tries.
3. Listen When the Server Tells You How Long
Backoff is a guess. For 429s, many APIs tell you the answer. The standard way is a Retry-After header in seconds. The WhoisFreaks API sends its own rate limit headers instead. This is a real 429 from one of my burst runs:
HTTP 429 Too Many Requests
x-ratelimit-allowed-requests: 20
x-ratelimit-remaining-requests: 0
x-ratelimit-remaining-time: 59948000000
retry-after: null
x-ratelimit-remaining-time is in nanoseconds, so that is about 60 seconds until the window resets. Backing off for 1, 2, 4 and 8 seconds would spend all four retries inside the same blocked window. Reading the header gets it right with one wait:
// If the server says how long to wait, believe it.
function serverDelay(res) {
// Standard header, in seconds
const retryAfter = Number(res.headers.get("retry-after"));
if (retryAfter > 0) return retryAfter * 1000;
// WhoisFreaks sends the time left in the rate limit window, in nanoseconds
if (res.status === 429) {
const ns = Number(res.headers.get("x-ratelimit-remaining-time"));
if (ns > 0) {
const buffer = 250 + Math.random() * 750; // spread the retries out a bit
return Math.ceil(ns / 1_000_000 + buffer);
}
}
return null;
}
The docs suggest adding 100 to 250 ms to the reset time to cover clock differences. I add a random 0.25 to 1 second, so the requests waiting out a burst don't all wake up in the same millisecond.
4. Put It Together
export async function fetchWithRetry(url, options = {}, config = {}) {
const {
retries = 4, // retries after the first try
baseDelay = 1000, // first backoff wait, in ms
maxDelay = 30_000, // longest backoff wait, in ms
timeout = 60_000, // per attempt; bulk checks can be slow
} = config;
for (let attempt = 0; ; attempt++) {
let res, error;
try {
res = await fetch(url, { ...options, signal: AbortSignal.timeout(timeout) });
} catch (err) {
error = err; // network failure or timeout
}
// Success, or an error that retrying won't fix (400, 401, 413...)
if (!error && !RETRY_ON.includes(res.status)) return res;
// Out of retries: give the caller the last error or response
if (attempt === retries) {
if (error) throw error;
return res;
}
const wait =
(res && serverDelay(res)) ?? backoffDelay(attempt, baseDelay, maxDelay);
const reason = error ? error.name : res.status;
const secs = (wait / 1000).toFixed(1);
console.log(` ${reason} on attempt ${attempt + 1}, retrying in ${secs}s`);
await res?.body?.cancel(); // we don't need this body, free the connection
await sleep(wait);
}
}
How fetchWithRetry handles each response

A few lines are worth a closer look:
AbortSignal.timeout(timeout) gives every attempt its own time limit. Without it, one hung connection would stall the whole retry chain.
- Running out of retries returns the last response instead of throwing. Callers already check
res.ok, so a final 503 is handled in the same place as any other error. A network error has no response, so that one is thrown.
res.body.cancel() discards the body of a failed response so the connection can be reused.
- Only retry requests that are safe to repeat. An availability check is a read, so asking twice does no harm. Don't retry a payment or an order unless the API supports idempotency keys.
D. Use It With the Domain Availability API
Here is the whole of whoisfreaks.js. The key comes from process.env, and both calls go through the wrapper, so they get retries for free:
// whoisfreaks.js
// Single and bulk calls to the WhoisFreaks Domain Availability API v2.
// Both go through fetchWithRetry.
import { fetchWithRetry } from "./retry.js";
const API_KEY = process.env.WHOISFREAKS_API_KEY;
if (!API_KEY) {
console.error("Missing WHOISFREAKS_API_KEY. Add it to your .env file.");
process.exit(1);
}
const BASE_URL = "https://api.whoisfreaks.com/v2.0/domain/availability";
// One name: GET, returns { domain, availability }
export async function checkOne(domain) {
const url = `${BASE_URL}?apiKey=${API_KEY}&domain=${encodeURIComponent(domain)}`;
const res = await fetchWithRetry(url);
if (!res.ok) throw new Error(`HTTP ${res.status}: ${await res.text()}`);
return res.json();
}
// Up to 100 names: POST, returns [{ domain, availability, status }, ...]
export async function checkMany(domains) {
const res = await fetchWithRetry(`${BASE_URL}?apiKey=${API_KEY}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ domainNames: domains }),
});
// 206 means some names couldn't be checked; res.ok is still true
if (!res.ok) throw new Error(`HTTP ${res.status}: ${await res.text()}`);
const data = await res.json();
return data.bulk_domain_availability_response;
}
res.ok is true for any 2xx status. That matters here, because the bulk endpoint answers 206 Partial Content when it couldn't check some names in the list. Those names come back as UNKNOWN. A 206 is not an error, so fetchWithRetry returns it like a 200. Treat UNKNOWN as "not checked", never as available. If the three statuses are new to you, How to Check if a Domain Name is Available to Register explains each one.
check.js takes one name as an argument, or reads domains.txt and sends it in chunks of 100. That makes it a small bulk domain availability checker:
// check.js
// node --env-file=.env check.js example.com -> check one name
// node --env-file=.env check.js -> check every name in domains.txt
import { readFileSync } from "node:fs";
import { checkOne, checkMany } from "./whoisfreaks.js";
const name = process.argv[2];
if (name) {
console.log(await checkOne(name));
} else {
const domains = readFileSync("domains.txt", "utf8")
.split("\n")
.map((line) => line.trim())
.filter(Boolean);
// The bulk endpoint takes at most 100 names per request
for (let i = 0; i < domains.length; i += 100) {
const results = await checkMany(domains.slice(i, i + 100));
for (const r of results) {
console.log(r.availability.padEnd(12), r.domain);
}
}
}
Output of check.js: one name, then domains.txt

The second run hit a real 429, because the burst test had just used up that minute's budget. The wrapper read the header, waited 53.7 seconds and finished the list. Nothing in check.js had to change.
E. Watch It Recover From a Burst
Now the same 25-request burst, through the wrapper:
const jobs = Array.from({ length: total }, async (_, i) => {
await checkMany(names);
console.log(`request ${String(i + 1).padStart(2)} done at ${seconds()}s`);
});
const results = await Promise.allSettled(jobs);
const failed = results.filter((r) => r.status === "rejected");
console.log(`\n${total - failed.length}/${total} succeeded in ${seconds()}s`);
burst.js with fetchWithRetry (the wait is fast-forwarded; the timer shows real time)

The five requests that got a 429 each waited about 60 seconds, the time left in the window, and then went through. Final count: 25 of 25 in 62.5 seconds.
No API key yet? Point fetchWithRetry at any URL that always returns 503. You'll see four retries, each wait roughly double the last, and then the final 503 comes back to your code.
F. Before You Use This in Production
- Pace big jobs instead of relying on retries. Retries rescue a burst, but they shouldn't be the plan. Send up to 100 names per bulk request, and slow down when
x-ratelimit-remaining-requests gets close to 0. Limits depend on your plan; x-ratelimit-allowed-requests tells you yours.
- Throttled requests are free. A request blocked by the rate limit doesn't use a credit, so waiting and retrying costs time, not money.
- Cap the total wait. Four retries with a 30 second cap suits a script. When a user is waiting on the other end, use fewer retries and a shorter timeout.
- Log every retry. That one-line log in the loop tells you a limit is too tight before your users do.
G. Summary
Retry with exponential backoff in JavaScript fits in one small function, and nothing in it is tied to one service. The same wrapper fits a check domain availability API call, a status poll or a weather lookup. Retry only the errors that can recover, double the wait each time with some jitter, and when the server says how long to wait, use that number. In my test against a 20-per-minute limit, plain fetch lost 5 of 25 requests. The same burst through fetchWithRetry lost none.
Everything you need is in the snippets above: retry.js in full across section C, plus whoisfreaks.js and check.js in section D. For endpoints, parameters and response fields, see the Domain Availability API docs.
References
- "Command-line API: --env-file," Node.js Documentation. https://nodejs.org/api/cli.html#--env-filefile (accessed Dec. 4, 2026)
- "API Errors & Status Codes," WhoisFreaks Documentation. https://whoisfreaks.com/documentation/errors (accessed Dec. 4, 2026)
- M. Brooker, "Exponential Backoff and Jitter," AWS Architecture Blog. https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/ (accessed Dec. 4, 2026)
- "Retry-After header," MDN Web Docs. https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Retry-After (accessed Dec. 4, 2026)
- "API Rate Limiting," WhoisFreaks Documentation. https://whoisfreaks.com/documentation/api-rate-limiting (accessed Dec. 4, 2026)
- "AbortSignal: timeout() static method," MDN Web Docs. https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/timeout_static (accessed Dec. 4, 2026)