Agentic Pattern Libraryby Vikas Goyal
← All patterns
16

Context Compaction

Also known as: context summarization, history pruning, rolling summary

Summarize or prune history so long tasks fit the context window.

TrackAgentic systems FamilyContext & memory Maturity Established ChangesContext
01

Problem

Long-running agents accumulate turns, tool outputs and intermediate results until the context window fills. Before it’s full, quality already drops: the model loses track of early instructions, attends to stale details and gets slower and more expensive with every step.

  • Long tasks need to remember decisions made early on.
  • Most old tool output is no longer relevant.
  • Summaries lose detail that sometimes turns out to matter.
  • Compacting itself takes a model call and time.
02

Solution

Watch context size and compact before it becomes a problem. Keep the essentials verbatim: the task, constraints, key decisions and open items. Replace old turns and bulky tool outputs with short summaries that record what was learned, not the raw data. Drop results that have been superseded. Save full raw history outside the context, in a file or store, so the agent can look up a detail if it needs it later. Trigger compaction at a set threshold, such as 70% of the window, or at natural breakpoints between subtasks.

03

Diagram

before · ~70% full task + constraints key decisions old turns · tool output superseded results Compactat threshold after · ~25% full task + constraints key decisions 1-line summaries room to keep working Raw history storesearchable later keep verbatim save raw

Compaction keeps the decisions and drops the bulk. The raw history moves to storage, so nothing is truly lost.

04

When to use

Use it when

  • Agents run for many steps or hours
  • Tool outputs are large (logs, documents, search results)
  • Early instructions or decisions must stay in force throughout
  • Cost and latency rise noticeably as context grows

Avoid it when

  • Short tasks that never approach the context limit
  • Every detail must stay exact, like legal text under review; use retrieval instead
  • You can't store the raw history for later lookup
05

Trade-offs

Latency Occasional summarization pass; faster steps after
Cost Smaller contexts on every following step
Complexity Thresholds, what to keep, raw-history store
Reliability Good if decisions are kept verbatim; risk of lost detail

Gains

  • Long tasks keep running without hitting the limit
  • Steady cost and latency per step
  • The model stays focused on what currently matters

Costs

  • Details dropped in a summary may be needed later
  • Bad summaries can distort earlier decisions
  • Extra calls and logic to manage
06

Worked example

Scenario
A coding agent spends 3 hours migrating 40 API endpoints to a new authentication library.
  1. Steps 1–60Context grows to about 70% of the window, mostly test output and file contents from endpoints already finished.
  2. CompactionKeeps the task, the rule “never change public response formats”, the chosen token-refresh approach and the 3 open issues word for word. It replaces 25 finished endpoints with one line each, such as “/orders: migrated, 18 tests pass.”
  3. StorageThe full raw log is saved to a progress file. Context drops to about 25% of the window.
  4. Step 140A test fails on /refunds with an error seen earlier. The agent searches the progress file, finds how it fixed the same error on /orders, and reuses the fix.
  5. ResultAll 40 endpoints migrated in one run. Per-step cost stayed flat instead of rising with each step.
07

Failure modes

FailureSymptomMitigation
Lost key decisionAgent reverses a choice made early in the taskKeep decisions and constraints verbatim, never summarized
Over-compressionAgent repeats work because the summary was too vagueRecord what was done and its result, not just "worked on X"
No way back to detailsNeeded detail exists only in the discarded historySave raw history externally and give the agent a search tool for it
Compacting too lateQuality already degraded before compaction runsCompact at a threshold well below the limit, or between subtasks