Back to AI Inference

Inference optimization: cut LLM latency and cost

Inference

Published 30 Nov 2026

Inference optimization, explained for developers: where your requests wait, how big the KV cache gets, and which settings fix it.

By Content Writer & Editor

Takeaways

  • Inference optimization means making a trained model answer faster, serve more people at once, and cost less per token. The right fix depends on where your requests actually wait: prefill, decode, memory, the queue, or the network.
  • Decode is memory-bound, so the biggest wins come from moving fewer bytes: quantized weights, a paged KV cache, and continuous batching.
  • vLLM and llama.cpp expose these techniques as settings, and every setting trades one user's speed for total throughput.
  • On a managed inference API with serving tiers, that tradeoff becomes one field on the request (service_tier), and cached input costs up to 88% less.

What is inference optimization and why does it matter?

Request queue
Request queue

Inference optimization is the work of improving latency, throughput, and cost per token once a trained model starts serving real traffic. Here's why it matters: you pay for training once, but you pay for inference on every single request, forever.

You've probably lived this. The model flies in your demo. Then launch week arrives, a few hundred people show up at once, and your p99 latency goes from fine to embarrassing. Nothing about the model changed. What changed is everything around it.

That "everything" has three layers:

  • The model: quantization, distillation, and pruning.
  • The serving stack: the runtime, batching, cache management, and where the GPUs sit.
  • The request path: the queue and the network between your app and the GPU.

Most guides cover the first two and stop. The third is where a model that benchmarks beautifully still times out on your users.

Before you start: this guide assumes you've called an LLM API and know roughly what a token is. You don't need to have written a CUDA kernel. We'll go from how a request runs, to the memory math, to the techniques, to the engine settings you'd actually change.

Prefill and decode: two phases, two different bottlenecks

Every request to a large language model happens in two phases, and you can't fix slowness until you know which one you're waiting on.

  • Prefill: the model reads your whole prompt in one go, as a big matrix operation. The GPU's compute units stay busy and happy.
  • Decode: the model writes its answer one token at a time. For every token, it pulls the model weights and the cached keys and values back out of GPU memory.

Think of decode like a chef who has to walk to the pantry for every single ingredient. The cooking is quick. The walking is what takes all night. That's what "memory-bound" means: the math per step is cheap, and the data movement is what you're waiting on. In other words, during decode your GPU spends more time fetching than thinking.

So a faster GPU helps decode less than you'd hope, and moving fewer bytes helps more. Nearly every technique in this article targets decode for that reason, and it's why your inference bill tracks memory bandwidth more closely than raw compute.

The metrics to record before you change anything

Optimization without a baseline is just guessing with extra steps. The quickest way to get one: send a streaming request, log when it leaves your app, when the first chunk arrives, and when the last one lands. Do that a few hundred times at realistic concurrency and you have most of what you need. Write down these five numbers first:

  • TTFT (time to first token): prefill plus time in the queue. It's the pause your chat and voice users feel before anything happens.
  • Time per output token: decode speed. It decides how fast the answer streams.
  • End-to-end latency: TTFT, plus every output token, plus the network. Anything with a timeout lives or dies on this number.
  • p99 latency: your slowest 1% of requests. This is what breaks SLAs and stalls agent tool loops.
  • Cost per token: GPU cost divided by throughput. It's the line on your invoice.

These numbers fight each other. Bigger batches push more tokens per second through the GPU, but each request waits longer to start, so TTFT climbs. You're picking an operating point under a latency target, and it's rarely the point of maximum throughput. Watch p99 and end-to-end latency, not averages, because your users don't experience averages.

End-to-end latency deserves the most attention, since the model is only one stop on the trip. As one Telnyx engineer puts it:

"There are a lot of very good products in this space, and many teams have done excellent work optimizing models, streaming, turn detection, and prompting. But in production, latency is often less about one slow model and more about the shape of the architecture: where the call enters, where media is anchored, where STT runs, where the LLM runs, where TTS runs, and how many vendor or cloud boundaries the audio crosses along the way." James Whedbee, VP of Engineering at Telnyx

One small trap: only compare tokens per second between models that share a tokenizer. A different tokenizer splits the same sentence into a different number of tokens, so its "tokens per second" is measuring in a different unit.

Measure open-weight models before you tune them

The Telnyx Inference API serves open-weight models on in-region GPUs behind OpenAI-compatible endpoints, so you can record TTFT and p99 before you touch a single setting.

LLM inference optimization techniques that move the numbers

The LLM inference optimization techniques worth your time do one of two things: they cut the bytes decode has to move, or they cut the work each token needs. None of them is free. Each one costs you something in accuracy, memory, or latency.

Quantization and the KV cache: the memory math

