Run an ADK agent in production: limits and incident drills
Plan budgets, rate limits, timeouts, streaming troubleshooting, version rollout and retention, and run an incident drill for tool and model failures.
By Invicly Tech, , in Google ADK with Python for AI Agents. About 12 minutes to read.
In short
An agent in production needs limits on money, requests and time, a safe way to release new versions, and a rehearsed plan for when a tool or the model fails. Budgets alert you, rate limits and max_llm_calls cap spend per user and per turn, and timeouts must shrink from the client inward so the user always gets an answer. Gradual rollouts with tagged Cloud Run revisions and regular incident drills turn outages into routine work.
Explained simply
Getting the agent online is the start. Keeping it healthy means setting limits before something goes wrong: how much money it may spend, how many requests one user may make, and how long each step may take.
Limits work in layers. A budget alert tells you when spending grows. A rate limit stops one user from flooding the service. A cap on model calls per turn stops one confused conversation from looping. Timeouts make sure a slow tool turns into a polite error instead of a hanging screen.
New versions should reach users gradually. You deploy the new version without traffic, test it on its own address, then give it a small share of users and watch. If something looks wrong, you move traffic back in seconds.
Finally, practise failure. Pretend the ticket system is down, or the model returns errors, and see what users would get, what alerts fire and how quickly the team responds. A drill on a quiet afternoon is much cheaper than a surprise at night.
Press Play on a diagram to walk through it one step at a time.
- 1Client
Waits longest, for example 120 s for a streamed reply
- 2Cloud Run request timeout
Default 300 s, set with --timeout, maximum 60 minutes
- 3Agent turn deadline
Your own limit, for example 60 s, plus max_llm_calls
- 4Model call
Retry with backoff on 429 and 503, a few attempts only
- 5Tool call
Shortest, for example 5 s, then a clear error result
- User to Agent: Status of T-1001?1Status of T-1001?
- Agent to Ticket tool: get_ticket_status(T-1001)2get_ticket_status(T-1001)
- Ticket tool to Agent: No reply within 5 s: error result3No reply within 5 s: error result
- Agent to Model: Tool error passed as function response4Tool error passed as function response
- Model to Agent: Apology, no guessed status, offer a human5Apology, no guessed status, offer a human
- Agent to User: Clear fallback message6Clear fallback message
In depth
Budgets, quotas and rate limits
Spend limits need several layers because each one catches a different problem. A Cloud Billing budget on the project emails you at thresholds such as 50, 90 and 100 percent; it never stops charges by itself. The model quota caps requests per minute and returns 429 RESOURCE_EXHAUSTED when exceeded, which protects the provider, not your budget.
In your service, cap work per turn with RunConfig max_llm_calls (default 500; a support agent needs about 10) and limit requests per user per minute, for example with a small counter keyed by user ID in Redis or the session database, or with a gateway in front of Cloud Run. On Cloud Run, --max-instances caps how far the service scales, and --concurrency sets how many requests one instance handles at once. Together they put a ceiling on parallel model calls.
- Budget alerts: notify, never block
- max_llm_calls: per-run cap on model calls
- Per-user rate limit in your app or gateway
- --max-instances and --concurrency cap parallel load
Timeouts end to end
Each layer must give up before the layer outside it, so the inner layer can still return a clean error. Start from the inside. Wrap each tool call in asyncio.wait_for with a few seconds and return an error result the model can explain. Retry model calls on 429 and 503 with exponential backoff and jitter, two or three attempts only. Give the whole turn a deadline, such as 60 seconds, and stop with a fallback message when it passes.
Outside the agent, the Cloud Run request timeout defaults to 300 seconds and can be set with --timeout up to 60 minutes; it also limits how long a streamed response can stay open. The client and any load balancer must wait longer than that. Write the chain down, for example tool 5 s, model 30 s, turn 60 s, Cloud Run 120 s, client 130 s.
Troubleshooting broken streams
The /run_sse endpoint sends events as Server-Sent Events when the request sets streaming to true: lines starting with data: followed by a JSON event, separated by blank lines. Most broken streams come from something between the agent and the user, not the agent.
Check in order. Does the stream work with curl -N straight to the Cloud Run URL? If yes, the problem is downstream: a proxy or framework buffering the response, a client that waits for the full body, or CORS blocking the browser. If the stream stops after a fixed time, compare it with the Cloud Run timeout and any proxy idle timeout. If it fails at the start, check the identity token, which expires after about an hour. Log a request ID and the event count at the server, so you can tell whether the agent stopped early or the client stopped reading.
- curl -N to see events unbuffered
- Fixed cut-off time: a timeout somewhere
- 401 or 403 mid-session: expired token
- Compare server event count with client count
Gradual rollout, retention and the incident drill
Deploy a new revision with --no-traffic and --tag, run the fixture tests and a few live cases against the tag URL, then use update-traffic --to-tags to move 10 percent, then 50, then all. Watch error rate, latency, tool errors and tokens per turn at each step, and roll back with --to-revisions if any crosses its limit.
Retention is part of reliability. Decide how long sessions are kept, for example 30 days, and run a scheduled job that deletes older ones; ADK's session services do not expire sessions for you unless the managed service offers a time-to-live. Cloud Logging's _Default bucket keeps logs for 30 days unless you change it.
Run a drill each quarter: make the ticket tool fail and the model return errors in staging, then check what the user sees, which alert fires, and how long recovery takes.
- 1Plan
Pick a failure: tool down, model 503, slow stream
- 2Inject
Feature flag or stub in staging
- 3Observe
User message, alerts, dashboards
- 4Respond
Follow the runbook, roll back if needed
- 5Improve
Fix gaps, add an eval case, update runbook
- Back to step 1
Learn it in 5 short steps
About 35m each. Track them with a timer in your plan.
- 1Set budgets and rate limits~35m
- 2Tune timeouts end to end~35m
- 3Troubleshoot broken streams~35m
- 4Roll out a new version gradually~35m
- 5Drill a tool and model outage~35m
Key points
- Cloud Billing budgets send alerts; they do not stop spending, so add hard caps in your own code.
- Cap work per turn with RunConfig max_llm_calls and per user with a request rate limit.
- Each inner timeout must be shorter than the one outside it, or callers see cut connections instead of errors.
- Deploy new versions with --no-traffic and a tag, test the tag URL, then shift traffic in steps.
- Set retention on sessions and logs on purpose, and run a drill for tool and model outages each quarter.
Key terms
Tap a card to flip it. 0/6 known
Examples
# deploy v2 with no traffic and a tag
gcloud run deploy support-agent --source . --region europe-west1 \
--no-traffic --tag v2
# test https://v2---<service-url-host> then shift 10 percent
gcloud run services update-traffic support-agent --region europe-west1 \
--to-tags v2=10
# all good: promote; problems: roll back to the old revision
gcloud run services update-traffic support-agent --region europe-west1 --to-latest
gcloud run services update-traffic support-agent --region europe-west1 \
--to-revisions support-agent-00012-abc=100A tagged canary, a 10 percent step, then promote or roll back.
A tool timeout that turns into a clean error
Step 1: wrap the slow call in asyncio.wait_for with a short limit. Step 2: on timeout, return a dictionary with an error field instead of raising, so the model gets a function response it can explain. Step 3: the instruction tells the agent never to guess a status after a tool error. Step 4: in the drill, point TICKET_API_URL at a stub that sleeps 10 seconds. Expected evidence: the reply apologises and offers a human, the trace shows one tool call with error timeout, and the turn ends in about 5 seconds.
import asyncio
async def get_ticket_status(ticket_id: str) -> dict:
"""Read the status of one of the user's tickets."""
try:
return await asyncio.wait_for(fetch_status(ticket_id), timeout=5)
except asyncio.TimeoutError:
return {"error": "timeout", "ticket_id": ticket_id,
"advice": "Do not guess. Apologise and offer a human."}Drilling a model outage with a fake model
Step 1: in staging, set a flag that swaps the model for a BaseLlm subclass that raises an error on every call. Step 2: send a test conversation. Step 3: check that the server returns a friendly fallback, not a stack trace, and that the error-rate alert fires within its window. Step 4: switch the flag off and confirm recovery. Record the time to detect and the time to recover in the drill log, and add an eval case for the fallback message.
from google.adk.models import BaseLlm
class OutageLlm(BaseLlm):
model: str = "outage-drill"
async def generate_content_async(self, llm_request, stream=False):
raise RuntimeError("503 UNAVAILABLE (drill)")
yield # makes this an async generator
# model = OutageLlm() if os.environ.get("DRILL_MODEL_OUTAGE") else "gemini-flash-latest"Quick reference
- Budget alerts notify only; enforce caps in code, quotas and --max-instances
- RunConfig(max_llm_calls=10) for a small agent; default is 500
- Timeout chain: tool < model retries < turn < Cloud Run --timeout < client
- Cloud Run request timeout: default 300 s, maximum 60 minutes
- Canary: deploy --no-traffic --tag v2, then update-traffic --to-tags v2=10
- Debug streams with curl -N directly against the Cloud Run URL
- Delete old sessions on a schedule; logs in _Default stay 30 days by default
- Drill tool and model outages quarterly in staging
Common mistakes
- Relying on a budget alert to stop costs; it only emails you.
- Setting a 30 s tool timeout behind a 30 s request timeout, so the platform cuts the stream before the agent can apologise.
- Testing streaming only with curl locally, then finding a proxy or client that buffers SSE in production.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write the timeout chain for the support agent with a number for each layer.
- Exercise 2medium
Write the commands to release v2 as a canary at 10 percent, promote it, and roll back if needed.
- Exercise 3hard
Plan an incident drill for a ticket tool outage: goal, injection, expected evidence, success criteria and cleanup.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- What happens when max_llm_calls is reached?
- The run stops with an error instead of calling the model again. Catch it in your server and return a clear fallback message, and treat it as a signal that the agent may be looping.
- Why does my browser not show streamed events while curl does?
- Something between them is buffering or blocking: a proxy, a framework that waits for the full body, or CORS. Test each hop and make sure the client reads the stream incrementally.
- How long should I keep sessions?
- Only as long as the agent and your support process need, often days or weeks. Write the period down, delete older sessions on a schedule and keep logs free of personal content.
- Do I need a paid project to practise this?
- No. Run the container locally, use the fake models for outages and a sleeping stub for tool timeouts. Traffic splitting is the one part that needs Cloud Run.