Retries, backoff and queues for busy model endpoints

A familiar complaint from people using popular models through shared providers: a single message takes a dozen or more attempts before it goes through, even though they are nowhere near their own quota. When a model is in high demand, and some providers now push hundreds of billions of tokens a day through a single model, capacity runs short at peak times and clients see errors that have nothing to do with their own usage.
This guide is for developers who call OpenAI-compatible APIs, whether DeepSeek, a gateway or the keyless endpoint on this site, and want their app to cope gracefully. You will build a retry helper that respects Retry-After, adds jittered backoff, distinguishes errors that are worth retrying from those that are not, and queues requests so you never exceed a concurrency limit in the first place.
This site is not affiliated with DeepSeek. The examples target free-ai, an independent open-weight model served here without keys, whose limits are documented: one request per second per IP with bursts of three, two in parallel, and 429 or 503 responses when you exceed them or the service is busy.
Frequently asked questions
What does HTTP 429 mean on a model API?
Too Many Requests: you, or the IP or key you share, have exceeded a rate limit. The server is fine; it is asking you to slow down. A Retry-After header, when present, says how many seconds to wait.
What does HTTP 503 mean?
Service Unavailable: the server or the model pool is temporarily overloaded or under maintenance. It is not your fault and usually resolves within seconds. On this site the guidance is to retry after two to five seconds.
How does exponential backoff differ from a fixed delay?
A fixed delay retries at the same interval every time. Exponential backoff doubles the wait after each failure, so a struggling server receives fewer and fewer retries instead of a steady stream that keeps it overloaded.
Why add random jitter to retries?
If many clients fail at the same moment and all retry after exactly two seconds, they collide again. Adding a random fraction spreads retries out and greatly improves the chance that each one succeeds.
Which errors should never be retried?
Client errors such as 400 for a malformed body, 401 or 403 for bad credentials and 404 for a wrong path. Retrying them wastes requests; fix the request instead.
Is it better to retry on the client or on the server?
For a public web app calling a keyless API, retry in the browser so each visitor's own IP carries its share of the limit. When a server proxy holds a paid key, retry on the server and keep the client simple.
How many retries are reasonable?
Three to five with backoff covers most transient problems. Beyond that, show the user a clear message and a button to try again rather than spinning indefinitely.
Step by step
- Classify errors — Write one function that marks 429, 5xx and network failures as retryable and client errors as permanent.
- Honour Retry-After — Read the header on every 429 and wait at least that many seconds before trying again.
- Add backoff with jitter — When no header is present, double a base delay after each failure and multiply by a random factor between 0.5 and 1.5.
- Limit concurrency — Route requests through a queue that allows two in flight and spaces starts by about one second.
- Show clear states — Display a short status message for waiting, retrying and failure, keep the user's input, and offer cancel.
Know which failures are temporary
Good retry logic starts with classification. Some failures are temporary and likely to succeed if you wait: rate limits, overloaded servers, gateway timeouts and dropped connections. Others are permanent for that request: invalid JSON, an unknown model name, a prompt longer than the context window. Treating both the same either hammers the server with hopeless requests or gives up on ones that would have worked.
Write the classification down once, in a single function, so every part of your app behaves the same way.
Context too long
A request that exceeds the 32,000-token context on this endpoint fails every time. Trim history or split the input instead of retrying; see fitting large inputs into the context.
Network errors
A TypeError from fetch usually means the connection failed before any status arrived. These are worth a retry, but also check the user is online.
- Retry: 429, 500, 502, 503, 504 and network errors
- Retry once at most: unexpected stream interruptions
- Do not retry: 400, 401, 403, 404, 413, 422
- Do not retry: user cancelled the request
Respect Retry-After first
When the server tells you how long to wait, believe it. A 429 from this endpoint includes a Retry-After header in seconds. Waiting at least that long avoids burning another request that would certainly fail. Only when the header is missing should your own backoff schedule decide.
In the browser, reading response headers from a cross-origin request requires the server to expose them. CORS is open here, but if a header is not readable in your environment, fall back to backoff rather than retrying immediately.
Parse defensively
The header may be a number of seconds or an HTTP date. Handle the number, treat anything unparseable as missing, and cap the wait so a strange value cannot freeze your interface.

