Llm Cost Optimization

Production-grade guide to llm cost optimization covering architecture patterns, implementation strategies, testing approaches, and operational best practices for enterprise engineering teams.

LLM cost optimization is the practice of reducing the total cost of running large language models across inference, training, and serving workloads, with focus on token usage, model selection, batching, and context management. It matters most when models serve high-throughput systems, real-time applications, or operate on constrained budgets, where every token and every second contributes directly to cost.

Selecting the Right Model for the Task

Choose a model that matches the task’s complexity and latency constraints. The model choice affects both compute and memory costs, and the most common mistake is using a large model where a smaller one suffices.

Use a prompt engineering baseline to define required quality: for a summarization task, target a 90-point average on a held-out set of documents. Start with a model size range: 7B, 13B, 34B, and 70B parameters. Evaluate each on a representative batch of 1,000 inputs with the same prompt and expected output format.

To evaluate model cost, calculate total cost as: total_cost = (input_tokens + output_tokens) × model_cost_per_token + (latency × cost_per_second)

Use curl to invoke a model endpoint with json input, and extract input_tokens, output_tokens, and latency from the response.

{
  "prompt": "Summarize the following article: ...",
  "max_tokens": 256,
  "temperature": 0.7,
  "top_p": 0.9,
  "presence_penalty": 0.2
}
curl -X POST https://api.model-serving.example/engines/llama-3-8b/infer \
  -H "Content-Type: application/json" \
  -d @prompt.json \
  -w "Latency: %{time_total}s\n" \
  -o response.json

The response includes:

{
  "text": "The document discusses...",
  "input_tokens": 217,
  "output_tokens": 143,
  "latency_ms": 824,
  "model_name": "llama-3-8b",
  "cost_per_token": 0.000015
}

For a task where output length is predictable and latency is critical, the 7B model may be sufficient, but for high-precision classification, the 34B model may justify its higher cost.

Avoid the trap of selecting a model based only on benchmark scores. A model with 85% accuracy on a dataset may still have high token cost due to long context usage, and the cost of processing 2,000 context tokens may exceed the model’s performance gain.

Optimizing Input Prompts and Context

Reduce input token count through prompt compression and context structuring. A common failure is sending full raw documents without preprocessing.

Use jq to trim and standardize input:

jq '
  .document |= .text
  | .metadata |= { title, author, published_at }
  | .prompt |= "Summarize the key points of the article titled \(.metadata.title) by \(.metadata.author)."
' input.json

For long documents, split into chunks of 1,024 tokens using a sliding window with 256-token overlap, and aggregate results.

python chunker.py --input article.txt --chunk-size 1024 --overlap 256

The output is a list of chunks with id, content, and start_token.

Before sending to the model, combine chunks into a single prompt with a template:

{% for chunk in chunks %}
  [Chunk {{ loop.index }}]
  {{ chunk.content }}
  {% endfor %}

Please summarize the above sections in a concise paragraph.

The combined prompt must not exceed the model’s context window. For a 4,096-token model, use max_tokens=4096 and track input_tokens and context_used in the model’s response.

Silently failing: when context exceeds the model’s limit, the model truncates input without warning. Use max_tokens and truncate_input in the API to ensure consistency.

Set truncate_input: true in the request to force the model to truncate and return an input_truncated: true field.

{
  "prompt": "Summarize the following sections...",
  "max_tokens": 4096,
  "truncate_input": true,
  "context_used": 4102,
  "input_truncated": true
}

The context_used field indicates how many tokens were used. If context_used > max_tokens, the input was truncated, and the model likely missed key content.

Efficient Batching for High-Throughput Inference

Batch multiple inputs into a single request to amortize model startup and I/O costs. Use batch_size in the request to group prompts.

{
  "prompts": [
    { "text": "Summarize this article..." },
    { "text": "Translate this text to German." },
    { "text": "Extract key entities from this document." }
  ],
  "batch_size": 16,
  "max_tokens": 512
}

The model processes all prompts in parallel and returns a list of responses.

Batching fails silently when input lengths vary widely. A batch of 16 prompts may have 100, 200, and 1,000 input tokens. The model processes the longest prompt first, and the shorter ones wait, leading to underutilized compute.

To balance work, use dynamic batching with a batching window:

Use redis to implement a batching queue:

redis-cli RPUSH batch_queue '{"prompt": "...", "id": "123"}'

A worker pulls from the queue and groups requests into batches.

import asyncio
import json
import aioredis

async def batch_worker():
    redis = aioredis.from_url("redis://localhost")
    while True:
        # Wait up to 500ms for more requests
        items = await redis.brpop("batch_queue", timeout=0.5)
        if not items:
            continue

        batch = [json.loads(item[1]) for item in items]
        batch_size = len(batch)

        # Send to model
        response = await model_infer(batch)
        for item, result in zip(batch, response):
            await redis.hset(f"result:{item['id']}", "result", result)

The model returns results with id and output, and the caller can correlate.

Failure mode: if the model does not support batch_size in the request, the caller must manually handle batching, and the response may be flat instead of nested.

Reducing Output Cost with Output Control

Control output length and structure to minimize output token usage. The most common failure is using max_tokens without stop_sequences.

Use stop_sequences to define sequences that signal end-of-output, reducing redundant tokens.

