Google ADK: Sliding Window Turn Management for Long-Running Autonomous Agents
Configure ADK's EventsCompactionConfig sliding-window and token-based compaction so an agent that runs for hundreds of turns keeps latency and cost flat.
Published on • December 4, 2026
AI Assistant

An autonomous agent that runs for two hundred turns has a growth problem that no amount of prompt tuning fixes: turn 199’s model call still carries turns 1 through 198. Every tool result, every intermediate reasoning blob, every user nudge is appended to session.events, and on include_contents='default' the whole pile becomes request contents. Latency climbs, cost climbs, and — worst — retrieval quality decays as the signal you care about drowns in a thousand messages of process traffic.
ADK’s answer is context compaction: summarize older event history on a schedule, keep a small raw tail, and let the model work from a compact window. Two triggers are available under one config object, EventsCompactionConfig — a sliding window counted in invocations, and a token-based safety net. The sliding window is the one you tune for long-running agents because it is deterministic: you always know that every N-th turn, history gets folded.
This tutorial wires up both, adds a custom summarizer, verifies compaction actually happened, and gives you a tuning table for compaction_interval and overlap_size.
Prerequisites
pip install google-adk— Python v1.16.0+ (the feature also ships in Go v2.3.0+, Java v0.2.0+, TypeScript v0.6.0+, Kotlin v0.7.0+)- An agent you can run for many turns in one
Session - Familiarity with
App,Runner, andsession.events
1. Where the growth happens
Inside the runtime, each user query starts an invocation; the Runner appends the query as an event, runs the agent, and commits every yielded event — user text, model text, FunctionCall, FunctionResponse — to session.events. Compaction targets exactly that history. session.state is a separate key-value store and is not summarized; it stays your cheap channel for things that must survive verbatim (ids, counters, the current plan).
So the design rule for long agents: put durable facts in state, let history hold the transcript, and let compaction shrink the transcript.
2. The two triggers
| Strategy | Trigger | Config fields | Best for |
|---|---|---|---|
| Sliding window (turn-based) | After a fixed number of new invocations | compaction_interval, overlap_size | Predictable, chatty, long-running agents |
| Token-based (primary) | Prompt exceeds an absolute token count | token_threshold, event_retention_size | Spiky workloads — pasted code, large files |
If you configure both, token-based wins: when the session crosses token_threshold, that compaction fires and the sliding-window pass is skipped for that turn. Configure them as complementary layers — the window as the routine cadence, the token threshold as the safety net.
Where it runs: token-based compaction is checked before a model call (via CompactionRequestProcessor in SingleFlow) and again in the Runner after each invocation; sliding-window compaction runs in the Runner after each invocation completes.
3. Step 1 — turn on the sliding window
from google.adk import Agent
from google.adk.apps.app import App, EventsCompactionConfig
root_agent = Agent(
name="ops_agent",
model="gemini-flash-latest",
instruction="Keep working the incident until it is resolved.",
tools=[check_status, create_ticket, page_oncall],
)
app = App(
name="ops-agent-app",
root_agent=root_agent,
events_compaction_config=EventsCompactionConfig(
compaction_interval=10, # fold history after every 10 new invocations
overlap_size=2, # keep the last 2 invocations raw, unpromoted
),
)
Semantics, exactly as documented: compaction_interval must be > 0 and must be set together with overlap_size. overlap_size is how many of the previously compacted invocations are pulled back into the newly compacted set. With compaction_interval=3 and overlap_size=1 the docs’ worked example folds at invocations 3, 6, 9 — and each subsequent fold includes one invocation from the previous window, so summaries are not built in isolation.
invocation 3 -> fold 1-3 (raw tail: 3)
invocation 6 -> fold 3-6 (overlap 1) (raw tail: 6)
invocation 9 -> fold 6-9 (overlap 1) (raw tail: 9)
4. Step 2 — add the token safety net
Turn counts lie about size: one 90KB paste is worth fifty chatty turns. Pair the window with an absolute cap:
events_compaction_config = EventsCompactionConfig(
# Layer 1: routine, turn-based cadence
compaction_interval=10,
overlap_size=2,
# Layer 2: absolute backstop
token_threshold=4000, # fold as soon as the prompt crosses 4,000 tokens
event_retention_size=5, # keep the 5 most recent events raw when it fires
)
event_retention_size is the token-based analogue of overlap_size: the number of recent events kept in raw, un-compacted form so the model still has immediate context and can resolve pronouns (“it”, “that ticket”) against the last few turns.
5. Step 3 — control how summaries are written
By default an LLM summarizer does the folding. To pick the model — typically a cheaper, faster one — pass a LlmEventSummarizer:
from google.adk.apps.app import App, EventsCompactionConfig
from google.adk.apps.llm_event_summarizer import LlmEventSummarizer
from google.adk.models import Gemini
summarization_llm = Gemini(model="gemini-flash-latest")
my_summarizer = LlmEventSummarizer(llm=summarization_llm)
app = App(
name="ops-agent-app",
root_agent=root_agent,
events_compaction_config=EventsCompactionConfig(
compaction_interval=10,
overlap_size=2,
token_threshold=4000,
event_retention_size=5,
summarizer=my_summarizer,
),
)
The summarizer prompt itself is customizable (prompt_template on LlmEventSummarizer in Python) — worth doing when your domain needs specific facts preserved: incident ids, file paths, decisions with owners. Everything you do not ask the summarizer to preserve is effectively gone from the model’s view.
6. Step 4 — prove it happened
Compaction is invisible unless you look. The simplest check is the shape of the history the agent sends:
async def history_size(runner, session_service, app_name, user_id, session_id):
session = await session_service.get_session(
app_name=app_name, user_id=user_id, session_id=session_id
)
return len(session.events)
# After turn 10 and again after turn 11:
# turn 10 -> compaction fired in the Runner after invocation 10
# turn 11 -> raw tail starts at the overlap boundary, not at turn 1
Two practical signals to log alongside it:
- Prompt tokens before the model call (from the
LlmRequestin abefore_model_callback) — a sawtooth that drops every 10th turn confirms the window. - The efficiency criteria ADK reports for free —
token_usage_v1,tool_call_count_v1,inference_call_count_v1, andinvocation_duration_v1are emitted automatically with no configuration and never fail an eval, so comparing them across runs catches a “quality flat, tokens doubled” regression.
For a full replay check, capture a session in adk web, open the Trace tab, and read the actual Request sent to the model for any turn — if it starts at turn 1 after your interval, compaction did not run.
7. Tuning table
| Setting | Too small | Too large | Practical starting point |
|---|---|---|---|
compaction_interval | Summarizer overhead every few turns; summaries churn before they stabilize | Prompt grows linearly with turns | 8–12 turns for chat-paced agents |
overlap_size (0 or 1) | Model loses the last exchange; pronoun resolution breaks | Raw tail grows, negating the savings | 1–2 |
token_threshold | Fires constantly, pays summarization tax | Approaches model context limits before folding | 50–75% of your usable window in tokens |
event_retention_size (1–5) | Tail too thin to ground the next answer | Same as overlap_size, in event units | 3–5 for tool-heavy agents |
Three interaction effects worth knowing before you tune:
- Summarization has a cost and a delay. The fold happens after the invocation completes, so the next turn is the first to benefit; the summarizer’s own model call is a real inference cost — which is exactly why pointing it at a Flash-class model matters.
- Compaction and caching pull in opposite directions. Folding rewrites the middle of the history, so cache prefixes from earlier turns will not match afterwards. Cache-friendly and compact are both worth having; just do not expect peak hit rates on turns where a fold landed.
- Compaction is not deletion of record. It rewrites what the model sees; the session’s own bookkeeping (state, artifacts,
output_keyvalues) is untouched, so keep anything auditable instateor an artifact rather than in the transcript.
TypeScript and Go configure the same logic through their own entry points — contextCompactors: [new TokenBasedContextCompactor({ tokenThreshold, eventRetentionSize, summarizer })] on the LlmAgent, and runner.Config{ Compaction: &compaction.Config{...} } in Go.
Checklist
- Set
compaction_interval+overlap_sizeonEventsCompactionConfigfor a predictable turn cadence. - Add
token_threshold+event_retention_sizeas the absolute backstop for oversized turns. - Remember token-based compaction takes priority when both would fire.
- Point
LlmEventSummarizerat a cheap model; the summarizer runs on every fold. - Put durable, verbatim facts in
session.state, not in the transcript. - Verify the interval by inspecting
len(session.events)or the prompt size in the Trace tab. - Track
token_usage_v1andinvocation_duration_v1across releases — they are reported for free. - Re-run trajectory evals after changing interval or overlap; expected turn structure shifts.
- Document your settings for the whole team: interval, overlap, threshold, retention.
Conclusion
Sliding-window compaction turns an unbounded transcript into a bounded working set on a schedule you choose: every compaction_interval invocations, older events fold into a summary while overlap_size recent ones stay raw. Back it with a token threshold for the turns where users paste a codebase, feed the summarizer a model you do not mind paying for, and the cost curve of a 500-turn run goes flat instead of climbing.
The tuning is empirical, not theoretical — instrument prompt size per turn, watch the sawtooth, and adjust interval and overlap until the raw tail is just large enough that pronouns still resolve. Long-running agents stop being expensive at exactly the point where you can see their context.