Your GPU memory holds two things that decide how much traffic you can serve: the model weights and the KV cache.

Start with the weights. In FP16, each parameter takes 2 bytes, so a 7B model needs about 14 GB before it has answered anything.

Then the KV cache. It's the model's scratchpad: it stores keys and values for every token in every layer, so the model doesn't redo work it already did. Its size per token is:

2 (keys plus values) x layers x hidden size x bytes per value

Walk it through for a Llama 2 7B class model with 32 layers and a hidden size of 4,096, stored in FP16:

  1. 2 x 32 x 4,096 x 2 bytes = 524,288 bytes, or about 0.5 MB per token.
  2. At a 4,096-token context, that's 4,096 x 0.5 MB, or about 2 GB for one user.
  3. Serve 8 users at that length and the cache needs about 16 GB, more than the weights themselves.

That third line is the one that surprises people. The cache grows with both batch size and sequence length, so the scratchpad, not the model, is usually what limits how many people you can serve at once.

Try it on your own model: open its config.json and plug in num_hidden_layers and hidden_size. If the config lists num_key_value_heads lower than num_attention_heads, the model uses grouped-query attention, so swap hidden size for num_key_value_heads x head dimension and your cache shrinks to match.

Each side has its own fix:

  • Quantization shrinks the weights. Weight-only INT8 or INT4 cuts the bytes decode reads on every step. Activations are harder to quantize because of outlier values. Post-training quantization (PTQ) is cheap; quantization-aware training (QAT) holds accuracy better but costs a training run. FP8, INT4, AWQ, and GPTQ are the common formats, and each one needs testing on your own prompts before it ships.
  • Grouped-query attention (GQA) and paging shrink the cache. Llama 2 70B uses GQA for exactly this reason.

It helps to see attention variants as a dial. Multi-head attention (MHA) gives every query head its own keys and values: the best quality and the biggest cache. Multi-query attention (MQA) makes all heads share one set: the smallest cache, with some quality risk. GQA sits in the middle, with small groups of heads sharing a set. You can't flip this dial on a model you've already got, since it's baked in at training or uptraining time, but it's worth checking before you pick a model to serve.

PagedAttention and continuous batching: filling the GPU

Picture a restaurant that seats every party of two at a 12-top, just in case friends show up. That's how older servers handled the KV cache: they reserved one contiguous slot per request at its maximum length. A 2,048-token slot holding a 50-token answer wastes almost all of it.

The PagedAttention paper names three kinds of waste: reserved space, internal fragmentation, and external fragmentation. PagedAttention fixes all three by storing the cache in small fixed-size blocks tracked by a block table, the same way an operating system pages memory. Parties sit wherever there's room.

Continuous batching, also called in-flight batching, puts that freed memory to work. Static batching is a tour bus that won't leave until everyone's back, so every request waits on the slowest one. Continuous batching is a city bus: finished sequences step off and new ones step on at every stop, so the GPU stays full and tokens per second per GPU goes up.

The throughput-vs-latency rule: Doubling the batch roughly doubles tokens per second per GPU until memory runs out, but every request now waits for the batch to form, so TTFT rises. Set the batch size from your latency target, then buy extra throughput with more replicas or a different serving tier.

Speculative decoding and prefix caching: doing less work per token

Speculative decoding pairs your big model with a small, fast draft model. The draft guesses the next few tokens, and the big model checks them all in one parallel pass. When the draft guesses right, you get several tokens for the price of one decode step.

Here's how one step plays out. Say your support agent has written "Your order" so far:

  1. The draft model proposes four tokens: "shipped," "on," "Tuesday," "morning."
  2. The target model checks all four in a single pass and agrees with "shipped," "on," and "Tuesday."
  3. It disagrees with "morning" and would have ended the sentence instead.
  4. The server keeps the three accepted tokens, throws away everything from the first mismatch onward, and appends the target's own token.

You got four tokens out of one expensive step instead of four. And because the target model has the final say on every token, the output matches what it would have written alone. Three things decide whether it pays off:

  • Acceptance rate: a draft that guesses wrong most of the time adds work instead of saving it.
  • Batch fullness: the gain shrinks when the batch already keeps the GPU busy.
  • Memory headroom: the draft model has to fit next to the target model and its cache.

Prefix caching skips work you've already done. It keeps the KV cache for a shared system prompt, tool schema, or conversation history and reuses it on the next request, so prefill only runs on the new tokens. If you're building retail and e-commerce agents or any agent that resends the same system prompt and tools on every call, that repeated prefill is a big slice of your input bill.

Tensor and pipeline parallelism come in when the model doesn't fit on one GPU. Both split it across devices to cut per-device memory, both add interconnect cost, and pipeline parallelism leaves idle bubbles while stages wait on each other. Find your bottleneck in the table below and read across.

