How to Reduce LLM Token Consumption: A Guide to Optimizing Structured Input
Large language models bill and process text by tokens, so how you format structured data directly affects cost and quality. This guide explains the difference between removing redundancy and losing information, shows how to compress repetitive JSON-style records using a shared-header format, covers semantic pitfalls such as missing values and type preservation, and provides a practical framework for validating token savings with real tokenizers, task accuracy metrics, and fallback mechanisms.
How to Reduce LLM Token Consumption: A Guide to Optimizing Structured Input
1. Reduce Redundancy, Not Information
When a large language model processes text, it first converts input into tokens via a tokenizer. Tokens don’t map one-to-one to characters: a word may split into multiple tokens, and digits, punctuation, whitespace, and different languages can all produce different segmentation results.
This means “shorter text” doesn’t necessarily mean “fewer tokens,” and neither guarantees better model performance. Removing necessary field descriptions, units, or business constraints may shorten the input, but it can also introduce ambiguity, leading to wrong answers and costly retries.
What’s actually worth optimizing is information the task doesn’t need, plus repetitive information that can be expressed in a more compact structure. The goal can be summarized as:
Reduce input redundancy while preserving the semantics the task requires, and control wasted tokens in output and multi-turn interactions.
For systems that send query results, business records, or retrieved materials to a model, structured data is usually where the easiest optimization opportunities lie.
2. Why Structured Data Creates Repeated Overhead
JSON is a universal data exchange format—clear, well-structured, and easy for programs to parse—but it wasn’t designed with LLM input costs in mind.
For example, the following data contains two user records:
{"users": [{"id": 1,"name": "Alice","role": "admin"},{"id": 2,"name": "Bob","role": "user"}]}
As the number of records grows, field names like id, name, and role repeat in every record. Quotes, braces, commas, and whitespace from pretty-printing all become part of the input.
It helps to distinguish two types of optimization:
- Formatting compression: removing meaningless line breaks and indentation without changing the structure.
- Structural compression: declaring repeated fields once and arranging record values in a fixed order.
Formatting compression is easy to implement and lets you keep existing parsing pipelines. Structural compression requires additional encoding rules, but usually offers more potential for large sets of homogeneous records.
That said, you shouldn’t treat any fixed savings ratio as a universal conclusion. Actual gains depend on the tokenizer, field lengths, record counts, nesting depth, and the comparison baseline. Savings may be significant compared to pretty-printed data, but much smaller compared to data that’s already compressed.
3. Use a Shared Header Plus Data Rows to Eliminate Repeated Fields
For arrays of objects with consistent fields and shallow nesting, you can borrow from tabular representation: declare field names once, then fill in values in the same order for each row.
For example, the records above could be expressed at the prompt layer as:
Dataset: usersRecord count: 2Field order: id,name,roleData:1,Alice,admin2,Bob,user
This is an illustrative custom input protocol, not a requirement that all data exchange between programs use this format. The core idea is to separate record structure from record content:
- The dataset name explains what the records represent.
- The field order defines what each column means.
- The record count helps verify completeness.
- Data rows contain only values, with no repeated field names.
When records grow from two to hundreds, the header still appears only once. Data with many fields, long field names, and consistent record structure is the best fit for this approach.
However, the record count is only an auxiliary constraint, not a reliability guarantee. Models can still skip, misread, or misreference rows; real completeness checks should be performed by code.
What Data Suits Tabular Formatting
Typical suitable scenarios include:
- Query results such as orders, inventory, or device status records;
- Lists of candidate items with consistent fields;
- Small datasets the model needs to filter, classify, or explain;
- Business objects sharing the same attribute definitions across records.
Cases that don’t suit direct tabular formatting include:
- Records with highly inconsistent field sets;
- Deeply nested objects or multi-level arrays;
- Fields that are mostly long free-form text;
- Field values containing many delimiters, quotes, and line breaks;
- Cases requiring precise preservation of complex types that the compact protocol doesn’t yet define.
For mixed data, don’t force a single format. Convert stable fields to a table, keep complex details in their original structure, or include details only when the task requires them.
4. Compact Expression Must Preserve Semantic Fidelity
Field deduplication is relatively straightforward; the hard part is ensuring the conversion doesn’t change meaning. If you want the format to support lossless round-trip conversion, you must explicitly define encoding and decoding rules.
1. Distinguish Missing Values, Nulls, and Empty Strings
The following states are not equivalent:
- The field is absent;
- The field exists but its value is
null; - The field value is an empty string;
- The field value is the string
"null".
If you encode all of them as blank cells, you save characters but lose semantics.
Your protocol should define distinct representations for these states and check whether reserved markers might collide with real data. Where collisions exist, you also need quoting or escaping rules. Don’t merge business states that should be distinguished just to save space.
2. Preserve the Distinction Between Numbers and Strings
An ID like "0012" may be a string identifier, not the number 12. If conversion strips quotes and treats it as a number, the leading zeros are lost.
Similarly, handle long integers, high-precision amounts, dates, and times carefully. You can document types, units, and time semantics in a shared field description, for example:
Field notes:record_id: string, preserve leading zerosamount: decimal amount, unit is USDcreated_at: timezone-aware datetime string
These notes add a small amount of input but prevent far costlier interpretation errors.
3. Handle Delimiters and Multi-line Text
If fields are comma-separated, text containing commas needs quoting rules; if records end with newlines, newlines inside field values need explicit handling too.
For example:
Field order: id,remarkData:1,"Needs review, not submitted yet"
Whether the quotes belong to the field value, and how to represent quotes inside text, should be defined by the protocol—not left for the model to guess.
For data containing lots of complex text, quoting and escaping themselves can add significant overhead. In that case, a compact format may not be cheaper than the original structure.
5. Keep the Compact Format at the Prompt Layer, Not Across the Whole System
A more robust engineering approach is to keep your existing internal data formats and convert only when constructing model input.
A possible pipeline:
Business data→ Permission and sensitive-data checks→ Task-relevant field filtering→ Structure and type validation→ Compact format encoding→ Construct model input→ Validate model output
This pipeline has two important implications.
First, compact expression is an input adaptation layer; it doesn’t need to affect storage, messaging, or existing APIs. The business system keeps using mature data structures—only the text sent to the model changes.
Second, filter information before compressing format. If the model only needs to determine whether an order is overdue, full addresses, internal notes, and irrelevant historical statuses usually don’t need to enter the context. Removing irrelevant fields is often more effective than compressing punctuation.
After the model returns results, don’t treat its natural-language judgments directly as trusted business instructions. If output involves state changes, monetary handling, or permission operations, validate types, ranges, permissions, and business rules.
6. Validate the Benefits—Don’t Rely on Gut Feeling
Structural optimization should be evaluated on at least three dimensions simultaneously: token count, task quality, and overall cost.
1. Use the Tokenizer Matching Your Actual Calls
Don’t just compare character counts, and don’t substitute a fixed character-to-token ratio for measurement. Use a tokenizer that matches or adapts to the actual model, and measure the full request.
What to measure includes:
- System instructions;
- Task descriptions;
- Format explanations;
- Input data;
- Necessary examples and conversation history.
If the compact format requires lengthy explanations, that overhead must be included too.
Input savings can be expressed as:
Input savings rate =(baseline input tokens - optimized input tokens)÷ baseline input tokens
When comparing, set both pretty-printed and compressed formatting as baselines, so you don’t exaggerate structural optimization gains by merely deleting whitespace.
2. Keep Other Variables Constant
Comparison tests should use the same data, task, model version, generation settings, and output requirements, changing only the input representation.
Test tasks shouldn’t cover only simple lookups; include conditional filtering, cross-record comparisons, missing-value detection, anomaly identification, and locating complex fields. Only then can you judge whether the format works across different task types.
3. Track Accuracy and Retry Costs
Record at least the following metrics:
- Input token count;
- Output token count;
- Accuracy of field location and task completion;
- Rate of unparseable outputs;
- Retry counts;
- Request latency;
- Average cost per successful task.
If a compact format saves input tokens but causes more clarification requests or failed retries, total cost may rise. The acceptance criterion should therefore be “lower cost to complete the same task,” not “a segment of input looks shorter.”
7. Beyond Format Compression: Optimize Context and Task Design
1. Delegate Deterministic Computations to Code
Tasks like summing, sorting, deduplication, and exact filtering can be done reliably by programs—don’t make the model process large volumes of raw data row by row.
A better approach is to compute summaries and flag anomalies first, then have the model explain causes, identify patterns, or generate user-facing descriptions. But preserve the evidence the task needs; don’t drop key details during summarization.
2. Control the Relevance of Retrieved Material
More retrieval results isn’t better. Duplicate passages, low-relevance documents, and overly long fragments all consume context. Filter by relevance, deduplicate content, and trim fragments before assembling the input.
If you need verifiable conclusions from the model, keep the necessary source identifiers and evidence locations—don’t just provide summaries stripped of their origins.
3. Manage Multi-turn Conversations
Long-running sessions shouldn’t accumulate history indefinitely. Consolidate confirmed context into a state summary, keeping the current task, key constraints, and unresolved issues.
Summaries risk omissions, so critical state such as account identifiers, amounts, time boundaries, and explicit decisions should be maintained separately by your program—not left entirely to model-generated conversation summaries.
4. Constrain Output Scope
Specifying fields, item counts, answer length, and whether explanations are needed reduces irrelevant output. But for risk assessment or ambiguity handling, allow the model to express necessary uncertainty; don’t force overly confident conclusions just to shorten answers.
8. Keep Fallback Capability and Safety Boundaries at Launch
Start with datasets that have stable fields, moderate scale, and low risk. Build automated tests first, then gradually expand coverage.
Key measures include:
- Verifying that row and column counts match the declared values after encoding;
- Building test cases for nulls, special characters, and type boundaries;
- Performing round-trip encode/decode verification where necessary;
- Falling back to the original format when compact parsing fails or quality degrades;
- Trimming overly long inputs early to prevent key instructions from being truncated;
- Sanitizing sensitive content in logs;
- Clearly separating trusted instructions from external data.
The last point is especially important: structured representation doesn’t automatically prevent prompt injection. Field values may still contain text attempting to change the task, so treat it as data to be processed, not instructions to execute. Permission controls and high-risk operation checks must not be delegated to the format itself.
Conclusion
Reducing LLM token consumption isn’t about simply deleting whitespace, or relying on some format for a fixed savings ratio. It’s about systematically eliminating irrelevant information, repetitive structure, and wasteful interactions.
For homogeneous records, a shared header with compact data rows reduces field repetition; for complex data, prioritize type and semantic correctness. In practice, the most reliable path is: filter for task-relevant information first, then encode the format; evaluate gains using real token counts and task accuracy; and keep program-side validation and fallback mechanisms in place.
The goal worth pursuing isn’t the shortest prompt—it’s completing the same business task reliably at lower total cost.
