Production LLM Inference: A Cost Engineering Guide for Agent Builders
TL;DR: Agent workloads are dominated by input tokens, because every turn resends the growing conversation. Prompt caching is therefore the first and largest lever for agents, often cutting a task's bill by around 70%. Batch processing halves the price of work nobody waits for. Model routing pays off most on output-heavy steps. Quantization and continuous batching only matter once you serve open-weight models yourself.
Key Takeaways
- Measure cost per completed task, not cost per request. A cheaper model that needs extra turns or retries to finish can cost more than the expensive one.
- An agent loop resends its system prompt, tool definitions and history on every turn, so input tokens usually make up most of the bill. That is why prompt caching beats every other lever for agents.
- On Anthropic's API, a 5-minute cache write costs 1.25x the base input price and a cache read costs a small fraction of it, so a prefix pays for itself on the second request.
- Batch APIs give a 50% discount for work that can wait up to 24 hours: evaluations, backfills, nightly enrichment and offline classification.
- Model routing saves most on output-heavy steps and simple sub-tasks. Caches are scoped to a model, so switching models mid-conversation throws the cache away.
- Self-hosting with vLLM or SGLang adds continuous batching, prefix caching and FP8 or INT4 quantization, but it only beats an API when you can keep the GPUs busy.
Why is inference cost different for agents than for chatbots?
A chatbot request is mostly a short question and a long answer. An agent request is the opposite. Each turn of an agent loop sends the full system prompt, every tool definition, and the whole conversation so far, including every tool result the agent has read. The model then writes a short reply: a tool call, a few lines of reasoning, a final answer.
That shape has two consequences that drive everything in this guide.
- Input tokens dominate. A ten-turn task with a 12,000-token prefix reads that prefix ten times. Tool results pile up on top of it. By the last turn the agent may be sending well over 20,000 tokens to produce a few hundred.
- The cost grows faster than the number of turns. Because each turn includes all the turns before it, the total input of an n-turn task grows roughly with n². An agent that takes twice as many steps costs far more than twice as much.
This is why cost advice written for chat applications ("use a smaller model", "shorten the answer") often misses for agents. The tokens you pay for are mostly tokens the model has already seen. The cheapest token is the one you don't pay full price for again.
How do you measure LLM inference cost properly?
Before you change anything, build a token profile per traffic class. An interactive support agent and a nightly enrichment job are different workloads, even when they share an API key. For each class, record four numbers from the usage object every provider returns:
| Metric | What it tells you |
|---|---|
| Uncached input tokens | What you pay full price for on every request |
| Cached input tokens (reads and writes) | Whether your caching is actually working |
| Output tokens, including reasoning | The part that model choice and effort settings control |
| Turns and retries per completed task | Whether a "cheaper" configuration is really cheaper |
Then compute cost per completed task: total spend for a task divided by tasks that reached an accepted result. This is the only number worth optimizing. Cost per request hides the case where a smaller model saves 60% per call but needs three times as many calls, or fails often enough that a human redoes the work.
Two practical rules help here. Log usage on every call from day one, because you cannot reconstruct it later. And keep an evaluation set for each workload, because every lever below other than caching and batching trades something for its savings, and you need a way to see what you gave up.
How does prompt caching cut agent costs?
Prompt caching stores the processed form of a prompt prefix so that a later request starting with the same bytes skips that work. Providers pass the saving on as a discount for the cached part.
On Anthropic's API, as of December 2026:
- A cache write costs 1.25x the base input price with the default 5-minute lifetime, or 2x with the 1-hour lifetime.
- A cache read costs a small fraction of base input. For Claude Opus 5.5 that is $0.20 per million tokens against a base input price of $4. For Claude Sonnet 5.5 it is $0.10 against $2.
- A read refreshes the entry's timer, so requests that arrive less than five minutes apart keep the cache warm indefinitely.
- The minimum cacheable prefix depends on the model. It is 512 tokens on the current generation and up to 4,096 on some older models. A shorter prefix silently does not cache.
The break-even is quick. With the 5-minute lifetime, one write plus one read costs about 1.3x the base price, compared with 2x for two uncached requests. The prefix pays for itself on the second request. Agent loops, where turns follow each other within seconds, are close to the ideal case.
Caching is a prefix match, which is where most implementations fail. Any byte that changes invalidates everything after it. The usual culprits:
- A timestamp, request ID or user name in the system prompt
- Tool definitions generated in a different order on each request
- JSON serialized with unstable key order
- A tool list that changes based on the user's request
- Editing or truncating earlier messages instead of appending
Put stable content first (system prompt, then tools, then long reference documents) and volatile content last. Then verify from the numbers, not from the code: on a warmed-up loop, cached reads should dwarf uncached input. If cache_read_input_tokens stays at zero, something in the prefix is changing.
What does prompt caching save on a real agent task?
Here is a worked example using Claude Opus 5.5 list prices ($4 per million input tokens, $20 per million output, $0.20 per million cache reads, $5 per million 5-minute cache writes). The task has ten turns, a 12,000-token prefix of system prompt and tools, about 1,500 new tokens of tool results per turn, and 400 output tokens per turn.
- Total input across the ten turns: 120,000 tokens of repeated prefix plus 67,500 tokens of accumulated history, so 187,500 tokens.
- Total output: 4,000 tokens.
Without caching: 187,500 input tokens cost $0.75 and 4,000 output tokens cost $0.08. That is $0.83 per task.
With caching: each turn writes only what is new and reads the rest. About 25,500 tokens are written (the first prefix plus each turn's new content) and about 162,000 are read.
| Component | Tokens | Rate per 1M | Cost |
|---|---|---|---|
| Cache writes | 25,500 | $5.00 | $0.128 |
| Cache reads | 162,000 | $0.20 | $0.032 |
| Output | 4,000 | $20.00 | $0.080 |
| Total | $0.24 |
That is about 71% less, with no change to the model, the prompt or the output. Note that output, the part people usually try to shrink, is a third of the cached bill and under a tenth of the uncached one. This is a simplified model: it ignores reasoning tokens, which are billed as output, and assumes turns stay inside the cache lifetime. Your numbers will differ. The shape will not.
Prompt caching vs model routing: which saves more?
Model routing sends each request to the cheapest model that can handle it: a small model for classification and extraction, a mid-sized model for routine tool use, a frontier model for hard reasoning. Research such as FrugalGPT and RouteLLM showed that cascades and learned routers can keep most of a strong model's quality at a fraction of its cost.
Run the same ten-turn task on Claude Sonnet 5.5 ($2 input, $10 output, $0.10 cache reads):
| Configuration | Cost per task | Saving vs baseline |
|---|---|---|
| Opus 5.5, no caching (baseline) | $0.83 | — |
| Sonnet 5.5, no caching (routing only) | $0.42 | 50% |
| Opus 5.5, cached (caching only) | $0.24 | 71% |
| Sonnet 5.5, cached (both) | $0.12 | 86% |
For this input-heavy agent shape, caching alone beats routing alone, and it costs you no quality. Routing also costs you an evaluation: you have to show that the smaller model completes the task as often, without extra turns.
The picture flips for output-heavy steps. Take a drafting step with 2,000 input tokens and 4,000 output tokens. On Opus 5.5 it costs about $0.088, almost all of it output, and caching has nothing to work with. Routing that step to Claude Haiku 5.5 ($0.10 input, $0.50 output) costs about $0.002. When the bill is output, the model choice is the lever.
Three interactions matter when you combine them:
- Caches are scoped to a model. If a router sends turn 4 of a conversation to one model and turn 5 to another, turn 5 starts with a cold cache. Route at the task or sub-agent boundary, not turn by turn inside one conversation.
- Try the cheaper setting of the same model first. Lowering the reasoning effort on a strong model often matches a weaker model at its highest effort, and it keeps one cache namespace.
- Use sub-agents for reading-heavy work. A small, cheap model can read fifty documents and hand back a summary, so the expensive model's context never carries those tokens at all.
Our earlier comparison of rules, classifiers and LLMs for routing decisions covers how to build the router itself, and the LLM gateway comparison covers where routing rules usually live.
When should you use a batch API?
Batch APIs accept a file or list of requests, process them asynchronously, and return results within a window, typically up to 24 hours. Anthropic and OpenAI both price batch work at 50% of the standard rate. On Anthropic's pricing, batch and cache discounts stack.
Batching fits any work where no person is waiting:
- Evaluation runs and regression suites
- Backfilling summaries, tags or embeddings over a corpus
- Nightly or weekly report generation
- Offline classification and data labelling
- Synthetic data generation
It does not fit an interactive agent loop, where each turn depends on the last. But many agent systems have a batchable half: the scheduled research job, the weekly evaluation, the enrichment step that runs after the user has left. Moving that half to batch is a pure 50% saving on it.
Two cautions. Results arrive in any order, so key them by an ID, never by position. And treat the 24-hour window as an expiry, not a promise: design for a result that arrives late or not at all.
What do batching and caching mean when you self-host?
If you serve open-weight models yourself, "batching" means something different. It is not a discount; it is how a GPU gets used.
A GPU generating one sequence at a time is mostly idle, because decoding is limited by memory bandwidth rather than compute. Continuous batching, introduced by the Orca system, schedules requests at the level of individual decoding steps: when one sequence finishes, a new one joins the batch at the next step. vLLM combined this with PagedAttention, which stores the attention key-value cache in small blocks instead of one contiguous region per request, so far more sequences fit in memory at once. The vLLM paper reported 2x to 4x higher throughput than earlier serving systems at the same latency. We cover how it works in What Is vLLM.
Self-hosted servers also do prompt caching. vLLM's automatic prefix caching and SGLang's RadixAttention keep the key-value cache of shared prefixes and reuse it across requests. For agents, whose requests share long system prompts and histories, this saves both GPU time and time to first token. The same rules apply: stable content first, and route requests that share a prefix to the same replica, or each replica builds its own cache.
How much does quantization reduce inference cost?
Quantization stores model weights, and sometimes activations and the key-value cache, in fewer bits. The main formats in production:
| Format | Weight memory vs BF16 | Typical use |
|---|---|---|
| FP8 | About half | Default on recent data-centre GPUs with native FP8 support; quality loss usually small |
| INT8 (weights) | About half | Older GPUs and CPU serving |
| INT4 (AWQ, GPTQ) | About a quarter | Fitting a large model on fewer or smaller GPUs; check quality on your tasks |
Quantization saves money in two ways. A smaller model fits on fewer GPUs, so each replica is cheaper. And the memory it frees goes to the key-value cache, which lets continuous batching run more concurrent sequences, so each GPU produces more tokens per second. Methods such as AWQ and GPTQ were designed to keep quality close to the original at 4 bits, but "close" is measured on public benchmarks. Run your own evaluation, especially for tool calling and structured output, which can degrade before general benchmark scores do.
Quantization does nothing for you on a hosted API, where the provider has already made that choice and the price per token is fixed.
Does speculative decoding save money?
Speculative decoding uses a small draft model to propose several tokens, which the large model then verifies in one pass. The output is identical to what the large model would have produced alone. It mainly cuts latency: fewer sequential passes of the large model per token.
Whether it cuts cost depends on load. At low concurrency, where the GPU is underused anyway, it turns idle compute into speed. At high concurrency, where continuous batching already keeps the GPU busy, the extra draft work can lower total throughput. Treat it as a latency tool and measure cost per token under your real load before assuming a saving.
When does self-hosting beat an API?
Self-hosting replaces a price per token with a price per GPU hour. The comparison comes down to one formula:
Self-hosted cost per million tokens = (GPU cost per hour ÷ tokens per hour at real utilization) × 1,000,000
The trap is "at real utilization". A node that can produce a high token rate under a synthetic benchmark may run at 20% load across a real day of uneven traffic, which multiplies its effective cost per token by five. Add the engineering time for upgrades, monitoring, autoscaling and on-call.
Self-hosting tends to pay off when:
- Traffic is high and steady enough to keep GPUs busy around the clock
- An open-weight model meets your quality bar on the tasks that matter
- Data residency or isolation rules make a hosted API difficult
- You need fine-tuned weights or custom decoding that APIs don't offer
For most agent teams the frontier model doing the hard reasoning stays on an API, and self-hosting, if it happens, takes the high-volume, low-difficulty steps: embeddings, classification, extraction.
In what order should you apply these levers?
Apply the levers that cost no quality first, then the ones that trade quality for savings, and measure after each change:
-
Instrument. Log
usageper call and compute cost per completed task per workload. - Cache. Stabilize the prefix, add cache breakpoints, and verify that cached reads dominate.
- Trim input. Remove unused tools, shorten tool results, and clear old tool output the agent no longer needs.
- Batch. Move every workload nobody waits on to a batch API.
- Tune effort. Lower reasoning effort per route where the evaluation says quality holds.
- Route. Send sub-tasks and output-heavy steps to smaller models, at task or sub-agent boundaries.
- Self-host selectively. Only for steady, high-volume steps that an open-weight model handles, with continuous batching, prefix caching and FP8 or INT4 quantization.
Steps 2 to 4 are free wins and stay on permanently. Steps 5 to 7 each need an evaluation run before and after, because a saving that lowers the completion rate is a cost increase in disguise.
Frequently Asked Questions
What is the biggest cost lever for LLM agents?
For most agents it is prompt caching. Agent loops resend the system prompt, tools and history on every turn, so input tokens dominate the bill. Caching that repeated prefix typically cuts the cost of a multi-turn task by well over half without changing the model or the output.
Is prompt caching or model routing cheaper?
For input-heavy agent loops, prompt caching usually saves more and costs no quality. In our worked example caching saved 71% against 50% for routing to a cheaper model. For output-heavy steps such as drafting long text, routing saves more, because caching only discounts input. The two combine well if you route at task boundaries, since caches are scoped to one model.
How much does a batch API save?
Anthropic and OpenAI price batch requests at half the standard rate, with results returned asynchronously within up to 24 hours. Batching suits evaluations, backfills, scheduled reports and offline labelling. It does not suit interactive agent turns that depend on each other.
Why is my prompt cache hit rate zero?
Something in the prefix changes between requests. Common causes are a timestamp or request ID in the system prompt, tools listed in a different order, unstable JSON key order, or editing earlier messages. A prefix shorter than the model's minimum cacheable length also silently does not cache.
Does quantization reduce cost on hosted APIs?
No. Quantization helps when you serve models yourself, by fitting a model on fewer GPUs and freeing memory for larger batches. On a hosted API the price per token is set by the provider, so your levers there are caching, batching, effort settings and model choice.
When is self-hosting an LLM cheaper than using an API?
Self-hosting is cheaper when traffic is high and steady enough to keep GPUs busy, and when an open-weight model meets your quality bar. Divide the GPU cost per hour by the tokens per hour you actually achieve under real traffic, not benchmark peaks, and include the engineering time to run it.
Sources
- Anthropic — Prompt caching documentation
- Anthropic — Batch processing documentation
- Kwon et al. — Efficient Memory Management for Large Language Model Serving with PagedAttention
- vLLM — Automatic prefix caching
- Zheng et al. — SGLang: Efficient Execution of Structured Language Model Programs
- Yu et al. — Orca: A Distributed Serving System for Transformer-Based Generative Models (OSDI 2022)
- Chen, Zaharia and Zou — FrugalGPT: How to Use Large Language Models While Reducing Cost and Improving Performance
- Ong et al. — RouteLLM: Learning to Route LLMs with Preference Data
- Lin et al. — AWQ: Activation-aware Weight Quantization for LLM Compression and Acceleration
- Frantar et al. — GPTQ: Accurate Post-Training Quantization for Generative Pre-trained Transformers
- Leviathan, Kalman and Matias — Fast Inference from Transformers via Speculative Decoding
Originally published at fp8.co. Subscribe for weekly AI engineering analysis at fp8.co/newsletters.
Top comments (0)