Skip to main content

Context Compaction: Working Memory for AI Agents

Managing working memory in multi-step agent loops without breaking prefix KV caching

Updated 7 min readMarkdown

If you have ever watched an AI coding agent work on a real task, you have probably seen this pattern: the first five steps are sharp and accurate, the next ten get noticeably slower, and by step twenty the agent forgets your original instructions or crashes with a context limit error.

The model did not suddenly get worse at reasoning. Its working memory got polluted.

In most basic agent loops, conversation history is just an append-only list. Every user prompt, assistant reply, file read, search result, and terminal log gets pushed onto the end of that list and the entire list gets sent back to the model on every single turn.

Managing that growing history without breaking the agent's train of thought is called context compaction.


Why Append-Only History Breaks Down

A single file read or test run can easily dump 3,000 to 10,000 tokens into the conversation. Over 15 or 20 steps, an unmanaged message list causes three predictable failures:

  • Attention drift ("lost in the middle"): Language models pay the most attention to the very beginning and the very end of a prompt. When 40,000 tokens of stale terminal logs pile up in the middle, the model starts missing rules you gave it at the start.
  • Rising latency and cost: Because every turn re-sends the full history, step 20 pays to re-process everything from steps 1 through 19. Tasks slow down and token costs compound quickly.
  • Hard crashes: Even large context windows have a ceiling. One massive grep output or stack trace can push the request over the limit and kill the run mid-task.
U-shaped attention curve showing high LLM focus on the system prompt at the start and recent turns at the end, with steep recall drop-off across stale logs in the middle

Why Naive Fixes Fail

When developers first hit token limits, they usually reach for one of two quick fixes. Both create new bugs.

1. Dropping the Oldest Messages (Sliding Window)

The simplest approach is to keep only the last N messages and delete older ones. The problem is that the oldest messages hold your system prompt, original goal, and key constraints. Once those fall off the window, the agent loses track of what it is actually trying to build.

2. Blindly Truncating Long Outputs

Another common shortcut is cutting off tool outputs at a fixed character count. Say, keeping only the first 2,000 characters of a terminal log. In practice, the useful signal (like the actual error message at the end of a build log or stack trace) sits at the bottom, so blind slicing throws away the exact detail the model needed.


How Context Compaction Works

A better way to design agent memory is to treat the context window like RAM, not a permanent log file. Active work stays hot and detailed; older work gets compressed or cleared out once it has served its purpose.

Building a reliable compaction loop comes down to four mechanics.

Before-and-after diagram showing a bloated append-only message list compressed into a system prompt, structured state checkpoint, pruned tool output stubs, and recent turns

1. Trigger Early With a High-Watermark Threshold

Do not wait for the API to throw a token-limit error. Before every model call, estimate the total tokens in the current message list. Once usage crosses a safe threshold, typically 75% to 80% of the model's context window, run compaction first.

Leaving that 20–25% buffer guarantees the model always has room to read a large file or write a detailed response on its next turn.

2. Prune Stale Tool Outputs First

Not all tokens age at the same rate. Raw tool payloads (full file contents, directory listings, search dumps) take up the most space and lose their value the fastest. Once the agent has read a 600-line file and decided what to edit, those 600 lines do not need to stay in history forever.

Instead of deleting the message completely, replace the bulky output with a short placeholder:

[Contents of src/config.ts omitted after reading]

Keeping the original tool call and this lightweight stub is an important detail: the agent still sees that it already inspected src/config.ts, so it does not waste turns reading the same file again.

3. Summarize Old Turns Into a State Checkpoint

For older conversational turns that still contain useful decisions, run a focused summarization step. Rather than asking the model for a vague "summary of the chat so far," force the output into a strict state structure:

  • Primary goal: What the user originally asked for.
  • Completed work: Steps already finished and verified.
  • Modified files: Which files were created or edited.
  • Current state & blockers: What still needs to be done or fixed.

This checkpoint replaces the older middle section of the conversation, while the system prompt at the top and the most recent 4 to 6 turns at the bottom remain untouched. The agent keeps both its long-term direction and its immediate short-term context.

4. Respect Message Pairing Rules

Most LLM APIs enforce strict structural rules on message history. In particular, an assistant message requesting a tool_call must always be followed immediately by its matching tool_result message.

If compaction slices the message array right between a tool_call and its tool_result, the next API request will fail validation. Any compaction boundary has to move cleanly around complete interaction pairs.


Why You Should Not Compact on Every Turn

A tempting mistake is to summarize or prune history after every single step to keep the prompt as small as possible. In practice, that backfires because of how LLM inference engines use prefix KV caching.

Providers cache the internal attention states of your prompt from the very first token onward. When you only append new messages to the end of the conversation, the engine reuses the cached prefix, charging a fraction of the normal input token rate and responding much faster.

If you summarize or edit earlier messages on every turn, you change the prefix. Prefix matching stops at the very first altered token, invalidating the cache for the rest of the prompt and forcing you to pay full uncached input rates on every step.

Strategy Tokens Sent / Turn KV Cache Behavior Relative Input Cost (10 Turns)
Append-only + batch compaction ~40,000 Prefix stays cached across turns ~1x (Baseline)
Summarize on every turn ~25,000 Prefix mutates every turn (0% cache hits) ~3x higher (+ summary calls)

The fix is batch compaction: keep the conversation strictly append-only until it hits your high-watermark threshold, rewrite and prune everything in a single checkpoint pass, and then let the new prefix stay cached for the next stretch of turns.

Sawtooth graph showing token usage growing across append-only KV-cached turns until hitting the 75–80% high-watermark threshold, then dropping after a single batch compaction pass

The Core Trade-Off

Context compaction is lossy compression. If you compact too aggressively, the agent forgets subtle details and wastes turns re-reading files it already checked. If you compact too late, noise builds up and reasoning quality drops.

The goal is not to preserve every raw byte of history—it is to preserve decisions and state while discarding raw bulk once it has been processed.

Larger context windows will keep arriving, and they help. But throwing more memory at an unbounded loop only delays the problem. Reliable long-running agents come from treating context as a finite resource and managing it deliberately.

No comments yet. Be the first to comment.