AiCredits
Reliability Engineering

Retrying LLM Calls: Exponential Backoff Patterns That Actually Work

Most LLM retry loops fail on classification and deadlines, not backoff math. A runnable jittered-backoff wrapper for DeepSeek, plus streaming and cost caveats.

Published 2026-11-24 Updated 2026-11-24 8 min

Almost every retry helper you find in an LLM codebase uses exponential backoff. Almost none of them work well. The formula is rarely the problem — base * 2 ** attempt is a one-liner. What breaks in production is everything around it: retrying errors that will never succeed, waiting past the point of usefulness, and quietly doubling your token spend because two retry layers stacked on top of each other.

This post is the version I wish more teams shipped: a small, readable wrapper you can paste into a DeepSeek-backed service today, plus the decisions that actually matter — what to retry, how long to wait, when to give up, and how streaming and cost change the answer.

Classify before you back off

Backoff is a treatment for transient failure. Applying it to deterministic failure is how you turn a fast, clear error into a slow, expensive one. A 400 from a malformed message will fail identically on attempt five; a 401 will not fix itself; a context-length error is arithmetic, not weather.

The rule is simple: retry when the failure is about transport or capacity, not about the request itself.

SignalRetry?Reasoning
429 Too Many RequestsYes, and honor Retry-AfterCapacity signal; the header is a better estimate than your formula
500 / 502 / 503 / 504Yes, with jitterTransient server or gateway trouble
Connection reset, DNS blip, socket timeoutYesTransport failure; the request may or may not have been processed
Request timeout you set yourselfYes, but fix the timeout tooOften your deadline is simply too tight for the output length
400 / 422 invalid requestNoDeterministic; the same bytes fail the same way
401 / 403NoCredentials or permissions — a human must act
Context length exceededNoTruncate, chunk, or shorten the prompt instead

A retry wrapper you can actually ship

Three details make this wrapper different from the usual snippet. First, max_retries=0 on the client: the OpenAI SDK already retries twice by default, and layering your loop on top turns five attempts into fifteen. Pick one layer. Second, the server's Retry-After wins over your computed ceiling whenever it is present — it can be a delta-seconds value or an HTTP date, and both forms appear in the wild. Third, the loop is bounded by a wall-clock deadline, not just an attempt count.

The jitter style is full jitter: sleep a uniform random amount between zero and the exponential ceiling. It spreads a thundering herd of clients far better than fixed or equal jitter, at the cost of occasionally retrying almost immediately.

import logging
import os
import random
import time
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime

import openai
from openai import OpenAI

log = logging.getLogger("llm-retry")

client = OpenAI(
    api_key=os.environ["AICREDITS_API_KEY"],
    base_url="https://api.aicreditsapi.com/v1",
    max_retries=0,   # we own the retry loop; never stack two layers
    timeout=60.0,    # per-attempt socket/read timeout
)

RETRYABLE_STATUS = {408, 409, 425, 429, 500, 502, 503, 504}
MAX_CEILING = 30.0   # cap the exponential ceiling, in seconds


def retry_after_seconds(exc):
    """Parse Retry-After as either delta-seconds or an HTTP date."""
    response = getattr(exc, "response", None)
    headers = getattr(response, "headers", None)
    if not headers:
        return None
    raw = headers.get("retry-after")
    if not raw:
        return None
    try:
        return max(0.0, float(raw))
    except ValueError:
        pass
    try:
        when = parsedate_to_datetime(raw)
    except (TypeError, ValueError):
        return None
    if when.tzinfo is None:
        when = when.replace(tzinfo=timezone.utc)
    return max(0.0, (when - datetime.now(timezone.utc)).total_seconds())


def complete(prompt, *, model="deepseek-v4-flash", max_attempts=5, deadline_s=90.0, **kwargs):
    start = time.monotonic()
    attempt = 0
    while True:
        attempt += 1
        try:
            return client.chat.completions.create(
                model=model,
                messages=[{"role": "user", "content": prompt}],
                **kwargs,
            )
        except openai.APIStatusError as exc:
            if exc.status_code not in RETRYABLE_STATUS:
                raise
            err = exc
        except (openai.APITimeoutError, openai.APIConnectionError) as exc:
            err = exc

        remaining = deadline_s - (time.monotonic() - start)
        if attempt >= max_attempts or remaining <= 0:
            raise err

        ceiling = min(MAX_CEILING, 0.5 * (2 ** (attempt - 1)))
        hinted = retry_after_seconds(err)
        delay = min(hinted, 60.0) if hinted is not None else random.uniform(0, ceiling)
        if delay >= remaining:
            raise err

        log.warning(
            "attempt %d/%d failed (%s, status=%s); sleeping %.2fs",
            attempt, max_attempts, type(err).__name__,
            getattr(err, "status_code", "n/a"), delay,
        )
        time.sleep(delay)


if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
    result = complete("In two sentences, explain why jitter matters in retry logic.")
    print(result.choices[0].message.content)

Deadlines beat attempt counts

