State Management and Cost Control Behind High Token Usage in AI Agents
High token usage in AI agents is not proof of greater capability. This article explains how persisted state, repeated history, tool output, and unbounded loops drive cost, and how layered storage, context budgets, execution limits, and deletion policies keep agents efficient and safe.
From usage rankings to architecture
When token usage for a class of agents grows quickly, the obvious explanations are more users, harder tasks, and more frequent calls. Totals alone cannot tell you whether the system is more capable or whether it creates more business value.
Token usage is driven by at least five factors: active users, task executions, input length per call, output length per call, and the number of reasoning and tool rounds per task. The same growth can mean healthy scale or a system that reloads history, dumps unfiltered tool output, and retries failed steps.
The more useful questions are: what does the system persist, when does it send that information to the model, and does it actually help finish the task?
Notes about accumulating interaction records can illustrate the issue. They are not evidence of any specific ranking, schema, or retention scope. The discussion below is about general agent architecture, not verified product facts.
A state store is an execution substrate, not infinite memory
Agents are often not one request and one answer. They decompose goals, call tools, read results, revise plans, and keep progress across steps. Persistence supports recovery and tracing.
A typical state store may record:
- Session, user, and task identifiers to correlate activity
- Message content, role, time, and source to reconstruct interaction
- Tool inputs, outputs, and execution status to analyze paths
- Checkpoints, pending steps, and failure reasons for resume
- Authorization records and confirmations to bound allowed actions
These are common design elements, not a claim that every system stores all of them. Real schemas depend on runtime, privacy, storage budget, and retention policy.
Growing records do not imply unbounded databases. Unbounded writes without cleanup will grow capacity, but production systems should define retention windows, size limits, and deletion rules.
Keep three concepts distinct:
Persisted state stores facts and execution traces: what happened and how far the run got.
Long-term memory is reusable information distilled from history, such as stated preferences, project constraints, and confirmed business context.
Model context is what one inference actually receives: what this step needs to know.
Saving all history does not mean loading all history on every call. Being able to retrieve history does not mean the result is correct or currently authorized.
Why reloading history inflates tokens
If a session keeps growing and every request resends the full history, earlier messages are processed more times.
Under a simplified assumption, if each round adds about m tokens and there are n rounds, cumulative historical input is about:
m × (1 + 2 + … + n) = m × n × (n + 1) / 2
This shows the growth pattern; it is not a billing forecast. Fixed prompts, output length, tool returns, truncation, and provider-side caching also matter.
Storage grows with rounds; cumulative input from rereading all history can grow faster.
Tool calls amplify this. Retrieval may return irrelevant text, logs may repeat stack traces, and data reads may return unused fields. If raw results stay in later context, input cost stays high even when the model writes a short conclusion.
Optimization should look at how history and tool results enter context, not only at answer length.
Layer storage instead of carrying all history
A more robust design layers data by use rather than treating the state store as all memory.
1. Runtime state: continue execution
Keep the current goal, stage, required parameters, pending confirmations, and recent checkpoints. Prefer compact, consistent state.
A file-processing task needs which files are done, which are waiting, and the last successful commit. Resume from that state; do not make the model guess from a long chat.
2. Interaction archive: audit and traceback
Raw messages, full tool results, and logs belong in an archive for audit, incident analysis, and precise lookup—not as default input to every inference.
For large tool results, store references, timestamps, size, and integrity checks in the state store, and put bodies in object storage. That reduces hot-path I/O, but references must stay valid, access controlled, and deletion consistent.
3. Reusable memory: recall what still applies
Long-term memory should hold filtered, stable facts, not a copy of the whole conversation. Each item should have source, update time, scope, and expiry.
Field-naming rules for one project may not apply after a project switch. A one-time user approval is not permanent authorization.
Memory extraction must allow correction and revocation. Otherwise, errors recalled repeatedly can be treated as facts.
4. Current context: serve the next step
Assemble the goal, necessary constraints, recent turns, relevant memories, and selected evidence. The rule is the minimum sufficient information for the next step, not maximum fill.
Persistence and use stay decoupled: keep a fuller audit trail while giving the model shorter, more relevant input.
Make a context budget enforceable
Do not rely only on the model, and do not only drop old messages when length overflows. Put budget and priority in the orchestrator.
A typical budget covers fixed constraints, current goal, runtime state, recent dialogue, retrieved evidence, tool results, and reserved output. Ratios depend on task type; there is no universal split.
A practical order:
- Keep the current goal and non-negotiable constraints. Dropping goals or authorization boundaries can derail the run even if context is shorter.
- Prefer information relevant to the current step, using task, time, source, and scope—not only text similarity.
- Deduplicate. Repeated errors, page fragments, and tool outputs should not re-enter by default.
- Extract structure from long results. For logs, keep exception type, key times, affected objects, and representative snippets. For data, extract required fields and stats, then fetch detail on demand.
- Summarize a stage when needed. Summaries should state confirmed facts, open issues, progress, and next steps—not only compress words.
Summaries cost extra inference and can lose detail. Use them when later reuse is likely, and keep original evidence for important conclusions.
Cost control must bound the execution path
A slim context is not enough if the loop never stops. Typical causes: tools returning the same error, the model retrying infeasible plans, and missing success or stop conditions.
Production systems should enforce:
- Maximum execution rounds
- Per-task token budget
- Maximum runtime
- Tool retry limits
- Detection of similar repeated failures
- Human confirmation for high-impact actions
These limits belong in code, not only in prompts. Prompts can guide behavior; they cannot replace deterministic resource control.
Retries should depend on error type. Transient connectivity issues may warrant limited retries. Missing permission, invalid parameters, or a missing target usually need a changed condition or a stop, not the same call again.
For operations that change external state, use idempotency and result verification. Do not resubmit because the model did not see success.
Persistence must include security and deletion
Interaction state may hold personal data, internal documents, credentials, or business records. More complete storage means a larger exposure surface. Apply least necessity.
Do not mix long-lived secrets into message logs or tool output. Manage credentials through controlled mechanisms; logs should keep only what troubleshooting needs.
In multi-user or multi-tenant setups, isolate access. A user id in a query is not a security boundary; storage and service layers must enforce authorization.
Deletion cannot stop at original messages. Summaries, memories, and search indexes must be updated too, or deleted text can still be recalled.
Treat history and tool results as data, not high-privilege instructions. External text may try to change behavior and can reappear in later tasks. Distinguish instruction source and privilege so “remembered text” is not treated as authorization.
Judge usage by task value
Total tokens show scale, not efficiency. More useful metrics include:
- Average tokens per successful task
- First-pass completion and human rework rates
- Average tool calls and wasted retry share
- Latency and abnormal termination rate
- Share of context from history, tool results, and retrieved evidence
- State-store growth, archive backlog, and deletion completion
Group by task difficulty. Higher usage on hard tasks can be reasonable; repeated failure on simple tasks is a signal. Chasing lower usage can also hurt completion if context is too thin.
Start small: pick representative tasks, record input composition and paths, find repeated history, redundant tool output, and useless retries, change one policy at a time, then compare quality, latency, and cost. Cost cuts are stable only if success rate and critical constraints hold.
Conclusion: agents succeed by using information selectively
Rising agent token usage is a signal that needs explanation, not proof of leadership. What matters is how the system stores state, resumes work, filters history, and bounds execution.
A sound state store makes work traceable; layered memory makes information reusable; a context budget keeps input relevant; programmatic limits keep runs controllable. Together they turn “a program that keeps calling a model” into an engineering system whose quality, cost, and safety can be governed.
