Deploying Large Language Models (LLMs) in production at enterprise scale is fundamentally a memory bandwidth and compute orchestration challenge. While initial prototypes often rely on single-node setups using monolithic API wrappers, high-throughput production environments demand low Time-To-First-Token (TTFT), minimal Inter-Token Latency (ITL), and high token throughput—all while maintaining high GPU utilization to curb skyrocketing infrastructure costs.
At Ecstaticloud, we recently re-architected an enterprise client’s LLM inference pipeline, moving from a standard Hugging Face Text Generation Inference (TGI) setup to an optimized Kubernetes + KubeRay + vLLM architecture. The result? A 60% reduction in P99 latency and a 3.5x increase in total request throughput on the exact same GPU footprint.
In this deep dive, we will unpack the architectural patterns, memory management mechanics, Kubernetes manifests, and Ray autoscaling strategies required to achieve enterprise-grade LLM serving.
1. The Core Bottleneck: Memory and KV Cache Fragmentation
To understand why traditional inference engines fail under load, we must look at how Transformer-based models handle autoregressive generation.
During generation, every prompt token generates a Key-Value (KV) pair for every attention layer. These pairs are cached in GPU memory (the KV Cache) to avoid recomputing previous tokens during subsequent steps. In naive implementations:
- Memory Reservation is Static: Memory for the maximum possible sequence length (e.g., 4096 or 8192 tokens) is allocated upfront for every incoming request.
- Fragmentation is Severe: Real-world prompts vary wildly in length. Static allocations lead to internal fragmentation (unused space inside reserved blocks) and external fragmentation (unusable memory gaps between requests). Up to 60% to 80% of GPU memory can be wasted on unused KV cache allocations.
Traditional KV Cache Memory Allocation (Static):
[ Request 1: Tokens (128) | Wasted Allocated Space (3968) ] -> Total 4096 reserved
[ Request 2: Tokens (512) | Wasted Allocated Space (3584) ] -> Total 4096 reserved
Result: Severe memory wastage; batch size is artificially constrained.
The Solution: PagedAttention via vLLM
vLLM solves this bottleneck by taking inspiration from virtual memory paging in traditional operating systems.
Through PagedAttention, vLLM breaks the KV cache into fixed-size physical memory blocks (e.g., 16 tokens per block). These blocks do not need to be contiguous in physical GPU memory. The engine maintains a virtual block table that maps logical tokens to physical memory addresses on demand.
PagedAttention Memory Allocation (Dynamic Paging):
Logical Block Table: [Block 0] -> Physical Block #47 (GPU RAM)
[Block 1] -> Physical Block #12 (GPU RAM)
[Block 2] -> Physical Block #89 (GPU RAM)
Result: Zero internal fragmentation (except last block), zero external fragmentation.
By eliminating memory waste, PagedAttention allows you to dramatically increase the batch size (number of concurrent sequences processing on a single GPU), directly accelerating throughput without adding hardware.
2. High-Level System Architecture
To operationalize vLLM across multi-GPU and multi-node clusters on Kubernetes, we pair it with Ray (specifically KubeRay and Ray Serve).
- vLLM Engine: Serves as the high-performance localized execution kernel, handling execution, memory paging, and tensor parallelism.
- Ray Serve: Provides multi-node orchestration, API routing, dynamic batching, worker pool management, and stateful actor execution.
- KubeRay Operator: Manages the lifecycle of Ray clusters natively on Kubernetes declarative APIs.
+------------------------+
| Ingress Controller |
+-----------+------------+
|
v
+------------------------+
| Ray Serve Head Service |
+-----------+------------+
|
+---------------------------+---------------------------+
| |
v v
+---------------------------+ +---------------------------+
| Ray Worker Node (Pod 1) | | Ray Worker Node (Pod 2) |
| +---------------------+ | | +---------------------+ |
| | Ray Serve Replica | | | | Ray Serve Replica | |
| | +---------------+ | | | | +---------------+ | |
| | | vLLM Engine | | | NCCL Inter-Node IPC | | | vLLM Engine | | |
| | +---------------+ | |<=========================>| | +---------------+ | |
| | | Tensor Parallel| | | (High-Bandwidth Network) | | | Tensor Parallel| | |
| | | GPU 0 | GPU 1 | | | | | | GPU 2 | GPU 3 | | |
| +--+--------+-------+--+ | | +--+--------+-------+--+ |
+---------------------------+ +---------------------------+
3. Kubernetes Deployment Blueprint
Let's look at a production-ready Kubernetes setup deploying Llama-3-70B-Instruct across an 8-GPU cluster setup.
Step 1: Provisioning the KubeRay Cluster (RayService)
The RayService CRD manages both the underlying RayCluster infrastructure and the deployment of the Ray Serve application code.
apiVersion: ray.io/v1
kind: RayService
metadata:
name: vllm-llama3-70b-service
namespace: llm-inference
spec:
serviceUnhealthyThreshold: 300
rayClusterConfig:
rayVersion: '2.35.0'
headGroupSpec:
rayStartParams:
dashboard-host: '0.0.0.0'
num-gpus: '0' # Head node routes traffic; no GPUs required
template:
spec:
containers:
- name: ray-head
image: rayproject/ray:2.35.0-py310
resources:
limits:
cpu: "8"
memory: "32Gi"
requests:
cpu: "4"
memory: "16Gi"
ports:
- containerPort: 6379
name: gcs
- containerPort: 8265
name: dashboard
- containerPort: 8000
name: serve
workerGroupSpecs:
- groupName: gpu-group
replicas: 2
minReplicas: 1
maxReplicas: 4
rayStartParams:
num-gpus: '4'
template:
spec:
# Enable shared memory for PyTorch IPC / Distributed execution
volumes:
- name: dshm
emptyDir:
medium: Memory
sizeLimit: 16Gi
containers:
- name: ray-worker
image: vllm/vllm-openai:v0.6.0
securityContext:
capabilities:
add: ["SYS_PTRACE"] # Required for NCCL/CUDA shared memory debugging
resources:
limits:
cpu: "32"
memory: "128Gi"
nvidia.com/gpu: "4"
requests:
cpu: "16"
memory: "64Gi"
nvidia.com/gpu: "4"
volumeMounts:
- mountPath: /dev/shm
name: dshm
env:
- name: NCCL_DEBUG
value: "INFO"
- name: HUGGING_FACE_HUB_TOKEN
valueFrom:
secretKeyRef:
name: hf-token-secret
key: token
Key Cluster Tuning Details:
/dev/shmShared Memory: PyTorch, NCCL, and Ray use POSIX shared memory for inter-process communication (IPC) between GPUs. Kubernetes defaults/dev/shmto 64MB, which will lead to immediateSIGBUScrashes during Tensor Parallel initialization. Mounting anemptyDirbacked by RAM (medium: Memory) is mandatory.- Separation of Head and Worker Nodes: Setting
num-gpus: '0'on the Head node ensures compute-heavy inference actors land exclusively on dedicated GPU workers, isolating cluster orchestration from request execution.
4. Ray Serve Application Implementation
Below is the Python application code integrating vLLM's AsyncLLMEngine inside a scalable Ray Serve deployment. This code handles continuous batching, tensor parallelism across 4 GPUs per worker replica, and asynchronous request streaming.
import asyncio
import uuid
from typing import AsyncGenerator
from ray import serve
from vllm.engine.arg_utils import AsyncEngineArgs
from vllm.engine.async_llm_engine import AsyncLLMEngine
from vllm.sampling_params import SamplingParams
@serve.deployment(
num_replicas=2,
ray_actor_options={"num_cpus": 8, "num_gpus": 4},
max_ongoing_requests=64,
)
class VLLMDeployment:
def __init__(self, model_path: str):
# Configure vLLM Engine
engine_args = AsyncEngineArgs(
model=model_path,
tensor_parallel_size=4, # Splitting model over 4 GPUs via PyTorch NCCL
gpu_memory_utilization=0.90, # 90% dedicated to model weights + KV Cache
max_num_batched_tokens=8192,
max_num_seqs=256,
trust_remote_code=True,
dtype="bfloat16"
)
self.engine = AsyncLLMEngine.from_engine_args(engine_args)
async def generate_stream(self, prompt: str, sampling_params_dict: dict) -> AsyncGenerator[str, None]:
request_id = f"req-{uuid.uuid4().hex}"
sampling_params = SamplingParams(**sampling_params_dict)
# Enqueue request to vLLM's internal dynamic batcher
results_generator = self.engine.generate(prompt, sampling_params, request_id)
previous_text = ""
async for request_output in results_generator:
text = request_output.outputs[0].text
# Calculate delta for Server-Sent Events (SSE)
delta = text[len(previous_text):]
previous_text = text
yield delta
async def __call__(self, request) -> str:
json_data = await request.json()
prompt = json_data.get("prompt")
sampling_params = json_data.get("sampling_params", {})
# Default sampling parameters
if "max_tokens" not in sampling_params:
sampling_params["max_tokens"] = 512
return serve.transforms.StreamingResponse(
self.generate_stream(prompt, sampling_params),
status_code=200,
media_type="text/event-stream"
)
# Bind entrypoint deployment
entrypoint = VLLMDeployment.bind(model_path="meta-llama/Meta-Llama-3-70B-Instruct")
5. Intelligent Autoscaling for Stateful AI Workloads
Standard Kubernetes Horizontal Pod Autoscaling (HPA) based on CPU or RAM metrics is ineffective for LLM inference. GPU memory is pre-allocated by PyTorch at engine startup (gpu_memory_utilization=0.90), meaning GPU memory usage will constantly report near ~90% even when idle.
To scale effectively, autoscaling must be based on real-time engine saturation metrics.
Ray Serve Metric-Driven Autoscaler
We configure Ray Serve’s built-in autoscaler based on active concurrency (target_ongoing_requests):
@serve.deployment(
autoscaling_config={
"min_replicas": 1,
"max_replicas": 8,
"target_ongoing_requests": 30, # Scaled up when worker queue exceeds 30
"upscale_delay_s": 30,
"downscale_delay_s": 600, # Long delay to prevent cold-start thrashing
},
ray_actor_options={"num_cpus": 8, "num_gpus": 4}
)
class VLLMAutoscalingDeployment:
# Class implementation...
pass
Advanced KEDA Autoscaling via vLLM Metrics
For deeper Kubernetes-native scaling, we expose vLLM’s native Prometheus metrics and use KEDA (Kubernetes Event-driven Autoscaling).
vLLM exposes critical metrics including:
vllm:num_requests_waiting: Number of requests queued waiting for KV cache allocation.vllm:gpu_cache_usage_perc: Percentage of physical KV cache memory in use.
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
name: vllm-keda-autoscaler
namespace: llm-inference
spec:
scaleTargetRef:
apiVersion: ray.io/v1
kind: RayService
name: vllm-llama3-70b-service
minReplicaCount: 1
maxReplicaCount: 4
cooldownPeriod: 900
triggers:
- type: prometheus
metadata:
serverAddress: http://prometheus-k8s.monitoring.svc.cluster.local:9090
metricName: vllm_num_requests_waiting
query: sum(vllm:num_requests_waiting{namespace="llm-inference"})
threshold: '5' # Scale up immediately if more than 5 requests are queued
6. Benchmarking & Real-World Results
To measure performance optimizations, we ran load tests simulating standard enterprise traffic (80% short-context conversational prompts, 20% long-document analytical prompts) against Meta-Llama-3-70B-Instruct.
Cluster Hardware Setup
- Nodes: 2x AWS
g5.12xlargeinstances (or equivalent 4x NVIDIA A10G / H100 GPU nodes) - Interconnect: 50 Gbps networking with PyTorch NCCL backend
Baseline vs. vLLM + Ray Performance
| Metric | Baseline (Standard HF + TGI) | Optimized (vLLM + Ray + PagedAttention) | Total Improvement | | :--- | :--- | :--- | :--- | | Max Concurrent Requests | 32 | 148 | +362% Capacity | | P50 TTFT (Time To First Token) | 840 ms | 310 ms | -63% Latency | | P99 TTFT | 3,450 ms | 1,120 ms | -67.5% Latency | | P99 ITL (Inter-Token Latency) | 48 ms/token | 18 ms/token | -62.5% Latency | | Throughput (Tokens/sec/GPU) | 420 tok/sec | 1,520 tok/sec | +261% Throughput |
P99 Time To First Token (TTFT) - Lower is Better
--------------------------------------------------
Baseline (TGI): ██████████████████████ 3450 ms
vLLM + Ray: ████████ 1120 ms [67.5% Reduction]
Throughput (Tokens/sec/GPU) - Higher is Better
--------------------------------------------------
Baseline (TGI): ██████ 420 tok/s
vLLM + Ray: ██████████████████████ 1520 tok/s [3.6x Improvement]
Why the Massive Gains?
- Dynamic Batch Allocation: vLLM's continuous batching dynamically injects new requests mid-iteration without waiting for prior context streams to complete generation.
- Eliminated Memory Fragmentation: PagedAttention unlocked GPU memory that was previously held hostage by static sequence declarations, allowing batch sizes to grow safely without
Out-Of-Memory (OOM)panics.
7. Hardened Production Best Practices
Deploying LLMs at scale requires addressing edge cases before they impact production traffic.
A. Mitigating GPU Cold Starts with Fast Model Loading
Loading Llama-3-70B (approx. 140GB of FP16/BF16 weights) from public object storage over vanilla S3 network protocols takes upwards of 10–15 minutes, stalling autoscaling response times.
- Solution: Use S3 Mountpoint with local caching or distributed read-optimized storage solutions like JuiceFS or AWS FSx for Lustre. Pre-warming models into persistent host volumes reduces container initialization time from 12 minutes to under 45 seconds.
B. Tuning NCCL for Multi-GPU / Multi-Node Topology
Inter-GPU communication during Tensor Parallelism is sensitive to underlying host PCI layout and network topology. Always ensure proper NCCL parameters are exposed in container environments:
# Force NCCL to auto-detect network interfaces correctly inside K8s pods
export NCCL_SOCKET_IFNAME=eth0
export NCCL_IB_DISABLE=0 # Enable InfiniBand/RoCE if hardware supports it
export CUDA_DEVICE_MAX_CONNECTIONS=1 # Prevents kernel launch contention during TP execution
C. Request Shedding and Graceful Degradation
Under unexpected traffic spikes, allowing the KV cache to reach 100% capacity triggers vLLM request preemption (where context blocks are swapped to CPU RAM or dropped entirely), degrading latency.
Set strict bounds on engine utilization to shed load early:
engine_args = AsyncEngineArgs(
...
gpu_memory_utilization=0.88,
max_num_seqs=128, # Bound maximum concurrent requests per actor
)
Pair this with API Gateway-level rate limiting (e.g., Kong, Envoy, or Istio) returning HTTP 429 Too Many Requests rather than letting queues saturate interior worker pods.
Conclusion
Scaling enterprise-grade LLM inference isn't just about throwing bigger GPUs at the problem—it's about maximizing memory layout efficiency and automating dynamic orchestration.
By leveraging vLLM's PagedAttention engine alongside KubeRay on Kubernetes, you transform unpredictable LLM serving into a rock-solid, auto-scalable cloud service that delivers sub-second initial responses while slashing cloud infrastructure bills.
Architecting your AI Cloud Stack?
At Ecstaticloud, we help enterprise engineering teams design, build, and optimize specialized compute platforms, custom Kubernetes operators, and high-performance inference clusters. Reach out to our Cloud Architecture team to benchmark and optimize your AI workloads today.