Ravindra BagaleCourses & study guides Track your progress

Generative AI

LLM API Errors in Python: 429 Rate Limits, Timeouts, Backoff Retries and a Cost Budget

Generative AI course · Build with Gen AI (APIs, RAG) · Estimated reading time: 20 minutes, plus the lab

Annapurna Tiffins wants to tag 300 customer reviews every evening with an AI model. The developer writes a simple loop and starts it. After forty reviews the provider answers with error 429, the loop crashes, and nobody knows which reviews were finished. The next night the developer adds a loop that retries forever. That night a billing problem causes every request to fail, the loop keeps hammering the API until morning, and the log file becomes huge. Neither version is safe. Today we will write a calm, polite loop that waits correctly, gives up at clear limits and never spends more than the budget we set.

In the first API call chapter we made one request from Python and saw what 401 and 429 mean. In the JSON validation chapter we retried when the reply text was wrong. This lesson handles the other kind of failure, where the request itself fails, and it adds a cost budget based on the token numbers that every reply returns.

What you will learn in this chapter

  1. You will sort API errors into two groups: temporary errors that may succeed later, and errors that need a fix before any retry.
  2. You will read the Retry-After header and treat it as the minimum waiting time.
  3. You will write capped exponential backoff with full jitter in plain Python.
  4. You will stop a retry loop by attempt count and by a total time budget.
  5. You will track token cost from the usage numbers in each reply and stop a batch before it can cross a budget.

Everything in this chapter is made up for learning

Synthetic classroom data only. Annapurna Tiffins, its reviews and every error or reply in the lab are fictional and hand typed. The lab uses a fake client, so it needs no API key, no internet and no installation beyond Python. The prices in the lab are made-up teaching numbers, not any provider's real price. Real rate limits and prices depend on your account, your project and the model, so you must always read them from the provider's own pages, response headers and usage fields.

1. What can go wrong on one API call

An API call travels from your program, across the internet, to the provider's servers and back. A failure can happen at any point on that path. The most important question for each failure is simple: if we wait and send the same request again, could it succeed?

Common API failures and whether a retry can help.
FailureWhat it usually meansShould the loop retry?
429 rate limitYou sent too many requests or tokens in a short time.Yes, after waiting. Follow Retry-After when it is present.
429 quota, credit or spend limitYour credit ran out or a spend or usage limit was reached.No. A person must add credit or change the limit first.
500 server errorSomething went wrong on the provider's side.Yes, a few times with growing waits.
503 or 529 overloadedThe service or model is temporarily busy.Yes, after waiting. Follow Retry-After when it is present.
Timeout or connection failureNo answer came back in time, or the request never arrived.Yes, a few times. Also check your network and your timeout setting.
400 bad requestThe request itself is wrong, for example a missing or invalid parameter.No. Sending the same wrong request again gives the same error.
401 or 403The key is wrong, or it has no permission for this resource.No. Fix the key or the permission.

Notice that 429 appears twice in this table. The same status number can mean “slow down” or “your money ran out.” That is why our code reads the error code inside the response, not only the status number.

2. What the official documentation says today

We opened each provider's official documentation on 16 November 2026 (IST) to check how they describe errors and retries. These are interface facts, not a ranking of providers, and the pages can change, so check them again on the day you build.

  • OpenAI's error codes guide lists several kinds of 429. For “Rate limit reached for requests” it says to pace your requests and follow the Retry-After header when it is present. For credit and spend limit codes such as credit_balance_exhausted, it says that retrying billing, spend or quota errors will not restore access. It describes 500 as an issue on its servers and 503 as a temporarily overloaded model.
  • OpenAI's rate limits guide says to treat Retry-After as a minimum and add a small random delay. When the header is missing, it recommends exponential backoff with jitter, and it says to limit both the number of attempts and the total time spent retrying. It also warns that unsuccessful requests count towards your per-minute limit, and that if you manage retries yourself you should disable SDK retries or count them, so that nested loops do not multiply requests.
  • Anthropic's errors page lists 429 rate_limit_error, 500 api_error, 504 timeout_error and 529 overloaded_error. It says a 429 caused by reaching the monthly spend cap has no retry-after header and keeps failing until access resumes. It also says the official SDK retries transient failures with exponential backoff, twice by default, and honours the retry-after header when present.
  • Google's Gemini troubleshooting guide recommends exponential backoff for errors such as 429 RESOURCE_EXHAUSTED and 503 UNAVAILABLE. It says to add jitter, to retry only transient errors such as 429, 408 and 5xx, not to retry client errors such as 400, 402 or 403, and to set a maximum number of retries. It says the Python SDK already retries transient errors up to four times by default.
Retry advice that all three providers' documentation shares.
AdviceWhy it matters
Retry only temporary errors.Bad requests, wrong keys and empty credit fail every time, so retrying only wastes time and requests.
Wait longer after each failure.A busy server needs time to recover, and quick repeated requests make the problem worse.
Add random jitter to each wait.Many programs that failed together will otherwise all retry at the same moment.
Set a maximum number of attempts.A loop without a limit can run all night and fill your logs.
Remember that the SDK may already retry.Your own loop on top of SDK retries can multiply the number of requests.

3. Rate limits differ for every account, so read your own

Beginners often search the internet for “the rate limit” of a provider. There is no single number. OpenAI's guide says limits are measured as requests per minute, requests per day, tokens per minute and tokens per day, that they are set for the organization and the project, and that they vary by model. Anthropic's rate limits page says limits depend on your usage tier and are set for the organization. Google's Gemini rate limits page says limits are applied per project, not per API key, and vary by model. All three say that hitting any one of the limits triggers an error, even if the others still have room.

