Context Management in LLM Agents: Metering, Compaction, Spilling, and Pruning

    This article provides a deep dive into context management mechanisms for LLM-based agents. It explains why the context window must be treated as a scarce resource, uses real token usage data from a three-step task to illustrate how prefix caching works, and breaks down four complementary mechanisms—metering, compaction, spilling, and pruning—that together form a layered defense for keeping agent sessions within budget while preserving critical information.

    Context Management in LLM Agents: Metering, Compaction, Spilling, and Pruning

    Introduction: Why Context Management Is Essential for Agent Systems

    When you build agents that execute multi-step tasks with large language models, you quickly run into a fundamental problem: the model’s context window is finite, but the agent’s conversation history grows without bound. Every tool call produces new results, and every reasoning step appends new messages. Left unmanaged, the session will eventually exceed the window limit, causing request failures or the truncation of critical information.

    Even with a very large window—some models claim support for a million tokens—“it fits” does not mean “it works well.” Ultra-long contexts mean higher inference costs, slower responses, and the “lost in the middle” problem, where the model’s attention to information in the middle of the context degrades. A mature agent runtime framework (harness) must therefore treat context as a scarce resource to be actively managed, rather than passively piling up historical messages.

    A complete context management solution in common engineering practice typically consists of four mechanisms working together: Metering, Compaction, Spilling, and Pruning. Based on a real four-stage pipeline implementation (corresponding to four independent functional modules) and measured token data, this article breaks down each of these mechanisms.

    1. The Token Ledger of a Single Task

    The best way to understand context management is to observe how tokens flow through a real task.

    Take a demo task with only three model calls. The number of input tokens per request shows a very interesting pattern:

    • Step 1: about 4,400 input tokens. The system prompt, tool definitions, and the initial user request are all sent for the first time—a “full cold start.”
    • Step 2: new input drops sharply to about 380 tokens, while roughly 4,480 tokens are reported as cache reads.
    • Step 3: new input falls further to about 130 tokens, with roughly 4,860 tokens read from cache.

    Why does new input drop by an order of magnitude at step 2? The answer is prefix caching, a feature widely supported by mainstream inference services: as long as the prefix of the current request is byte-for-byte identical to the previous one, the provider can reuse the cached KV (Key-Value) representations and only compute the incremental new portion. The only difference between step 1 and step 2 is the tool result appended after the previous step, so the new portion is just a few hundred tokens. The system prompt, tool definitions, and existing history—over four thousand tokens—all hit the cache, accelerating inference and avoiding repeated billing.

    This ledger gives us two key insights:

    1. Keep the session prefix stable. Any rewrite, reordering, or insertion into historical messages breaks prefix consistency and invalidates large portions of the cache. This is why compaction must be designed carefully—once compaction rewrites early content, all subsequent cache entries may be invalidated.
    2. Tokens are a precisely measurable, billable resource that can be optimized. This leads to the first mechanism: metering.

    2. Metering: Token Measurement Is the Prerequisite for All Optimization

    There is no optimization without measurement. The metering module’s job is to accurately estimate, before each request, how many tokens that request will consume and where the session’s cumulative usage stands.

    Key engineering points:

    • Combine estimation with calibration. Local token estimation typically uses a tokenizer aligned with the target model’s vocabulary. If the model provider does not disclose tokenizer details, you can use an approximate tokenizer plus an empirical coefficient, and continuously calibrate the error against the actual usage field returned by the API.
    • Separate structural overhead from dynamic overhead. The system prompt and tool definitions are relatively fixed structural costs; historical messages and tool results are dynamically growing costs. Tracking them separately tells you which part to act on.
    • Drive decisions with watermarks. The metering module outputs more than just numbers—it provides trigger conditions for downstream mechanisms, such as “current usage is 78%, compaction is about to trigger.”

    3. Compaction: Summarizing Old Content at 80% Usage

    When metering reports that usage has crossed a threshold (commonly set around 80% of the window capacity in practice), compaction kicks in: earlier historical messages are handed to the model (or to rules) to produce a summary, which replaces the original history and frees up space.

    The core tension in compaction design is the trade-off between information fidelity and space reclamation:

    • The summary must preserve the task goal, decisions already made, and key constraints, while discarding chit-chat, redundant reasoning, and intermediate steps that have been superseded by later results.
    • Compaction points should be chosen at semantic boundaries (e.g., after a subtask completes), rather than cutting off mid-conversation.
    • Be aware of the side effect: as described in Section 1, rewriting history breaks the prefix cache. Compaction should therefore be “batched and infrequent”—each pass should free enough space to avoid frequent re-triggering.
    • After compaction, mark the summary with a special role (e.g., a system-level “history summary” message) and retain its generation timestamp and coverage range for debugging and auditing.

    4. Spilling: Writing Oversized Tool Results to Disk with a Head-and-Tail Preview

    Compaction addresses “the history as a whole is too long,” but sometimes a single tool return is enough to blow the budget—for example, reading a large file or a query returning tens of thousands of log lines. For these single oversized results, the spill mechanism is more effective:

    1. When a tool result exceeds a preset threshold, write the full content to a local disk file;
    2. Keep only the first and last few lines in the session as a preview, along with a note that “the full content has been persisted to a given path and can be read on demand in pages”;
    3. If the agent later needs details, it can call the tool again to read specific segments by page number or offset.

    This design borrows the paging concept from operating systems: swap infrequently used bulk data out of memory while keeping an index and a small amount of hot data. It gives the agent the ability to handle outputs of arbitrary size while keeping the session compact. Implementation concerns include lifecycle management of persisted paths (cleanup after the task ends), permission control on the read tool, and the preview selection strategy—head-and-tail previews usually carry higher information density than random excerpts.

    5. Pruning: Turning Over-Budget Tool Results into “Head + Omission + Tail”

    Spilling targets “exceptionally large” results, while pruning handles the middle ground—results that exceed the budget but are not big enough to warrant disk persistence: directly truncate the tool result structurally, keeping a number of tokens at the beginning and end, with an explicit omission marker in between.

    Pruning looks simple, but a few details determine its effectiveness:

    • Keeping the tail matters. For log-like outputs, the critical information is often at the end (error stacks, final status); truncating only the head loses the most valuable part.
    • Make the omission marker explicit. Use a placeholder like “[N tokens omitted in the middle]” to inform the model that truncation occurred, preventing it from assuming the content is complete and drawing wrong conclusions.
    • Make budgets configurable. Different tools have different reasonable budgets—retrieval results and file-read results should have separate thresholds.

    6. How the Four Mechanisms Work Together

    Viewed together, the four mechanisms form a clear layered defense:

    Mechanism Target Trigger Recoverability
    Metering Global Every request Lossless (observation only)
    Pruning Single tool result Exceeds per-item budget Not recoverable
    Spilling Oversized tool result Exceeds spill threshold Readable on demand
    Compaction Entire history Watermark over threshold (e.g., 80%) Irreversible summarization

    Metering is the eyes, continuously providing usage data; pruning and spilling act as gatekeepers the moment data enters the session; compaction is the last line of defense on total volume. When implementing this in your own agent framework, you can follow the same approach: first establish an observable token ledger, then add mechanisms in the order of “entry throttling → layered handling → total-volume backstop,” while always respecting the stability constraints of the prefix cache.

    Conclusion

    No matter how large the context window is, it remains a finite resource. Metering, compaction, spilling, and pruning do not depend on any specific model or platform—they are a general engineering methodology for building reliable agent systems. By understanding how tokens flow through the ledger, we can find the balance between cost, latency, and information fidelity that fits our own business, enabling agents to not only finish long tasks, but finish them well.