A retry helper with backoff and jitter
The function below wraps fetch for JSON requests. It retries temporary failures up to a limit, prefers Retry-After, otherwise doubles a base delay with random jitter, and supports cancellation through an AbortSignal. It is small enough to paste into any front-end project.
Why the cap matters
Exponential growth gets large quickly. Capping the wait at about thirty seconds keeps the experience bounded; after that, it is better to tell the user than to wait silently.
Report each wait
The onWait callback lets the interface show 'busy, retrying in 3 s' instead of a frozen spinner, which makes the delay feel intentional.
const RETRYABLE = new Set([429, 500, 502, 503, 504]);
const sleep = (ms, signal) => new Promise((res, rej) => {
const t = setTimeout(res, ms);
signal?.addEventListener("abort", () => { clearTimeout(t); rej(new DOMException("aborted", "AbortError")); });
});
async function postWithRetry(url, body, { tries = 5, base = 1500, signal, onWait } = {}) {
for (let attempt = 1; ; attempt++) {
let res;
try {
res = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), signal });
} catch (err) {
if (err.name === "AbortError" || attempt >= tries) throw err;
res = null;
}
if (res && res.ok) return res.json();
if (res && !RETRYABLE.has(res.status)) throw new Error("HTTP " + res.status + ": " + (await res.text()));
if (attempt >= tries) throw new Error("gave up after " + tries + " attempts");
const header = res ? Number(res.headers.get("Retry-After")) : NaN;
const backoff = base * 2 ** (attempt - 1) * (0.5 + Math.random());
const wait = Math.min(Number.isFinite(header) && header > 0 ? header * 1000 : backoff, 30000);
onWait?.(Math.round(wait / 1000), attempt);
await sleep(wait, signal);
}
}
postWithRetry("https://api.apideepseekfreekey.com/v1/chat/completions", {
model: "free-ai",
messages: [{ role: "user", content: "Give one tip for writing clear error messages." }]
}, { onWait: (s, n) => console.log("retry", n, "in", s, "s") })
.then(d => console.log(d.choices[0].message.content));Prevent 429s with a small request queue
Retries handle errors after they happen; a queue prevents many of them. If your page can fire several requests at once, for example summarising a list of items, a queue that limits concurrency to two and spaces starts by about a second keeps you inside the per-IP limits of this endpoint, so 429s become rare instead of routine.
The queue below is generic: give it a limit and a minimum gap, and push async tasks into it.
Queue per tab
Each browser tab has its own queue, but the limit is per IP. If users often open several tabs, consider a lower concurrency or a BroadcastChannel to coordinate.
function createQueue(limit = 2, gapMs = 1100) {
let active = 0, last = 0;
const waiting = [];
const next = () => {
if (active >= limit || waiting.length === 0) return;
const delay = Math.max(0, last + gapMs - Date.now());
setTimeout(() => {
if (active >= limit || waiting.length === 0) return;
if (Date.now() < last + gapMs) return next();
const { task, resolve, reject } = waiting.shift();
active++; last = Date.now();
task().then(resolve, reject).finally(() => { active--; next(); });
next();
}, delay);
};
return task => new Promise((resolve, reject) => { waiting.push({ task, resolve, reject }); next(); });
}
const enqueue = createQueue();
const items = ["caching", "retries", "timeouts"];
Promise.all(items.map(topic => enqueue(() => postWithRetry(
"https://api.apideepseekfreekey.com/v1/chat/completions",
{ model: "free-ai", max_tokens: 80, messages: [{ role: "user", content: "One sentence on " + topic }] }
)))).then(rs => rs.forEach(r => console.log(r.choices[0].message.content)));
Streaming requests need slightly different handling
With "stream": true, an error can arrive in two places: as a non-200 status before any data, or as a connection that drops halfway through. The first case is handled exactly like a normal request. The second is trickier, because the user has already seen part of the answer.
For interrupted streams, the friendliest behaviour is to keep the partial text visible, mark it as incomplete, and offer a 'continue' or 'retry' button rather than silently starting again and replacing what the user was reading.
Check status before reading
Only start the stream reader if res.ok is true. Otherwise read the body as text, classify the status, and hand it to the same retry logic.
Detect a clean finish
A complete stream on this endpoint ends with data: [DONE]. If the reader finishes without it, treat the answer as interrupted.
Honest interface states
Users tolerate delays far better when they understand them. Map each technical state to a short, plain message and keep the controls consistent. Never pretend a request is still running when it has failed, and never hide that the answer came after several retries if that took noticeably long.
A small status line under the input box is usually enough. Disable sending while a request is active, show a countdown during waits, and offer cancel at every stage.
Keep the user's text
If a request fails, leave the user's message in the input box. Losing a carefully typed prompt is the most frustrating outcome of all.
- Sending: 'Asking the model…'
- Rate limited: 'Too many requests, retrying in 3 s'
- Busy: 'The service is busy, trying again'
- Gave up: 'Could not get an answer, try again in a minute'
- Interrupted: 'Answer cut off, continue?'

