A cost engineering guide for agent builders: prompt caching, batching, model routing and quantization, with worked numbers on which lever saves the most.

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.
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.
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.
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:
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.
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:
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:
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.
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.
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.
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.
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):
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:
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.
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:
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.
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.
Quantization stores model weights, and sometimes activations and the key-value cache, in fewer bits. The main formats in production:
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.
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.
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:
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.
Apply the levers that cost no quality first, then the ones that trade quality for savings, and measure after each change:
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.
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.
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.
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.
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.
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.
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.
Aaron is an engineering leader, software architect, and founder with 18 years building distributed systems and cloud infrastructure. Now focused on LLM-powered platforms, agent orchestration, and production AI. He shares hands-on technical guides and framework comparisons at fp8.co.
LLM vs classical models for routing steps: when a rule, a small classifier or gradient boosting beats a prompt on cost, latency and accuracy.
AI EngineeringLiteLLM, Portkey, OpenRouter, Cloudflare and Vercel AI Gateway compared on fallbacks, fees, self-hosting and lock-in. Which LLM gateway fits your stack?
AI EngineeringLearn how vLLM uses PagedAttention and continuous batching to increase LLM serving throughput while reducing GPU memory waste.
LLM Infrastructure