En este modulo
The challenge of scaling LLMs
Scaling a traditional web service means adding servers behind a load balancer. Scaling an LLM service is fundamentally different because the bottleneck is not CPU or RAM: it is GPU VRAM, which is expensive and scarce.
A web server handles 10,000 requests per second. An LLM server handles 10-50. This 3 orders of magnitude difference forces rethinking the entire scalability strategy. Every request you can avoid (cache), every token you can not generate (optimization), and every millisecond you can cut (async) has direct impact on capacity and cost.
The 3 scalability levers
- Reduce requests (caching): if 30% of queries are similar, semantic cache eliminates 30% of GPU load.
- Reduce tokens (optimization): shorter prompts, more concise outputs, more efficient models.
- Distribute load (balancing): multiple GPUs, multiple servers, intelligent routing.
Prompt caching: save compute for free
Prompt caching reuses the KV cache of prompt prefixes that repeat between requests. If your system prompt is 2000 tokens and all requests share it, the prefill of those 2000 tokens is calculated once and reused. In vLLM, enable with --enable-prefix-caching. Measured impact on a chatbot with 2000-token system prompt: 47% less TTFT latency, 33% more throughput.
Semantic cache: intelligent caching
Prompt caching works with identical prefixes. Semantic cache goes one step further: it caches responses for semantically similar queries. If one user asks "what is GDPR" and another asks "explain the general data protection regulation", semantic cache detects they are the same question and returns the cached response. Implementation uses embeddings + Redis with a similarity threshold (typically 0.92).
Caution with semantic cache
Not all queries are cacheable. Queries that depend on the user, timestamp, or mutable state should not be cached. Implement a "cacheability check" layer. Factual queries (FAQ, documentation) are ideal. Personalized or time-sensitive queries are not.
Load balancing for inference
With multiple vLLM instances, you need a load balancer that distributes traffic intelligently. Round-robin isn't enough: a 100-token request and a 10,000-token request don't consume the same resources. Use least-loaded strategy based on GPU metrics, or task-based routing with different models for different complexity levels.
Async patterns for high throughput
LLM calls are IO-bound (waiting for GPU response). Async patterns allow the server to process multiple requests while waiting for the GPU, maximizing throughput without adding hardware. Key patterns: request queue with worker pool, batch processing for non-interactive loads, fire-and-forget for non-critical tasks (logging, scoring, analytics).
Cost optimization
Two axes: reduce tokens (prompt compression, output truncation, context window management) and reduce cost per token (batch API at 50% discount, tiered models for 80% of simple queries, self-hosting during off-peak hours, prompt caching for 90% reduction on cached tokens).
The 80/20 rule of costs
80% of your inference cost comes from 20% of your endpoints. Identify the top 3 endpoints by token consumption, optimize those first. The rest probably doesn't justify the optimization effort.
Auto-scaling: scale on demand
Auto-scaling for LLMs is more complex than for web services. A vLLM instance takes 30-60 seconds to start (load model into VRAM). You can't scale in milliseconds. Strategies: pre-warming + conservative thresholds, warm replicas (pre-started but without traffic), scale up when GPU utilization >80%, scale down when <30% for 15 minutes.
Scalability benchmarking
Benchmark at multiple concurrency levels (1, 5, 10, 20, 50, 100) to identify the saturation point. Measure throughput (req/s), P50 latency, P99 latency and error count at each level.
Ejercicio practico
- Enable prefix caching on your vLLM instance from TE03. Benchmark with and without caching. Measure the difference in TTFT and throughput.
- Implement semantic cache with Redis (or in-memory dictionary for prototype). Measure cache hit rate with 100 queries (30% repeated with variations).
- Implement the task router with tiered models: use Phi-4 for simple queries and Qwen3.5-27B for complex ones. Measure the average latency reduction.
- Run the scalability benchmark at 1, 5, 10, 20, 50 concurrents. Identify the saturation point of your hardware.
- Implement context window management: limit conversation to last 5 turns + summary. Measure the token reduction per request.
- Calculate monthly savings if you applied all optimizations to a system with 10,000 requests/day.
Bonus: Deploy 2 vLLM instances behind Nginx with least_conn. Verify traffic distributes and total throughput is ~1.8x of a single instance.
Puntos clave
Puntos clave from TE08
- The 3 LLM scalability levers: reduce requests (cache), reduce tokens (prompt optimization), distribute load (load balancing). In that order of impact/effort.
- Prompt caching is free and reduces TTFT by 40-60%. Always enable it. Semantic cache eliminates 20-40% of repetitive requests for FAQ and documentation.
- Tiered models: small model for 80% of simple queries. Average cost drops 60% with minimal quality loss.
- LLM auto-scaling is slow (60s cold start). Keep warm replicas or pre-scale before known peaks.
- Scalability benchmarking is mandatory. Without it, you don't know your hardware's saturation point or how many users you can serve.
Guia de estudio — Conceptos clave de TE08
El desafio de escalar LLMs
- Reducir requests (caching):si el 30% de las queries son similares, cache semantico elimina el 30% de la carga de GPU.
- Reducir tokens (optimizacion):prompts mas cortos, outputs mas concisos, modelos mas eficientes.
- Distribuir carga (balanceo):multiples GPUs, multiples servidores, routing inteligente.
Semantic cache: cache inteligente
- Precaucion con semantic cache: No todas las queries son cacheables. Queries que dependen del usuario, del timestamp, o de estado mutable no deben cachearse. Implementa una capa de "cacheability check" que determine si una query puede servirse desde cache. Queries factuales (FAQ, documentacion) son ideales. Queries personalizadas o con datos recientes, no.
Optimizacion de costes
- Severidad: \n Categoria: \n..."
- Batch API:Anthropic y OpenAI ofrecen batch pricing con 50% de descuento. Para cargas no real-time (analisis nocturno, procesamiento de documentos), siempre usar batch.
- Tiered models:modelo pequeno para el 80% de queries simples, modelo grande solo para el 20% complejo. Coste medio baja un 60%.
- Self-hosting en horas valle:si tu trafico tiene patron diurno, las GPUs estan idle de noche. Programar procesamiento batch para esas horas.
- Prompt caching:reduce coste de tokens cacheados un 90% en APIs comerciales.
- Regla del 80/20 de costes: El 80% de tu coste de inferencia viene del 20% de tus endpoints. Identifica los top 3 endpoints por consumo de tokens, optimiza esos primero. El resto probablemente no justifica el esfuerzo de optimizacion.
Benchmarking de escalabilidad
- # 1 1.2/s 0.82s 0.85s 0
- Saturacion
- Degradacion
Siguiente: TE09 - DevOps for AI
Your system scales. Now you need the infrastructure that supports it: Docker for ML, Kubernetes, GPU scheduling and IaC.
Ir al modulo TE09