{
  "prompt": "Explain the concept of transformer models.",
  "max_tokens": 256,
  "stop_sequences": ["\n\n", "###", "##", "END"],
  "temperature": 0.6,
  "top_p": 0.8
}

The model stops generating when it produces any of the sequences, leading to consistent, shorter outputs.

Use logprobs to guide output length and reduce uncertainty.

{
  "prompt": "Write a 200-word summary.",
  "max_tokens": 200,
  "logprobs": 5,
  "top_logprobs": 5
}

The response includes logprobs for the top 5 tokens at each step, enabling downstream processing of uncertainty.

The model returns:

{
  "text": "Transformers are neural networks...",
  "logprobs": [
    {
      "token": "Transformers",
      "logprob": -0.12,
      "top_logprobs": [
        { "token": "Transformers", "logprob": -0.12 },
        { "token": "Transformers", "logprob": -0.13 },
        { "token": "Transformers", "logprob": -0.15 }
      ]
    },
    {
      "token": "are",
      "logprob": -0.21,
      "top_logprobs": [
        { "token": "are", "logprob": -0.21 },
        { "token": "were", "logprob": -0.24 }
      ]
    },
    ...
  ]
}

Use logprobs to detect when output is likely to be incomplete and trigger continuation.

Managing Cost with Model Inference Strategies

Use speculative decoding to reduce latency and cost. The strategy involves a small, fast model (e.g., 7B) predicting the next tokens, which the large model (e.g., 70B) then verifies.

Use the small model to generate a draft sequence:

{
  "prompt": "Explain quantum computing.",
  "draft_tokens": 32,
  "temperature": 0.8
}

The small model returns a list of draft tokens.

The large model then validates the draft using verify_draft:

{
  "prompt": "Explain quantum computing.",
  "draft_tokens": ["Quantum", "computing", "uses", "qubits", "..."],
  "verify_draft": true
}

The large model returns:

{
  "text": "Quantum computing uses qubits to perform computations...",
  "draft_verified": true,
  "draft_tokens": ["Quantum", "computing", "uses", "qubits", "to", "perform"],
  "verification_cost": 0.15,
  "input_tokens": 112,
  "output_tokens": 89
}

The draft_verified flag indicates whether the draft was accepted. If not, the model continues generating.

This reduces total output tokens and latency, and can be used in production to reduce cost per inference.

Handling Costly Edge Cases

Handle long-running, high-precision tasks with stepwise processing.

For a complex task like document QA over a 10,000-word document, use a multi-stage pipeline:

  1. First pass: Use a 7B model to extract candidate answers.
  2. Second pass: Use a 34B model to rank and refine candidates.
  3. Third pass: Use a 70B model to generate final answers with citations.

Use async processing with uuid-based request tracking.

{
  "request_id": "abc123",
  "document": "full-text-of-a-10k-word-article",
  "pipeline": [
    { "model": "llama-3-7b", "task": "extract_candidates" },
    { "model": "llama-3-34b", "task": "rank_and_refine" },
    { "model": "llama-3-70b", "task": "generate_final_answer" }
  ]
}

Each stage returns a stage_result with request_id, stage, output, and cost.

The final result aggregates all stages.

Failure mode: the pipeline does not propagate request_id across stages. The final result is missing information from earlier stages.

Use request_id to correlate logs across services, and ensure all models return request_id in their response.

Monitoring and Detecting Cost Drift

Set up logging and alerting based on input_tokens, output_tokens, and latency.

Use a cost_per_inference metric computed as:

cost_per_inference = (input_tokens × input_cost_per_token) + (output_tokens × output_cost_per_token)

Log each inference with timestamp, model_name, request_id, input_tokens, output_tokens, latency_ms, and cost.

Alert when:

Use prometheus to scrape metrics and grafana to visualize cost trends.


scrape_configs:
  - job_name: 'llm-inference'
    static_configs:
      - targets: ['llm-service:8080']
    metrics_path: '/metrics'
// In Go service
func (s *LLMService) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    start := time.Now()
    inputTokens := countTokens(r.Body)
    outputTokens := 0

    result, err := s.model.Infer(r.Body)
    outputTokens = countTokens(result.Text)

    cost := inputTokens*0.000012 + outputTokens*0.000018

    duration := time.Since(start).Seconds()

    prometheus.MustRegister(
        prometheus.NewGaugeVec(
            prometheus.GaugeOpts{
                Name: "llm_inference_cost",
                Help: "Cost per inference",
            },
            []string{"model", "request_id"},
        ).WithLabelValues("llama-3-7b", r.Header.Get("X-Request-ID")),
    )

    prometheus.MustRegister(
        prometheus.NewHistogramVec(
            prometheus.HistogramOpts{
                Name: "llm_inference_latency",
                Help: "Latency of inference",
                Buckets: []float64{0.1, 0.5, 1.0, 2.0, 5.0},
            },
            []string{"model"},
        ).WithLabelValues("llama-3-7b").Observe(duration),
    )
}

Silently failing: cost is not updated in the metrics. The cost drifts, but no alert triggers.

Add a cost_per_inference counter and a cost_per_token gauge.

Summary of Key Patterns

The most common failure: assuming the model generates perfect output, but missing cost due to over-prompting, under-batching, or uncontrolled output length.

This page was rewritten on 15 October 2026. It replaced a templated version that was not specific to its own title. How these pages are written and checked. If anything here is wrong, tell us at [email protected] and we will correct it.