LLM inference optimization techniques by bottleneck and cost

TechniquePhase or bottleneck it fixesWhat it costs you
Quantization (INT8, INT4, FP8)Decode memory traffic, weight footprintPossible accuracy loss, needs evaluation
MQA or GQAKV cache sizeNeeds training or uptraining
PagedAttentionKV cache fragmentation, batch sizeRuntime support (vLLM)
Continuous batchingGPU utilization, throughputPer-request TTFT rises as the batch fills
Speculative decodingDecode latency at low batchA draft model to run, gains fall at high batch
Prefix cachingRepeated prefill of shared promptsCache memory, cache-aware routing
Tensor or pipeline parallelismModel doesn't fit one GPUInterconnect cost, pipeline bubbles

Apply them in order: record a baseline, quantize the weights, page the KV cache, batch continuously, then pick a serving tier or add replicas. Each step changes one number you can check against the last, so you always know what helped.

vLLM inference optimization and the llama.cpp equivalents

So far you've seen why decode waits on memory, how big the cache really gets, and which techniques shrink the work. The next question is practical: where do these show up in the software you'd actually run? vLLM and llama.cpp are the two engines most teams use, and they're built for different jobs.

What vLLM gives you out of the box, and what you still tune

vLLM is built around PagedAttention and continuous batching, so your first big win is on by default. It also supports tensor parallelism across GPUs.

What's left for you are the operating-point levers, each of which maps to a technique from the last section:

  • How much GPU memory the engine claims (--gpu-memory-utilization), most of which becomes KV cache space
  • Batch limits (--max-num-batched-tokens and --max-num-seqs)
  • The quantization format of your checkpoint (--quantization)
  • Prefix caching (--enable-prefix-caching)
  • Tensor parallelism (--tensor-parallel-size)
  • Speculative decoding, configured through a speculative config whose shape has changed between releases

Every one of them trades latency for throughput. More cache memory allows bigger batches, and bigger batches raise TTFT. Change one lever at a time, rerun your baseline, and keep the change only if the number you care about moved. Flag names shift between versions, so confirm them against the vLLM documentation for your release.

Change what you measured first: Giving the KV cache more memory raises throughput and TTFT together. If your real complaint is p99 timeouts, look at queueing and batch limits before you quantize anything.

Where llama.cpp fits: quantized weights on CPUs and small GPUs

llama.cpp runs quantized weights on CPUs, Apple silicon, and single consumer GPUs. Tuning it mostly comes down to two choices: the quantization level of the GGUF weight file you download (Q4_K_M and Q8_0 are common starting points) and how many layers you offload to the GPU (-ngl). Context length (-c) and thread count (-t) round out the list. Here the memory math from earlier gets personal: every layer you offload and every token of context you allow has to fit on one small device. It's the right tool for edge devices, local tools, and low-concurrency work where the model has to squeeze onto a small machine.

Side by side, the two engines split like this:

  • vLLM: continuous batching, PagedAttention block allocation, pre-quantized checkpoints, and tensor parallelism across GPUs. Best for many concurrent users on server GPUs.
  • llama.cpp: single or small batches, a contiguous cache sized by context length, a quantization level chosen per weight file, and layer offload to one GPU. Best for local, edge, and low-concurrency use.

TensorRT-LLM, SGLang, and other engines make different tradeoffs again, so benchmark them on your own traffic if neither of these fits.

When self-hosting stops paying for itself

Self-hosting pays off while your GPUs stay busy and your team has time to babysit the stack. Watch for three signs that it's stopped:

  • Upgrade overhead: your engineers lose weeks every quarter to new engine versions and new model releases.
  • Idle GPUs: your cards sit unused between traffic bursts, and you pay for them anyway.
  • Unexplained timeouts: p99 spikes show up that your own metrics can't trace to a cause.

If two of those show up in the same month, run the same open-weight model behind an OpenAI-compatible managed endpoint and compare. Autoscaling from zero takes the idle-GPU problem off your books.

Which is the best platform for AI inference optimization?

To recap: every technique above moves you along the same curve between per-user speed and total throughput. Self-hosting means you pick that point by tuning a cluster. A managed platform can let you pick it per request.

The best platform for AI inference optimization lets you choose your latency-vs-throughput operating point on each request, instead of re-tuning a cluster every time your traffic changes. Telnyx Inference is built that way.

It serves a curated library of open-weight models, including models from z.ai, DeepSeek, and MiniMax, on GPUs Telnyx owns. The endpoints are OpenAI-compatible, so moving over is mostly a base URL change, and the OpenAI migration guide walks through it.

It costs up to 75% less than proprietary alternatives, with no GPU rental fees or minimums, and it supports structured output through JSON mode. The hosted model list shows the current lineup.

