State Compression Between Pipeline Stages to Minimize Token Waste
Cut token cost in ADK pipelines by compressing what each stage writes to session state, isolating stages from history, and passing distilled handoffs instead of raw transcripts.
Published on • November 30, 2026
AI Assistant

A three-stage ADK pipeline can quietly burn three times the tokens you budgeted. The crawler stage fetches 60 KB of pages, the analyst stage receives all 60 KB, the writer stage receives the crawler output and the analyst’s chain of tool calls, and every downstream stage also inherits whatever conversation history ADK passes along. Cost grows quadratically with pipeline length while the model’s job — “turn 200 words of notes into a summary” — barely changes.
This post is about state compression between pipeline stages: the discipline of deciding, at every handoff, exactly what the next stage needs and storing no more than that. We will look at how ADK actually moves data between stages (session.state, output_key, state_delta, {key} templating), how to stop stages from re-consuming conversation history with include_contents, and where the line is between “compressed enough” and “destroyed the evidence.”
1. Where the Tokens Actually Go
In a pipeline built on SequentialAgent (or a coordinator with sub_agents), three separate costs stack up:
Stage A (crawler) Stage B (analyst) Stage C (writer)
┌─────────────────────┐ ┌──────────────────────────┐ ┌───────────────────────┐
│ instruction ~800 t │ │ instruction ~900 t │ │ instruction ~700 t │
│ history ~2,000 t │ ──► │ history* ~12,000 t │ ► │ history* ~9,000 t │
│ tool results 40,000│ state │ + A's raw notes 8,000 t │ │ + A + B + C 20,000 t │
│ final answer 3,000│ handoff └──────────────────────────┘ └───────────────────────┘
└─────────────────────┘
* history = prior contents re-sent on every model call
The single biggest lever is not a smaller model or a cleverer prompt. It is refusing to hand the next stage anything it does not consume. State compression attacks all three layers: what each stage writes, what the next stage reads, and what history is re-sent.
2. How Handoffs Really Work in ADK
Three mechanisms matter, and conflating them is the usual source of token bloat.
output_key → state_delta. When you set output_key="raw_notes" on an LlmAgent, the agent’s final response text is written into the session’s state through the event’s state_delta (ADK does this by populating EventActions.state_delta on the emitted event, which the Runner passes to session_service.append_event). Whatever text the stage produces becomes the next stage’s input — verbatim.
{key} templating. The next stage reads that value by referencing {raw_notes} in its instruction. ADK substitutes the live state value before the model call. A missing key raises an error, so use {raw_notes?} when the key may not exist yet.
Shared invocation context. Sub-agents of a SequentialAgent — and, more generally, any agent in the same invocation — share one InvocationContext and therefore the same session.state, including the temp: namespace. That shared dict is the handoff channel. There is no separate “pipeline payload.”
The consequence is blunt: whatever your stage says, the next stage pays for. If the crawler’s final message is its entire scrape, you have just made the analyst pay 8,000 tokens of raw HTML for a job that needed 600 tokens of extracted facts.
3. The Compression Contract
Before writing agents, write down a contract: one line per stage, stating what it may store and roughly how big.
| Stage | Key | Allowed content | Budget |
|---|---|---|---|
| crawler | raw_notes | extracted text + URL per claim | ≤ 4 KB |
| analyst | findings | ranked findings, 1 line each | ≤ 1.5 KB |
| writer | draft | the draft itself | ≤ 6 KB |
| any | temp:* | scratch within one invocation | discarded after run |
Two rules keep this honest:
- Store the artifact, not the journey. The crawler’s tool calls, retries, and 40 tool responses belong in the event history (for auditing), not in the handoff key. The handoff is a product.
- One key per stage. Several small keys are fine, but a single named key per handoff makes budget violations obvious in a log line.
4. Stage Agents That Don’t Re-Read History
History re-sending is the invisible multiplier. ADK’s include_contents parameter controls it directly:
'default'(the default): the agent receives the relevant conversation history.'none': the agent receives only its current instruction and current-turn input.
Pipeline stages that operate purely on state should opt out of history:
from google.adk.agents import Agent
from google.adk.agents import SequentialAgent
MODEL = "gemini-flash-latest"
crawler = Agent(
name="crawler",
model=MODEL,
instruction="""
Fetch and extract the facts that matter for: {research_question}
Store ONLY distilled facts with source URLs — one line each.
Never paste raw page content into your final answer.
""",
tools=[fetch_and_extract], # returns pages internally
output_key="raw_notes",
include_contents="none", # stage reads state, not chat history
)
analyst = Agent(
name="analyst",
model=MODEL,
instruction="""
You receive {raw_notes?}.
Rank the notes by importance. Discard duplicates and anything unsupported.
Output a markdown list of at most 15 findings, each: finding, source URL.
""",
output_key="findings",
include_contents="none",
)
writer = Agent(
name="writer",
model=MODEL,
instruction="""
Write a short report from {findings?} only.
Keep every claim sourced. Maximum 500 words.
""",
output_key="draft",
include_contents="none",
)
pipeline = SequentialAgent(
name="research_pipeline",
sub_agents=[crawler, analyst, writer],
)
With include_contents="none", each stage’s input is exactly: its instruction, the substituted state value, and nothing else. The analyst no longer pays for the crawler’s tool traffic, and the writer no longer pays for the analyst’s reasoning trace.
Caveat: include_contents="none" is correct only for stateless stages. If a stage must react to what the user said two turns ago, keep default contents for that stage and accept the cost — or copy the relevant sentence into state yourself and let the stage stay stateless.
5. Compressing the Value, Not Just the Message
Setting include_contents stops history bleed, but the state value itself can still be enormous. Compress at write time.
A compression tool on the writing stage
from google.adk.tools import ToolContext
def store_notes(notes: str, tool_context: ToolContext) -> dict:
"""Persist distilled notes to session state under a size budget.
Args:
notes: Distilled facts, one per line, each with a source URL.
tool_context: ADK tool context (injected automatically).
Returns:
A status dict with the number of notes kept and their size.
"""
lines = [ln for ln in notes.splitlines() if ln.strip()][:40]
compressed = "\n".join(lines)
if len(compressed) > 4000: # hard budget, characters
compressed = compressed[:4000] + "\n[TRUNCATED]"
# The recommended way to mutate state inside a tool:
# modify the state on the provided context so ADK records the delta.
tool_context.state["raw_notes"] = compressed
return {"kept": len(lines), "bytes": len(compressed)}
Writing through the context (rather than mutating a Session object you fetched yourself) is what keeps ADK’s event tracking intact: the change travels as a state_delta on the next event, so persistence, concurrency, and any downstream observer see it consistently.
Time-boxed scratch with the temp: namespace
Namespaces encode scope, and scope encodes lifetime:
raw_notes— session-scoped, survives across turns of this conversation.user:research_style— user-scoped, survives every session for this user.app:pipeline_version— app-scoped, shared by all users.temp:page_3_dump— invocation-scoped, discarded when the run finishes.
If a stage needs a large intermediate (a full HTML page, a big tool payload) but nothing after it does, park it under temp:. It stays available to sibling stages during the invocation and evaporates afterwards — free compression, enforced by lifetime instead of by code.
6. Measure Before You Trust the Numbers
Compression without measurement is superstition. Because state changes arrive as state_deltas on events, you can audit a whole pipeline in a few lines:
async def audit(runner, session_service, user_id, session_id, message):
session = await session_service.get_session(
app_name=runner.app_name, user_id=user_id, session_id=session_id
)
before = dict(session.state)
async for event in runner.run_async(
user_id=user_id, session_id=session_id, new_message=message
):
delta = getattr(event.actions, "state_delta", None) or {}
for key, value in delta.items():
size = len(str(value))
flag = " <-- OVER BUDGET" if size > 4000 else ""
print(f"[{event.author}] {key}: {size} chars{flag}")
session = await session_service.get_session(
app_name=runner.app_name, user_id=user_id, session_id=session_id
)
total = sum(len(str(v)) for v in session.state.values())
print(f"state total: {total} chars (was {sum(len(str(v)) for v in before.values())})")
Run it once per change to a stage instruction and keep the output next to your latency/cost dashboard. A stage that suddenly writes 4× its budget is a regression even if the final answer still looks fine.
For very long multi-turn sessions — where the event history itself becomes the dominant cost — ADK also ships context compression/compaction under Agent context → Context compression in the docs. Compaction and stage compression solve different layers: compaction shrinks what the model re-reads across turns; stage compression shrinks what passes between stages within a run. Use both.
7. Checklist
- One handoff key per stage, with a documented character budget.
- Stage final responses contain the product, never the tool traffic that produced it.
- Stateless stages set
include_contents="none"; interactive stages keep default. - Large, single-invocation intermediates live under
temp:so they self-delete. - State mutations go through the context/
state_deltapath, not rawSessionmutation. - An audit pass prints every
state_deltasize and flags budget overruns in CI. - Compression never drops provenance: source URLs and claim identifiers survive every cut.
Takeaway: token waste in pipelines is a contract problem, not a model problem. Decide what each stage may write, cap it, isolate the stage from history, and let invocation-scoped state clean up after itself. Do that, and a four-stage pipeline costs roughly what one stage costs today — with the same output quality.
Sources
- Google ADK Documentation: https://adk.dev/
- State: The Session’s Scratchpad: https://adk.dev/sessions/state/
- Simple agents with LlmAgent (
include_contents): https://adk.dev/agents/llm-agents/