Deploying Large Language Models (LLMs) like Llama 3 70B or Mixtral 8x22B in production introduces systemic infrastructure bottlenecks that standard microservice patterns cannot solve. Traditional Kubernetes horizontal pod autoscaling (HPA) relies on CPU or GPU utilization metrics—metrics that quickly break when applied to LLM serving engines. Because engines like vLLM pre-allocate VRAM for Key-Value (KV) caching upon initialization, GPU utilization metrics remain pegged near 100% regardless of whether the engine is processing active queries or sitting idle.
Furthermore, serving multi-billion parameter models requires partitioning state across multiple GPUs—and frequently across multiple nodes—using Tensor Parallelism (TP) and Pipeline Parallelism (PP). Standard Kubernetes primitives lack awareness of intra-node GPU topologies and inter-node network fabrics like AWS Elastic Fabric Adapter (EFA).
To deliver low sub-second Time to First Token (TTFT) and high Time Per Output Token (TPOT) throughput without inflating infrastructure costs, platform engineers must combine hardware-aware runtime engines with distributed application orchestrators.
In this deep dive, we will architect a production-grade, multi-node distributed LLM inference system on AWS Elastic Kubernetes Service (EKS) using vLLM as the high-performance execution engine and Ray Serve as the distributed orchestration layer.
1. Deconstructing the Inference Bottleneck
To optimize LLM inference, we must first analyze where memory allocations and latency spikes occur during the forward pass.
+-------------------------------------------------------+
| Total GPU Memory |
+-------------------------------------------------------+
| Model Weights | KV Cache Pool | Activations |
| (FP16/BF16/INT4) | (PagedAttention) | & Overhead |
+-------------------------------------------------------+
The Memory Breakdown
The static VRAM footprint for an unquantized model scaled in FP16 precision is dictated by:
$$\text{Memory}_{\text{weights}} \approx 2 \times \text{Parameter Count (in billions) GB}$$
For Llama 3 70B, the model weights alone consume approximately 140 GB of VRAM. Beyond the static weights, two dynamic allocations compete for memory:
- Activation Memory: Temporary buffers required for intermediate layer outputs during the forward pass.
- KV Cache Memory: Retained key-value tensors for previous tokens in a sequence, preventing redundant recomputation during auto-regressive generation.
The KV Cache Bloat and Fragmentation
In standard Transformers implementations, the KV cache allocation is contiguous and sized according to the maximum theoretical sequence length (max_seq_len). For long context windows (e.g., 8k to 128k tokens), this results in severe internal memory fragmentation. If a request terminates early, memory allocated for its theoretical max sequence length remains locked, reducing overall system throughput.
2. vLLM Engine Optimization Strategies
vLLM addresses these memory and scheduling constraints through two core mechanisms: PagedAttention and Continuous Batching.
Logical KV Cache Blocks (Virtual Memory)
+---------+---------+---------+
| Block 0 | Block 1 | Block 2 | ...
+---------+---------+---------+
| | | (Page Table Mapping)
v v v
+---------+---------+---------+
| Frame B | Frame A | Frame C | ...
+---------+---------+---------+
Physical GPU Memory Pages (Non-Contiguous VRAM)
PagedAttention
Inspired by virtual memory paging in operating systems, PagedAttention partitions the KV cache into fixed-size physical memory blocks (typically 16 or 32 tokens).
- Logical vs. Physical Memory: Physical blocks do not need to be contiguous in VRAM. The vLLM engine maintains a lookup table mapping logical request sequences to physical GPU memory pages.
- Near-Zero Waste: Memory allocation occurs on-demand per block generation. Unused space is restricted to the final block of a sequence, reducing KV cache memory waste from over 60–80% down to under 4%.
Continuous (Iteration-Level) Batching
Traditional serving platforms use dynamic batching at the sequence level. A batch sits in memory until the slowest request finishes generating all tokens (tail latency amplification).
vLLM implements iteration-level continuous batching:
- After every single forward pass (token generation step), completed sequences are evicted immediately, freeing their KV cache blocks.
- Waiting requests in the queue are scheduled directly into the next forward-pass iteration alongside ongoing generations.
3. Distributed Architecture: Ray Serve + vLLM on EKS
While vLLM optimizes single-node/single-GPU performance, orchestrating multi-node execution requires higher-level abstractions. Ray Serve manages distributed placement, dynamic routing, request queues, and distributed deployment scaling across heterogeneous compute pools.
Architectural Layout
[ Ingress Layer / AWS ALB ]
|
v
[ Ray Serve Router Pod ]
/ \
/ \
[ Ray Head Node ] [ Worker Node (NVIDIA GPU) ]
+------------------+ +----------------------------+
| Ray Cluster | | Ray Worker Actor |
| Orchestrator | | +------------------------+ |
| & Service Mesh | | | vLLM Engine Replica | |
+------------------+ | | (Tensor Parallel = 4) | |
| +------------------------+ |
+----------------------------+
|| (EFA / NCCL)
+----------------------------+
| Worker Node (NVIDIA GPU) |
| Ray Worker Actor |
| +------------------------+ |
| | vLLM Engine Replica | |
| | (Pipeline Parallel = 2)| |
| +------------------------+ |
+----------------------------+
Infrastructure Components
- AWS EKS Control Plane: Manages Kubernetes native resources.
- Karpenter: Automates rapid provisioning of specialized GPU node types (
g5.12xlarge,p4d.24xlarge,p5.48xlarge). - KubeRay Operator: Manages lifecycle of
RayClustercustom resources (Head vs. Worker pods). - AWS Elastic Fabric Adapter (EFA): Network interface bypassing the OS kernel for high-throughput, low-latency inter-node communication using NCCL (NVIDIA Collective Communications Library).
4. Provisioning Infrastructure with Karpenter
Standard Cluster Autoscaler is too slow when bootstrapping GPU instances with large storage footprints. We utilize Karpenter to rapidly scale EC2 instances configured with high-performance local NVMe drives and EFA devices.
Karpenter EC2NodeClass Manifest
Save this manifest as karpenter-gpu-nodeclass.yaml:
apiVersion: karpenter.k8s.aws/v1beta1
kind: EC2NodeClass
metadata:
name: gpu-efa-nodeclass
spec:
amiFamily: AL2
role: "KarpenterNodeRole-EKS-LLM-Cluster"
subnetSelectorTerms:
- tags:
karpenter.sh/discovery: "eks-llm-cluster"
securityGroupSelectorTerms:
- tags:
karpenter.sh/discovery: "eks-llm-cluster"
amiSelectorTerms:
- name: "amazon-eks-gpu-node-1.30-*"
# Configure local NVMe SSD raid arrays for model weights caching
userData: |
#!/bin/bash
set -o errexit
set -o pipefail
set -o nounset
# Format and mount NVMe drives for fast ephemeral caching
if lsblk | grep -q nvme1n1; then
mkfs.ext4 /dev/nvme1n1
mkdir -p /mnt/fast-scratch
mount /dev/nvme1n1 /mnt/fast-scratch
chmod 777 /mnt/fast-scratch
fi
blockDeviceMappings:
- deviceName: /dev/xvda
ebs:
volumeSize: 200Gi
volumeType: gp3
iops: 10000
throughput: 1000
Karpenter NodePool Manifest
Save this manifest as karpenter-gpu-nodepool.yaml:
apiVersion: karpenter.sh/v1beta1
kind: NodePool
metadata:
name: gpu-nodepool-p4d
spec:
template:
metadata:
labels:
workload: llm-inference
accelerator: nvidia-a100
spec:
nodeClassRef:
name: gpu-efa-nodeclass
requirements:
- key: "karpenter.k8s.aws/instance-family"
operator: In
values: ["p4d", "g5"]
- key: "karpenter.k8s.aws/instance-size"
operator: In
values: ["24xlarge", "12xlarge"]
- key: "kubernetes.io/arch"
operator: In
values: ["amd64"]
- key: "karpenter.sh/capacity-type"
operator: In
values: ["on-demand"]
taints:
- key: nvidia.com/gpu
value: "true"
effect: NoSchedule
limits:
cpu: 1000
memory: 4000Gi
nvidia.com/gpu: 64
disruption:
consolidationPolicy: WhenEmpty
consolidateAfter: 30m
5. KubeRay Deployment Configuration
With the infrastructure provisioning tier ready, we define the RayCluster spec using the KubeRay Operator. This establishes the orchestration fabric for Ray workers.
Save this manifest as ray-cluster-vllm.yaml:
apiVersion: ray.io/v1
kind: RayCluster
metadata:
name: ray-vllm-cluster
namespace: llm-serving
spec:
rayVersion: '2.35.0'
headGroupSpec:
rayStartParams:
dashboard-host: '0.0.0.0'
num-gpus: '0'
template:
spec:
containers:
- name: ray-head
image: rayproject/ray-ml:2.35.0-py310-gpu
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:
block: 'true'
template:
spec:
nodeSelector:
workload: llm-inference
tolerations:
- key: nvidia.com/gpu
operator: Exists
effect: NoSchedule
containers:
- name: ray-worker
image: rayproject/ray-ml:2.35.0-py310-gpu
securityContext:
capabilities:
add: ["SYS_PTRACE"]
resources:
limits:
cpu: "48"
memory: "192Gi"
nvidia.com/gpu: "4"
vpc.amazonaws.com/efa: "4"
requests:
cpu: "40"
memory: "160Gi"
nvidia.com/gpu: "4"
vpc.amazonaws.com/efa: "4"
volumeMounts:
- mountPath: /tmp/ray
name: ray-health-tmp
- mountPath: /mnt/fast-scratch
name: model-cache
volumes:
- name: ray-health-tmp
emptyDir: {}
- name: model-cache
hostPath:
path: /mnt/fast-scratch
type: DirectoryOrCreate
6. Developing the Distributed Ray Serve Deployment
We now build an asynchronous, concurrent Ray Serve class that integrates with vLLM's AsyncLLMEngine. This application parses distributed requests, handles batch streaming, and coordinates Tensor Parallelism execution.
Save this script as deploy_vllm_serve.py:
import os
import asyncio
from typing import AsyncGenerator
import json
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
from vllm.utils import random_uuid
@serve.deployment(
name="vLLM-Deployment",
num_replicas=2,
ray_actor_options={
"num_cpus": 8,
"num_gpus": 4, # Allocates 4 GPUs per replica via Tensor Parallelism
},
max_ongoing_requests=256
)
class VLLMServeDeployment:
def __init__(self):
# Configure model loading and hardware parallelism engine configuration
model_name = os.getenv("MODEL_ID", "meta-llama/Meta-Llama-3-70B-Instruct")
engine_args = AsyncEngineArgs(
model=model_name,
tensor_parallel_size=4, # Split model across 4 GPUs
pipeline_parallel_size=1,
trust_remote_code=True,
gpu_memory_utilization=0.90, # 90% of VRAM reserved for KV Cache
max_num_batched_tokens=32768,
max_model_len=8192,
download_dir="/mnt/fast-scratch/huggingface",
dtype="bfloat16",
engine_use_ray=True,
)
# Instantiate vLLM Async Engine
self.engine = AsyncLLMEngine.from_engine_args(engine_args)
async def generate(self, prompt: str, sampling_params_dict: dict) -> AsyncGenerator[str, None]:
"""Asynchronously streams generated tokens from vLLM dynamic execution engine."""
sampling_params = SamplingParams(**sampling_params_dict)
request_id = f"req-{random_uuid()}"
results_generator = self.engine.generate(prompt, sampling_params, request_id)
previous_text = ""
async for request_output in results_generator:
# Calculate stream diff (delta) for SSE output
text_chunk = request_output.outputs[0].text[len(previous_text):]
previous_text = request_output.outputs[0].text
response_payload = {
"text": text_chunk,
"finished": request_output.finished,
"request_id": request_id
}
yield f"data: {json.dumps(response_payload)}\n\n"
async def __call__(self, request) -> serve.responses.StreamingResponse:
"""HTTP Protocol Handler for API Routing."""
json_data = await request.json()
prompt = json_data.get("prompt", "")
sampling_params = json_data.get("sampling_params", {
"temperature": 0.7,
"max_tokens": 512,
"top_p": 0.95
})
return serve.responses.StreamingResponse(
self.generate(prompt, sampling_params),
status_code=200,
media_type="text/event-stream"
)
# Instantiate deployable Serve application
app = VLLMServeDeployment.bind()
7. Optimizing AWS Inter-Node Networking (EFA & NCCL)
When executing cross-node distributed inference (e.g., standard Pipeline Parallelism across multiple g5.12xlarge instances), network inter-node latency dominates token generation speeds.
Enabling Elastic Fabric Adapter (EFA)
EFA provides OS-bypass hardware capabilities, exposing standard Libfabric APIs to NVIDIA NCCL. To optimize inter-GPU communication over the network topology, ensure the following environment configurations are injected into the Ray container runtime:
env:
- name: FI_PROVIDER
value: "efa"
- name: FI_EFA_USE_DEVICE_RDMA
value: "1" # Enables direct GPUDirect RDMA transfers over EFA
- name: NCCL_DEBUG
value: "INFO"
- name: NCCL_BUFFSIZE
value: "4194304" # Increase payload buffer size to 4MB for high-throughput all-reduce
8. Performance Benchmarking & Scaling Strategy
Autoscale Driven by Queue Latency
Do not use CPU/GPU metrics to target HPA scaling thresholds. Instead, monitor Ray Serve metric abstractions:
ray_serve_deployment_queued_queries: Total requests waiting in system backpressure queues.ray_serve_deployment_processing_latency_ms: Total execution latency.
Configure Ray Serve dynamic autoscaling based on pending queue backpressure within the script deployment spec:
@serve.deployment(
autoscaling_config={
"min_replicas": 2,
"max_replicas": 8,
"target_ongoing_requests": 64, # Scale out when average request queue hits 64
"upscale_delay_s": 30,
"downscale_delay_s": 600,
}
)
Critical Metrics Breakdown
| Metric | Target Optimization | Primary Bottleneck Factors |
| :--- | :--- | :--- |
| TTFT (Time to First Token) | Low Latency (<200ms) | Prefill phase execution time, Compute bound (GEMM operations), Context Length size. |
| TPOT (Time Per Output Token)| High Throughput (<30ms/tok)| Decode phase execution time, Memory Bandwidth bound, KV Cache access overhead. |
| KV Cache Memory Usage | High Allocation (>85%) | Misconfigured gpu_memory_utilization, excessive sequence context length limits. |
Summary Checklist for Production Readiness
- Memory Isolation: Set
gpu_memory_utilizationto 0.90–0.95, ensuring enough host-side buffer space for system activations while maximizing PagedAttention memory pools. - Fast Cache Storage: Use high-performance instance storage (local NVMe) or AWS FSx for Lustre mapped to Kubernetes
hostPathvolumes for fast cold-start model weight loads from HuggingFace/S3. - Optimized Networking: Enable AWS EFA device plugins and expose NCCL GPUDirect RDMA environment configurations across all inter-node deployments.
- Custom Metrics Autoscaling: Autoscale compute tiers via Ray's Queue Backpressure metrics rather than standard Kubernetes CPU/GPU HPA primitives.