Context compaction for agents: when to summarise the history and what it saves
An agent resends its whole history every step, so input grows until it hits the context window. Compaction replaces the old history with a summary when the input reaches a trigger. Run the loop to step 150 and watch the sawtooth, the number of compactions and the money saved.
Interactive simulation. It needs JavaScript; the text below explains what it shows.
What you are looking at
The table is a trace of a coding agent that never compacts: for each of its first 40 model calls, the input tokens it sent and the output tokens it wrote. The input grows every step because the model is stateless and each call carries the system prompt, the task and every earlier tool result. The big jumps are file reads and test logs.
The chart shows the recorded inputs as points with a dashed linear fit, the line the full history would follow. The solid sawtooth is the same agent with compaction: the input climbs until it would reach the trigger, falls back to the base prompt plus a summary, and climbs again. The two horizontal dashed lines are the trigger and the context window, and the vertical mark is the step of the first compaction. The bars show the cost of each recorded step, which rises with the input.
Press play to run the agent loop step by step to step 150. The tracked value is the input of the next step, so you can watch it saw up and down.
The algorithm
Fit the growth. A least-squares line through the trace gives the growth per step, g = cov(k, x_k) / var(k), and the fitted first-step input a. The input at step k without compaction is a + g(k − 1).
Find where the window runs out. The last step whose input fits in a window of W tokens is k_max = floor((W − a) / g) + 1.
Compact at the trigger. Before each step, if the input would reach the trigger T, an extra model call reads that history and writes a summary of r tokens. The step then runs on a + r tokens: the base prompt plus the summary. The first compaction happens at k_1 = ceil((T − a) / g) + 1, and after that one comes every m = ceil((T − a − r) / g) steps, because each cycle starts from a + r instead of a.
Count the cost. Each step costs input × p_in + output × p_out. A compaction adds its own call: it reads the full history and writes the summary. The loop adds up both costs and, beside them, the cost of the same steps if the full history had fitted.
Worked example. With the default settings the trace grows by 4,127 tokens a step from 13,874 at the start and reaches 175,000 at step 40. Without compaction the input passes the 200,000-token window after step 46. With a trigger of 150,000 tokens and an 8,000-token summary, the first compaction comes at step 34 (the input would have been 150,055 tokens; it drops to 21,874), and then every 32 steps, at steps 66, 98 and 130. After 150 steps the agent has compacted 4 times and spent $39.56 at $3 and $15 per million input and output tokens, compaction calls included. Had the full history fitted, the same 150 steps would have cost $145.22, so compaction saves 72.8%. Over the 40 recorded steps alone the saving is only 18.5% ($9.37 against $11.49): compaction pays off in long runs.
Things to try
- Lower the trigger to 100,000 tokens. The first compaction moves to step 22, the agent compacts 7 times, and the cost falls to $29.52 (79.7% saved).
- Lower it to the API minimum of 50,000 tokens. The agent compacts 21 times, once every 7 steps, and spends only $21.62. It is cheaper, but every summary loses detail, and 21 summaries of summaries lose a lot.
- Raise the summary size to 20,000 tokens. Each cycle starts higher and is shorter (29 steps), so there are 5 compactions and the run costs $44.33. Set it to 2,000 and the run costs $37.56, if the agent can work from so little.
- Raise the trigger to 190,000 tokens. Only 3 compactions happen, but the run costs $46.72 because most steps carry a long history; a near-full window also leaves little room for the next tool result.
- Set the context window to 1,000,000 tokens. The full history now fits until step 239, but the cost of the full-history run is unchanged: a bigger window postpones the failure, not the bill.
How it works in real systems
The Claude API offers server-side compaction. With threshold compaction you add the compact_20260112 strategy to context_management.edits, and the trigger is an input_tokens value that defaults to 150,000 and must be at least 50,000. The docs state that compaction needs an additional sampling step that counts towards rate limits and billing, and that its usage appears as a separate compaction entry in usage.iterations, not in the top-level token counts: sum the iterations to get the true cost. A custom instructions prompt replaces the default summarisation prompt completely.
The Claude Agent SDK compacts automatically when the context approaches its limit and emits a compact_boundary system message; a PreCompact hook can archive the full transcript first. Because compaction can drop early instructions, the SDK docs recommend keeping persistent rules in CLAUDE.md, which is sent with every request. In LangChain, SummarizationMiddleware takes a trigger such as ("tokens", 4000) or ("fraction", 0.8) and a keep setting that defaults to the last 20 messages, which this model folds into the summary size r.
Real runs differ from the model in three ways. Growth is lumpy, so a trigger well below the window leaves room for one huge tool result. Compaction changes the prompt prefix, so the prompt cache has to be rebuilt after each one. And quality matters more than tokens: a summary that drops a file path or a failed test can cost more steps than it saves. Clearing old tool results, keeping notes in agent memory and handing subtasks to sub-agents are the other tools of context engineering. The agent loop token cost simulation shows why the full-history cost grows with the square of the steps.