Managed API or your own stack: the decision rule

The real question is who should own the infrastructure. A short rule settles it:

  • Self-host when you need a model no managed provider hosts, need custom kernels or a fine-tuned checkpoint you can't upload, or run steady load that keeps your own GPUs busy around the clock.
  • Use a managed API when your traffic is bursty, the model you want is in the hosted lineup, you have regional compute requirements, or your team's time is better spent on the product your customers actually see.

Pick the operating point per request with a serving tier

On Telnyx, the same hosted model and context window run on different serving capacity, so only latency and price change between tiers. You pick with the service_tier field on each request, and the service tiers docs show which models support which tier:

  • Default: standard capacity at standard rates. Every published benchmark and price comparison refers to this tier, and it's what you get if you leave service_tier out.
  • Priority: faster serving capacity for interactive work where a late answer ruins the experience, like orchestration for Voice AI Agents and contact center AI. It's live on select models today, with more models and regions coming.
  • Flex: the lowest rates, for background jobs like offline evaluation, document processing, and summarization where a few minutes of end-to-end latency is fine. Requests stay synchronous, and Flex is available in the US on select models.

That turns the batch-size tradeoff from earlier into a single request field. Test your interactive traffic on Priority, and compare providers on Default so your numbers line up with published benchmarks. Cached input is up to 88% off, which puts a real price tag on prefix caching. You can see the rates for each tier on inference API pricing.

"We often obsess over LLM inference speeds, but in Voice AI, the network is often the silent killer." Ian Reither, COO at Telnyx

The request path is the layer most optimization work skips. Telnyx Inference runs on GPUs across the Americas, Europe, MENA, and APAC, with LATAM coming soon, and the regions and availability page explains how requests route to the nearest region. There's zero data retention and no training on your data, and there are no inter-provider hops between your request and the model. The service autoscales from zero to thousands of requests per second with no cold starts.

Send one request to the Telnyx Inference API

Here's an OpenAI-compatible chat completion sent to the Telnyx endpoint with a model name and one message. To choose a serving tier, add the service_tier field to the request body.

curl -i -X POST "https://api.telnyx.com/v2/ai/chat/completions" \
  -H "Authorization: Bearer $TELNYX_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "moonshotai/Kimi-K3",
    "messages": [{"role": "user", "content": "Hello, World!"}]
  }'

From here, name your bottleneck and pick your fix: tune it yourself in vLLM or llama.cpp, or change one field on a Telnyx request.

Inference optimization FAQ

How much can moving from a closed frontier model to an open-weight model cut our inference cost?

It depends on the model pair and your token mix, but the gap is usually large. Telnyx Inference lists open-weight models at up to 75% less than proprietary alternatives, and cached input at up to 88% off. Agents that resend the same system prompt on every call save the most, because that repeated input is exactly what cached pricing discounts.

Why does the same open-weight model time out or run slower on one provider than another?

The weights are identical, but the serving stack isn't. Providers pick different batch sizes, cache memory, quantization formats, and capacity, and your requests cross different networks to reach the GPU. Bigger batches raise throughput and TTFT together, so a provider tuned for throughput can show p99 spikes that trip your timeout. Compare providers on p99 and end-to-end latency, not average tokens per second.

Are open-weight models good enough to replace a closed model for production AI agents?

For many agent workloads, yes, but test on your own traffic before you switch. Run your real prompts, tool calls, and output formats through the open-weight model, check accuracy, schema adherence, and latency against your current model, and move traffic over in stages. Structured output features like JSON mode help keep tool calls and formats consistent.

What is inference optimization?

Inference optimization is the work of cutting latency, raising throughput, and lowering cost per token when a trained model serves production traffic. It covers the model (quantization, distillation, pruning), the serving stack (batching, cache management, parallelism), and the request path between your app and the GPU. The right technique depends on which of those is your bottleneck.

Is inference optimization still worth doing, or will faster GPUs make it irrelevant?

It's still worth doing. Decode is limited by how fast memory moves bytes, and memory bandwidth improves more slowly than compute, so a faster GPU helps less than quantization or cache paging. Models and context windows also keep growing, which raises memory demand. And no GPU removes queueing delay or a network hop, so the request path still needs your attention.

Fix your bottleneck with one request field

Find your bottleneck, then tune it yourself or change the base URL and one field on a Telnyx request. OpenAI-compatible, in-region GPUs, up to 75% less than proprietary alternatives.

By Content Writer & Editor
Eli is the content writer and editor at Telnyx. Born and raised in Chicago, Eli attended the University of Missouri where he obtained a BA in Journalism. Eli joined Telnyx in August of 2025. In his spare time, you'll find Eli reading, playing video games, or running.
Learn more about Eli Mogul