The integration had survived dozens of local runs. Then a late-night traffic spike hit production, 429s chained into timeouts, and I rolled the whole thing back. It was the first time I had wired Antigravity into one of my own products, and I had shipped it with little more than the SDK quickstart.
The SDK itself was fine. client.models.generate_content() is one call and you are off. But putting that single call in front of real users is like merging onto a highway without buckling up.
What follows is the smallest set of safeguards that survived that night: retries, timeouts and a circuit breaker. I also have to correct the earlier version of this page, because its code did not run.
The earlier version of this code did not run
The old sample retried on genai_errors.ResourceExhausted and excluded genai_errors.PermissionDenied from the breaker. Neither class exists. In google-genai (I checked 2.32.0), the errors module exposes APIError, ClientError and ServerError, and the first line of the sample would have died with an AttributeError.
There was a second flaw. The SDK's HTTP timeout is raised by httpx, and httpx timeouts do not inherit from the built-in TimeoutError:
>>> import httpx
>>> issubclass(httpx.ReadTimeout, TimeoutError)
FalseSo "retry on TimeoutError" let the SDK's own timeouts slip straight past the retry logic. Both are the kind of defect you only meet during an outage, which is the worst moment to meet it. The code below fixes both and has been run against simulated failures.
Why a bare SDK call breaks under real traffic
Failures fall into three rough buckets. Transient errors (429 rate limits, a brief 5xx, a network blip) usually pass if you wait a second or two. Long-running calls leave your handler waiting indefinitely when a heavy prompt takes far longer than expected. Persistent outages, whether a real incident upstream or a misconfigured key, will not heal no matter how often you retry.
The SDK default is "call once, raise on error," which is bare against all three. The matching remedies:
- Retries, to absorb transient errors
- Timeouts, to cap a single call
- A circuit breaker, to stop hammering an outage
Before adding any of them, I make one decision. Decide up front what is worth retrying and what must never count as a failure. The rest of this page hangs on that line.
Safeguard 1: Retries with exponential backoff and jitter
Start with tenacity, and start by writing the predicate. Do not use a flat "sleep three seconds" loop. Use exponential backoff with jitter; without jitter, every process that hit the incident retries at the same instant and slows the provider's recovery.
# transient.py — one place that decides "is this worth retrying?"
import httpx
from google.genai import errors as genai_errors
def is_transient(exc: BaseException) -> bool:
"""True only for errors that a retry can plausibly fix."""
if isinstance(exc, genai_errors.ServerError): # 5xx
return True
if isinstance(exc, genai_errors.ClientError): # only 429 among the 4xx
return exc.code == 429
# The SDK's HTTP timeout comes from httpx, not the built-in TimeoutError
return isinstance(exc, (httpx.TimeoutException, httpx.ConnectError, TimeoutError))
def is_permanent(exc: BaseException) -> bool:
"""Auth or argument errors. Retrying will not help, and they must not trip the breaker."""
return isinstance(exc, genai_errors.ClientError) and exc.code != 429ClientError covers every 4xx, so the code separates 429 by its code. A 401, 403 or 400 returns False from is_transient and surfaces immediately, which prevents the classic mistake of hitting the API four times with a wrong key.
It is tempting to retry everything. Permanent errors are better failed fast: you would only be making the end user wait for something that was never going to work.
Safeguard 2: Timeouts — one per attempt, one for the whole thing
What stopped me for a while was the worst-case wait once retries and timeouts combine. A 15-second timeout with four attempts already exceeds a minute, and to a user that is indistinguishable from an outage. So I write the budget down before choosing numbers.
| Setting | Value | What it does |
|---|---|---|
| HTTP timeout per attempt | 8 s | SDK HttpOptions(timeout=...), passed in milliseconds |
| Max attempts | 3 | 8 s × 3 = 24 s |
| Wait between attempts | about 1–2 s, then about 2–3 s | 1 s and 2 s base, plus 0–1 s of jitter |
| Overall cut-off | 25 s | stop_after_delay(25), checked before each new attempt |
The worst case is just under 30 seconds. If that still feels long for an interactive path, drop to 5 seconds and two attempts. My own rule of thumb is 10–20 seconds for interactive calls and 60 for batch.
One caveat: stop_after_delay looks at elapsed time after an attempt finishes. It does not interrupt a call in flight, which is exactly why the per-attempt HTTP timeout has to exist separately.
A long deadline feels generous. In practice a shorter one with a graceful fallback is kinder, because it keeps your connection pool from draining and protects every other user.
Safeguard 3: A circuit breaker to stop chain failures
The third piece is pybreaker. When the provider is genuinely down, retries only burn your own CPU and connections. A breaker watches for consecutive failures, opens past a threshold so calls fail instantly, waits a cooldown, then lets a single probe through.
Here is the stack assembled:
# guarded.py — breaker → retry → timeout (synchronous version)
import logging
import os
import pybreaker
from google import genai
from google.genai import types
from tenacity import (
before_sleep_log,
retry,
retry_if_exception,
stop_after_attempt,
stop_after_delay,
wait_exponential_jitter,
)
from transient import is_permanent, is_transient
log = logging.getLogger("guarded")
MODEL = os.environ.get("GEN_MODEL", "gemini-3.8-flash") # confirm the ID on the deprecations page
client = genai.Client() # the API key is read from the environment
class StateLogger(pybreaker.CircuitBreakerListener):
def state_change(self, cb, old_state, new_state):
log.warning("breaker %s -> %s", old_state.name, new_state.name)
breaker = pybreaker.CircuitBreaker(
fail_max=5, # open after 5 consecutive failures
reset_timeout=60, # after 60 s, probe once in HALF-OPEN
exclude=[is_permanent], # auth errors never count
listeners=[StateLogger()],
)
@breaker
@retry(
retry=retry_if_exception(is_transient),
stop=stop_after_attempt(3) | stop_after_delay(25),
wait=wait_exponential_jitter(initial=1, max=8),
before_sleep=before_sleep_log(log, logging.WARNING),
reraise=True,
)
def generate(prompt: str) -> str:
resp = client.models.generate_content(
model=MODEL,
contents=prompt,
config=types.GenerateContentConfig(
http_options=types.HttpOptions(timeout=8_000), # 8 s per attempt
),
)
return resp.textThe decorator order is the point. The breaker sits outside, retries inside it, and the per-attempt timeout innermost. An open breaker skips retries entirely; a closed one retries, and every attempt carries its own timeout.
The caller then separates "breaker open" from everything else:
import pybreaker
from guarded import generate
def answer(prompt: str) -> str:
try:
return generate(prompt)
except pybreaker.CircuitBreakerError:
return "The AI service is busy right now. Please try again in a moment."
except Exception as e:
return f"A temporary error occurred ({type(e).__name__})"On serverless platforms such as Cloud Run or Vercel, breaker state is not shared between instances. If that matters, pybreaker ships a CircuitRedisStorage that keeps the state in Redis.
@breaker on an async def does nothing
If you are tempted to carry this pattern into async code, as I was, be careful. Decorating an async def with a pybreaker breaker never counts a failure:
b = pybreaker.CircuitBreaker(fail_max=2, reset_timeout=1)
@b
async def boom():
raise RuntimeError("x")
# After four awaits, fail_counter was still 0 and the state still "closed"The decorator returns a coroutine object that finishes "successfully" before anything is awaited, and no error is raised. You end up believing you are protected when nothing is. For async code, isolate the breaker in a synchronous function and call it through asyncio.to_thread, or pick a library that awaits.
Prove it with a simulated outage
A safeguard is "installed" only until you have watched it fire. This script feeds failures from a fake upstream in a fixed order, with no real API call:
# guard_demo.py — verify the stacking order without touching the API
import time
import pybreaker
from google.genai import errors as genai_errors
from tenacity import retry, retry_if_exception, stop_after_attempt, wait_exponential_jitter
from transient import is_permanent, is_transient
breaker = pybreaker.CircuitBreaker(fail_max=3, reset_timeout=1, exclude=[is_permanent])
calls = {"n": 0}
def upstream(script):
"""A fake API: returns each scripted step in order, raising if it is an exception."""
calls["n"] += 1
step = script[min(calls["n"] - 1, len(script) - 1)]
if isinstance(step, Exception):
raise step
return step
@breaker
@retry(
retry=retry_if_exception(is_transient),
stop=stop_after_attempt(3),
wait=wait_exponential_jitter(initial=0.01, max=0.05),
reraise=True,
)
def guarded(script):
return upstream(script)
def run(label, script, times=1):
calls["n"] = 0
for _ in range(times):
try:
out = guarded(script)
print(f"{label}: OK {out!r} (upstream={calls['n']}, breaker={breaker.current_state})")
except Exception as exc:
print(f"{label}: {type(exc).__name__} (upstream={calls['n']}, breaker={breaker.current_state})")
e429 = genai_errors.ClientError(429, {"error": {"message": "quota"}})
e403 = genai_errors.ClientError(403, {"error": {"message": "denied"}})
e503 = genai_errors.ServerError(503, {"error": {"message": "unavailable"}})
run("A two 429s then success", [e429, e429, "hello"])
run("B 403 fails fast ", [e403, "hello"])
print(" breaker failures after B:", breaker.fail_counter)
run("C 503s keep coming x3 ", [e503], times=3)
run("D call while OPEN ", ["hello"])
time.sleep(1.1)
print(" state after 1.1 s:", breaker.current_state)
run("E first call after it ", ["hello"])This is what it printed on my machine:
A two 429s then success: OK 'hello' (upstream=3, breaker=closed)
B 403 fails fast : ClientError (upstream=1, breaker=closed)
breaker failures after B: 0
C 503s keep coming x3 : ServerError (upstream=3, breaker=closed)
C 503s keep coming x3 : ServerError (upstream=6, breaker=closed)
C 503s keep coming x3 : CircuitBreakerError (upstream=9, breaker=open)
D call while OPEN : CircuitBreakerError (upstream=0, breaker=open)
state after 1.1 s: open
E first call after it : OK 'hello' (upstream=1, breaker=closed)Four things are worth reading out of it.
First, A needed three upstream calls and ended in success: two 429s absorbed. Second, B's 403 failed on the first call and left the breaker's failure count at zero, so a bad key can never open the circuit.
Third, in C it takes three upstream calls to register one failure. Failures inside the retry loop are invisible to the breaker, so fail_max=5 means fifteen real calls upstream. The call that reaches the threshold also surfaces as CircuitBreakerError rather than the original ServerError.
Fourth, even after reset_timeout had passed, current_state still read open. The move to HALF-OPEN happens when the next call arrives. If you poll the state for monitoring, a long-lived "open" reading and an actually blocked circuit are not the same thing.
One bad night, traced through
Take the settings above (8 s per attempt, three attempts, five consecutive failures to open, 60 s before a probe) and imagine a provider incident starting at 23:47, with 5xx responses throughout.
| When | What happens | What the user sees |
|---|---|---|
| 23:47 | First request: three attempts, all fail; the breaker records one failure | A few seconds, then the fallback text |
| 23:47 onward | Requests two to five fail the same way; the fifth turns into CircuitBreakerError and the state becomes OPEN | Same (only these first requests wait) |
| After that | While OPEN, nothing reaches the upstream; fallbacks return in milliseconds | No waiting at all |
| Once it recovers | The first call after 60 s goes through as the HALF-OPEN probe; success closes the circuit | Normal answers resume unnoticed |
The thing to notice is that only the first handful of requests wait. Without the breaker, every request during the incident would wait close to thirty seconds. Jitter keeps retries from several processes from landing in lockstep.
Observability: a safeguard you cannot see is not a safeguard
To remove the "I think it is installed" feeling, put the observation points in at the same time. The code already carries two.
- A log line on every retry.
before_sleep_logemits a warning just before each retry. Add a prompt hash and the attempt number and you can grep for retry storms afterwards. - A log line on every breaker transition. The
state_changelistener records closed → open → half-open → closed. Push it into a time-series store and alert on "open for more than five minutes", and ordinary traffic wobble stays quiet while a real incident gets noticed.
My rule is that resilience code ships with its logs and metrics in the same pull request. Otherwise it goes live on a feeling.
What each layer protects
| Layer | Tool | Protects against | If you leave it out |
|---|---|---|---|
| Outer | Circuit breaker | Wasted calls during a sustained outage | Every request waits the full worst case while the provider is down |
| Middle | Retry + backoff + jitter | 429s and momentary 5xx | A transient blip becomes a user-visible failure |
| Inner | HTTP timeout + overall cut-off | Calls that never return | Connections pile up and drag other users down with them |
Model IDs deserve the same inventory as the safeguards. The code above reads MODEL from an environment variable, but today's default will not necessarily be valid next month. For a script that lists the model IDs you call and checks them against the official table, see the Gemini model shutdown-date inventory.
One concrete next step
Pick a single call site in your own code and add is_transient with a retry decorator first. Then write a fake upstream like guard_demo.py and watch it fail on an input that must fail, once. The timeout and the breaker can come afterwards, one layer at a time.
That is the line I keep holding: decide what is worth protecting before you write the protection, and let a simulated outage tell you whether it works. I still feel it was the right order.