LLM Load Balancing: Spread Traffic and Fail Over Cleanly

9 min read

LLM load balancing is how you spread requests across several copies of the same model so that no single GPU server becomes the bottleneck, and how you keep answering when one of them fails. The short version: do not use plain round-robin, send each request to the replica with the fewest requests in flight, keep conversations on the replica that already has their prompt cached when you can, and put timeouts, limited retries and a fallback model behind all of it.

This is a different job from model routing. A router picks which model should answer, for example a small model for a summary and a vision model for an image. A load balancer takes the model as given and picks which replica of it gets the request. Most production setups do both, in that order. Our post on LLM routing covers the first half; this one covers the second.

Why round-robin is a poor fit for LLM load balancing

Round-robin works for web servers because most requests cost about the same. LLM requests do not. The time a request holds a GPU depends mostly on how many tokens it generates, and that varies by two orders of magnitude within one app.

Take two requests to the same model. One asks to classify a ticket and produces 20 tokens. The other asks for a report and produces 1,500. At 40 tokens per second per stream, the first is done in half a second and the second holds its slot for over 37 seconds. Round-robin counts both as "one request" and keeps dealing them out evenly. After a few minutes, one replica can be holding five long generations while its neighbor sits nearly idle, and every new request that lands on the busy one waits.

Inference servers that batch requests together make this worse in a quieter way. A replica with many active sequences gives each one a smaller share of the GPU, so time per output token rises for everyone on it. The client sees slow streaming, not an error.

Least outstanding requests and queue-aware balancing

The simplest fix is to count what is in flight. A least-connections or least-requests balancer sends each new request to the replica currently handling the fewest. Long generations keep their connection open, so they naturally steer new traffic away from the replica that has them.

  • NGINX has least_conn, which passes a request "to the server with the least number of active connections, taking into account weights of servers".
  • Envoy has the least request policy. With equal weights it samples two random healthy hosts by default and picks the one with fewer active requests. The docs note that with only two hosts this picks the busier one 25% of the time, so test its behavior if you run only a few replicas.
  • LiteLLM offers a least-busy routing strategy across deployments that share a model name.

Counting connections is a proxy for load. The real signal sits inside the inference server: how many requests are waiting in its queue and how full its KV cache is (the per-request memory that holds attention state, covered in KV cache explained). On Kubernetes, the Gateway API Inference Extension adds an endpoint picker that reads metrics from the model servers before choosing one. Google's GKE Inference Gateway, built on it, scores servers on KV cache utilization and pending queue depth. If you already run models on Kubernetes, as in our guide to deploying an LLM on Kubernetes, this is worth testing before you write your own.

Prefix-aware routing and session affinity

Many requests share a long beginning: the same system prompt, the same few-shot examples, or the earlier turns of one conversation. Inference servers can reuse the computed attention state for a prefix they have already seen. vLLM calls this automatic prefix caching, which "caches the KV cache of existing queries" so a new request sharing that prefix skips recomputing it.

The cache lives on one replica. If turn five of a chat lands on a different replica from turns one to four, the whole history is processed again from scratch, and time to first token goes up with it. Two ways to keep requests where their cache is:

  1. Session affinity. Hash a session or conversation ID to a replica. The vLLM production stack router lists round-robin, session-ID based routing and prefix-aware routing (marked work in progress when we checked in November 2026).
  2. Prefix-aware routing. The balancer tracks which prefixes each replica has served and prefers the longest match. The SGLang router does this by default with an approximate prefix tree.

Affinity and even load pull against each other. Pin too hard and one popular system prompt melts a single replica. SGLang's router handles this by switching to shortest-queue balancing when the load gap between workers passes a threshold, and using cache-aware routing only while the pool is balanced. Copy that idea whatever tool you use: prefer the cached replica, but only while it is not much busier than the rest.

Health checks that match how models fail

A model server has more ways to be unhealthy than a web server. It can be up but still loading weights, which takes minutes for a large model. It can be healthy but so far behind that every request times out.

Use three layers:

  • Readiness, not liveness, gates traffic. A replica joins the pool only after the model is loaded and a real request succeeds. A one-token completion against the actual model is a better probe than an HTTP 200 from a status page.
  • Passive checks catch failures in live traffic. In open-source NGINX, max_fails and fail_timeout mark a server unavailable after a number of failed attempts within a window (defaults: 1 failure, 10 seconds). Active periodic health checks are part of NGINX's commercial subscription. Envoy's outlier detection, which it describes as "a form of passive health checking", ejects hosts after consecutive 5xx errors.
  • Latency counts as failure. A replica whose time to first token is five times the pool average is broken for an interactive app even if it returns 200. Alert on it from your LLM observability dashboards.

Timeouts, retries and circuit breakers

LLM requests are long, so the default timeouts of most proxies are wrong in one direction or the other.

