Google ADK: Context Engineering in 2026 — Balancing Large Windows, Cost, and Recall
How to trade off million-token windows against input cost and retrieval accuracy in 2026: prefix caching, ADK compaction, and what to keep out of the window entirely.
Published on • December 4, 2026
AI Assistant

Context windows in 2026 are enormous, and that has quietly inverted the old problem. Teams no longer fight to fit context in — they fight to keep a million tokens of accumulated history from inflating every invoice while still recalling the one detail from turn three that actually mattered. Big windows make stuffing feel free; your billing dashboard disagrees, and so does your accuracy curve.
Context engineering is the discipline of deciding what enters the window, what stays cached, what gets compressed, and what never belongs in the prompt at all. This article breaks the problem into its three competing axes — window size, cost, and recall — then shows the concrete levers ADK and the Gemini API give you to balance them.
1. The three-way trade-off
Every context decision moves all three dials:
| Decision | Window | Cost | Recall |
|---|---|---|---|
| Stuff full history every turn | Grows unbounded | Linear growth per turn | High for recent, degraded for old (lost-in-middle) |
| Cache the shared prefix | Unchanged | Up to 90–95% off cached input | Unchanged |
| Compact old turns into summaries | Bounded | Bounded | Recent verbatim; old turns summarized |
| Move facts to state/memory, out of prompt | Small | Small | Retrieved on demand, exact |
The insight that separates 2026 practitioners from 2024 ones: cost and recall are not in direct conflict. Caching cuts cost without touching recall, and memory-based recall can improve accuracy while shrinking the window. The real conflict is between window size and everything else — and unbounded windows hurt both cost and, counterintuitively, retrieval quality.
2. Large windows change the failure mode
When the window was 8K, the failure was truncation. With six-figure windows, the failure is inertia: every turn resends the entire accumulated history, so a 40-turn conversation pays for 40 turns of tokens on turn 41 — and the model must wade through all of it, where needle-in-a-haystack retrieval gets measurably harder as irrelevant filler accumulates.
ADK’s own answer to this is context compaction: summarizing older session history — instructions, inputs, and model responses — to keep the window compact, explicitly framed as optimizing latency and reducing cost while retaining recent interactions. In other words, the framework treats window size as a resource to actively manage, not a budget to fill.
3. Cost axis: caching is the cheapest tokens you will ever buy
Before compressing anything, make the tokens you do send cheap. Gemini’s implicit caching is enabled by default on Gemini 2.5 and newer: when a request matches a cached prefix above the model’s token floor, those tokens are billed at the cached rate — 95% off on Gemini 4 models, 90% on Gemini 3, with no storage fees.
The catch is prefix discipline. The API serializes every request in a fixed order — model configuration, then tools, then system_instruction, then conversation history — and the first differing token breaks the cache for everything after it. The most common self-inflicted misses:
| Cache-breaking pattern | Fix |
|---|---|
Timestamps/UUIDs in system_instruction | Keep it static; volatile values go in the final user message |
| Mutating or reordering non-deferred tools | Freeze the tools array; defer large catalogs with defer_loading: true |
Changing thinking_level mid-session | One level per session — it serializes first and busts 100% |
| Reordering JSON keys or file arrays | Sort keys; keep file order stable across requests |
Measure it every turn: total_cached_tokens / total_input_tokens from the response usage metadata. If that ratio drops after a release, a prompt edit broke your prefix — you can catch a cost regression before the invoice does.
4. Compress deliberately with ADK compaction
When the history itself must shrink, ADK’s EventsCompactionConfig runs automatically under rules you set. Two strategies, with token-based taking priority when both are configured:
from google.adk.apps.app import App, EventsCompactionConfig
from google.adk.agents import Agent
from google.adk.apps.llm_event_summarizer import LlmEventSummarizer
from google.adk.models import Gemini
root_agent = Agent(
name="research_agent",
model="gemini-flash-latest",
instruction="Answer questions using the conversation context.",
)
app = App(
name="compacting-research-app",
root_agent=root_agent,
events_compaction_config=EventsCompactionConfig(
# Safety net: compact once the prompt exceeds 40K tokens...
token_threshold=40000,
# ...keeping the 5 most recent events verbatim for pronoun resolution
event_retention_size=5,
# Supplementary turn-based trigger: every 10 invocations,
# retaining 1 overlapping invocation for continuity
compaction_interval=10,
overlap_size=2,
summarizer=LlmEventSummarizer(
llm=Gemini(model="gemini-flash-latest"), # summarize with a cheap model
),
),
)
Design notes that matter in practice:
event_retention_sizeis your recall guarantee. It is the number of recent events kept raw; too small and the model loses pronoun resolution (“it”, “that order”) in the very turns users care about most.- Summarize with a cheaper model. Compaction itself is a model call — a
gemini-flashsummarizer keeps overhead far below the savings from shrinking the main model’s input. - Token-based is the absolute safety net for unpredictable loads (pasted code blocks, uploaded files); sliding-window suits regular, predictable chat.
5. Recall axis: keep durable facts out of the window
Compaction summarizes history — and a summary of “the user’s passport number is X” is a lossy place to keep a passport number. Anything that must be exact and reusable should leave the window entirely and live in ADK’s other context stores:
| Store | Scope | Read path | Use for |
|---|---|---|---|
session.state (no prefix) | Current session | {key} instruction templating | Workflow step, open ticket ID |
user: state | All sessions of a user | get_user_state / templating | Preferences, identity facts |
MemoryService | Cross-session archive | load_memory / preload_memory tools | Prior conversations, learned facts |
| Artifacts | Binary blobs | Artifact API | Files that must not be re-uploaded |
The compaction config and memory tools compose naturally: history gets summarized at a token threshold, while the facts worth remembering verbatim are extracted into MemoryService via an after_agent_callback that calls add_session_to_memory — then recalled on demand instead of riding along in every prompt.
6. A reference decision table
| Workload | Window strategy | Cost strategy | Recall strategy |
|---|---|---|---|
| Short support chat (< 20 turns) | Full history | Implicit caching (static prefix) | Full history is the recall mechanism |
| Long research session | Compaction at 40K tokens | Prefix caching + flash summarizer | event_retention_size ≥ 5, facts to state |
| Agent with large tool catalog | Defer tools (defer_loading) | Avoids tool-prefix bloat and cuts input | Tool retrieval appends schemas inline |
| Voice / realtime | context_window_compression at ~78% of window | Bounded input per turn | Critical facts preloaded into memory |
| Multi-document RAG | Files via Files API, stable order | File tokens cache at the same discount | Vector memory, not prompt stuffing |
Two Gemini-specific numbers worth hard-coding into your thinking: requests need at least 4,096 input tokens (Gemini 4/3) before implicit caching activates, and every Gemini 4 request recomputes a trailing 2,050-token window at standard rates — so tiny follow-up turns get no discount, while tool-heavy agent turns (thoughts + tool results easily exceeding 2,050 tokens) keep the full prior turn cached.
Whichever row you land on, verify both cost and recall after every change: log the cache hit ratio from usage metadata, and run a small eval set of questions about early conversation turns before and after enabling compaction. A configuration that saves 40% on input but can no longer answer “what did I tell you in my first message?” has not balanced the triangle — it has just moved the failure.
Checklist
- Prefix audited: no timestamps, UUIDs, or unstable key order in
system_instructionor tools -
total_cached_tokens / total_input_tokenslogged every turn as a regression metric -
EventsCompactionConfigset with bothtoken_thresholdandevent_retention_size - Summarizer runs on a cheap model (
gemini-flash), not the main agent model - Exact-reuse facts stored in
user:state orMemoryService, never only in history - Sessions with large tool lists use deferred loading to protect the prefix
- Window utilization targeted at 70–80% before compression triggers, per channel
- Recall quality tested on old-turn questions after compaction, not just recent ones
Conclusion
Context engineering in 2026 is no longer about squeezing tokens into a window — it is about running three ledgers at once. Windows are plentiful, so the scarce resources are the dollars spent re-sending history and the model’s ability to find what matters inside it.
Balance comes from layering, not choosing: freeze your prompt prefix so caching discounts the bulk of input, compact old turns so the window stays bounded, and lift durable facts into state and memory so recall survives compression. Do all three and the trade-off largely dissolves — large context becomes an on-demand resource rather than a per-turn tax.