Deploying Long-Context LLM Inference Services: Capacity Planning and API Design
A practical guide to deploying large language model inference services for long-context workloads. Covers KV cache sizing, hardware and parallelism choices, KV cache management, prefill-decode disaggregation, reasoning effort tiers, tool call parsing, observability, and a pre-launch checklist.
Deploying Long-Context LLM Inference Services: Capacity Planning and API Design
1. Where the Deployment Cost of Long-Context Inference Comes From
GPU memory usage in LLM inference comes from two sources: model weights and the KV cache. Weight memory is determined by parameter count and numerical precision, and is independent of request content. The KV cache, however, grows with context length and the number of concurrent requests. A single long-context request, without cache compression, can produce a KV cache larger than the weights themselves—so both should be estimated separately during capacity planning.
KV cache capacity can be estimated with this rule of thumb:
KV cache size ≈ 2 × num_layers × num_KV_heads × head_dim × context_length × bytes_per_element × num_concurrent_requests
The “2” accounts for separate Key and Value caches. As an illustrative calculation (using hypothetical parameters to show the method, not a real model’s configuration): 60 layers, 8 KV heads, head dimension 128, context length 128K (131,072 tokens), 2 bytes per element (FP16). A single request’s KV cache comes to roughly 30 GiB. Serving 4 such requests concurrently requires about 120 GiB of cache.
Two takeaways are worth remembering. First, doubling the context length doubles the cache requirement. Second, concurrency often drives memory pressure harder than single-request length. Quantizing the KV cache to 8 bits halves its footprint, at the cost of verifying that output quality remains acceptable.
2. Hardware Selection and Parallelism Strategies
2.1 Single-Node Multi-GPU vs. Multi-Node
Interconnect bandwidth between accelerators within a single node is typically higher than cross-node networking, so when the model is large, prefer tensor parallelism within a single node. Cross-node deployment introduces additional communication latency and is better suited to cases where a single node cannot fit the model.
2.2 Choosing a Parallelism Scheme
Common parallelism schemes include:
- Tensor parallelism: splits the matrix computations of each layer across multiple GPUs, reducing per-GPU memory usage, but requires inter-GPU communication at every layer.
- Data parallelism: runs multiple full replicas, each handling different requests to improve throughput, but each replica must hold the complete weights.
- Expert parallelism: for Mixture-of-Experts (MoE) architectures, distributes different experts across GPUs, requiring handling of expert routing and load balancing.
The number of data-parallel replicas should evenly divide the GPU count. For example, 8 GPUs can host 2 replicas (4 GPUs each) or 4 replicas (2 GPUs each), but not an uneven allocation.
2.3 Example Deployment Configuration
A deployment configuration typically includes the following elements; use the parameter names documented by your inference framework:
service:gpu_count: 8parallel_mode: tensor_and_data # Combined tensor and data parallelismdata_parallel_size: 2 # 2 replicas, 4 GPUs eachkv_cache_dtype: fp8 # KV cache quantization precisionmax_model_len: 131072 # Max context per requestmax_num_seqs: 16 # Max concurrently processed sequences
3. KV Cache Management and Block Size
Mainstream inference frameworks typically manage the KV cache with paged allocation, dividing GPU memory into fixed-size blocks. Block size affects memory fragmentation and attention computation efficiency. Many low-level compute kernels impose requirements on block size, so in practice it is a hard constraint—follow the framework’s recommended value rather than changing it arbitrarily.
Another common optimization is prefix caching. When multiple requests share the same system prompt or document prefix, the server can reuse the already-computed KV cache, avoiding repeated prefill computation. On the application side, placing fixed instructions at the beginning of messages and variable content at the end significantly improves prefix cache hit rates.
4. Prefill and Decode Disaggregation
LLM inference has two phases. The prefill phase processes the entire input at once; it is compute-intensive and largely compute-bound. The decode phase generates output tokens one at a time, reading large amounts of KV cache at every step; it is largely memory-bandwidth-bound. Because the two phases have different hardware demands, colocating them on the same set of instances often causes them to interfere with each other.
Prefill-decode (PD) disaggregation works as follows: one group of instances handles prefill exclusively, another handles decode exclusively, and once prefill completes, the KV cache is transferred to the decode instances over a high-speed network.
Client -> Router -> Prefill instances --KV cache transfer--> Decode instances -> Client
The benefit of disaggregation is that the two instance groups can scale independently, and long-input requests no longer block short requests’ output. The cost is that KV cache transfer requires a high-bandwidth, low-latency network; otherwise transfer time erases the gains. Whether to adopt a disaggregated architecture should be decided only after load testing with a realistic distribution of input and output lengths.
The router distributes requests. Round-robin is simple to implement and suits workloads with fairly uniform request lengths. When request lengths vary widely or prefix cache hit rate matters, consider load-aware or cache-aware routing strategies.
5. Designing Reasoning Effort Tiers
The same model often supports multiple reasoning effort levels—for example, no thinking, light thinking, and deep thinking. Each tier makes different trade-offs among first-token latency, generation length, and output quality:
| Tier | Typical Use Cases | Characteristics |
|---|---|---|
| No thinking | Simple Q&A, format conversion, batch classification | Lowest latency, lowest cost |
| Light thinking | General analysis, code completion | Moderate latency, balanced quality |
| Deep thinking | Complex reasoning, hard math and coding problems | Many generated tokens, high latency, highest quality |
In production, do not route all requests to the highest tier. The recommended approach: map business scenarios to tiers at the gateway layer, and set a maximum output token budget for each tier. This controls cost and prevents individual requests from occupying decode resources for extended periods.
A single request’s duration can be roughly estimated as first-token latency plus output token count divided by decode speed. Deep thinking tiers often generate several times more tokens than standard tiers, so they have the greatest impact on timeout settings and concurrency limits.
6. API Calls and Tool Call Parsing
6.1 Request Format
Most inference services use a message structure similar to common chat completion APIs, with role and content fields. Below is a generic example; the endpoint, model identifier, and key are injected via environment variables to avoid hardcoding:
import jsonimport osimport urllib.requestdef ask(prompt: str) -> str:payload = {"model": os.environ["MODEL_ID"],"messages": [{"role": "user", "content": prompt}],"max_tokens": 1024,}req = urllib.request.Request(url=os.environ["SERVICE_URL"],data=json.dumps(payload).encode("utf-8"),headers={"Content-Type": "application/json","Authorization": f"Bearer {os.environ['SERVICE_API_KEY']}",},method="POST",)with urllib.request.urlopen(req, timeout=120) as resp:body = json.loads(resp.read().decode("utf-8"))return body["choices"][0]["message"]["content"]
Timeouts should match the reasoning effort tier. Deep thinking tiers need significantly longer timeouts than no-thinking tiers; otherwise the server may still be computing while the client has already disconnected.
6.2 Parsing Tool Calls
When the model needs external capabilities, it emits structured tool call content. The server must use a parser to convert the model’s text output back into function names and arguments. The parser must match the model’s chat template and output format; on a format mismatch, tool calls may be returned as plain text or fail to parse.
After receiving a tool call, the application should do three things:
- Verify that the function name is on the allowlist.
- Validate argument types and value ranges against the parameter schema.
- Design idempotency mechanisms for side-effecting operations so retries don’t cause duplicate execution.
Model-generated arguments are untrusted and should be treated like external user input—never concatenated directly into database queries or system commands.
7. Observability and Capacity Planning
An inference service should at minimum monitor the following metrics:
- Time to first token (TTFT): time from request to the first output token, reflecting perceived responsiveness.
- Time per output token (TPOT): average decode speed, reflecting the experience of long outputs.
- Throughput: tokens or requests processed per unit of time.
- Queue length and wait time: indicates whether the service is saturated.
- KV cache utilization: near capacity, new requests get queued or rejected.
- Error rate and timeout rate: tracked separately by reasoning tier and business line.
Capacity planning should be based on real traffic. First sample the input and output length distributions of production requests, then load test with those distributions to find the maximum concurrency that meets latency targets. Load testing with fixed-length test data tends to overestimate service capacity.
Rate limiting can be computed in tokens rather than requests. A request with a million-token context can consume thousands of times more resources than a short question—per-request rate limiting cannot reflect that difference.
8. Pre-Launch Checklist
- KV cache estimated based on context length and concurrency, with headroom reserved.
- Parallelism configuration matches the GPU count; replica counts divide evenly.
- KV cache precision and block size validated against framework requirements; output quality spot-checked.
- Reasoning tiers mapped to business scenarios, with output token caps and timeouts set per tier.
- Parser matches the model’s output format; tool call arguments validated against schemas.
- Secrets injected via environment variables or a secrets manager; no sensitive data in logs.
- Monitoring and alerting configured for TTFT, throughput, KV cache utilization, and other key metrics.
- Load testing completed with realistic length distributions, and capacity limits documented.
The core of deploying LLM services is getting the constraints of three resource classes—memory, compute, and network—clearly quantified, then choosing parallelism, caching strategies, and reasoning tiers accordingly. Estimate first, load test second, launch last: this avoids most incidents caused by capacity misjudgment.
