# 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.

<div data-sim="specx" data-spec="{&#34;head&#34;:&#34;Context compaction: when to summarise an agent&#39;s history and what it saves&#34;,&#34;sub&#34;:&#34;A forty-step coding-agent trace whose input grows every step. Set the compaction trigger and the summary size, then run the agent to step 150 and watch the context saw up and down while the cost stays under control.&#34;,&#34;params&#34;:[{&#34;id&#34;:&#34;trig&#34;,&#34;label&#34;:&#34;Compaction trigger&#34;,&#34;min&#34;:50000,&#34;max&#34;:195000,&#34;step&#34;:5000,&#34;value&#34;:150000,&#34;unit&#34;:&#34;tokens&#34;,&#34;note&#34;:&#34;Summarise when the next input would reach this; the Claude API default is 150,000&#34;},{&#34;id&#34;:&#34;summ&#34;,&#34;label&#34;:&#34;Summary size&#34;,&#34;min&#34;:1000,&#34;max&#34;:30000,&#34;step&#34;:1000,&#34;value&#34;:8000,&#34;unit&#34;:&#34;tokens&#34;,&#34;note&#34;:&#34;Tokens the summary keeps from the old history&#34;},{&#34;id&#34;:&#34;win&#34;,&#34;label&#34;:&#34;Context window&#34;,&#34;min&#34;:100000,&#34;max&#34;:1000000,&#34;step&#34;:10000,&#34;value&#34;:200000,&#34;unit&#34;:&#34;tokens&#34;},{&#34;id&#34;:&#34;pin&#34;,&#34;label&#34;:&#34;Input price&#34;,&#34;min&#34;:0.1,&#34;max&#34;:15,&#34;step&#34;:0.1,&#34;value&#34;:3,&#34;unit&#34;:&#34;$ / M tokens&#34;},{&#34;id&#34;:&#34;pout&#34;,&#34;label&#34;:&#34;Output price&#34;,&#34;min&#34;:0.4,&#34;max&#34;:75,&#34;step&#34;:0.1,&#34;value&#34;:15,&#34;unit&#34;:&#34;$ / M tokens&#34;}],&#34;data&#34;:{&#34;columns&#34;:[&#34;step&#34;,&#34;in_tok&#34;,&#34;out_tok&#34;],&#34;rows&#34;:[[1,14200,310],[2,17300,180],[3,22100,240],[4,24700,420],[5,31600,200],[6,34900,260],[7,37800,190],[8,43200,350],[9,47000,220],[10,49200,280],[11,56800,230],[12,60300,170],[13,63300,400],[14,67500,210],[15,70200,260],[16,76100,190],[17,79400,240],[18,81900,520],[19,90700,200],[20,94300,230],[21,97200,280],[22,101300,210],[23,104500,190],[24,106900,460],[25,113100,250],[26,116800,200],[27,119600,300],[28,124100,220],[29,127200,380],[30,136600,240],[31,139900,180],[32,142500,260],[33,146400,410],[34,151600,210],[35,154300,230],[36,157700,330],[37,162400,190],[38,165300,250],[39,168900,640],[40,175000,520]],&#34;note&#34;:&#34;An illustrative trace of a coding agent with no compaction: input and output tokens of each model call, as exported from LangSmith or Langfuse. Big jumps are file reads and test logs. Paste your own run to fit its growth.&#34;},&#34;pre&#34;:[{&#34;id&#34;:&#34;g&#34;,&#34;label&#34;:&#34;Context growth per step (tokens)&#34;,&#34;expr&#34;:&#34;cov(step, in_tok)/vari(step)&#34;,&#34;fmt&#34;:&#34;i&#34;,&#34;tex&#34;:&#34;g = \\frac{\\operatorname{cov}(k, x_k)}{\\operatorname{var}(k)}&#34;},{&#34;id&#34;:&#34;a0&#34;,&#34;label&#34;:&#34;First-step input, fitted (tokens)&#34;,&#34;expr&#34;:&#34;mean(in_tok) - g*(mean(step) - 1)&#34;,&#34;fmt&#34;:&#34;i&#34;},{&#34;id&#34;:&#34;ybar&#34;,&#34;label&#34;:&#34;Mean output per step (tokens)&#34;,&#34;expr&#34;:&#34;mean(out_tok)&#34;,&#34;fmt&#34;:&#34;i&#34;,&#34;hide&#34;:true},{&#34;id&#34;:&#34;t1&#34;,&#34;label&#34;:&#34;Step of the first compaction&#34;,&#34;expr&#34;:&#34;ceil((trig - a0)/g) + 1&#34;,&#34;fmt&#34;:&#34;i&#34;,&#34;tex&#34;:&#34;k_1 = \\left\\lceil \\frac{T - a}{g} \\right\\rceil + 1&#34;},{&#34;id&#34;:&#34;cyc&#34;,&#34;label&#34;:&#34;Steps between later compactions&#34;,&#34;expr&#34;:&#34;ceil((trig - a0 - summ)/g)&#34;,&#34;fmt&#34;:&#34;i&#34;,&#34;tex&#34;:&#34;m = \\left\\lceil \\frac{T - a - r}{g} \\right\\rceil&#34;},{&#34;id&#34;:&#34;lastfit&#34;,&#34;label&#34;:&#34;Last step that fits without compaction&#34;,&#34;expr&#34;:&#34;floor((win - a0)/g) + 1&#34;,&#34;fmt&#34;:&#34;i&#34;,&#34;tex&#34;:&#34;k_{max} = \\left\\lfloor \\frac{W - a}{g} \\right\\rfloor + 1&#34;}],&#34;row&#34;:[{&#34;id&#34;:&#34;fit_in&#34;,&#34;label&#34;:&#34;fitted input&#34;,&#34;expr&#34;:&#34;a0 + g*(step - 1)&#34;,&#34;fmt&#34;:&#34;i&#34;,&#34;hide&#34;:true},{&#34;id&#34;:&#34;cmp_in&#34;,&#34;label&#34;:&#34;input with compaction&#34;,&#34;expr&#34;:&#34;ifelse(ge(step, t1), a0 + summ + g*((step - t1) - cyc*floor((step - t1)/cyc)), a0 + g*(step - 1))&#34;,&#34;fmt&#34;:&#34;i&#34;,&#34;tex&#34;:&#34;x_k^{c} = a + r + g\\,\\big((k - k_1) \\bmod m\\big) \\quad (k \\ge k_1)&#34;},{&#34;id&#34;:&#34;cost&#34;,&#34;label&#34;:&#34;cost of the step ($)&#34;,&#34;expr&#34;:&#34;(in_tok*pin + out_tok*pout)/1000000&#34;,&#34;tex&#34;:&#34;c_k = \\frac{x_k\\,p_{in} + y_k\\,p_{out}}{10^6}&#34;}],&#34;derived&#34;:[{&#34;id&#34;:&#34;run_cost&#34;,&#34;label&#34;:&#34;Cost of the recorded 40 steps ($)&#34;,&#34;expr&#34;:&#34;sum(cost)&#34;},{&#34;id&#34;:&#34;peak&#34;,&#34;label&#34;:&#34;Largest input in the trace (tokens)&#34;,&#34;expr&#34;:&#34;amax(in_tok)&#34;,&#34;fmt&#34;:&#34;i&#34;},{&#34;id&#34;:&#34;ctx_now&#34;,&#34;label&#34;:&#34;Input of the next step (tokens)&#34;,&#34;expr&#34;:&#34;a0 + e&#34;,&#34;fmt&#34;:&#34;i&#34;},{&#34;id&#34;:&#34;saving&#34;,&#34;label&#34;:&#34;Cost saved by compaction&#34;,&#34;expr&#34;:&#34;1 - spend/max(spend0, 0.000001)&#34;,&#34;fmt&#34;:&#34;p&#34;,&#34;tex&#34;:&#34;\\text{saving} = 1 - \\frac{C_{compact}}{C_{full}}&#34;}],&#34;iterate&#34;:{&#34;state&#34;:[{&#34;id&#34;:&#34;k&#34;,&#34;label&#34;:&#34;Steps run&#34;,&#34;init&#34;:&#34;0&#34;},{&#34;id&#34;:&#34;e&#34;,&#34;label&#34;:&#34;History in the next input (tokens)&#34;,&#34;init&#34;:&#34;0&#34;},{&#34;id&#34;:&#34;ncomp&#34;,&#34;label&#34;:&#34;Compactions so far&#34;,&#34;init&#34;:&#34;0&#34;},{&#34;id&#34;:&#34;spend&#34;,&#34;label&#34;:&#34;Cost with compaction ($)&#34;,&#34;init&#34;:&#34;0&#34;},{&#34;id&#34;:&#34;spend0&#34;,&#34;label&#34;:&#34;Cost without compaction ($)&#34;,&#34;init&#34;:&#34;0&#34;}],&#34;update&#34;:[{&#34;id&#34;:&#34;k&#34;,&#34;expr&#34;:&#34;k + 1&#34;},{&#34;id&#34;:&#34;e&#34;,&#34;expr&#34;:&#34;ifelse(ge(a0 + e, trig), summ, e) + g&#34;},{&#34;id&#34;:&#34;ncomp&#34;,&#34;expr&#34;:&#34;ncomp + ge(a0 + e, trig)&#34;},{&#34;id&#34;:&#34;spend&#34;,&#34;expr&#34;:&#34;spend + (ifelse(ge(a0 + e, trig), (a0 + e)*pin + summ*pout + (a0 + summ)*pin, (a0 + e)*pin) + ybar*pout)/1000000&#34;},{&#34;id&#34;:&#34;spend0&#34;,&#34;expr&#34;:&#34;spend0 + ((a0 + g*k)*pin + ybar*pout)/1000000&#34;}],&#34;max&#34;:150,&#34;per&#34;:1,&#34;track&#34;:&#34;ctx_now&#34;},&#34;chart&#34;:{&#34;title&#34;:&#34;Input tokens per step: full history against compaction&#34;,&#34;x&#34;:{&#34;var&#34;:&#34;t&#34;,&#34;label&#34;:&#34;Step of the agent loop&#34;,&#34;from&#34;:1,&#34;to&#34;:150},&#34;y&#34;:{&#34;from&#34;:0,&#34;to&#34;:300000},&#34;series&#34;:[{&#34;label&#34;:&#34;Full history (linear fit)&#34;,&#34;expr&#34;:&#34;a0 + g*(t - 1)&#34;,&#34;dash&#34;:true},{&#34;label&#34;:&#34;With compaction&#34;,&#34;expr&#34;:&#34;ifelse(ge(t, t1), a0 + summ + g*((t - t1) - cyc*floor((t - t1)/cyc)), a0 + g*(t - 1))&#34;},{&#34;label&#34;:&#34;Compaction trigger&#34;,&#34;expr&#34;:&#34;trig&#34;,&#34;dash&#34;:true},{&#34;label&#34;:&#34;Context window&#34;,&#34;expr&#34;:&#34;win&#34;,&#34;dash&#34;:true}],&#34;points&#34;:{&#34;x&#34;:&#34;step&#34;,&#34;y&#34;:&#34;in_tok&#34;,&#34;label&#34;:&#34;Recorded input tokens (no compaction)&#34;},&#34;mark&#34;:&#34;t1&#34;},&#34;level&#34;:&#34;intermediate&#34;,&#34;bars&#34;:{&#34;title&#34;:&#34;Cost of each recorded step without compaction ($)&#34;,&#34;y&#34;:&#34;cost&#34;,&#34;label&#34;:&#34;step&#34;},&#34;steps&#34;:[{&#34;title&#34;:&#34;Measure how fast the context grows&#34;,&#34;text&#34;:&#34;Every step resends the whole history plus the new tool result. In this trace the input grows by about {g} tokens a step from {a0} at the start, and reaches {peak} by step 40.&#34;,&#34;show&#34;:[&#34;g&#34;,&#34;a0&#34;,&#34;peak&#34;]},{&#34;title&#34;:&#34;See where the window runs out&#34;,&#34;text&#34;:&#34;Without compaction the fitted input passes the {win}-token window after step {lastfit}: the run would fail there, however well it was going.&#34;,&#34;show&#34;:[&#34;lastfit&#34;]},{&#34;title&#34;:&#34;Compact at the trigger&#34;,&#34;text&#34;:&#34;When the next input would reach {trig} tokens, an extra model call reads the history and writes a {summ}-token summary. That first happens at step {t1}.&#34;,&#34;show&#34;:[&#34;t1&#34;]},{&#34;title&#34;:&#34;Restart from the summary&#34;,&#34;text&#34;:&#34;The next step sends the system prompt, the task and the summary, then grows again by {g} tokens a step, so a new compaction comes every {cyc} steps.&#34;,&#34;show&#34;:[&#34;cyc&#34;]},{&#34;title&#34;:&#34;Run the loop and count the cost&#34;,&#34;text&#34;:&#34;After {k} steps the agent has compacted {ncomp} times. It has spent ${spend}, including the compaction calls, against ${spend0} if the full history had fitted: {saving:p} saved.&#34;,&#34;show&#34;:[&#34;ncomp&#34;,&#34;spend&#34;,&#34;spend0&#34;,&#34;saving&#34;]},{&#34;title&#34;:&#34;Pay for it in detail&#34;,&#34;text&#34;:&#34;Each summary drops detail from the old steps. A lower trigger is cheaper but summarises more often; the next input is now {ctx_now} tokens.&#34;,&#34;show&#34;:[&#34;ctx_now&#34;]}]}"><p>Interactive simulation. It needs JavaScript; the text below explains what it shows.</p></div>

## 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](/tools/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](/ai-simulations/prompt-cache-hits-agent-session) 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](/tools/agent-memory) and handing subtasks to [sub-agents](/tools/sub-agents) are the other tools of [context engineering](/tools/context-engineering). The [agent loop token cost](/ai-simulations/agent-loop-token-cost) simulation shows why the full-history cost grows with the square of the steps.

## Sources

- [Claude API docs: Threshold compaction](https://platform.claude.com/docs/en/build-with-claude/compaction-threshold)
- [Claude API docs: Compaction](https://platform.claude.com/docs/en/build-with-claude/compaction)
- [Claude Agent SDK docs: How the agent loop works](https://code.claude.com/docs/en/agent-sdk/agent-loop)
- [LangChain docs: Built-in middleware](https://docs.langchain.com/oss/python/langchain/middleware/built-in)
