Managing High Token Consumption in AI Agents: State Governance Practices

    High Token consumption in agent applications is rarely just a modeling problem—it usually reflects poor state management. This article explains why Token usage climbs across multi-turn sessions, how unbounded state persistence and missing observability compound the issue, and how to fix it with layered hot/warm/cold state architecture, event-stream data modeling, context compression, lifecycle policies, retrieval isolation, fine-grained metrics, and budget controls. It also provides a six-phase implementation roadmap and highlights common pitfalls to avoid, so teams can reduce cost while preserving agent reliability and recoverability.

    1. Problem Background: Rising Token Consumption Isn’t Just “More Model Calls”

    After agent applications move into real business scenarios, a common phenomenon appears: individual tasks don’t look complicated, yet overall Token consumption rises quickly. Many teams initially attribute this to increased model call counts or overly long prompts. But if you break down the system’s execution chain, the deeper causes usually come from three areas.

    First, more conversation turns cause context to accumulate continuously. To complete a task, an agent often goes through multiple rounds of reasoning, tool calls, result validation, and re-planning. Each round may carry historical messages back into the context. Without a proper trimming mechanism, Token consumption grows roughly linearly—or even faster—with the number of turns.

    Second, state information is over-persisted. Some agent frameworks write sessions, tool call records, intermediate results, user inputs, and system feedback—all of it—into the local state database. In the short term, this helps restore context and trace issues; over the long term, without a cleanup strategy, the database keeps growing, slowing reads and writes, increasing backup costs, and amplifying privacy and compliance risks.

    Third, observability is missing. Many systems can only see total Token consumption, but cannot answer questions like “which session types consume the most,” “which tool calls are repeated most often,” or “which historical fragments are never used again.” Without fine-grained metrics, optimization relies only on experience and cannot form a closed loop.

    Therefore, the core of governing high Token consumption is not simply compressing prompts, but establishing a full lifecycle management mechanism for agent runtime state.

    2. Root Causes of State Bloat: From “Save Everything” to “Save on Demand”

    An agent system typically needs to store several types of state: session identifiers, source channels, user inputs, model outputs, tool call parameters, tool results, error messages, timestamps, retry counts, context summaries, and so on. Saving all of these indiscriminately causes three problems.

    2.1 Severe Data Redundancy

    The same piece of information can appear in multiple places. For example, a user question may be stored in the original message, in the context window, and again in a summary field. Tool call results may exist simultaneously in a temporary cache and in the persistent database. Redundancy not only wastes storage but also causes duplicate loading during session recovery.

    2.2 Unclear Lifecycles

    When data is created, there’s often no clear definition of “how long to keep it, who can access it, and when to delete it.” Debug logs might only need to be kept for a few hours, while business audit data may need to be retained much longer. If all data shares the same lifecycle, the system either retains data too long or accidentally deletes critical data.

    2.3 Mismatched Access Patterns

    Session recovery requires low-latency reads of recent state, while historical analysis is more about batch statistics. If all data sits in one state store, online requests get slowed by historical data, and offline analysis may scan too many irrelevant records.

    Therefore, the first step of state governance is shifting from “save everything” to “layered storage, on-demand access, and expiry-based cleanup.”

    3. Architecture Design: State Layering and Hot/Cold Separation

    A mature agent state architecture typically distinguishes hot, warm, and cold state.

    Hot State

    Hot state serves real-time inference for the current session, demanding low latency and high reliability. It usually holds only the most recent rounds of messages, the current task goal, key variables already obtained, and the pending tool call queue. Hot state should not be too large, or it will significantly increase context length and inference cost.

    Warm State

    Warm state supports recent session recovery, issue tracking, and short-term analysis. It stores structured event streams such as user requests, model responses, tool call summaries, and exception records. Warm state fits well in a database with fast queries and should have a short retention period.

    Cold State

    Cold state serves long-term auditing, offline analysis, and model optimization. It is usually large in volume and rarely accessed, making object storage or archival storage a good fit. Cold data should be desensitized, compressed, and indexed to avoid directly exposing raw sensitive content.

    With this layering, the system balances performance, cost, and traceability. A schematic structure:

    1. Online inference layer
    2. ├─ Current context window
    3. ├─ Recent tool result summaries
    4. └─ Task state machine
    5. Short-term state layer
    6. ├─ Session event streams
    7. ├─ Call chain indexes
    8. └─ Exceptions and retry records
    9. Long-term archive layer
    10. ├─ Desensitized interaction samples
    11. ├─ Aggregated statistics
    12. └─ Minimal audit fields

    4. Data Model: Replace “Big Object Stacking” with Event Streams

    One reason state stores bloat is that complete sessions are repeatedly overwritten as a single large object. A better approach is an event-stream model: every user input, model output, tool call, and state change is recorded as an immutable event.

    The event-stream model has several advantages.

    First, traceability. Each event has a unique ID, timestamp, session ID, and event type, making it easy to locate issues.

    Second, replayability. By replaying events, you can reconstruct the session state at any point in time, without relying on a single snapshot.

    Third, trimmability. Different events can have different retention policies—for example, raw tool returns keep only a summary, and error stacks keep only essential fields.

    A simplified event structure:

    1. {
    2. "event_id": "evt_001",
    3. "session_id": "s_123",
    4. "type": "tool_result",
    5. "timestamp": "2026-01-01T10:00:00Z",
    6. "payload": {
    7. "tool": "search",
    8. "status": "success",
    9. "summary": "Returned 3 candidate results"
    10. },
    11. "retention": "7d"
    12. }

    The key point here: what gets persisted should be “the minimum information needed for recovery,” not all raw content written indiscriminately.

    5. Context Compression: Not “the Shorter the Better,” but Preserve Decision-Critical Information

    Context compression is often misunderstood as simple truncation. In reality, the goal is to preserve key information that affects subsequent decisions while removing low-value duplicate content. The following strategies can be used.

    5.1 Sliding Window

    Keep only the most recent N rounds of complete dialogue, summarizing earlier content. This suits scenarios with frequent interactions and rapidly changing task goals.

    5.2 Task Summaries

    Compress completed subtasks into structured summaries covering goals, constraints, tools already called, key conclusions, and unresolved issues. This reduces Tokens while maintaining task continuity.

    5.3 Tool Result Summarization

    Tool returns often contain many irrelevant fields. Keep only call status, key fields, error codes, and referenceable snippets. For example, search results should keep titles, link summaries, and relevance scores—not full page content.

    5.4 Deduplication and Merging

    Templatize repeatedly occurring system prompts, fixed instructions, and identical tool descriptions to avoid carrying them every round. Merge similar user questions into a single intent node.

    Note that compression must not break recoverability. It’s better to keep “pointers to raw data” rather than the raw data itself. For example, a summary records the original event IDs, and raw data can be fetched on demand when needed.

    6. Lifecycle Management: Give Data a Clear Birth, Usage, and Exit

    State governance must include lifecycle policies. Different data types can have different retention periods:

    • Current session context: clean up or convert to a summary after the session ends.
    • Tool call details: retain for hours to days for troubleshooting.
    • Raw user input: desensitize or shorten retention according to compliance requirements.
    • Model outputs: retain for quality evaluation, but limit field sizes.
    • Errors and retry records: retain for stability analysis, avoiding unbounded growth.
    • Audit data: keep only the minimal necessary fields and apply a long-term archival policy.

    Lifecycle management can be implemented with scheduled tasks, or by writing expiry times at insertion. Schematic pseudocode:

    1. def store_event(event):
    2. event["expire_at"] = now() + retention_policy(event["type"])
    3. db.insert(event)
    4. def cleanup_expired():
    5. db.delete("expire_at < now()")
    6. archive_if_needed()

    The key principle: design for deletion at write time, rather than remediating after the database has already ballooned.

    7. Retrieval and Isolation: Keep Historical Data from Slowing Down the Online Path

    When the state store grows, online requests suffer most from full-table scans. Indexes and isolation are needed.

    7.1 Index by Session

    The most common query is restoring context by session, so the session identifier should be a core index.

    7.2 Partition by Time

    Historical data can be partitioned by day or week, making bulk deletion and archiving easy.

    7.3 Read/Write Separation

    Online inference reads only hot state and the necessary warm state; historical analysis goes through a separate query channel to avoid mutual interference.

    7.4 Summary First

    When restoring context, load summaries and key variables first, and only fetch raw events when explicitly needed.

    This significantly reduces per-request data loading and also cuts context Token consumption.

    8. Observability: Without Metrics, There Is No Optimization

    To govern Token consumption, you must build fine-grained monitoring. At minimum, track:

    • Total Tokens per session
    • Average Token increment per turn
    • Context hit rate
    • Tool call repetition rate
    • Average tool return size
    • State store growth rate
    • Expired-data cleanup success rate
    • Summary compression ratio
    • Session recovery latency
    • Exception retry count

    Furthermore, group statistics by scenario, channel, task type, and model version. This reveals the sources of high consumption—for example, a certain tool returning oversized payloads, certain prompts being repeatedly carried, or certain tasks retrying excessively.

    In cloud environments, you can build this observability stack using common capabilities such as log services, monitoring and alerting, and object storage. For example, on Baidu AI Cloud, a common approach is to manage runtime logs, metrics data, and archive files in separate layers, and use monitoring alerts to catch abnormal state store growth or Token consumption spikes early.

    9. Cost Control: From “After-the-Fact Bills” to “Upfront Budgets”

    High Token consumption ultimately shows up as cost pressure. Mature systems introduce budgets at design time.

    9.1 Session-Level Budgets

    Set a Token limit per session. When approaching the threshold, trigger compression, summarization, or human confirmation.

    9.2 Task-Level Budgets

    Complex tasks can be split into multiple subtasks, each with its own limit, preventing a single runaway point from blowing the budget.

    9.3 Model Tiering

    Use low-cost models for simple tasks and escalate to higher-capability models only for complex reasoning. Routing strategies reduce unnecessary high-cost calls.

    9.4 Cache Reuse

    Cache fixed prompts, tool descriptions, and FAQs to reduce repeated generation.

    9.5 Budget Alerts

    When certain sessions consistently exceed their budgets, automatically alert and generate optimization suggestions instead of passively reacting when the bill arrives.

    10. Implementation Path: Start with Minimum Viable Governance

    For systems already experiencing state bloat and rising Token consumption, follow this route:

    Phase 1 — Stop the bleeding: limit per-session context length, disable unnecessary full persistence, and set a maximum retention period for the state store.

    Phase 2 — Layer: split hot, warm, and cold state, migrating historical data to archival storage.

    Phase 3 — Compress: introduce summarization, deduplication, tool result trimming, and template reuse.

    Phase 4 — Observe: build session-level, task-level, and tool-level metrics to locate the biggest consumers.

    Phase 5 — Automate: turn lifecycle cleanup, budget control, exception alerting, and archiving into platform capabilities.

    Phase 6 — Continuously optimize: adjust retention periods, compression ratios, and model routing strategies as the business evolves.

    11. Common Pitfalls

    Pitfall 1: Only Compressing Prompts

    Prompts are only one part of Token consumption. Tool returns, historical messages, and retry content can also amplify it.

    Pitfall 2: Assuming More Saved State Is Safer

    Over-persisting brings storage, performance, privacy, and compliance risks. Save the “minimum information needed for recovery.”

    Pitfall 3: Treating Compression as Truncation

    Crude truncation may discard critical constraints, causing task failures and repeated calls—which actually increases Tokens.

    Pitfall 4: Only Looking at Total Cost

    Without session-level and task-level metrics, you can’t locate problems or implement budget control.

    12. Conclusion

    High Token consumption in agent applications appears to be a model-calling problem on the surface, but it is essentially a state management problem. Unbounded accumulation of conversation context, undifferentiated growth of state databases, and historical data without lifecycle governance all drive system costs up. The solution is not a single-point fix but a complete framework: state layering, event-stream modeling, context compression, lifecycle cleanup, retrieval isolation, observability, and budget control working together.

    When a team shifts from “save everything” to “save on demand, govern in layers, make it observable, and make it recyclable,” agent systems can run stably in real businesses over the long term, achieving a better balance among effectiveness, cost, and maintainability.