Sub topic 16
Serving-side techniques for self-hosted models
This chapter assumes you have read the earlier chapters on tokens, latency anatomy, and measurement. It also assumes you can run Python and have a rough idea of what a GPU does. Everything here applies only if you run the model yourself. With a hosted API, the provider applies these techniques for you, and you can only see their effect in price and speed.
The weight of this chapter is small on purpose. Most teams should exhaust the earlier levers first: right-sized models, shorter prompts, output limits, caching, and batching. Serving-side work pays off when you run enough traffic to keep GPUs busy, or when data rules prevent you from using a hosted API.
Why serving is different from calling an API
When you call a hosted API, you pay per token. When you host a model, you pay for GPU time, whether the GPU is busy or idle. Cost per token then depends on utilization:
cost per token = GPU cost per hour / tokens produced per hour
Every technique below does one of two things. It raises the tokens produced per GPU hour, or it lowers the latency each request sees. Often it trades one against the other.
Recall the two phases of a request from the latency chapter:
- Prefill processes the whole prompt in parallel. It is limited by compute.
- Decoding produces one token at a time. Each step must read the model weights and the cached attention state from GPU memory, so it is limited by memory bandwidth.
Because decoding is bandwidth-bound, a GPU running one request leaves most of its compute idle. Most serving techniques exist to put that idle compute to use.
Continuous batching
Static batching groups requests, runs them together, and waits until the longest one finishes. Short requests sit idle while long ones continue, and new requests wait for the whole batch.
Continuous batching (also called in-flight batching) schedules at the level of single decoding steps. After every step, finished requests leave the batch and waiting requests join. The GPU stays full, and short requests are not held hostage by long ones.
This is the default in modern serving engines such as vLLM, TensorRT-LLM, and Hugging Face Text Generation Inference. If you write your own loop around a model with a fixed batch, you are probably leaving large throughput gains unused.
The trade-off is that a busier batch makes each decoding step slightly slower. Throughput rises sharply, while per-request inter-token time rises modestly. Under heavy load, queueing delay grows when the batch is full, so time to first token suffers first.
The KV cache and memory
During decoding, the model stores the attention keys and values for every earlier token. This is the KV cache. It avoids recomputing the whole prompt at each step, but it takes GPU memory, and the amount grows with:
- the number of concurrent requests,
- the length of each request (prompt plus output),
- the model's size and number of layers.
The KV cache, not compute, often limits how many requests you can run at once. A long context window that you rarely use can still reduce concurrency if the server reserves memory for it.
Engines such as vLLM use paged attention. They split the KV cache into small blocks that are allocated on demand, like virtual memory pages. This removes most of the waste from reserving the maximum length for every request, and it lets more requests share a GPU.
Practical consequences:
- Set the maximum context length to what you need, not to the model's maximum.
- Set output limits (the earlier chapter on output control), because they cap KV growth.
- Watch KV cache utilization as a metric. When it nears full, the server queues or evicts requests, and latency spikes.
Prefix caching
The provider prompt caching chapter described reusing stable prompt prefixes on hosted APIs. Self-hosted engines offer the same idea. With prefix caching, the server keeps the KV cache for prompts it has already processed. A new request that starts with the same tokens skips prefill for that shared part.
This helps most when many requests share a long system prompt, a fixed set of few-shot examples, or a shared document. It reduces time to first token and prefill compute. It works only for an exact token prefix, so the same rule applies as before: put stable content first and variable content last.
Quantization
Quantization stores model weights (and sometimes the KV cache) in fewer bits. A model in 16-bit precision can often run in 8-bit or 4-bit.
| Precision | Weight memory per billion parameters | Typical effect |
|---|---|---|
| 16-bit | about 2 GB | Baseline quality |
| 8-bit | about 1 GB | Small quality loss, often hard to notice |
| 4-bit | about 0.5 GB | Larger memory savings, quality loss varies by model and task |
Smaller weights help in two ways. The model fits on fewer or cheaper GPUs, and decoding reads fewer bytes per step, so it runs faster. The risk is quality loss, especially on reasoning, code, and non-English text. Quantization is a model change, so it goes through your evaluation set like any other model change. Do not assume a benchmark result from the model card holds for your task.
Speculative decoding
Decoding is one token per step, and each step is bandwidth-bound. Speculative decoding uses a small draft model to guess several tokens ahead. The large model then checks all the guessed tokens in a single parallel pass and keeps the ones it agrees with.
Under the standard acceptance rule, the output distribution matches what the large model would have produced alone. You get lower latency without a change in quality, in principle. The gain depends on the acceptance rate:
- Predictable text, such as code, structured output, or text that copies from the prompt, gets high acceptance and a good speedup.
- Creative or high-temperature output gets lower acceptance, and the speedup shrinks.
- At high load, the GPU has less idle compute to spend on verification, so the benefit falls.
Speculative decoding mainly improves latency for individual requests. It does not usually help throughput under heavy load.
Parallelism across GPUs
If a model does not fit on one GPU, you split it. Tensor parallelism splits each layer across GPUs, which lowers per-token latency but needs fast links between them. Pipeline parallelism assigns different layers to different GPUs, which is easier on interconnects but adds latency. Prefer the smallest number of GPUs that fits the model with room for the KV cache. Adding GPUs to a model that already fits mostly adds communication overhead. Often you get better value by running several independent replicas behind a load balancer.
Disaggregating prefill and decoding
Prefill is compute-heavy and decoding is memory-heavy. On the same GPU, a long prefill can stall decoding for other requests, which shows up as stutter in streamed output. Two mitigations exist:
- Chunked prefill splits long prompts into pieces that are interleaved with decoding steps.
- Disaggregated serving runs prefill and decoding on separate GPU pools.
Both are advanced options. Try chunked prefill first, since many engines support it with one setting.
A decision flow
Measuring a self-hosted server
The baseline from the measurement chapter still applies. Add server-side metrics:
- Queue time and time to first token, per percentile.
- Inter-token latency and output tokens per second.
- GPU utilization and KV cache utilization.
- Number of running and waiting requests.
- Cost per million tokens, computed from GPU price and real throughput.
The last one lets you compare self-hosting against a hosted API fairly. The following sketch computes it. The GPU price and throughput are placeholders, so replace them with your own numbers.
def cost_per_million_tokens(gpu_cost_per_hour: float,
gpus: int,
tokens_per_second: float,
utilization: float) -> float:
"""Cost of one million output tokens on a self-hosted deployment.
utilization is the fraction of time the server is doing useful work (0 to 1).
"""
tokens_per_hour = tokens_per_second * 3600 * utilization
hourly_cost = gpu_cost_per_hour * gpus
return hourly_cost / tokens_per_hour * 1_000_000
# Placeholder numbers: replace with your own measurements.
busy = cost_per_million_tokens(2.50, 1, 1500, 0.70)
quiet = cost_per_million_tokens(2.50, 1, 1500, 0.10)
print(f"70% utilized: ${busy:.2f} per million tokens")
print(f"10% utilized: ${quiet:.2f} per million tokens")The same hardware costs seven times more per token at 10% utilization than at 70%. Self-hosting rarely wins at low or spiky traffic, because you pay for idle GPUs.
Common errors
- Tuning before measuring. Changing batch limits or precision without a baseline makes it impossible to tell what helped.
- Optimizing throughput when users feel latency. A large batch limit raises tokens per second but can push time to first token past your target.
- Shipping quantized models without evaluation. Memory savings are easy to verify, quality loss is not.
- Leaving the maximum context length at the model default, which wastes KV cache memory.
- Comparing self-hosting cost at peak utilization only. Use average utilization over a week.
- Ignoring operations cost. Engineers' time, on-call, upgrades, and GPU capacity planning belong in the comparison.
When to stay on a hosted API
Stay hosted when traffic is low or uneven, when you need the strongest models, or when you lack staff to run GPU infrastructure. Move to self-hosting when utilization stays high, when you can use a smaller or fine-tuned model that fits your task, or when data control requires it. Many teams keep a hybrid: self-host the high-volume, simple traffic, and route hard requests to a hosted model using the routing and cascade approach from the previous chapters.
Exercise
Your self-hosted server shows high GPU utilization, KV cache utilization near 100%, and a growing waiting queue. Time to first token has doubled this week. Name two changes that could reduce the pressure on the KV cache, and one risk of each.
Show answer
Options include lowering the maximum context length or adding output limits (risk: some legitimate long requests are truncated or rejected), quantizing the weights or KV cache (risk: quality loss on your task, so re-run the evaluation set), and adding a replica (risk: higher GPU cost). Any two of these with their risks are correct. Enabling prefix caching also reduces pressure if many requests share a prefix, with the risk that it only helps for exact shared prefixes.
Exercise
A server costs $3.00 per hour and produces 2,000 output tokens per second at 50% utilization. What is the cost per million output tokens? Would doubling utilization to 100% at the same speed halve it?
Show answer
Tokens per hour = 2,000 x 3,600 x 0.5 = 3,600,000. Cost per million = 3.00 / 3,600,000 x 1,000,000 = about $0.83. Yes, doubling utilization at the same throughput while busy halves the cost to about $0.42, but only if there is enough traffic and latency stays acceptable at that load.