Cost and latency of ADK routing, tools and retrieval
Analyse example traces to compare the cost and latency of routing, sequential or parallel tools, retrieval depth and cache boundaries.
By Invicly Tech, , in Google ADK with Python for AI Agents. About 13 minutes to read.
In short
Every model call, tool call and retrieved passage shows up in a trace as time and tokens, so cost and latency questions can be answered from evidence instead of guesses. The big levers are the number of model calls (routing hops add one each), whether independent tools run in parallel, how much retrieved text you send back to the model, and whether a stable prompt prefix can be cached. Change one lever at a time and compare traces before and after.
Think of it like this: Tuning an agent is like cutting a commute: first find which leg of the journey is slow, then fix that leg, not the whole route.
Explained simply
An agent turn feels slow or costs too much for a few clear reasons, and a trace shows which one. A trace is a timed list of every step in one request: each model call, each tool call, how long each took and how many tokens went in and out.
Model calls are usually the biggest cost. Every call resends the instructions, the history and any tool results, so a turn with three model calls pays for that context three times. A router agent that only picks another agent adds a whole extra call.
Tools add waiting time. If the model asks for two independent lookups, ADK can run them at the same time, but only if they are written as async functions. Retrieval adds tokens: every passage you return is read by the model on every later call in that turn.
Caching can help when a long part of the prompt stays the same, such as a big instruction block. Change one thing at a time, run the same test questions before and after, and keep the change only if quality holds and the trace shows a real saving.
Press Play on a diagram to walk through it one step at a time.
- 1Router model call
0.9 s, picks the support agent
- 2Support model call
1.1 s, asks for two tools
- 3Doc search + ticket lookup
0.6 s if parallel, 1.0 s if sequential
- 4Final model call
1.4 s, 6 passages in context
- 5Total
About 4 s; the router hop is 22 percent
- Time is the sum of each tool
- Simple to read in a trace
- Needed when one tool uses another's result
- Sync tools force this behaviour
- Time is roughly the slowest tool
- Needs async def tools with async I/O
- Only for independent lookups
- Same tokens, less waiting
- Model calls
- Remove routing hops
- Merge dependent tools
- Smaller model for simple steps
- Tokens
- Lower top-k
- Shorter excerpts
- Trim history or compact events
- Tool time
- async def tools
- Parallel independent lookups
- Timeouts on slow backends
- Reuse
- Context caching on stable prefix
- Cache tool results in code
In depth
Reading cost and latency from a trace
Turn on tracing (adk web shows a trace view locally, and the observability docs cover exporting OpenTelemetry spans). For one turn, write down four numbers: the count of model calls, the time spent in model calls, the time spent in tools, and the total input and output tokens. Each ADK event that comes from a model response carries usage_metadata with prompt and candidate token counts, and the evaluation framework also reports tool_call_count_v1, inference_call_count_v1, token_usage_v1 and invocation_duration_v1 as information-only metrics. Cost per turn is then input tokens times the input price plus output tokens times the output price, plus any tool or search charges. Use your provider's current price sheet and keep the figures in a spreadsheet next to the trace ID. Average over at least twenty representative questions; single turns vary too much.
- Model calls per turn
- Seconds in model calls vs tools
- Input and output tokens
- Cached tokens, if caching is on
- Cost per turn and per 1,000 turns
Sequential and parallel tools
When the model returns several function calls in one response, ADK for Python (since 1.10.0) tries to run them in parallel. The gain only appears if the tools are async def functions that await non-blocking I/O, such as an async HTTP or database client. A plain def tool, or an async tool that calls a blocking library, holds the event loop and forces the others to wait. Parallel calls do not save tokens: the model still reads every result. They save waiting time, so total tool time drops from the sum of the tools to roughly the slowest one. Some lookups cannot be parallel because one needs the other's output; in that case consider whether a single tool that does both steps in code removes a model round trip altogether.
- Model to ADK runtime: Two function calls in one reply1Two function calls in one reply
- ADK runtime to search_docs: Start search (0.6 s)2Start search (0.6 s)
- ADK runtime to get_ticket_status: Start ticket lookup (0.4 s)3Start ticket lookup (0.4 s)
- get_ticket_status to ADK runtime: Ticket result4Ticket result
- search_docs to ADK runtime: Doc passages5Doc passages
- ADK runtime to Model: Both results in one next call6Both results in one next call
Tuning retrieval depth
Retrieval depth, or top-k, is how many passages the doc lookup returns. More passages raise the chance that the right one is included, but every passage adds input tokens to each later model call and can distract the model with near-misses. Tune it with data. Take your grounding eval cases, run them at k equal to 2, 4 and 8, and record for each run whether the correct source ID was retrieved, whether the answer cited it, the input tokens and the latency. Pick the smallest k where retrieval recall and answer accuracy stop improving. Also trim passages: return a short excerpt with its source ID rather than a whole page. If the right passage is not in the top results at any k, the fix is better chunking or search, not a bigger k.
- Measure recall: was the right source retrieved?
- Measure answer accuracy and citations
- Record input tokens per k
- Return excerpts, not whole pages
Context caching boundaries
Context caching stores a repeated prompt prefix so later requests reuse it. In ADK you set it on the App with ContextCacheConfig (experimental, Python 1.15.0 and later). The settings are min_tokens (default 0), ttl_seconds (default 1800) and cache_intervals, the maximum reuses before refresh (default 10, range 1 to 100). It works with Gemini 2.0 and later models that support caching, and the first request in a session is never cached. Caching only pays off when a large part of the request stays byte-for-byte stable: long instructions, tool declarations and fixed reference text. Put changing values, such as the date or user name injected from state, late in the prompt or in the user turn, so they do not break the shared prefix. Check the cached token count in usage_metadata to see whether it is working.
- 1Instructions
Long and identical every turn: cacheable
- 2Tool declarations
Fixed schemas: cacheable
- 3Earlier history
Grows each turn, stable once written
- 4Retrieved passages
Change per question
- 5Latest user message
Always new
Removing a routing hop
A common first design has a coordinator agent that reads every message and transfers to a docs agent or a tickets agent. The trace shows the price: one extra model call per turn, often a fifth to a third of total latency, plus the coordinator's own instructions in the input tokens. Alternatives are a single agent with both tools, or a deterministic router in code, for example a regular expression that spots a ticket ID, in a graph workflow before any model call. Run the same eval set on both designs and compare accuracy, tool trajectory scores, model calls, tokens and latency. Keep the router only if it clearly improves accuracy or safety, for example by giving a narrow agent fewer tools to misuse.
Learn it in 5 short steps
About 35m each. Track them with a timer in your plan.
- 1Read cost and latency from traces~35m
- 2Compare sequential and parallel tools~35m
- 3Tune retrieval depth~35m
- 4Use context caching~35m
- 5Remove a routing hop~35m
Key points
- Read a trace per turn: count model calls, note each tool's duration, and sum input and output tokens.
- Model calls usually dominate both cost and latency; a routing hop is a whole extra model call.
- ADK runs function tools the model requests together in parallel, but only async tools gain from it.
- More retrieved passages raise input tokens on every later call; tune top-k against grounding evals.
- Context caching on the App reuses a long stable prefix on supported Gemini models; the first request in a session is never cached.
Key terms
Tap a card to flip it. 0/6 known
Examples
from google.adk.agents.context_cache_config import ContextCacheConfig
from google.adk.apps import App
from support_agent.agent import root_agent
app = App(
name="support_agent",
root_agent=root_agent,
context_cache_config=ContextCacheConfig(
min_tokens=2048, # skip caching for short prompts
ttl_seconds=600, # default is 1800
cache_intervals=5, # reuse at most 5 times, default 10
),
)ContextCacheConfig is marked experimental; check the pinned release before relying on it.
Comparing a router design with a single agent
Prerequisites: the eval set from module 7 and a live model run (paid; with a mock model you can still compare call counts but not real latency). Step 1: run 20 cases on the router design and record model calls, input tokens and duration per case. Step 2: run the same cases on a single agent with both tools. Step 3: compare. In this synthetic result, the single agent used 2.1 model calls per turn instead of 3.1 and was 0.9 s faster at the median, with the same tool trajectory score. Decision: drop the router, record it in an ADR, keep the traces.
design calls/turn input tok p50 s traj score answer ok
router 3.1 9,400 4.0 0.95 18/20
single agent 2.1 6,100 3.1 0.95 18/20
# synthetic numbers for illustrationMaking two tools run in parallel
The trace showed doc search and ticket lookup running one after the other, 1.0 s in total. Both tools were plain def functions using a blocking HTTP client. Step 1: rewrite them as async def with an async client. Step 2: add one line to the instructions saying independent lookups can be requested together. Step 3: rerun the trace. Expected evidence: the two tool spans now overlap and tool time drops to about 0.6 s. Token counts stay the same.
import httpx
client = httpx.AsyncClient(timeout=2.0)
async def search_docs(query: str) -> dict:
"""Search public product docs. Safe to call alongside other lookups."""
r = await client.get("http://docs.internal.example.com/search", params={"q": query, "k": 4})
r.raise_for_status()
return {"status": "ok", "passages": r.json()["passages"]}Quick reference
- Per turn, record: model calls, model seconds, tool seconds, input and output tokens.
- event.usage_metadata holds token counts for model response events.
- Parallel tools need async def and non-blocking I/O; sync tools block the others.
- Parallel saves waiting time, not tokens.
- Tune top-k on grounding evals; pick the smallest k where recall stops improving.
- ContextCacheConfig defaults: min_tokens 0, ttl_seconds 1800, cache_intervals 10.
- Keep changing values late in the prompt so the cached prefix stays stable.
- A router agent costs one extra model call per turn; prove it earns its keep.
Common mistakes
- Optimising tool code when the trace shows 80 percent of the time is spent in model calls.
- Writing tools as plain def functions, so parallel calls still run one after another.
- Raising top-k to fix a wrong answer without checking whether the right passage was ever retrieved.
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
From a trace of one turn, fill in model calls, model seconds, tool seconds, input tokens and output tokens.
- Exercise 2medium
Run your grounding eval cases at top-k 2, 4 and 8 and choose a value.
- Exercise 3hard
Replace the coordinator agent with a code router in a graph workflow and compare both designs on the same eval set.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Is parallel tool calling on by default?
- Yes, ADK for Python attempts to run tool calls from one model response in parallel since 1.10.0. You only benefit if the tools are async and non-blocking.
- Does context caching change answers?
- It should not; it reuses the same prompt prefix. Still rerun your eval set after turning it on, and check the cached token count to confirm it is used.
- Can I measure cost without paying for a live model?
- You can count model calls and estimate tokens with a mock model and a token counter, but real latency and billed tokens need a live run.
- Should I always use the smallest model?
- Use the smallest model that passes your eval set. Simple routing or extraction steps often work on a smaller model, while the final grounded answer may need a larger one.