Skip to content
Blog

Handling Rate Limits (429) and Quota Exhaustion with Exponential Backoff

Classifying 429s and RESOURCE_EXHAUSTED errors, implementing exponential backoff with full jitter, a reusable async retry helper for ADK tools and runners, and when retrying makes things worse.

Published on • November 27, 2026

AI Assistant

A rate limit is not a failure — it is the API telling you that your timing was wrong. The difference between a 429 that costs a user one slow turn and a 429 that takes down your whole agent fleet is almost entirely about how you respond: what you classify as retryable, how long you wait, and how many retries you are willing to spend.

This post is a tutorial on getting that right in an ADK application: classifying errors, backoff with jitter, a helper you can drop into tools and runners, and the cases where retrying is actively harmful.

What a 429 actually tells you

There are several distinct limits wearing the same status code:

  • Per-minute request or token quotas (the classic RPM/TPM limit) — usually recoverable after a short wait.
  • Daily quotas — waiting 2 seconds will not help; you are done until the window resets.
  • Concurrency limits — the request is valid, you just have too many in flight.
  • Billing or project-level exhaustion — requires a human, not a retry.
  • Transient server pressure surfaced as 429 — busy endpoint, recoverable with a short delay.

On the Google APIs, the equivalent failures often arrive as gRPC RESOURCE_EXHAUSTED with a RetryInfo hint in the error details. Read that hint when it exists: the service is telling you how long to wait.

The classification rule that matters:

Retry only what is transient and bounded — 429 with a short horizon, 500/503/504, connection resets, timeouts on idempotent work. Everything else is a terminal error with a different job attached (alerting, quota request, user message).

Backoff with full jitter

The naive retry — fixed 1 s, 2 s, 4 s — synchronises every client in your fleet. They all wait the same interval, retry together, and produce a second thundering herd exactly where the first one landed.

The fix is full jitter: sleep for a random duration in [0, base · 2^attempt]:

delay = random.uniform(0, min(max_delay, base_delay * 2 ** attempt))

Exponential growth bounds your exposure, randomness decorrelates your clients, and the cap stops you from sleeping for an hour. Add retry-after honouring: if the response carries Retry-After or retry_info, use it — the service knows better than your formula.

import asyncio
import random

RETRYABLE = {'429', '500', '502', '503', '504', 'RESOURCE_EXHAUSTED', 'UNAVAILABLE'}

async def with_backoff(
    fn,
    *,
    base_delay: float = 0.5,
    max_delay: float = 30.0,
    max_attempts: int = 5,
    retry_after: float | None = None,
):
    """Run `fn`, retrying transient failures with full-jitter backoff."""
    last_exc: Exception | None = None
    for attempt in range(max_attempts):
        try:
            return await fn()
        except Exception as exc:  # narrow this to your client's exception types
            code = str(getattr(exc, 'code', '') or getattr(exc, 'status_code', ''))
            if code.upper() not in RETRYABLE or attempt == max_attempts - 1:
                raise
            last_exc = exc
            ceiling = min(max_delay, base_delay * (2 ** attempt))
            delay = retry_after if retry_after else random.uniform(0, ceiling)
            await asyncio.sleep(delay)
    raise last_exc  # pragma: no cover

Three details that are easy to skip and expensive to miss:

  1. Honour retry_after when the error carries it, clamped to a sane ceiling.
  2. Spend the attempts on the whole operation, not per sub-call. If one agent turn calls the model four times, a budget of five retries per call means twenty retries per turn.
  3. Jitter the ceiling, not just the delay, or clients that started at different times still converge.

Where retries belong in an ADK application

There are three sensible seams, and one that is not:

Inside a tool that wraps an external call. Best place for API-level retries — the tool returns a result or a clean error, and the model never sees the transient noise:

import httpx

async def get_invoice(invoice_id: str, tool_context) -> dict:
    """Fetch an invoice by ID.

    Args:
        invoice_id (str): The invoice identifier.
    """
    async with httpx.AsyncClient(timeout=10) as client:
        resp = await with_backoff(
            lambda: client.get(f'{BILLING_URL}/invoices/{invoice_id}'),
            max_attempts=4,
        )
        if resp.status_code == 404:
            return {'status': 'error', 'error_message': f'Invoice {invoice_id} not found.'}
        resp.raise_for_status()
        return {'status': 'success', 'invoice': resp.json()}

Around the model call. Useful when you own the invocation (custom model wrapper or a plugin) and can re-run the request with the same contents. Re-running is cheap in tokens only if you have not already streamed a partial answer to the user.

At the transport layer. A reverse proxy or HTTP client pool that retries idempotent GETs protects everything above it.

Not around a whole run_async loop. Re-running an agent invocation re-executes tool side effects — the email may already have been sent, the row already inserted. Retrying at this level without idempotency keys is how a transient error becomes duplicate work.

Idempotency: the precondition for all of the above

Retry is only safe if repeating the request produces the same outcome. For tools that mutate state:

  • Take an idempotency key derived from the tool call ID and pass it upstream; a duplicate retry then returns the original result.
  • Use natural keys (invoice_id, user_id + date) so a repeat converges instead of duplicating.
  • Make the tool idempotent even if the upstream API is not, by checking state first.

If none of that is possible, treat the operation as non-retryable and let the failure surface to the model, which can ask the user what to do.

Quota exhaustion is not a retry problem

When the limit is a daily quota or a hard concurrent-request cap, backoff converts a clear signal into a stalled user experience. Handle it differently:

SituationResponse
Short-horizon 429Backoff + jitter, honour Retry-After
Daily/hard quotaFail fast with a structured error; shed load; alert
Sustained 429s from one tenantPer-tenant rate limiter in front of the model
Repeated RESOURCE_EXHAUSTED on large promptsReduce prompt size — the quota is token-based

Add a circuit breaker: if the error rate for the model endpoint crosses a threshold, stop sending traffic for a cooldown window and shed to a fallback or a queued mode. Endless retries against a broken endpoint only burn your remaining quota.

Takeaways

  • Classify before you retry: transient and bounded — yes; quota, billing, validation — no.
  • Use exponential backoff with full jitter, honour server hints, and cap both delay and attempt count.
  • Retry at the tool seam, where side effects are controlled; never blindly re-run an agent turn.
  • Make mutations idempotent first — that is the precondition for every retry strategy.
  • Distinguish rate limiting from quota exhaustion: one is a scheduling problem, the other is a capacity and signalling problem.

Further reading