costrouting

LLM cost optimization: measure first, then route and cache

LLM cost optimization works best in a fixed order: measure cost per task, route each task to the cheapest model that passes a quality floor, then compress, cache, cap retries and set budgets. What each lever saves, what it costs, and where free models fit.

A weighing scale with coins and a ladder of progressively cheaper model boxes, plus a small cache drawer, illustrating LLM cost levers

LLM cost optimization is a sequence, and the order matters. First measure what each kind of request costs and how good it has to be. Then move each task to the cheapest model that still clears that quality floor, which changes the price of every token it sends. Only after that, shrink the prompts that remain, cache what repeats, stop retries from multiplying spend, and put a budget on whatever is left. Teams that start with compression or caching often optimize tokens that a cheaper model, or a free one, would have handled without any trimming at all.

This guide ranks the levers by what they touch: which model answers, how many tokens it reads, how often you pay for the same answer twice, and how much a failure costs.

Why measure before you optimize?

Because tokens are not equally avoidable. A long system prompt sent with every request is a compression and caching problem. A premium model labelling support tickets is a routing problem. A loop that retries a failing call over and over is a reliability problem. Each needs a different fix, and you cannot tell them apart from a monthly invoice.

The measurement you need is per task type, with two columns: cost and a quality verdict. Cost is simple arithmetic once you log token counts. Kong’s LLM cost optimization cookbook uses the same formula most providers bill with: cost = (prompt_tokens x input_cost + completion_tokens x output_cost) / 1,000,000, with prices expressed per million tokens. Log it per request and tag the request with its task type (classification, extraction, code, long-form writing) so you can sum by task, not by model.

The quality column is harder and more important. Pick a small, fixed set of real tasks per type, decide what “good enough” means for each, and score a candidate model against your current one. Without that floor, every later cut is a guess.

How do you reduce LLM API costs with model routing?

Routing changes the price of every token at once, where compression and caching only remove some of them. The rule is per task: send each type of work to the cheapest model that passes its quality floor.

Ficelle’s own free vs paid LLM benchmark measured this on 76 tasks against gpt-5. Its criterion is a “quality-safe share”: the fraction of tasks where a neutral LLM judge, scoring both answers against a per-task rubric, rated the free answer a tie or a win against gpt-5. Free routing was quality-safe on 100% of classification tasks, 95% of JSON extraction tasks and 94% of reasoning and code tasks. On polished long-form writing it was quality-safe on only 50% of tasks, so that work stays on a paid model or goes through a human editor. The benchmark itself cost $0.68 to run, which is a reminder that measuring is cheap next to the spend it informs. The results were judged by an LLM against rubrics, so treat them as directional and rerun the comparison on your own tasks.

Kong’s cookbook routes by meaning: it embeds each prompt and sends it to the target whose description it matches best, so simple queries go to a cheap model and complex ones to a premium model. That works well when one gateway serves many unrelated callers. When you control the caller, routing by task type is simpler and easier to audit: the classifier step asks for a cheap model by name, the drafting step asks for the expensive one.

Where does free model routing fit?

Free models are the floor of that price ladder, and they come in different forms: models with a zero price, renewable free quotas, trial credits that run out, and paid APIs with a free tier attached. Only the first two help over time, and both are limited by the account behind them. The provider directory records each provider’s free access and limits.

The risk with free routing is the fallback. A free model rate-limits, the client retries on a paid model, and the saving disappears without anyone noticing. Strict-zero routing is Ficelle’s answer to that: paid fallback is hardcoded off, the router refuses to start if it reads any other value, and any model that reports billing is quarantined. When a free model rate-limits, Ficelle marks it as cooling down and answers from the best working free alternative, when another eligible model is available; when none is, the request fails instead of billing you.

How much does prompt compression save?

Compression attacks input tokens you pay for on every call: verbose instructions, repeated context, long retrieved passages. Kong’s cookbook puts the inflation from verbose inputs at 20 to 40%, and its example sends longer prompts through an LLMLingua service where a 200-token prompt becomes a 120-token prompt. Its compression ratio setting is direct: a value of 0.6 keeps 60% of tokens, a 40% reduction.

Two limits apply. Compression removes tokens a model might have used, so it needs the same quality floor as routing; test it on the task types where you plan to use it. And it saves only input tokens, so a task whose cost is mostly output (long answers, generated code) gains little.

Start with the manual version, which costs nothing: delete instructions the model ignores, stop resending the full conversation when a summary will do, and retrieve fewer, shorter passages.

Which kind of caching should you use?

There are two, and they save different things.

Provider prompt caching discounts the repeated prefix of a prompt. On the OpenAI API, prompt caching is on by default for supported models, applies from 1,024 tokens for GPT-5.6 and later, and bills reused tokens at a cached-input rate discounted up to 95%. It only matches when the whole prefix is identical, so put stable instructions and reference material first and the changing part last. Anthropic makes caching explicit: per its prompt caching documentation, writing to the cache costs 1.25 times the base input price for a 5-minute lifetime (2 times for 1 hour), and reading from it costs 0.1 times, with per-model exceptions listed in its pricing table. A cache that is written and rarely read costs more than no cache.

Semantic caching skips the model call entirely when a similar question was already answered. Kong’s cookbook embeds the prompt, looks for a close match in Redis, and returns the stored answer without calling a model; its default expiry is 5 minutes (300 seconds), raised to 3600 (1 hour) or more for factual answers that rarely change. It pays off on repeated public questions and is wrong for anything personal, time-sensitive or agentic, where two similar prompts need different answers.

Do retries and fallbacks inflate the bill?

They can, and they rarely show up in cost dashboards as their own line. A retry can be billed again for its input, depending on how far the provider processed the failed attempt; check each provider’s billing terms for failed requests. The larger risk is an agent loop that restarts a whole multi-step plan: the steps that had already succeeded were billed once, and rerunning them bills them a second time. Cap retries, back off on rate limits instead of hammering the same endpoint, and separate billing errors from throttling before retrying at all; the LLM fallback guide covers that distinction.

Fallback chains deserve the same scrutiny. Read the chain to its last entry and check what that model costs: a chain that ends on a premium model turns every free-tier outage into premium spend.

What should a budget cap do?

Budgets are the last line, after the levers above have done their work. Token limits are a weak proxy, as Kong’s cookbook notes: “10,000 tokens per hour” costs very different amounts on different models. Its example uses cost-based limits instead, with standard-tier users sharing a $1/hour budget and premium users a $5/hour budget, and a 429 response once a tier runs out. If you run a gateway, cap spend in currency per team or key; if you call providers directly, set the spending limit in each provider console.

The optimization order, in one list

  1. Measure cost and quality per task type.
  2. Route each task to the cheapest model that clears its floor, free models included where they hold quality.
  3. Compress the input of the expensive tasks that remain.
  4. Cache stable prefixes, and repeated public answers where it is safe.
  5. Cap retries and read every fallback chain to its last entry.
  6. Budget in currency, as a backstop.

Step 2 is where a router helps. Retry caps and budgets (steps 5 and 6) stay settings you configure in your client, agent framework or provider console. Ficelle’s open core is free under BSL 1.1, runs locally at http://127.0.0.1:8646/v1, and ships strict-zero routing with the OpenRouter and Nous reference providers. Pro adds the maintained, curated provider pool with fixes when a provider breaks, native prompt compression, model fusion and custom virtual models. If you want that layer maintained for you, see Ficelle Pro pricing. For the work where free models measurably fall short, polished writing first, keep a paid model in your own stack.


Install Ficelle → One command. No account, and it can't charge you.