DEV Community

Hammad Malik
Hammad Malik

Posted on Originally published at apicostlab.com

API Retry Costs: Build a Cost-Aware Retry Wrapper for the Gemini API in Python


Originally published at API Cost Lab.

API Retry Costs: Build a Cost-Aware Retry Wrapper for the Gemini API in Python

Last updated: November 2026

Every retry of a failed API call re-sends the whole prompt and bills it again, so a retry loop that retries every error can turn one failed call into four bills for zero answers. The fix is a small wrapper that retries only the errors that can clear on their own — 429s and 500-series errors — waits longer after each failure, and stops retrying once the call's own spend passes a cap you set. The code below does that for the Gemini API in about sixty lines.

A library default of three retries sounds harmless until you multiply it by a whole day of traffic.

A failed call still has a bill

Take one call to Gemini 2.5 Flash with a 20,000-token prompt — a system prompt plus a help-centre document, as in our tool-loop investigation — and a 1,000-token answer. Rates are the published standard rates, verified 20 November 2026 on Google's pricing page: input $0.30, output $2.50 per million tokens. One attempt costs 20,000 × $0.30 ÷ 1,000,000 = $0.006 of input plus 1,000 × $2.50 ÷ 1,000,000 = $0.0025 of output: $0.0085 in total.

Now the call fails, and your code retries three times — the usual default. Every attempt re-sends the whole 20,000-token prompt, so the $0.006 input charge repeats in full, and output is billed for whatever the model produced before the error. Worst case, each attempt costs the full $0.0085. Four attempts on one question: $0.034, for an answer you never got.

Attempts What happened Cost
1 Success on the first try $0.0085
2 One 500 error, then success $0.0170
4 Three blind retries on a 400 error $0.0340

At volume the gap stops looking small. Say your app makes 10,000 calls a day and 5 percent hit a transient 500 error. That is 500 calls a day, each retried three times: 1,500 extra attempts × $0.0085 = $12.75 a day, about $382 a month — annoying, but at least the money buys a completed call. The pure waste is the other kind of failure. If 1 percent of calls are bad requests and each is retried three times, that is 100 calls × 3 wasted attempts × $0.0085 = $2.55 a day, $76.50 a month, paying four times for an error that will fail identically every time. Run your own daily call count through our AI API Cost Calculator with the per-call figure from your logs, and the monthly retry waste is the number to stare at.

Which errors deserve a second try

The whole wrapper is one decision, repeated: is this error the kind that can clear on its own? A rate-limit 429 clears when the quota window rolls over. A 500, 502, 503 or 504 is the provider's problem, and a minute later it is often gone. Everything else is your problem, and retrying it is paying to be told the same thing again. A 400 means the request itself is wrong — a bad parameter, a prompt the model refuses — and it will be wrong on the fifth try too. A 401 or 403 means the key or access is wrong. A 404 means the model name does not exist.

Error Retry? Why
429 rate limit Yes, with backoff Clears when the quota window rolls over
500 / 502 / 503 / 504 Yes, with backoff The provider's problem, often gone in a minute
400 bad request Never Your request is wrong and stays wrong
401 / 403 Never Your key or access is wrong, not the timing
404 Never The model name does not exist

One more case: a client-side timeout. Retry it only if no response arrived at all — a timeout after the model already answered can double-bill a call that succeeded. If your HTTP layer cannot tell you whether a response arrived, treat a timeout as non-retryable and log it.

The wrapper

Install the SDK with pip install google-genai and set GEMINI_API_KEY in your environment. Save the code below as gemini_retry.py and call call_with_retry() instead of calling client.models.generate_content directly. It returns the original response untouched and logs every attempt.

import logging
import random
import time

from google import genai
from google.genai import errors

# Rates per 1M tokens, verified 20 November 2026 on Google's
# Gemini API pricing page. From 1 December 2026, gemini-2.5-flash
# routes to gemini-3.5-flash-lite, billed at that model's rates.
INPUT_PER_MILLION = 0.30    # fresh text input
OUTPUT_PER_MILLION = 2.50   # visible output + thinking tokens

# Retry only errors that can clear on their own: not 400s (bad
# request), 401/403s (bad key), or 404s (bad model name).
RETRYABLE_STATUS = {429, 500, 502, 503, 504}

client = genai.Client()  # reads GEMINI_API_KEY from the environment
log = logging.getLogger("gemini_retry")


