How to Cut LLM Token Consumption: A Structured Data Optimization Guide
This article explores practical strategies for reducing token usage when sending structured business data to large language models (LLMs) in production. It explains the difference between character count, token count, and actual API cost, and provides a step-by-step framework that covers field-level data trimming, compact serialization formats, semantic rule enforcement, program-side validation, and evaluation methods. Designed for engineers working with AI-powered data analysis pipelines, this guide emphasizes measurable gains without sacrificing output accuracy or reliability.
1. Token Reduction Is Not Just About Writing Shorter Prompts
In most LLM applications, the input is not just the user’s question. It includes system instructions, conversation history, retrieved documents, business records, and output formatting requirements. When large sets of structured records are passed into the context, field names, punctuation, and repeated descriptors consume a significant portion of the available space.
For example, when checking for anomalies in a batch of orders, the model might only need order IDs, amounts, statuses, and error reasons. If the backend sends the entire order object—including shipping details, display text, and internal tracking fields—the model ends up processing an unnecessary amount of data.
The goal is not simply to shorten the text, but to:
Reduce the amount of irrelevant content and redundant expressions the model must process, while preserving the information required to complete the task.
This objective can be understood across three levels:
- Content-level optimization: Decide which data fields are worth sending at all.
- Representation-level optimization: Decide how to express the same data more compactly.
- Invocation-level optimization: Decide which context needs to be repeated across calls and how much output should be constrained.
Structured format optimization primarily addresses the second level, but it must work together with the other two to yield stable, meaningful benefits.
2. Distinguish Between Character Count, Token Count, and Cost
A token is the fundamental text unit a model processes, but it is not equivalent to a character, a Chinese character, or a word. Different models use different tokenization strategies, meaning the same text may produce different token counts on different systems.
This has several practical implications:
- Removing ten characters does not always result in a fixed reduction in tokens.
- A shorter abbreviation might not consume fewer tokens than a more common full-length word that the tokenizer recognizes efficiently.
- Changing delimiters may alter token counts in subtle or negligible ways.
- Chinese text, digits, punctuation, code, and random identifiers often tokenize very differently.
Given this, you cannot rely on string length alone to estimate optimization gains. In a production environment, use the token counting method provided by your target model provider, or use usage metrics returned by the API itself.
If a service charges separately for input and output tokens, the conceptual cost per request is:
Cost per request = Input tokens × Input price+ Output tokens × Output price
Note that real-world pricing may also involve cache hits, batch discounts, and other variables. Always reference the official pricing rules for your specific provider.
Also remember that shorter input does not automatically mean proportionally faster responses. Model size, output length, server load, and processing mechanisms all affect latency. Always validate performance through end-to-end testing.
3. Why Structured Data Tends to Be Redundant
Consider a typical JSON payload:
{"users": [{"id": 101, "name": "Alice", "role": "admin"},{"id": 102, "name": "Bob", "role": "reviewer"},{"id": 103, "name": "Carol", "role": "guest"}]}
This format provides clear structural boundaries and is easy for programs to parse. However, if every object in the array repeats the same set of keys, the names id, name, and role are written out over and over again.
For small datasets this duplication is rarely a problem. But when the dataset grows—especially with long field names—the repeated keys and structural syntax can represent a large share of the input.
You can think of structured data cost as having three components:
Total expression cost ≈ actual values + structural overhead + visual formatting
Where:
- Actual values are the core business data (necessary).
- Structural overhead includes field names, object boundaries, and hierarchy markers.
- Visual formatting includes indentation, line breaks, and whitespace.
The correct order of operations is: first remove irrelevant business data, then compress any repetitive structure, and finally remove unnecessary whitespace. Just stripping spaces rarely solves the real problem.
4. Step One: Trim Fields and Filter Data
The most effective savings usually come from simply not sending data the model does not need.
4.1 Select Fields Based on the Task
If the task is to detect abnormal account permission configurations, the model may only need user ID, account status, role, and permission sets. It does not need avatar URLs, UI preferences, or marketing tags.
Field selection should be driven by task requirements, not intuition. For recurring tasks, maintain an explicit field requirement map. For example:
Task: Check permission configuration anomaliesRequired fields: user ID, account status, role, permission setOptional fields: departmentDo not send: avatar, UI preferences, marketing tags
Whether optional fields are retained should be determined by testing on real samples. Over-trimming can deprive the model of context it needs to make a correct decision.
4.2 Filter Records with Programmatic Rules
Anything that can be reliably done with deterministic code should be done before the LLM call. That includes time range filtering, status matching, numeric threshold checks, and deduplication.
If the user’s question only concerns failed tasks from the last seven days, do not pass the full historical log by default.
4.3 Do Precise Calculations Outside the Model
Summation, counting, sorting, deduplication, and exact conditional checks are usually better done in code. Use the model for interpretation, pattern detection, and generating recommendations.
That said, avoid over-summarizing when the task requires traceability. If the model is expected to explain the cause of an anomaly, provide relevant evidence records or referencing identifiers alongside the computed results.
5. Step Two: Adopt a Compact Representation That Fits the Task
5.1 Start with Compact JSON
The simplest, lowest-friction improvement is to remove unnecessary whitespace and indentation from JSON without changing its structure:
{"users":[{"id":101,"name":"Alice","role":"admin"},{"id":102,"name":"Bob","role":"reviewer"}]}
This is easy to fit into most existing pipelines and preserves the semantic structure. However, it still repeats key names for every record.
5.2 Use a Header-and-Rows Representation for Homogeneous Arrays
When every record has the exact same schema, you can declare the field names once:
Dataset: usersRecord count: 3Field order: id,name,role101,Alice,admin102,Bob,reviewer103,Carol,guest
The core idea here is not the specific format, but separating field definitions from record values. This type of layout tends to be worth testing when the record count is high, the schema is stable, and cell values are simple.
This approach reduces duplicated keys and helps the model interpret each row based on the shared column definitions.
However, this is not a universal replacement for structured formats. For datasets with highly variable schemas, deeply nested objects, or long free-text fields, a tabular layout may introduce more interpretation overhead than it saves.
5.3 Do Not Sacrifice Semantics for Brevity
Renaming every field to a single letter is counterproductive. For example:
a,b,c101,1,0
Without additional explanation, the model has no way of knowing what those columns mean. Including a separate field dictionary adds back the very overhead you were trying to avoid.
A safer approach is to keep concise but meaningful field names—like “status” or “risk_level”—and use them consistently across all inputs for the same task.
6. Step Three: Define Semantic Rules for Compact Formats
The most common failure points of compact representations have less to do with regular rows than with edge cases.
6.1 Distinguish Null, Missing, and Empty String
The following cases are not the same and should not be conflated:
- Field does not exist
- Field exists but is explicitly null
- Field exists and is an empty string
- Field exists and has value
0 - Field exists and has boolean
false
If you omit these states indiscriminately, downstream statistical analysis, filtering, and anomaly detection can break. Define exactly how each state is encoded before you deploy, and make sure both the encoder and the model follow the same rules.
One additional caution: if you use a sentinel text value (like “null”) as the empty marker, you must handle the case where the real string content is literally “null”.
6.2 Define Delimiters and Escaping Rules
If field values can contain commas, line breaks, or quotation marks, simply joining rows with a delimiter will introduce ambiguity.
For example:
104,Dan,review and approve,second review
The model may interpret “review and approve,second review” as two separate fields. Therefore, a compact format must define quoting and escaping rules explicitly. The model should never be left to guess.
If the data is highly unpredictable or contains complex string content, a standard structured format may still be the safer and more reliable choice.
6.3 Preserve Types and Units
Be especially careful with numeric IDs, amounts, ratios, timestamps, and code-like values:
- Leading zeros in IDs must not be removed.
- Currency amounts should include a currency or unit.
- Percentages should specify whether numbers are decimals or ratio values.
- Timestamps should include format definitions and timezone if relevant.
- Large integers and high-precision decimals should not be inadvertently rounded or converted.
“Lossless” compression only holds when values, types, and structural relationships can be reliably restored according to explicit rules—not merely because they look similar to an observer.
7. Structural Metadata Is a Diagnostic Cue, Not a Guarantee
You can append metadata like record count, column count, and field order to a compact payload:
Record count: 3Column count: 3Field order: id,name,role
This helps the model detect obvious problems such as missing rows or misplaced columns, but it does not guarantee correct parsing or perfect reasoning.
A more reliable approach is to enforce validation programmatically:
- Check that the record count matches the number of rows before sending.
- Verify column count and field types for each row.
- Validate that all string quoting and escaping rules are legal.
- Round-trip test: serialize → parse → re-serialize to confirm no information is lost.
- After receiving the model response, validate both its structure and business rules.
Also, clearly separate instructions from data. Even if business text contains phrases like “ignore all previous instructions,” the model must treat this as data to be analyzed—it should never gain instruction-level authority. Compaction alone does not solve prompt injection risks.
8. Do Not Apply Fixed Savings Ratios Across the Board
The benefit of structured compression depends heavily on data shape and density. A specific savings ratio from one benchmark should not be treated as a universal result.
At minimum, build the following comparison groups:
- Original formatted JSON
- Compact JSON with irrelevant fields removed
- Header-and-rows representation for the same fields and records
- Final input after task-level record filtering
To fairly evaluate the benefit of a representation change alone, all groups should contain the same business information. Otherwise, you cannot tell whether the savings came from removing fields or from changing the format.
The input savings ratio can be calculated as:
Input savings ratio =(Baseline input tokens − Optimized input tokens)÷ Baseline input tokens
When measuring, include any field descriptions, escaping rules, and necessary examples in the measurement—not just the data region. For very small datasets, the extra format explanation can quickly offset the savings.
Beyond token counts, also track:
- Answer accuracy
- Record omission rate
- Field reference accuracy
- Result parseability
- Number of retries
- End-to-end latency
- Average total cost per successful task
If shorter input leads to more errors and retries, the final cost may end up higher.
9. Bake Optimization into the Engineering Pipeline
A reliable processing pipeline looks like this:
Raw business data→ Filter records and fields for the task→ Apply data masking and type checks→ Choose a suitable serialization format→ Validate completeness and count tokens→ Compose instructions, question, and data→ Call the model→ Validate results and log metrics
Format selection does not have to be one-size-fits-all. Define a strategy based on data characteristics:
- Small, complex data: keep clear structured formatting.
- Large, homogeneous data: evaluate header-and-rows separation.
- Data dominated by long free text: prioritize selecting the most relevant fragments.
- Precise statistical tasks: handle the math programmatically.
- Tasks that require traceability: retain record identifiers and supporting evidence.
For critical workloads, design a conservative fallback mechanism. If parse failure rates or task error rates exceed a predefined threshold, fall back to a more explicit format instead of letting the model guess.
10. Beyond Input: Control Output and Session Context
Verbose output also consumes tokens. Explicitly constrain what the model should return—for example, only anomaly IDs, reasons, and suggested actions—rather than echoing back the entire input dataset.
But when limiting output length, do not strip away necessary evidence or uncertainty statements. The goal is to reduce repetitive explanation, not to make the conclusions impossible to verify.
For multi-turn conversations, maintain clear context boundaries: preserve the current task objective, confirmed facts, and open questions; remove obsolete intermediate discussion. If you summarize long history, be careful to protect key numbers, constraints, and the user’s latest corrections so that summaries do not accumulate drift across turns.
Conclusion
Reducing LLM token consumption is fundamentally an exercise in information engineering. The right order of operations is: learn what the task actually needs, remove unrelated data, compress repeated structure, and then confirm the gains through real measurements.
For large, homogeneous arrays, separating field definitions from record rows is a broadly applicable pattern worth testing. For complex, nested data, clear and reliable structure often matters more than extreme compaction.
The metric that matters is not just how many characters a single request saved, but whether you can complete a reliable task at a lower total cost—while meeting quality, safety, and maintainability requirements.