Where to read the limits that apply to your own account.
ProviderWhere the documentation says to look
OpenAIThe Limits page in your organization settings, and response headers such as x-ratelimit-remaining-requests and x-ratelimit-remaining-tokens.
AnthropicThe Rate limits page in the Claude Console, and response headers that start with anthropic-ratelimit.
Google GeminiThe rate limit page in Google AI Studio for your project.

This lesson deliberately prints no limit numbers and no prices, because they change and they differ between accounts. Your code should read limits and usage from the provider at run time, and your plan should be based on what your own console shows today.

Ravindra Bagale's Tip

Not every 429 means “wait a little.” Before you retry, read the error code. If it says rate limit, wait and try again. If it says quota, credit or spend limit, stop the loop and tell a person, because no amount of waiting will refill an empty wallet.

4. Read the Retry-After header first

Sometimes the provider tells you exactly how long to wait. It does this with a response header called Retry-After. The HTTP standard, RFC 9110, says the value is either a whole number of seconds, such as 120, or a date and time, such as “Fri, 31 Dec 1999 23:59:59 GMT.” Our lab reads both forms. For the date form it uses email.utils.parsedate_to_datetime, which the Python email.utils documentation describes.

  1. If the header is missing, empty or not valid, ignore it and use backoff instead.
  2. If the header is valid, wait at least that many seconds, then add a small random extra delay.
  3. If the requested wait is longer than your own maximum, do not retry sooner than asked. Stop and schedule the job for later instead. OpenAI's rate limits guide gives the same advice.

5. Capped exponential backoff with full jitter

When there is no Retry-After header, we choose the wait ourselves. Exponential backoff means that the waiting limit doubles after each failure. A cap stops the limit from growing forever. Full jitter means that the real wait is a random number between zero and the current limit, so that many programs do not retry at the same moment. Our lab uses random.uniform, which the Python random documentation describes, and it lets tests pass in their own random source so that results are repeatable.