Timeouts: the error nobody returns
Not every failure arrives as a status code. Sometimes a request simply hangs: the connection is open, nothing comes back, and the user waits forever. Browsers do not impose a short timeout on fetch by themselves, so you need to add one. An AbortController with a timer is the usual tool, and the same controller can power a cancel button.
Choose the timeout by mode. A short chat answer that has not started after thirty seconds is almost certainly stuck. A long answer with reasoning enabled, which can legitimately think for a while before writing, deserves a more generous limit, or better, a streaming request where you time out only if no new chunk arrives for a while.
Treat a timeout as retryable, but count it against the same attempt limit as other errors. If several consecutive attempts time out, the service is probably struggling, and the kindest thing is to stop and tell the user rather than queueing more stuck requests that occupy both of the parallel slots each IP is allowed.
Idle timeouts for streams
For streaming, reset a timer each time a chunk arrives and abort only when the stream has been silent for, say, twenty seconds. A long but steadily flowing answer is never cut off.
Check health before blaming the network
A quick GET /health tells you whether the service itself is up. If it answers but chat requests fail, the problem is load or limits, not connectivity.
function withTimeout(ms, outer) {
const ctrl = new AbortController();
const timer = setTimeout(() => ctrl.abort(), ms);
outer?.addEventListener("abort", () => ctrl.abort());
return { signal: ctrl.signal, done: () => clearTimeout(timer) };
}
const t = withTimeout(30000);
fetch("https://api.apideepseekfreekey.com/health", { signal: t.signal })
.then(r => console.log("health", r.status))
.catch(e => console.log("failed or timed out:", e.name))
.finally(t.done);Daily quotas and graceful degradation
Beyond per-second limits there is a daily ceiling: 10,000 requests or 10 million tokens per IP on this endpoint, resetting at 00:00 UTC. Few individual users reach it, but automated scripts and shared office IPs can. When retries keep returning 429 for a long time, assume a daily cap and stop retrying until the reset.
For apps with a paid fallback behind a proxy, this is the moment to switch: route the request to the other provider and note it in your logs. The pattern is described in keeping providers swappable.
Show the reset time
Converting midnight UTC into the user's local time and displaying it is a small kindness that turns a dead end into a clear expectation.

Open the home page and send a request to the keyless endpoint straight from your browser, no account or key needed.
Read also
- How to build a Telegram assistant bot on a free OpenAI-compatible API
- Why does an AI model drop accents or garble non-English text?
- Direct DeepSeek API vs a unified gateway: which is better value?
- What should your app do if DeepSeek API prices go up?
- How to build a small RAG demo in the browser with no backend