Agent Token Sprawl: Memory Design and Cost Governance

    Rising agent token usage does not by itself prove better outcomes. This article explains how to separate interaction logs, long-term memory, and runtime context; how to extract, compress, and retrieve information with permissions and conflict checks; and how observability, execution state, and evaluation close the loop so cost maps to successful tasks rather than wasted work.

    What rising token usage actually means

    When an agent system’s token consumption grows quickly, a common assumption is that more people are using it and that it is completing more complex work. Volume of consumption only shows that the system performed more model computation. It does not, by itself, prove task quality, user satisfaction, or engineering maturity.

    Without a defined scope, time window, and accounting method, “highest consumption” is not a technical conclusion. Whether counts include input and output, all model calls, failed retries, and background jobs all change the result.

    From an engineering view, growth usually comes from two sources:

    • More useful work: more users, longer task chains, harder reasoning, or more business material to process.
    • More wasted work: repeatedly carrying history, retrieving large amounts of irrelevant information, oversized tool results, repeated retries, and no clear signal that a task is done.

    The question worth asking is not “how many tokens were used,” but how much of that usage turned into successfully completed tasks.

    For developers, agent competitiveness is a balance of quality, cost, latency, and safety—not a single consumption metric.

    Saving every conversation is not long-term memory

    Many agents write interactions to a local database or remote store. Typical records include session IDs, user IDs, message bodies, model configuration, prompt snapshots, tool arguments, tool results, and execution time and status.

    That design mainly supports traceability: how a task started, which steps ran, and why it failed can be reconstructed. It does not mean the system automatically has stable, accurate long-term memory.

    Three concepts need to be kept separate.

    1. Interaction logs: what happened

    Logs usually store raw events in time order. They are useful for audit, debugging, and replay.

    Their value is completeness, which also means duplication, stale data, temporary guesses, and sensitive content. Treating logs as memory makes retrieval and context assembly harder.

    Without retention, archival, and cleanup, logs grow without bound. That is a storage-policy outcome, not proof that every agent database grows forever.

    2. Long-term memory: information still useful later

    Long-term memory is filtered, structured, and governed: confirmed output preferences, project constraints, verified facts, and reusable task experience.

    It should not store only a conclusion. Prefer also recording source, scope of applicability, update time, and validity. For example, “use a concise report format” may apply to one project, not every task for that user.

    3. Runtime context: what this call actually sees

    Runtime context is what the model receives on this call: system constraints, the current request, recent messages, recalled memory, and necessary tool results.

    Even if the database holds full history, the model cannot use it unless the right information is retrieved and placed in the current context.

    “Recorded,” “findable,” and “used correctly” are three different things. Apparent forgetting often happens in retrieval or context assembly, not storage.

    Continuous improvement must be a verifiable mechanism

    Saving history does not automatically change model weights. For most application-layer agents, “getting better with use” comes from memory updates, preference extraction, reuse of task experience, and policy changes—not from training after every conversation.

    That improvement involves at least four steps:

    Discover information → judge value → update memory → use it correctly on later tasks.

    Failure in any step weakens the effect. For example:

    • The user corrects a fact, but old memory is not updated.
    • New information is saved without marking old information invalid.
    • Retrieval finds the right record but also contradictory historical conclusions.
    • The model sees a constraint and still ignores it when generating.

    Evaluating continuous improvement is not counting memory entries. Check whether corrections take effect, conflicts drop, and similar tasks actually complete better.

    Why agents remember the wrong things

    Raw interaction mixes facts, preferences, hypotheses, emotion, and one-off instructions. If the system judges importance with keywords or a single summary, it easily confuses them.

    “Don’t write this one in too much detail” is a current-task constraint. “Documents submitted for review should always include a risk list” may be a lasting preference. Both are requests; their scope differs.

    More reliable extraction should consider at least these dimensions:

    Dimension Question to answer
    Information type Fact, preference, constraint, or unverified speculation?
    Scope This task only, this project, or this user?
    Source credibility User confirmation, reliable material, or model inference?
    Time validity Does it change over time? Does it need periodic review?
    Conflicts Does it override or negate existing memory?
    Sensitivity Should it be stored, and who may access it?

    For critical constraints, ask the user to confirm long-term storage. Treat model-inferred preferences more cautiously so one-off behavior is not frozen into a lasting profile.

    The goal of memory governance is not “store as much as possible,” but “store information that is evidenced, updatable, and revocable.”

    Context compression is not only about being shorter

    Context windows are limited while history, business documents, and tool returns can keep growing. Compression is necessary, and it loses information.

    A common approach is replacing older turns with a summary. That cuts input size but can drop exception conditions, negation, units, or decision rationale.

    Compressing “proceed only after approval and sufficient inventory” into “proceed after approval” removes an important precondition. The summary is shorter; the business meaning has changed.

    A more reliable layout is layered:

    1. Recent raw turns: keep recent critical interaction so the current task stays continuous.
    2. Task state: goal, completed steps, remaining work, blockers, and stop conditions.
    3. Confirmed facts: verified conclusions and constraints that must not be lost.
    4. Historical summary: background and staged progress so the story remains understandable.
    5. Original evidence: citations or locators so key content can be reopened.

    Task state should not rely only on free-text summaries. Maintaining explicit state such as “approved or not” and “which step we are on” reduces guesswork and repeated execution.

    After compression, check that goals, constraints, negations, numbers, units, open issues, and evidence sources remain. For high-risk work, keep relevant original text rather than always minimizing context.

    History recall needs relevance and boundaries

    Retrieval should not maximize the number of past messages. It should find what helps the current task and that the current user is allowed to access.

    Keyword-only search can miss the same idea phrased differently. Semantic similarity alone can surface thematically close content with different conditions. Combine structured filters, keyword match, and semantic retrieval, then rank candidates further.

    A typical flow:

    Current request → identify task scope → permission filter → multi-path retrieval → conflict and freshness checks → rank and deduplicate → assemble context under budget.

    Three details are easy to miss.

    1. Apply permissions early

    In multi-user, multi-project, or multi-tenant systems, access control should not wait until the final answer. Candidates should be filtered before retrieval and ranking so other users’ history never enters the current task.

    2. Similar is not valid

    A past solution may target an old process; preferences may have changed. Recalled items should carry source, time, and scope—not a decontextualized snippet.

    3. Have a policy when retrieval fails

    If there is no reliable memory, ask the user, re-query business data, or state uncertainty. Do not invent facts from vague history.

    Long-term memory is supporting information. It should not be treated as more authoritative than current business facts by default.

    Why cost grows across multi-step runs

    A typical model input includes:

    Fixed instructions + current request + recent dialogue + recalled memory + tool results + necessary execution state.

    Across turns, some of that is sent again. If each turn adds a similar-length message and every call resends the full prior history, with no truncation or compression, cumulative input can grow roughly quadratically.

    A long tool result therefore costs more than the call that first returned it. If it stays in context, it can affect every later call.

    Actual spend depends on model class, input/output pricing, and caching. A single unit price does not cover all cases.

    Cost control can follow four directions:

    • Control input: limit recall count, drop duplicates, trim material to the current task.
    • Control output: bound the answer; avoid long content unrelated to the task.
    • Control execution: call budgets, retry caps, timeouts, and stop conditions.
    • Split work: give deterministic programs well-specified steps; reserve the model for understanding and judgment.

    Tool returns should put necessary information first. Queries can return a summary, key fields, and locators, then load detail on demand. Those summaries must keep error states and required constraints; do not hide failures to save tokens.

    Repeated tool calls are often a state problem

    Repeating queries or actions does not always mean the model is weak. Common causes include:

    • Tool results that do not clearly distinguish success, failure, and partial success.
    • Timeouts with no confirmation whether the action completed.
    • Current state not persisted.
    • No explicit completion criteria.
    • Retries that do not separate retryable from non-retryable errors.
    • Historical results compressed away so the system thinks the step never ran.

    For actions with external effects, emphasize idempotency. A second submission of the same business operation should recognize an existing result or enter a clear verification path, not blindly run again.

    When budget or execution limits are hit, do not drop the task silently. A better degradation is to save progress, state what finished, why the rest did not, and a next step—and continue after user confirmation if needed.

    Observability shows which layer failed

    A total bill cannot explain why cost grew. A final answer cannot explain why the system “forgot.”

    For each task, consider recording:

    • Model call count, input/output tokens, and stage latency.
    • Tool names and types, call status, retries, and payload size.
    • Memory query conditions, candidate count, items actually used, and sources.
    • Information size before and after compression, and whether key constraints survived.
    • End state and reason for ending.
    • Human takeover, user corrections, and failure types.

    Observability records also need redaction and access control. Do not copy all sensitive content into logs for debugging.

    With that data, debug by layer:

    • Information never stored: write and extraction paths.
    • Stored but not found: indexes, filters, recall strategy.
    • Found but not included: context budget and assembly rules.
    • Included but used wrongly: conflicts, wording, and whether the model followed instructions.
    • Succeeded but ran again: state persistence, result confirmation, retry policy.

    Layered diagnosis beats swapping models or blindly enlarging context.

    Measure whether memory is actually useful

    After long-term memory ships, regress on a fixed task set. Do not rely on a few smooth conversations.

    Cover lasting preferences, new-vs-old fact conflicts, irrelevant memory noise, cross-project isolation, user deletion, oversized tool results, interrupt-and-resume, and duplicate submissions.

    Core metrics can include:

    • Task success rate: whether predefined acceptance criteria are met.
    • Recall quality: needed information found; irrelevant information kept out.
    • Correction effectiveness: updated facts replace old conclusions.
    • Cost per successful task: total cost over a period divided by successful tasks.
    • Repeat-execution rate: unnecessary queries, retries, or external actions.
    • End-to-end latency: time from request to a usable result.
    • Permission incidents: unauthorized retrieval, out-of-scope citation, or sensitive leakage.

    Also compare “no long-term memory,” “structured preferences only,” and “full memory pipeline.” Expanding memory is justified only when quality gains cover extra cost and risk.

    Conclusion: from consumption volume to useful output

    Higher token use may mean harder work, or it may mean the system is repeatedly processing useless information. Scale alone cannot tell which dominates.

    A mature system distinguishes raw logs, long-term memory, and runtime context, and connects extraction, compression, recall, permissions, execution state, and cost budgets into one path.

    Moving from “it runs” to “it delivers reliably” is not saving all history or letting the model think without limit. It is giving every memory a source, every call a purpose, every task a boundary, and every cost an explanation.