Skip to content
Blog

Global Timeouts and Execution Deadlines in ADK Agents

How to bound agent runtime end to end — RunConfig call limits, asyncio timeouts around the runner, ambient-agent trigger deadlines, and layered watchdogs that fail predictably.

Published on • November 25, 2026

AI Assistant

An agent loop has no natural ending. The model can keep calling tools, a tool can block on a slow HTTP endpoint, and a sub-agent can spawn another round of calls — until a request that should take five seconds has consumed five minutes of compute and one very confused user. Deadlines are what turn an open-ended loop into a predictable system.

ADK does not ship one big global_timeout= knob. Instead it gives you several bounding mechanisms at different layers, and production systems combine them. The pattern is the same one you’d use anywhere else: an inner bound on each step, a call budget on the loop, and a hard outer deadline that nothing may exceed.

Layer 1: cap the number of LLM calls

RunConfig has an explicit budget for model calls per invocation: max_llm_calls, defaulting to 500. When the budget is exhausted, the run stops instead of spiraling.

from google.adk.runners import Runner, RunConfig

runner = Runner(
    agent=root_agent,
    app_name="ops_assistant",
    session_service=session_service,
    run_config=RunConfig(max_llm_calls=50),
)

Think of this as a work bound rather than a time bound — 500 calls with a fast model is seconds; with a slow reasoning model it’s minutes. It is still the single most valuable safety net, because it catches runaway agent graphs (a LoopAgent or workflow cycle that never converges) regardless of how fast each step is.

Set it deliberately per surface:

  • Interactive chat — low double digits. A user-facing turn that needs 50 model calls has lost the plot.
  • Background/ambient work — higher, but finite.
  • Evaluation runs — generous; you want the agent to finish the scenario.

Layer 2: bound each step with asyncio

The runner’s entry point is run_async, an async generator. Because it’s plain asyncio, the standard tooling applies: wrap consumption in asyncio.wait_for or asyncio.timeout.

import asyncio
from google.adk.runners import Runner

DEADLINE_SECONDS = 30

async def run_turn(runner: Runner, user_id: str, session_id: str, text: str) -> list:
    async def consume():
        events = []
        async for event in runner.run_async(
            user_id=user_id,
            session_id=session_id,
            new_message=Content(role="user", parts=[Part(text=text)]),
        ):
            events.append(event)
        return events

    try:
        return await asyncio.wait_for(consume(), timeout=DEADLINE_SECONDS)
    except asyncio.TimeoutError:
        raise AgentDeadlineExceeded(DEADLINE_SECONDS)

Two details matter:

  1. Cancelling the generator cancels the work. When wait_for fires, the awaiting task is cancelled, which propagates into the async generator and tears down the in-flight model call. The deadline is real, not cosmetic.
  2. Handle it at the boundary. Convert TimeoutError into your own domain exception with context (session, phase, elapsed) so the caller can respond — a partial event stream, a “timed out, try again” message, or a retry on a fresh session.

For long generations you may prefer soft deadlines: stop collecting new events after N seconds but let the final in-flight event settle. That’s just a flag checked inside the consume loop rather than a hard cancel.

Layer 3: bound the tool, not just the run

A single hanging tool will burn the entire run deadline from the inside. Give every tool its own, tighter timeout — much like circuit breakers in ordinary services:

import httpx

async def fetch_metrics(service: str, tool_context) -> dict:
    """Fetch current service metrics. Fails fast when the metrics backend is slow."""
    async with httpx.AsyncClient(timeout=httpx.Timeout(3.0, connect=1.0)) as client:
        resp = await client.get(f"{METRICS_URL}/{service}/current")
        resp.raise_for_status()
        return resp.json()

The hierarchy should always read: tool timeout < run deadline < caller’s patience. If your outer deadline can expire while the tool timeout is still pending, you’ll get cancellations that look like flaky timeouts rather than clean failures.

Synchronous tools get the same treatment with asyncio.to_thread plus a wait:

result = await asyncio.wait_for(
    asyncio.to_thread(blocking_lookup, key),
    timeout=2.0,
)

Layer 4: ambient and background triggers have their own clock

Headless/ambient agent runs — the trigger-based flows that start an agent from a webhook, cron, or event — carry deployment-level limits of their own. In ADK’s ambient agent runtime:

  • each trigger invocation is bounded (requests that run past 10 minutes are cut off),
  • concurrency is capped (ADK_TRIGGER_MAX_CONCURRENT, default 10 in Python),
  • and failed runs are retried a bounded number of times (ADK_TRIGGER_MAX_RETRIES, default 3).
export ADK_TRIGGER_MAX_CONCURRENT=4
export ADK_TRIGGER_MAX_RETRIES=2

These are exactly the knobs you want in front of an unattended workload: without them, one slow trigger can queue behind dozens of others and amplify into a backlog.

Making failure predictable

Bounding is only half the job — the other half is deciding what each deadline does:

Failure pointRecommended response
Tool timeoutReturn a typed error to the model; let it retry or answer with degraded data
max_llm_calls exhaustedEnd run, persist partial state, tell the user the task needs more steps
Hard run deadlineCancel cleanly, record deadline_exceeded in session events, resume in a new turn
Ambient trigger deadlineLet the platform retry; make handlers idempotent first

Idempotency is the prerequisite. Any deadline can fire after side effects have already happened. If a tool has already charged a card when the outer timeout hits, a blind retry multiplies the damage. Design tools so a repeated call with the same key converges on the same state, then make retries safe.

A compact way to enforce the whole stack:

class RunBudget:
    def __init__(self, max_calls: int, deadline_s: float):
        self.calls = 0
        self.max_calls = max_calls
        self.deadline = time.monotonic() + deadline_s

    def check(self) -> None:
        self.calls += 1
        if self.calls > self.max_calls:
            raise BudgetExceeded(f"exceeded {self.max_calls} model calls")
        if time.monotonic() > self.deadline:
            raise DeadlineExceeded("run deadline passed")

Check it from callbacks (before-model and after-model) so it fires between steps rather than only at the edges.

Observability: you can’t tune what you can’t see

Log elapsed_ms, llm_calls, and final_status per invocation. Those three numbers immediately answer the questions that matter: is the tail driven by a slow tool or by too many model rounds? Which deadline is actually firing? A simple alert on p95 elapsed approaching the configured deadline usually reveals a budget set far too loosely.

Where to go next

Deadlines pair naturally with failure handling — once a run can end early, you need graceful exception handling and fallback strategies for what happens when it does. For the mechanism that carries budgets and deadlines through a run, see the InvocationContext lifecycle, and for bounding unattended workloads see headless background agents and async queues.

References