High-Concurrency LLM Serving: Traffic Scheduling and Inference Optimization

    This article examines the primary bottlenecks in high-concurrency large language model inference services, focusing on GPU memory pressure from KV Cache and latency variability. It provides a practical guide to optimization across three layers: gateway-level traffic scheduling based on token count and memory capacity, container-platform autoscaling driven by queue depth and GPU utilization, and inference engine enhancements through PagedAttention and Continuous Batching. It also covers monitoring metrics, pre-launch stress testing, circuit breaking, and degradation strategies for production reliability.

    The rapid growth in large language model (LLM) inference demand has put increasing pressure on serving infrastructure. This article takes a general architectural perspective to identify the key bottlenecks in high-concurrency scenarios and outlines optimization methods across three layers: scheduling, inference engine, and high availability.

    Two Bottlenecks of High-Concurrency LLM Inference

    Traditional web services typically bottleneck at CPU or network bandwidth. LLM inference services, however, are primarily limited by two different categories of constraints.

    1. GPU Memory Pressure and KV Cache

    During autoregressive generation, the model must store the Key and Value tensors of historical tokens in GPU memory. This data is collectively referred to as the KV Cache. The size of the KV Cache for a single request can be estimated using the following formula:

    KV Cache bytes = 2 × num_layers × num_kv_heads × head_dim × sequence_length × bytes_per_element

    Using a model with 32 layers, 8 KV heads, a head dimension of 128, FP16 precision, and a sequence length of 4096 as an example, a single request consumes approximately 512 MiB. The KV Cache grows linearly with both sequence length and the number of concurrent requests. Sixteen such concurrent requests would demand roughly 8 GiB of GPU memory, before accounting for model weights and intermediate activations. Without proper scheduling that accounts for this overhead, out-of-memory (OOM) errors can crash inference processes.

    2. Tail Latency and Time to First Token (TTFT)

    Static batching requires new requests to wait until the current batch finishes execution or the queue is filled. During traffic peaks, queuing time for new requests becomes unpredictable, causing significant variance in TTFT. The P99 metric is typically far worse than the average, and user-perceived sluggishness often stems from these tail requests.

    Gateway-Level Traffic Scheduling

    The scheduling gateway serves as the first line of defense for high-concurrency distribution. The gateway must parse request bodies, extract the token count of the prompt, the maximum generation length, and the tenant priority, then make routing decisions based on this information. The prompt length should be calculated using the tokenizer’s token count, not the character count, otherwise GPU memory estimates can be significantly inaccurate.

    The following code demonstrates routing based on available GPU memory and priority. This is a simplified example and is not intended for direct production use.

    1. from dataclasses import dataclass
    2. BYTES_PER_ELEM = 2 # FP16, 2 bytes per element
    3. @dataclass
    4. class ModelSpec:
    5. num_layers: int = 32
    6. num_kv_heads: int = 8
    7. head_dim: int = 128
    8. class LLMRouter:
    9. """Simplified example: demonstrates routing based on free memory and priority.
    10. Does not include load testing or failure tolerance details.
    11. Each node in the pool provides these attributes:
    12. - endpoint: node access address
    13. - is_healthy: health status (boolean)
    14. - free_vram_bytes: free GPU memory, in bytes
    15. - current_qps: current requests per second
    16. - weight: positive integer weight
    17. """
    18. def __init__(self, node_pool, spec: ModelSpec, safety_ratio: float = 0.9):
    19. self.nodes = node_pool
    20. self.spec = spec
    21. self.safety_ratio = safety_ratio # Reserve 10% memory as buffer
    22. self._rr_index = 0
    23. def estimate_kv_cache(self, seq_len: int) -> int:
    24. """Estimate KV Cache size in bytes for a given sequence length."""
    25. s = self.spec
    26. return 2 * s.num_layers * s.num_kv_heads * s.head_dim * seq_len * BYTES_PER_ELEM
    27. def route_request(self, request: dict):
    28. prompt_tokens = request.get("prompt_tokens") # Provided by upstream tokenizer
    29. max_tokens = request.get("max_tokens", 1024)
    30. priority = request.get("priority", "normal")
    31. if prompt_tokens is None or prompt_tokens < 0 or max_tokens <= 0:
    32. raise ValueError("Invalid request length parameters")
    33. # Reserve for worst case: prompt length plus max generation length
    34. required = self.estimate_kv_cache(prompt_tokens + max_tokens)
    35. candidates = [
    36. n for n in self.nodes
    37. if n.is_healthy and n.free_vram_bytes * self.safety_ratio >= required
    38. ]
    39. if not candidates:
    40. raise RuntimeError("No healthy node has enough free memory for this request")
    41. if priority == "high":
    42. # High-priority requests go to the node with the lowest current load
    43. target = min(candidates, key=lambda n: n.current_qps)
    44. else:
    45. target = self.weighted_round_robin(candidates)
    46. return target.endpoint
    47. def weighted_round_robin(self, nodes):
    48. """Simple weighted round-robin. Weights must be positive integers.
    49. Expands the list on every call, which is inefficient and for illustration only.
    50. """
    51. expanded = [n for n in nodes for _ in range(max(1, int(n.weight)))]
    52. node = expanded[self._rr_index % len(expanded)]
    53. self._rr_index += 1
    54. return node

    Reserving GPU memory based on the worst case reduces a single node’s concurrent capacity, but it avoids OOM failures. In production, the reserved value can be adjusted to a percentile (e.g., P95) based on the historical distribution of generation lengths, combined with circuit breaking as a safety net.

    Elastic Scaling on a Container Platform

    Inference nodes can run on a cloud-native container platform that automatically scales based on load. The scaling rules should be designed around the gateway’s queue depth and GPU utilization. A common approach is as follows:

    • Scale-out condition: Queue depth exceeds a threshold for a sustained period, and GPU utilization is above a specified level.
    • Scale-in condition: Only reclaim instances after the load has remained below the threshold for a sustained period to avoid thrashing.
    • Cold start handling: Model loading takes considerable time, so a number of pre-warmed instances should be retained.
    • Rollback condition: If the P99 TTFT does not improve after scaling out, stop further scaling, trigger an alert, and initiate manual investigation.

    Thresholds and time windows must be determined through load testing. Values from other services should not be applied directly.

    Inference Engine Optimizations

    Traffic scheduling handles resource allocation. The primary gains in throughput depend on the inference engine itself, with two techniques being the most common.

    1. PagedAttention

    PagedAttention draws inspiration from virtual memory paging in operating systems. It divides the KV Cache into fixed-size blocks, and each request maps to non-contiguous physical blocks through a block table. This eliminates the need for contiguous large blocks of GPU memory, significantly reducing memory fragmentation and improving effective memory utilization. This allows a single GPU to accommodate more concurrent requests. Actual benefits depend on block size, request length distribution, and the scheduling policy: smaller blocks increase block-table management overhead, while larger blocks waste more space in the tail portion.

    2. Continuous Batching (Dynamic Batching)

    Continuous Batching allows completed requests to be removed from the batch at each decoding step, while new requests waiting in the queue are added. Requests no longer wait for the entire batch to finish, GPU compute is utilized more efficiently, and overall token throughput increases. The trade-off is more complex scheduling logic, and a single request’s TPOT (Time Per Output Token) may increase as batch size grows.

    The comparison between the two techniques is summarized below:

    Dimension PagedAttention Continuous Batching
    Problem addressed Memory fragmentation and concurrent capacity Request waiting and compute idle time
    Primary benefit More concurrent requests per GPU Higher overall token throughput
    Impact on latency Minimal direct negative impact TPOT may increase with larger batches
    Implementation dependency Engine-supported paged memory management Engine-level iteration scheduler

    Monitoring, Load Testing, and High Availability

    1. Core Monitoring Metrics

    • TTFT (Time to First Token): Reflects queuing and prefill efficiency.
    • TPOT (Time Per Output Token): Reflects decoding phase compute and memory access efficiency.
    • GPU memory and compute utilization: Identifies resource waste or bottlenecks.
    • Queue depth, OOM count, circuit breaker trips: Indicate whether capacity is sufficient.

    2. Pre-Launch Load Testing Checklist

    • The change curve of P99 TTFT and TPOT as concurrency increases step by step.
    • Peak GPU memory usage under different prompt length and generation length combinations.
    • Whether scale-out triggers as expected when queue depth reaches the threshold.
    • Whether circuit breaking and retries work correctly when a node fails.

    3. Circuit Breaking and Degradation

    The gateway should set circuit breaker rules for each inference node. When a node’s error rate or timeout ratio exceeds the threshold for a sustained period, the gateway removes it from the available set. After a cooldown period, probe requests are sent to verify recovery before the node is returned to service. Thresholds must be based on load test results.

    When compute capacity is insufficient during traffic peaks, degradation should be carried out in the following order:

    1. Rate-limit low-priority requests.
    2. Reduce the default max_tokens.
    3. Fail fast on queued requests that have exceeded their wait time, rather than continuing to consume resources.
    4. Retry only on healthy nodes.

    Retries amplify load. Non-idempotent and streaming requests are not suitable for direct retries, and a retry budget should be set to prevent localized failures from becoming a cascading outage. Since degradation strategies can also affect normal business, a dedicated priority channel for core traffic should be preserved at each step, and alerts should be observed to evaluate the effect.

    4. Common Issues

    • High TTFT under load: Check queue depth first, then assess GPU memory pressure on nodes, and finally confirm whether the batching policy is appropriate.
    • KV Cache fragmentation: Monitor block utilization and free block counts exposed by the engine, and record OOM occurrence counts.
    • Dynamic batching is suitable for online services with high concurrency and wide variance in request lengths. For offline batch jobs, static batching is simpler to implement and may yield comparable benefits.

    Summary

    High-concurrency challenges in LLM serving cannot be solved by simply scaling up hardware. The gateway must route based on token count and available GPU memory, the container platform must autoscale based on queue depth and GPU utilization, the inference engine must improve throughput through PagedAttention and Continuous Batching, and the outer layer must ensure availability through circuit breaking, degradation, and monitoring. Thresholds at each layer should be determined through load testing and continuously adjusted as traffic patterns evolve.