Five attempts sounds conservative until you remember the delays compound: with a thirty-second ceiling, a single request can sit in your worker for well over a minute before it fails. If your request path owns an HTTP deadline of thirty seconds, that retry loop is a lie — it will be cancelled by the caller anyway, and you have paid for the attempts.

Set the deadline from the outside in. A user-facing request might get a short total budget and only two or three attempts; a background enrichment job can afford a longer deadline and more attempts. Pass the deadline in as a parameter rather than hard-coding it, and check remaining before every sleep — that single comparison prevents most zombie retry loops.

Also raise your per-attempt timeout when you raise output length. A timeout you chose is not the provider being flaky; it is usually your own client giving up on a legitimately long completion.

Streaming breaks naive retries

  • Once tokens have been emitted to a user or written to a buffer, restarting the request produces duplicated or contradictory output. Close the stream and surface the error instead.

  • Wrap only the connection setup. Create the stream inside the same classification logic, but stop retrying the moment the first chunk arrives.

  • Keep a hard timeout on the stream itself — a stalled stream that never raises is worse than a fast failure.

  • Always close the stream object in a finally block so the underlying socket is released when the caller abandons the generator early.

  • For anything that must be complete, prefer non-streaming requests with an explicit deadline over clever stream-recovery code.

Idempotency is the part nobody tests

A retried chat completion is not dangerous by itself: the model holds no state, so repeating it just costs tokens. The danger is what you do with the result. If a completion triggers a tool call that charges a card, writes a row, or sends an email, an at-least-once retry policy becomes at-least-once side effects.

Attach a client-generated request ID via extra_headers on every attempt so a retried call is traceable, and make the downstream action idempotent — a unique constraint on the derived row, a dedupe key on the tool invocation, or an outbox pattern. Then a retry that succeeds twice is boring instead of an incident.

One more nuance: treating a timeout as a failure is a guess. The server may have finished the work after your client stopped waiting. Design for that rather than pretending the request never happened.

What retries actually cost

Every retry is another billed generation attempt. Off-peak traffic generally costs less than peak, prompt-cache hits are cheaper than cold prompts, and deepseek-v4-flash is the economical default while deepseek-v4-pro costs more for harder tasks. That means a retry loop tuned at 2 a.m. behaves differently at midday — not just in latency, but in what your failed attempts are worth. Current rates live at aicreditsapi.com/deepseek-prices, and it is worth reading them once with your retry multiplier in hand rather than guessing.

Two practical consequences. First, use deepseek-v4-flash for the retry-heavy paths — batch classification, extraction, tagging — where a second attempt is cheap and the task is well specified. Second, resist the temptation to "retry with a bigger model": swapping to deepseek-v4-pro on the final attempt is escalation, not retrying. It can be a good pattern for genuinely hard requests, but it changes the answer you get and costs more per attempt, so decide it deliberately rather than burying it in an exception handler.

Instrument the loop, or you are guessing

  • Log attempt number, error class, HTTP status, and sleep duration on every retry — the distribution of statuses tells you whether the problem is capacity or your own prompt sizes.

  • Track a retry rate per endpoint. If a meaningful share of calls need a second attempt, the fix is usually concurrency limits or longer timeouts, not more backoff.

  • Emit time-to-first-token separately from total latency when streaming; they fail for different reasons.

  • Add a circuit breaker for hard outages: after consecutive failures, fail fast for a short window instead of holding worker threads in time.sleep.

  • If this lives in a larger codebase, AiCredits' linting tools are a quick way to catch copy-pasted retry loops that never got the max_retries=0 memo.

FAQ

Should I just use the OpenAI SDK's built-in retries?

For a script or a prototype, yes — the SDK retries twice by default. For anything with a latency budget, no: the built-in loop does not know your deadline and will happily stack with a retry layer you added yourself. Disable it with max_retries=0 and own the loop.

How many attempts should a retry loop allow?

Bound it by time, not by a magic number. Pick the total budget the caller can tolerate, then let attempts fall out of that. In practice that lands around three to five attempts for background work and one or two for interactive requests.

Why not retry a 429 immediately?

Because you are one of many clients. Immediate retries turn a capacity blip into a self-inflicted stampede. Honor Retry-After when it is present, and otherwise use full jitter so your clients spread out instead of synchronizing.

Does retrying an LLM call double-charge me?

It can cost you twice if the first attempt actually completed on the server after your client gave up. You cannot know from the client side, so treat completions as at-least-once: make downstream side effects idempotent and keep attempt counts low.

Is exponential backoff ever the wrong choice?

Yes — for deterministic 4xx errors it is pure delay. And for long-running batch jobs, a queue with a scheduled re-drive is usually better than holding a worker in sleep.

Try Lint in 2 seconds

Wrote something? Paste it here for a free grammar check. No account needed.

More Tools →

Related Tools

💻Code Explainer

Was this article helpful?

| Share on X Reddit Copy link

服务器宕机了?别等用户告诉你

Wakeless 梦哨 帮你 30 秒监控网站 / API / SSL 证书,宕机秒级告警到邮箱、飞书、Slack。免费档 30 个监控,永久免费,无需信用卡。

免费开始监控 →
💬
反馈意见 / Feedback ×