def _estimate_tokens(text):
    """Rough token estimate for English text: ~4 chars per token."""
    return max(len(str(text)) // 4, 1)


def _attempt_estimate(contents, expected_output_tokens=1000):
    """Rough cost of one attempt, used only to enforce the cap."""
    prompt_tokens = sum(_estimate_tokens(c) for c in contents) \
        if isinstance(contents, list) else _estimate_tokens(contents)
    return (prompt_tokens * INPUT_PER_MILLION
            + expected_output_tokens * OUTPUT_PER_MILLION) / 1_000_000


def _measured_cost(usage):
    """Exact cost of a finished call, from the usage object."""
    if usage is None:
        return 0.0
    prompt = getattr(usage, "prompt_token_count", 0) or 0
    output = getattr(usage, "candidates_token_count", 0) or 0
    thoughts = getattr(usage, "thoughts_token_count", 0) or 0
    # Thinking tokens bill at the output rate, though you never see them.
    return (prompt * INPUT_PER_MILLION
            + (output + thoughts) * OUTPUT_PER_MILLION) / 1_000_000


def call_with_retry(model, contents, feature="unknown",
                    max_attempts=3, max_cost_per_call=0.03,
                    base_delay=1.0, **kwargs):
    """Call generate_content with cost-aware retries: only 429/5xx,
    longer waits after each failure, and no retry once the estimated
    spend for this call passes max_cost_per_call."""
    estimate = _attempt_estimate(contents)
    spent_estimate = 0.0
    last_error = None
    for attempt in range(1, max_attempts + 1):
        if spent_estimate + estimate > max_cost_per_call:
            log.warning("cost cap $%.4f hit on %s after %d attempts",
                        max_cost_per_call, feature, attempt - 1)
            break
        try:
            response = client.models.generate_content(
                model=model, contents=contents, **kwargs
            )
        except errors.APIError as e:
            status = getattr(e, "code", None)
            last_error = e
            spent_estimate += estimate
            log.warning("attempt %d/%d failed: HTTP %s (%s)",
                        attempt, max_attempts, status, feature)
            if status not in RETRYABLE_STATUS or attempt == max_attempts:
                raise
            delay = min(base_delay * 2 ** (attempt - 1), 30) \
                + random.uniform(0, 1)
            time.sleep(delay)
            continue
        cost = _measured_cost(getattr(response, "usage_metadata", None))
        log.info("feature=%s attempts=%d cost_usd=%.6f",
                 feature, attempt, cost)
        return response
    raise last_error
Enter fullscreen mode Exit fullscreen mode

Using it is one line different from a normal call. Replace client.models.generate_content(model="gemini-2.5-flash", contents=prompt) with call_with_retry("gemini-2.5-flash", prompt, feature="support_reply"). The feature label is the one to get right: it is what you will group by later, so name it after your product ("support_reply", "summariser", "nightly_report"), not your code. With the defaults above, a 20,000-token prompt is estimated at $0.0085 an attempt, so three attempts fit under the $0.03 cap.

Two settings that matter more than the code

The first is the backoff. The delay doubles after each failure — one second, then two, then four — plus a random fraction of a second. Without it, a hundred clients retrying a 500 at once all hit the recovering server at the same instant. The random jitter spreads them out, and the 30-second ceiling stops a long chain from waiting minutes for a call nobody is watching.

The second is the cap, and it needs to be set from your own numbers, not copied from this article. Take the cost of one attempt for your biggest prompt and set max_cost_per_call to a small multiple of it — three attempts' worth is a sane default. Set it from your cheapest prompt and your biggest prompt gets capped after one failed attempt — as it should: a prompt costing $0.05 a try should never be retried three times on autopilot. The cap is also what protects you from the failure mode no error list can catch: an error your code classifies as retryable that never clears.

Seeing retries in your own logs

The wrapper earns its keep when you read the log lines it writes. Two numbers tell the story: attempts per call, and cost per call. A feature that averages 1.0 attempts is healthy. A feature that averages 1.4 attempts is paying a 40 percent retry tax, and the HTTP status in the warning lines says whether the tax is rate limits — fix it by slowing down or raising quota — or 500s, which are the provider's and mostly out of your hands. If the warnings are all 400s, the wrapper already saved the retries; fix the request, because the original call still cost $0.0085 each time.

Pair the retry log with the per-call cost log from our Gemini usage logger: the logger records what a finished call cost, the wrapper records what the failed attempts cost, and together they are the whole bill. If one user is behind most of the retries, the per-user spending guard caps their share before it eats the budget the other users need. And retries are only one multiplier on an agent's bill: our tool-loop investigation showed a five-round agent task costs six times a single call, because every round re-sends the whole conversation — a retry inside that loop multiplies a bill that is already multiplied.

Rates verified 20 November 2026 on Google's Gemini API pricing page (ai.google.dev/gemini-api/docs/pricing): Gemini 2.5 Flash standard tier, input $0.30, output $2.50 (including thinking tokens) per million tokens. All worked figures are arithmetic on those published rates, using the stated example token counts — not measured runs. Gemini 2.5 Flash is deprecated and routes to Gemini 3.5 Flash-Lite from 1 December 2026, billed at that model's rates.

Top comments (0)