NGINX's proxy_read_timeout (default 60 seconds) applies between two reads, not to the whole response. For streaming, that works as a stall detector: if no token arrives for 60 seconds, something is wrong. For non-streaming requests the server sends nothing until it has finished, so a 1,500-token answer can trip it. Set timeouts per request type: a short one for time to first token, a longer one for the full generation.

Retry rules for LLM traffic:

  • Retry connection errors, 502, 503 and 429 on another replica. Do not retry a 400 caused by a prompt longer than the context window; send it to a model with a longer window instead, or reject it.
  • Cap attempts at two or three, with a total time budget. Without the budget, three slow attempts become one very slow failure.
  • Once tokens have started streaming to the client, you cannot fail over. NGINX states this directly: passing a request to the next server "is only possible if nothing has been sent to a client yet."
  • NGINX does not retry a POST that has already reached an upstream unless you add non_idempotent. Chat completions have no side effects on the server, so enabling it is usually safe. The cost is GPU time spent on the abandoned attempt.

A circuit breaker stops sending traffic to a replica that keeps failing, then lets a trial request through after a cool-off. LiteLLM implements this as cooldowns: allowed_fails within a window puts a deployment in cooldown for cooldown_time seconds. Envoy uses the name differently: its circuit breakers cap pending and outstanding requests per cluster, which is load shedding. For LLMs you want both: eject a broken replica, and refuse new work with a 503 when the whole pool is full rather than letting the queue grow until every request times out.

Fallback chains across models

When every replica of a model is down or saturated, a fallback sends the request to a different model. A sensible chain for a chat feature on a 14B model:

  1. Another replica of the same model (the balancer handles this).
  2. A larger model, if it has spare capacity, or a model with a longer context window for prompts that did not fit.
  3. A fast, clear error with Retry-After, so the client can back off.

Two cautions. A fallback model changes the answers: different style, different JSON habits. Log which model served each request so quality reviews can separate them. And watch the fallback rate: if the primary pool degrades, every request lands on the fallback and overloads it too.

A worked config: NGINX for replicas, LiteLLM for fallbacks

For three replicas of one model behind one endpoint, NGINX is enough. The directives below are from the upstream and proxy module docs:

upstream qwen14b {
    least_conn;
    server 10.0.1.11:8000 max_fails=3 fail_timeout=30s;
    server 10.0.1.12:8000 max_fails=3 fail_timeout=30s;
    server 10.0.1.13:8000 backup;
    keepalive 32;
}

server {
    listen 443 ssl;
    server_name llm.internal.example.com;
    # ssl_certificate and ssl_certificate_key go here

    location /v1/ {
        proxy_pass http://qwen14b;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        proxy_buffering off;              # stream tokens as they arrive
        proxy_read_timeout 300s;          # allow long non-streaming answers
        proxy_next_upstream error timeout http_502 http_503 http_429 non_idempotent;
        proxy_next_upstream_tries 2;
        proxy_next_upstream_timeout 15s;
    }
}

The backup server only gets traffic when both primaries are marked down, which suits a replica on a cheaper GPU.

When you need fallbacks to a different model, a gateway is the better place. In a LiteLLM proxy config, deployments that share a model_name are balanced as one group:

model_list:
  - model_name: chat-default
    litellm_params:
      model: openai/qwen2.5-14b-instruct
      api_base: http://10.0.1.11:8000/v1
      api_key: os.environ/LLM_API_KEY
      timeout: 120
  - model_name: chat-default
    litellm_params:
      model: openai/qwen2.5-14b-instruct
      api_base: http://10.0.1.12:8000/v1
      api_key: os.environ/LLM_API_KEY
      timeout: 120
  - model_name: chat-large
    litellm_params:
      model: openai/llama-3.3-70b-instruct
      api_base: http://10.0.2.21:8000/v1
      api_key: os.environ/LLM_API_KEY
      timeout: 180

router_settings:
  routing_strategy: least-busy
  num_retries: 2
  allowed_fails: 3
  cooldown_time: 30
  fallbacks: [{"chat-default": ["chat-large"]}]
  context_window_fallbacks: [{"chat-default": ["chat-large"]}]

Apps call chat-default. Failed replicas cool down for 30 seconds, and if the group cannot answer, the request goes to the 70B model. Our LLM gateway post covers what else that layer can do.

Where AI Refinery fits

AI Refinery, a self-hosted LLM platform, runs the models behind your balancer inside your own infrastructure: your cloud, your VPC, on-premise or air-gapped. Each model you deploy from its catalog exposes an OpenAI-compatible /v1/chat/completions endpoint, so NGINX, Envoy or LiteLLM can treat it as an ordinary upstream. On Professional and Enterprise plans, smart model routing sends each request to the best available model for the task (vision, text, embeddings or code), which covers the "which model" half. The dashboard shows request volume, latency, token usage and errors per inference server, which is the data you need to tune the balancer.

It is not a load balancer. Replica-level balancing, retries, circuit breaking and fallback chains are the layer you put in front, with the configs above. And if one replica of one model handles your peak with room to spare, you do not need any of this yet: measure first, and add a second replica when the queue says so.