Systematic Token Optimization for Large Language Models: A Practical Guide
This article breaks down where LLM tokens are actually spent and presents a systematic optimization workflow: measure first, then locate the hotspots, then act. It covers compact tabular formatting for structured input, prompt and context governance, output contracts to constrain generation, and engineering techniques such as prefix caching, semantic caching, batching, and model tiering. It also defines the metrics needed to close the loop and highlights common pitfalls, followed by a recommended rollout order.
1. Understand the Cost Structure First: Where Do Tokens Actually Go?
The first step in reducing token consumption is not deleting words, but breaking down the token composition of a single LLM call. A billed request typically consists of three parts: the system prompt and role definition, the context carried with the request (conversation history, retrieved passages, structured data), and the output generated by the model. Many teams optimize only the output length and then find the bill barely changed, because the input side usually accounts for the overwhelming majority.
Optimization should therefore follow the order “measure, locate, then act.” A practical approach is to build call logging on the application side, recording input tokens, output tokens, latency, and the business outcome for each request, then aggregate by scenario to find the call chains with the highest consumption. Without measurement, any optimization is guesswork.
2. Input-Side Optimization: Compact Representation of Structured Data
When a task requires handing large amounts of structured data to the model for judgment, the choice of representation format directly affects token count. Take a set of user records as an example: a traditional nested format repeats field names, brackets, and quotes for every record, and field names are transmitted over and over inside the array. A token-oriented tabular representation instead hoists the “column names” into a header written only once, after which each row keeps only values separated by commas.
Illustrative comparison (field names appear only once):
# Nested representation (field names repeated per record){"users":[{"id":1,"name":"Alice","role":"admin"},{"id":2,"name":"Bob","role":"user"}]}# Compact tabular representationusers[2]{id,name,role}:1,Alice,admin2,Bob,user
This style pays off in three ways. First, it eliminates the repeated overhead of field names; the larger the data volume and the more uniform the fields, the more obvious the savings. Second, treating the array as a two-dimensional table makes row and column boundaries clear, so the model is less likely to misalign rows in extraction and comparison tasks. Third, the length information is written explicitly in the header, so the model can self-check the number of records, reducing hallucinations such as “writing an extra row” or “dropping a row.”
It is worth stressing that such compact formats should be used as a “prompt-layer format,” not as a replacement for internal data exchange formats. The more robust engineering layering is: backend and storage keep using mature data exchange formats to guarantee interoperability and ecosystem compatibility, and a conversion layer serializes the data into the compact representation when the prompt is constructed. This captures the token savings without sacrificing maintainability.
The input side also has several frequently overlooked details: field pruning (send only the columns the current task actually needs), short representations for numbers and enums, a unified compact format for dates and times, and removal of empty fields and default values that carry no information. Each change looks small, but the cumulative effect in batch tasks is considerable.
3. Prompt and Context Governance: Cut Redundancy at the Source
The common problem with system prompts is “wanting to teach everything,” stuffing in large numbers of examples, disclaimers, and capability lists at once, most of which contribute nothing to a single request. The direction for improvement is to split prompt templates by scenario, loading only the role constraints and a few high-quality examples the current task requires, and periodically reviewing real call data to see which sections have never affected output quality.
The core of context governance is “relevance over completeness.” In retrieval-augmented scenarios, recalling more passages does not equal better results; noisy passages raise both token count and error rate. A more reasonable strategy is: coarse recall first, then reranking, then truncation against a budget, with a hard cap set on the context; for long conversations, use rolling summarization that compresses early history into structured key points (conclusions, constraints, to-dos) rather than copying the original text.
4. Output-Side Optimization: Replace Free Reign with Format Constraints
A “long-winded” output is often not the model being disobedient, but the absence of clear boundaries. Actionable constraints include: limiting the output structure (such as structured output with fixed fields), limiting length (number of key points, word range), limiting tone and granularity (conclusion first, then evidence; no restating the question), and requiring the model to “state missing information directly when information is insufficient” instead of filling in guesses.
A practical pattern is to write an “output contract” into the prompt: explicitly list the keys that must be returned, the type and value range of each key, and declare that any extra explanation is omitted. This both compresses output tokens and makes downstream parsing more stable, reducing retries caused by format drift, and retries are the part of the bill most likely to spiral out of control.
5. Engineering Pipeline Optimization: Caching, Batching, and Model Tiering
At the application layer, prefix caching can significantly reduce the cost of repeated context: put the stable system prompt and fixed knowledge at the request prefix and keep the prefix byte-for-byte identical, allowing the server side to reuse the computed result. Semantic caching suits high-frequency repeated questions, matching historical answers by similarity; note that scenarios with strong time sensitivity need a shorter expiration.
Model tiering is another main line: stratify tasks by difficulty, route deterministic tasks such as classification, extraction, and formatting to smaller and cheaper models, and escalate to more capable models only for complex reasoning; at the same time, use rule engines, template rendering, and traditional retrieval to handle work that does not need the model at all. Batch interfaces generally suit latency-insensitive tasks and can achieve a better balance of cost and throughput.
6. Measuring Results and Common Pitfalls
Optimization must close the loop: establish a unit business cost metric (average tokens and cost per successful task), quality metrics (accuracy, format compliance rate, manual rework rate), and stability metrics (retry rate, timeout rate). Compressing tokens while quality declines simply shifts the cost downstream.
There are four common pitfalls. First, believing “fewer words is always better” and ignoring that deleting key constraints makes output longer and unusable. Second, using compact formats for inter-system data exchange, which breaks compatibility. Third, appending context without limit, causing diminishing marginal returns and even diluted attention. Fourth, skipping canary release and switching prompts or model versions for all traffic at once, which makes problems hard to attribute. A/B testing or small-traffic canary validation is recommended, with a rollback switch kept in place.
7. Recommended Rollout Order
Proceed in order of return on investment: first, connect call metering and a dashboard; second, do field pruning and set context budgets; third, introduce the compact prompt-layer format and output contracts; fourth, roll out caching and model tiering; fifth, run targeted tuning for high-consumption scenarios. In cloud environments that already have container platforms, logging services, and monitoring and alerting systems, these capabilities can reuse existing infrastructure directly, without introducing proprietary components, making cost optimization a sustainable daily practice rather than a one-off campaign.