Backoff limits in our lab with a 1 second base and an 8 second cap (our own settings, not a provider's).
Retry numberLimit before the capLimit after the capReal wait
11 second1 secondA random value from 0 to 1 second.
22 seconds2 secondsA random value from 0 to 2 seconds.
34 seconds4 secondsA random value from 0 to 4 seconds.
48 seconds8 secondsA random value from 0 to 8 seconds.
516 seconds8 secondsA random value from 0 to 8 seconds.

The Python random module is fine for spreading out retries. Its documentation warns that it must not be used for security purposes such as passwords or tokens, and that is not what we use it for here.

6. The retry loop: one clear decision at every step

Our function call_with_retries() follows the same steps for every failure. It measures time with time.monotonic(), because the Python time documentation says this clock cannot go backwards and is not affected by system clock updates.

  1. Call the API. If the call succeeds, return the reply and stop.
  2. If the error is not temporary, such as 400, 401 or a quota code, stop at once and report it.
  3. If this was the last allowed attempt, stop and report the last error.
  4. If a valid Retry-After value is present and longer than our maximum, stop and mark the job as deferred.
  5. Otherwise, choose the wait: the Retry-After value plus a little jitter, or the backoff wait with full jitter.
  6. If waiting would take the total time past our time budget, stop now instead of sleeping.
  7. Sleep for the chosen time, write one log line, and go back to step 1.
Outcome labels that the retry loop returns.
Outcome labelMeaningWhat to do next
okA reply arrived, possibly after some retries.Use the reply and record its usage.
not_retryableThe error needs a fix, not a wait.Fix the request, the key or the credit, then re-run only the failed items.
max_attemptsEvery allowed attempt failed with temporary errors.Keep the item for a later re-run and check the provider's status page.
time_budgetWaiting longer would break our time limit.Keep the item for a later re-run.
deferredThe provider asked for a wait longer than we allow.Schedule the job after the requested time.

A real SDK may already retry inside its own code. If you use the loop from this lesson around an SDK call, turn the SDK's retries off or set your attempt limit with them in mind. Otherwise four attempts in your loop multiplied by the SDK's own retries can send many more requests than you planned.

7. Tokens, usage and a cost budget

Providers charge for the tokens you send and the tokens you receive, and the price depends on the model. Every successful reply includes a usage section that reports the real token counts. OpenAI's Responses API reference lists usage.input_tokens and usage.output_tokens. Anthropic's Messages API reference lists usage.input_tokens and usage.output_tokens, and adds that cached input is counted in separate fields. Google's token counting page describes a usage object with fields such as total_input_tokens and total_output_tokens. The names differ, so your provider wrapper should translate them into one shape before the budget code sees them.

The cost formula used in the lab.
PartHow it is calculated
Input costInput tokens multiplied by the input price per million tokens, divided by one million.
Output costOutput tokens multiplied by the output price per million tokens, divided by one million.
Cost of one callInput cost plus output cost.
Worst case before a callAn estimate of the input tokens plus the full output token limit that we set on the request.

The prices are passed in as settings, so the same code works with any provider. In the lab we use example prices of 1.00 per million input tokens and 4.00 per million output tokens in made-up “units.” These are teaching numbers only. Before a real project, copy the current prices for your chosen model from the provider's pricing page, and check them again when you change models. The lab uses Python's Decimal type for money, so that adding many tiny amounts does not create rounding errors.

  1. Before each call, estimate the input tokens. Google's documentation says that for Gemini models a token is about four characters, and the lab uses that rough rule only for this estimate.
  2. Add the full output limit to get the worst case, and convert it to cost.
  3. If the worst case is more than the remaining budget, stop the batch before sending the request.
  4. After a successful reply, record the real usage numbers, not the estimate.
  5. At the end, print the calls, input tokens, output tokens, total spent and the amount left.

Keep a budget in your provider's dashboard as well. The budget in your code protects one job, while a dashboard spend limit protects the whole account if a bug slips through.

Ravindra Bagale's Tip

Before you run a job on 300 rows, run it on 5 rows and print the tokens in and the tokens out for each one. Multiply the average by 300 and by today's price. This two-minute habit has saved my students more money than any clever prompt.

8. Run the offline lab

Save the two files below in one folder. Use Python 3.9 or newer. No package installation is needed. Run python3 -B api_guard.py, then python3 -B -m unittest -v test_api_guard. You should see 56 tests pass. A class called FakeLLMClient plays the provider by replaying a script of errors and replies, and a FakeClock moves time forward instantly, so the whole demo finishes in a fraction of a second and gives the same result every time.

Demo output (synthetic)

SYNTHETIC DEMO - fake provider, made-up prices, no network

# 429 with Retry-After 2, then success
  attempt 1: 429 -> wait 2.32s (Retry-After 2s + jitter)
  attempt 2: success
  outcome=ok attempts=2 waited=2.32s

# 500, timeout, then success
  attempt 1: 500 -> wait 0.32s (backoff with full jitter)
  attempt 2: APITimeout -> wait 0.30s (backoff with full jitter)
  attempt 3: success
  outcome=ok attempts=3 waited=0.63s

# 400 bad request
  attempt 1: 400 invalid_request -> stop, not retryable
  outcome=not_retryable attempts=1 waited=0.00s

# 429 quota ran out
  attempt 1: 429 insufficient_quota -> stop, not retryable
  outcome=not_retryable attempts=1 waited=0.00s

# 503 four times
  attempt 1: 503 -> wait 0.32s (backoff with full jitter)
  attempt 2: 503 -> wait 0.30s (backoff with full jitter)
  attempt 3: 503 -> wait 2.60s (backoff with full jitter)
  attempt 4: 503 -> stop, attempt limit reached
  outcome=max_attempts attempts=4 waited=3.23s

# 429 asks for 600s
  attempt 1: 429 -> stop, server asks 600s, defer the job
  outcome=deferred attempts=1 waited=0.00s

# 503 asks for 25s twice
  attempt 1: 503 -> wait 25.32s (Retry-After 25s + jitter)
  attempt 2: 503 -> stop, waiting 25.15s would pass the 30s budget
  outcome=time_budget attempts=2 waited=25.32s

# Batch of 6 reviews, budget 0.0003 units, EXAMPLE prices 1.00 in / 4.00 out per million tokens
  R1: ok quality
  R2: ok praise
  R3: ok late
  R4: ok price
  R5: budget_stop
  calls=4 tokens in=186 out=8 spent=0.000218 remaining=0.000082

Test runner tail

Ran 56 tests in 0.002s
OK

Read the demo from top to bottom. The first case waits for the Retry-After time plus a little jitter. The 400 error and the quota error stop after one attempt, because waiting cannot fix them. The 503 case uses all four attempts and then stops. The 600 second request is deferred instead of retried early, and the 25 second case stops because a second wait would pass the 30 second time budget. In the batch, review R5 is never sent, because its worst-case cost would not fit in the money that remains.

api_guard.py

"""api_guard.py - offline lab: retries with backoff and a token cost budget.

SYNTHETIC classroom material. No network, no API key, standard library only.
FakeLLMClient plays the AI provider by replaying a hand-written script.
The prices below are MADE-UP TEACHING NUMBERS, not any provider's real price.
"""
import email.utils
import math
import random
import time
from decimal import Decimal

# ---------- 1. Errors that a provider wrapper can raise ----------

class LLMError(Exception):
    """Base class for every error in this lab."""

class APIStatusError(LLMError):
    """The provider answered with an HTTP error status."""
    def __init__(self, status, code="", retry_after=None):
        super().__init__(f"HTTP {status} {code}".strip())
        self.status = status
        self.code = code
        self.retry_after = retry_after  # raw header text, or None

class APITimeout(LLMError):
    """No answer arrived before our own timeout."""

class APIConnectionFailed(LLMError):
    """The request never reached the provider."""

class BudgetExceeded(LLMError):
    """The next call could push spending over the budget."""

# ---------- 2. Which errors are worth retrying ----------

RETRYABLE_STATUS = {408, 429, 500, 502, 503, 504, 529}
# 429 codes that mean "money or quota ran out". Waiting will not fix them.
NO_RETRY_CODES = {
    "insufficient_quota", "credit_balance_exhausted",
    "organization_spend_limit_exceeded", "project_spend_limit_exceeded",
    "organization_usage_limit_exceeded", "enforced_spend_limit_reached",
    "quota_exceeded",
}

def is_retryable(error):
    """Return True only for temporary problems that a later attempt may fix."""
    if isinstance(error, (APITimeout, APIConnectionFailed)):
        return True
    if isinstance(error, APIStatusError):
        if error.code in NO_RETRY_CODES:
            return False
        return error.status in RETRYABLE_STATUS
    return False

# ---------- 3. Reading Retry-After ----------

def parse_retry_after(value, now=None):
    """Turn a Retry-After header into seconds, or None if missing or invalid.

    The header is either whole seconds ("7") or an HTTP date
    ("Mon, 16 Nov 2026 08:30:05 GMT"). `now` is a Unix time for tests.
    """
    if value is None:
        return None
    text = str(value).strip()
    if text.isdigit():
        return float(int(text))
    try:
        when = email.utils.parsedate_to_datetime(text)
    except (TypeError, ValueError, IndexError):
        return None
    if when is None or when.tzinfo is None:
        return None
    now = time.time() if now is None else now
    return max(0.0, when.timestamp() - now)

# ---------- 4. Capped exponential backoff with full jitter ----------

def backoff_delay(retry_number, base=1.0, cap=30.0, rng=random):
    """Wait a random time between 0 and min(cap, base * 2 ** (retry_number - 1))."""
    if retry_number < 1:
        raise ValueError("retry_number starts at 1")
    ceiling = min(cap, base * (2 ** (retry_number - 1)))
    return rng.uniform(0, ceiling)

class RetryResult:
    def __init__(self, outcome, value=None, attempts=0, waited=0.0, log=None, error=None):
        self.outcome = outcome      # ok, not_retryable, max_attempts, time_budget, deferred
        self.value = value
        self.attempts = attempts
        self.waited = waited
        self.log = log or []
        self.error = error

    @property
    def ok(self):
        return self.outcome == "ok"

def call_with_retries(call, *, max_attempts=4, base=1.0, cap=30.0,
                      total_budget=60.0, max_retry_after=60.0,
                      retry_after_jitter=1.0, sleep=time.sleep,
                      clock=time.monotonic, rng=None, now=None):
    """Call `call()` until it succeeds or a clear limit is reached.

    Steps: try; on a non-retryable error stop at once; read Retry-After if
    present, else use backoff with full jitter; never sleep past the total
    time budget; stop after max_attempts.
    """
    if max_attempts < 1:
        raise ValueError("max_attempts must be at least 1")
    rng = rng or random.Random()
    start = clock()
    waited = 0.0
    log = []
    for attempt in range(1, max_attempts + 1):
        try:
            value = call()
        except LLMError as err:
            name = type(err).__name__ if not isinstance(err, APIStatusError) else f"{err.status} {err.code}".strip()
            if not is_retryable(err):
                log.append(f"attempt {attempt}: {name} -> stop, not retryable")
                return RetryResult("not_retryable", attempts=attempt, waited=waited, log=log, error=err)
            if attempt == max_attempts:
                log.append(f"attempt {attempt}: {name} -> stop, attempt limit reached")
                return RetryResult("max_attempts", attempts=attempt, waited=waited, log=log, error=err)
            hint = parse_retry_after(getattr(err, "retry_after", None), now=now)
            if hint is not None:
                if hint > max_retry_after:
                    log.append(f"attempt {attempt}: {name} -> stop, server asks {hint:.0f}s, defer the job")
                    return RetryResult("deferred", attempts=attempt, waited=waited, log=log, error=err)
                delay = hint + rng.uniform(0, retry_after_jitter)
                why = f"Retry-After {hint:.0f}s + jitter"
            else:
                delay = backoff_delay(attempt, base, cap, rng)
                why = "backoff with full jitter"
            if (clock() - start) + delay > total_budget:
                log.append(f"attempt {attempt}: {name} -> stop, waiting {delay:.2f}s would pass the {total_budget:.0f}s budget")
                return RetryResult("time_budget", attempts=attempt, waited=waited, log=log, error=err)
            log.append(f"attempt {attempt}: {name} -> wait {delay:.2f}s ({why})")
            sleep(delay)
            waited += delay
        else:
            log.append(f"attempt {attempt}: success")
            return RetryResult("ok", value=value, attempts=attempt, waited=waited, log=log)
    raise AssertionError("unreachable")

# ---------- 5. Token cost budget ----------

def rough_token_estimate(text):
    """Very rough guess: about 4 characters per token. Real counts come from usage."""
    return max(1, math.ceil(len(text) / 4))

class CostBudget:
    """Track spending from the usage numbers each reply returns.

    Prices are passed in per one million tokens, so the class works with
    any provider. Read real prices from the provider's pricing page.
    """
    def __init__(self, budget, input_price_per_million, output_price_per_million):
        self.budget = Decimal(str(budget))
        self.in_price = Decimal(str(input_price_per_million))
        self.out_price = Decimal(str(output_price_per_million))
        if self.budget < 0 or self.in_price < 0 or self.out_price < 0:
            raise ValueError("budget and prices must not be negative")
        self.spent = Decimal("0")
        self.input_tokens = 0
        self.output_tokens = 0
        self.calls = 0

    def cost(self, input_tokens, output_tokens):
        for n in (input_tokens, output_tokens):
            if isinstance(n, bool) or not isinstance(n, int) or n < 0:
                raise ValueError(f"token count must be a whole number >= 0, got {n!r}")
        return (self.in_price * input_tokens + self.out_price * output_tokens) / Decimal(1_000_000)

    @property
    def remaining(self):
        return self.budget - self.spent

    def check_before_call(self, est_input_tokens, max_output_tokens):
        """Worst case = estimated input + the full output limit. Raise if it will not fit."""
        worst = self.cost(est_input_tokens, max_output_tokens)
        if worst > self.remaining:
            raise BudgetExceeded(f"worst case {worst} > remaining {self.remaining}")
        return worst

    def record(self, usage):
        """Add the real numbers from a reply's usage field."""
        if not isinstance(usage, dict) or "input_tokens" not in usage or "output_tokens" not in usage:
            raise ValueError("usage must contain input_tokens and output_tokens")
        c = self.cost(usage["input_tokens"], usage["output_tokens"])
        self.spent += c
        self.input_tokens += usage["input_tokens"]
        self.output_tokens += usage["output_tokens"]
        self.calls += 1
        return c

# ---------- 6. A fake provider for offline practice ----------

class FakeLLMClient:
    """Replays a script. Each step is a dict such as
    {"status": 429, "retry_after": "2"}, {"timeout": True},
    {"connection": True} or {"status": 200, "text": "late", "usage": {...}}.
    """
    def __init__(self, script):
        self.script = list(script)
        self.calls = 0

    def create(self, prompt, max_output_tokens=50):
        self.calls += 1
        if not self.script:
            raise AssertionError("FakeLLMClient script ran out")
        step = self.script.pop(0)
        if step.get("timeout"):
            raise APITimeout("no reply before our timeout")
        if step.get("connection"):
            raise APIConnectionFailed("network unreachable")
        status = step.get("status", 200)
        if status != 200:
            raise APIStatusError(status, step.get("code", ""), step.get("retry_after"))
        return {"text": step.get("text", ""), "usage": step["usage"]}

# ---------- 7. A small batch job that uses everything ----------

def tag_reviews(reviews, client, budget, max_output_tokens=20, prompt_overhead=40, **retry_kwargs):
    """Tag each review once. Stop the whole batch before the budget can be crossed."""
    results = []
    for rid, text in reviews:
        est_in = rough_token_estimate(text) + prompt_overhead
        try:
            budget.check_before_call(est_in, max_output_tokens)
        except BudgetExceeded:
            results.append((rid, "budget_stop", None))
            break
        r = call_with_retries(lambda: client.create(text, max_output_tokens), **retry_kwargs)
        if r.ok:
            budget.record(r.value["usage"])
            results.append((rid, "ok", r.value["text"]))
        else:
            results.append((rid, r.outcome, None))  # keep it for a later re-run
    return results

# ---------- Demo ----------

class FakeClock:
    """A clock that only moves when fake_sleep is called, so demos run instantly."""
    def __init__(self):
        self.t = 0.0
    def __call__(self):
        return self.t
    def sleep(self, s):
        self.t += s

def demo():
    print("SYNTHETIC DEMO - fake provider, made-up prices, no network")
    u = {"input_tokens": 52, "output_tokens": 3}
    cases = [
        ("429 with Retry-After 2, then success", [{"status": 429, "retry_after": "2"}, {"status": 200, "text": "late", "usage": u}]),
        ("500, timeout, then success", [{"status": 500}, {"timeout": True}, {"status": 200, "text": "quality", "usage": u}]),
        ("400 bad request", [{"status": 400, "code": "invalid_request"}]),
        ("429 quota ran out", [{"status": 429, "code": "insufficient_quota"}]),
        ("503 four times", [{"status": 503}] * 4),
        ("429 asks for 600s", [{"status": 429, "retry_after": "600"}]),
        ("503 asks for 25s twice", [{"status": 503, "retry_after": "25"}] * 2 + [{"status": 200, "text": "late", "usage": u}]),
    ]
    for title, script in cases:
        clock = FakeClock()
        client = FakeLLMClient(script)
        r = call_with_retries(lambda: client.create("Tiffin came 40 minutes late"), max_attempts=4,
                              base=1.0, cap=8.0, total_budget=30.0, sleep=clock.sleep,
                              clock=clock, rng=random.Random(7))
        print(f"\n# {title}")
        for line in r.log:
            print("  " + line)
        print(f"  outcome={r.outcome} attempts={r.attempts} waited={r.waited:.2f}s")
    print("\n# Batch of 6 reviews, budget 0.0003 units, EXAMPLE prices 1.00 in / 4.00 out per million tokens")
    reviews = [(f"R{i}", t) for i, t in enumerate([
        "Dal was cold today.", "Lovely poha, thank you!", "Driver came very late again.",
        "Price went up without notice.", "Roti was hard.", "Best tiffin in Pune."], 1)]
    script = []
    for i in range(6):
        if i == 1:
            script.append({"status": 429, "retry_after": "1"})
        script.append({"status": 200, "text": ["quality", "praise", "late", "price", "quality", "praise"][i],
                       "usage": {"input_tokens": 45 + i, "output_tokens": 2}})
    clock = FakeClock()
    budget = CostBudget("0.0003", "1.00", "4.00")
    out = tag_reviews(reviews, FakeLLMClient(script), budget, max_output_tokens=20,
                      sleep=clock.sleep, clock=clock, rng=random.Random(7))
    for rid, status, label in out:
        print(f"  {rid}: {status} {label or ''}".rstrip())
    print(f"  calls={budget.calls} tokens in={budget.input_tokens} out={budget.output_tokens} spent={budget.spent} remaining={budget.remaining}")

if __name__ == "__main__":
    demo()

test_api_guard.py

"""Tests for api_guard.py. Run: python3 -B -m unittest -v test_api_guard"""
import random
import unittest
from decimal import Decimal

from api_guard import (APIConnectionFailed, APIStatusError, APITimeout, BudgetExceeded,
                       CostBudget, FakeClock, FakeLLMClient, backoff_delay, call_with_retries,
                       is_retryable, parse_retry_after, rough_token_estimate, tag_reviews)

U = {"input_tokens": 50, "output_tokens": 5}
OK = {"status": 200, "text": "late", "usage": U}

class MaxRng:
    """Always returns the top of the range, so delays are predictable."""
    def uniform(self, a, b):
        return b

class ZeroRng:
    def uniform(self, a, b):
        return a

def run(script, **kw):
    clock = FakeClock()
    client = FakeLLMClient(script)
    sleeps = []
    def sleep(s):
        sleeps.append(s)
        clock.sleep(s)
    opts = dict(max_attempts=4, base=1.0, cap=8.0, total_budget=60.0, sleep=sleep, clock=clock, rng=MaxRng())
    opts.update(kw)
    r = call_with_retries(lambda: client.create("hello"), **opts)
    return r, client, sleeps

class TestIsRetryable(unittest.TestCase):
    def test_429_rate_limit_is_retryable(self):
        self.assertTrue(is_retryable(APIStatusError(429)))
    def test_500_502_503_504_529_are_retryable(self):
        for s in (500, 502, 503, 504, 529):
            self.assertTrue(is_retryable(APIStatusError(s)), s)
    def test_408_is_retryable(self):
        self.assertTrue(is_retryable(APIStatusError(408)))
    def test_timeout_and_connection_are_retryable(self):
        self.assertTrue(is_retryable(APITimeout()))
        self.assertTrue(is_retryable(APIConnectionFailed()))
    def test_client_errors_are_not_retryable(self):
        for s in (400, 401, 402, 403, 404, 413, 422):
            self.assertFalse(is_retryable(APIStatusError(s)), s)
    def test_quota_and_spend_codes_are_not_retryable(self):
        for c in ("insufficient_quota", "credit_balance_exhausted", "project_spend_limit_exceeded",
                  "enforced_spend_limit_reached", "quota_exceeded"):
            self.assertFalse(is_retryable(APIStatusError(429, c)), c)
    def test_plain_python_errors_are_not_retryable(self):
        self.assertFalse(is_retryable(ValueError("bug")))

class TestParseRetryAfter(unittest.TestCase):
    def test_missing(self):
        self.assertIsNone(parse_retry_after(None))
    def test_seconds(self):
        self.assertEqual(parse_retry_after("7"), 7.0)
    def test_seconds_with_spaces(self):
        self.assertEqual(parse_retry_after(" 12 "), 12.0)
    def test_zero(self):
        self.assertEqual(parse_retry_after("0"), 0.0)
    def test_negative_is_invalid(self):
        self.assertIsNone(parse_retry_after("-5"))
    def test_decimal_is_invalid(self):
        self.assertIsNone(parse_retry_after("1.5"))
    def test_garbage_is_invalid(self):
        self.assertIsNone(parse_retry_after("soon"))
        self.assertIsNone(parse_retry_after(""))
    def test_http_date_in_future(self):
        now = 1794806400.0  # 2026-11-16 05:20:00 UTC
        self.assertAlmostEqual(parse_retry_after("Mon, 16 Nov 2026 05:20:30 GMT", now=now), 30.0)
    def test_http_date_in_past_gives_zero(self):
        now = 1794806400.0
        self.assertEqual(parse_retry_after("Mon, 16 Nov 2026 05:19:00 GMT", now=now), 0.0)

class TestBackoff(unittest.TestCase):
    def test_ceiling_doubles(self):
        self.assertEqual([backoff_delay(n, 1.0, 100, MaxRng()) for n in (1, 2, 3, 4)], [1.0, 2.0, 4.0, 8.0])
    def test_cap(self):
        self.assertEqual(backoff_delay(10, 1.0, 8.0, MaxRng()), 8.0)
    def test_full_jitter_can_be_zero(self):
        self.assertEqual(backoff_delay(3, 1.0, 8.0, ZeroRng()), 0.0)
    def test_random_values_stay_in_range(self):
        rng = random.Random(1)
        for n in range(1, 8):
            d = backoff_delay(n, 0.5, 5.0, rng)
            self.assertTrue(0 <= d <= min(5.0, 0.5 * 2 ** (n - 1)))
    def test_same_seed_same_delays(self):
        a = [backoff_delay(n, 1, 30, random.Random(42)) for n in (1, 2, 3)]
        b = [backoff_delay(n, 1, 30, random.Random(42)) for n in (1, 2, 3)]
        self.assertEqual(a, b)
    def test_retry_number_must_start_at_one(self):
        with self.assertRaises(ValueError):
            backoff_delay(0)

class TestCallWithRetries(unittest.TestCase):
    def test_success_first_time(self):
        r, c, sleeps = run([OK])
        self.assertEqual((r.outcome, r.attempts, c.calls, sleeps), ("ok", 1, 1, []))
        self.assertEqual(r.value["text"], "late")
    def test_429_then_success_uses_backoff(self):
        r, c, sleeps = run([{"status": 429}, OK])
        self.assertTrue(r.ok)
        self.assertEqual(sleeps, [1.0])
    def test_retry_after_is_honoured_as_minimum(self):
        r, c, sleeps = run([{"status": 429, "retry_after": "5"}, OK], retry_after_jitter=0.5)
        self.assertEqual(sleeps, [5.5])
        self.assertGreaterEqual(sleeps[0], 5)
    def test_invalid_retry_after_falls_back_to_backoff(self):
        r, c, sleeps = run([{"status": 503, "retry_after": "later"}, OK])
        self.assertEqual(sleeps, [1.0])
    def test_500_then_timeout_then_success(self):
        r, c, sleeps = run([{"status": 500}, {"timeout": True}, OK])
        self.assertEqual((r.outcome, r.attempts), ("ok", 3))
        self.assertEqual(sleeps, [1.0, 2.0])
    def test_connection_error_is_retried(self):
        r, c, _ = run([{"connection": True}, OK])
        self.assertTrue(r.ok)
    def test_400_stops_immediately(self):
        r, c, sleeps = run([{"status": 400, "code": "invalid_request"}, OK])
        self.assertEqual((r.outcome, c.calls, sleeps), ("not_retryable", 1, []))
    def test_401_stops_immediately(self):
        r, c, _ = run([{"status": 401}])
        self.assertEqual(r.outcome, "not_retryable")
    def test_quota_429_stops_immediately(self):
        r, c, sleeps = run([{"status": 429, "code": "insufficient_quota"}])
        self.assertEqual((r.outcome, sleeps), ("not_retryable", []))
    def test_max_attempts(self):
        r, c, sleeps = run([{"status": 503}] * 4)
        self.assertEqual((r.outcome, r.attempts, c.calls), ("max_attempts", 4, 4))
        self.assertEqual(len(sleeps), 3)
    def test_no_sleep_after_last_attempt(self):
        r, c, sleeps = run([{"status": 503}] * 2, max_attempts=2)
        self.assertEqual(sleeps, [1.0])
    def test_max_attempts_one_means_no_retry(self):
        r, c, sleeps = run([{"status": 429}], max_attempts=1)
        self.assertEqual((r.outcome, sleeps), ("max_attempts", []))
    def test_max_attempts_zero_rejected(self):
        with self.assertRaises(ValueError):
            run([OK], max_attempts=0)
    def test_time_budget_stops_before_sleeping(self):
        r, c, sleeps = run([{"status": 503, "retry_after": "25"}] * 3, total_budget=30.0, retry_after_jitter=0)
        self.assertEqual(r.outcome, "time_budget")
        self.assertEqual(sleeps, [25.0])
        self.assertEqual(c.calls, 2)
    def test_long_retry_after_is_deferred(self):
        r, c, sleeps = run([{"status": 429, "retry_after": "600"}], max_retry_after=60)
        self.assertEqual((r.outcome, sleeps), ("deferred", []))
    def test_waited_adds_up(self):
        r, _, sleeps = run([{"status": 500}, {"status": 500}, OK])
        self.assertAlmostEqual(r.waited, sum(sleeps))
    def test_error_is_kept_on_failure(self):
        r, _, _ = run([{"status": 400}])
        self.assertIsInstance(r.error, APIStatusError)
        self.assertEqual(r.error.status, 400)
    def test_log_has_one_line_per_attempt(self):
        r, _, _ = run([{"status": 429}, {"timeout": True}, OK])
        self.assertEqual(len(r.log), 3)
        self.assertIn("success", r.log[-1])
    def test_bug_in_our_code_is_not_swallowed(self):
        def broken():
            raise KeyError("typo")
        with self.assertRaises(KeyError):
            call_with_retries(broken, sleep=lambda s: None)
    def test_deterministic_with_seeded_rng(self):
        a = run([{"status": 500}] * 3 + [OK], rng=random.Random(3))[2]
        b = run([{"status": 500}] * 3 + [OK], rng=random.Random(3))[2]
        self.assertEqual(a, b)

class TestCostBudget(unittest.TestCase):
    def setUp(self):
        self.b = CostBudget("0.001", "1.00", "4.00")  # EXAMPLE numbers only
    def test_cost_formula(self):
        self.assertEqual(self.b.cost(1_000_000, 0), Decimal("1.00"))
        self.assertEqual(self.b.cost(0, 1_000_000), Decimal("4.00"))
        self.assertEqual(self.b.cost(100, 10), Decimal("0.00014"))
    def test_record_uses_usage_numbers(self):
        c = self.b.record({"input_tokens": 200, "output_tokens": 50})
        self.assertEqual(c, Decimal("0.0004"))
        self.assertEqual((self.b.input_tokens, self.b.output_tokens, self.b.calls), (200, 50, 1))
        self.assertEqual(self.b.remaining, Decimal("0.0006"))
    def test_decimal_has_no_float_drift(self):
        for _ in range(10):
            self.b.record({"input_tokens": 10, "output_tokens": 0})
        self.assertEqual(self.b.spent, Decimal("0.0001"))
    def test_check_before_call_allows_when_it_fits(self):
        self.assertEqual(self.b.check_before_call(100, 20), Decimal("0.00018"))
    def test_check_before_call_blocks_worst_case(self):
        self.b.record({"input_tokens": 900, "output_tokens": 0})
        with self.assertRaises(BudgetExceeded):
            self.b.check_before_call(50, 20)
    def test_bad_usage_rejected(self):
        for bad in (None, {}, {"input_tokens": 5}, {"input_tokens": -1, "output_tokens": 1},
                    {"input_tokens": "5", "output_tokens": 1}, {"input_tokens": True, "output_tokens": 1}):
            with self.assertRaises(ValueError):
                self.b.record(bad)
        self.assertEqual(self.b.calls, 0)
    def test_negative_price_rejected(self):
        with self.assertRaises(ValueError):
            CostBudget("1", "-1", "1")
    def test_rough_estimate(self):
        self.assertEqual(rough_token_estimate(""), 1)
        self.assertEqual(rough_token_estimate("abcd"), 1)
        self.assertEqual(rough_token_estimate("abcde"), 2)

class TestFakeClient(unittest.TestCase):
    def test_script_runs_out_loudly(self):
        c = FakeLLMClient([])
        with self.assertRaises(AssertionError):
            c.create("x")
    def test_status_error_carries_fields(self):
        c = FakeLLMClient([{"status": 429, "code": "slow_down", "retry_after": "3"}])
        with self.assertRaises(APIStatusError) as cm:
            c.create("x")
        self.assertEqual((cm.exception.status, cm.exception.code, cm.exception.retry_after), (429, "slow_down", "3"))

class TestTagReviews(unittest.TestCase):
    def kw(self):
        clock = FakeClock()
        return dict(sleep=clock.sleep, clock=clock, rng=random.Random(0))
    def test_all_ok_with_one_retry(self):
        b = CostBudget("1", "1", "4")
        script = [OK, {"status": 429, "retry_after": "1"}, OK]
        out = tag_reviews([("A", "x"), ("B", "y")], FakeLLMClient(script), b, **self.kw())
        self.assertEqual([s for _, s, _ in out], ["ok", "ok"])
        self.assertEqual(b.calls, 2)
    def test_budget_stop_before_call(self):
        b = CostBudget("0.0001", "1", "4")
        client = FakeLLMClient([OK, OK])
        out = tag_reviews([("A", "x"), ("B", "y")], client, b, **self.kw())
        self.assertEqual(out[-1][1], "budget_stop")
        self.assertLessEqual(b.spent, b.budget)
    def test_failed_review_kept_for_rerun(self):
        b = CostBudget("1", "1", "4")
        client = FakeLLMClient([{"status": 400}, OK])
        out = tag_reviews([("A", "x"), ("B", "y")], client, b, **self.kw())
        self.assertEqual([s for _, s, _ in out], ["not_retryable", "ok"])
        self.assertEqual(b.calls, 1)
    def test_never_exceeds_budget(self):
        b = CostBudget("0.0005", "1", "4")
        script = [{"status": 200, "text": "t", "usage": {"input_tokens": 60, "output_tokens": 20}}] * 20
        tag_reviews([(str(i), "review text") for i in range(20)], FakeLLMClient(script), b, **self.kw())
        self.assertLessEqual(b.spent, b.budget)

if __name__ == "__main__":
    unittest.main()

9. Connect a real SDK later, without changing the loop

The retry loop only needs a function that either returns a reply or raises one of the lab's error classes. To use a real provider, write a small wrapper with that shape and keep it as the only file that knows about the provider.

  1. Keep your API key in a .env file, as shown in the first API call chapter.
  2. Decide who retries. Either turn off the SDK's own retries and use this loop, or keep the SDK retries and set this loop's attempt limit to one.
  3. Catch the SDK's error classes and translate them into APIStatusError, APITimeout or APIConnectionFailed, copying the status, the error code and the Retry-After header.
  4. Translate the reply's usage field into input_tokens and output_tokens for the budget.
  5. Log the outcome label, the attempt count and the provider's request ID for each item, without logging customer personal details.
  6. Run the batch on five rows first, compare the spent amount with your dashboard, and only then run the full file.

SDK class names, header names and defaults change between versions, so read the documentation for the version you install.

10. Beginner mistakes and quick fixes

Common mistakes when calling AI APIs in a loop.
MistakeQuick fix
Retrying every error, including 400 and 401.Retry only temporary errors, and stop at once on request, key and permission errors.
Retrying a 429 that says the credit or quota ran out.Read the error code, stop the loop and ask a person to fix the billing or limit.
Waiting the same fixed time after every failure.Use capped exponential backoff with full jitter.
Retrying sooner than Retry-After asks.Wait at least the requested time, or defer the job if the wait is too long.
A loop with no attempt limit and no time limit.Set both, and return a clear outcome label when a limit is reached.
Your loop and the SDK both retrying.Turn one of them off, or count both in your plan.
Guessing the cost from the prompt length only.Record the real usage numbers from every reply, and check the worst case before each call.
Copying a price or limit from a blog post.Read the provider's own pricing and limits pages on the day you build.

11. Practise before you connect a real model

  1. Add 502 to a script and confirm that it is retried. Then add 413 and confirm that it is not.
  2. Change the backoff cap to 4 seconds and predict the wait limits for retries one to five before you run the tests.
  3. Write a test where Retry-After is an HTTP date thirty seconds in the future.
  4. Change the total time budget to 10 seconds and run the demo again. Explain which outcome labels change and why.
  5. Add a counter that shows how many items ended as max_attempts, and print it at the end of the batch.
  6. Change the example prices to the real current prices for a model you plan to use, copied from the provider's pricing page, and record the date you copied them.

Quick self-check quiz (5 questions)

Client-only quiz — not saved. Browser-only practice. Your answers are not sent anywhere, are not saved, and do not count towards any course progress or certificate.

1. The API returns 400 bad request. What should the retry loop do?
2. A 429 response carries the header Retry-After: 20. What is the polite action?
3. Why do we add random jitter to each backoff wait?
4. A 429 response has the code insufficient_quota. What should happen?
5. Before each call, the budget check compares the remaining money with which amount?

Recap

  1. Sort every failure first: temporary errors may succeed later, while bad requests, wrong keys and empty credit need a fix.
  2. The same 429 status can mean “slow down” or “quota ran out,” so read the error code.
  3. Follow Retry-After as a minimum wait, and defer the job if the wait is too long.
  4. Without Retry-After, use capped exponential backoff with full jitter.
  5. Stop at an attempt limit and a total time budget, and remember that the SDK may already retry.
  6. Record real usage numbers from every reply, check the worst-case cost before each call, and read real prices and limits from the provider.

Continue learning

Ravindra Bagale, trainer: linkedin.com/in/ravindra-bagale. Annapurna Tiffins, its reviews, every error and reply in the lab, and the example prices are made up / SYNTHETIC classroom material. Official interface details were checked against the linked documentation on 16 Nov 2026 (Asia/Calcutta); real limits and prices vary by account and model, and no provider endorsement or guarantee is claimed.