> ## Documentation Index
> Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Designing a Load Balancer

> Overview of load balancing strategies, health checks, warm-up behavior, NGINX examples, and production considerations for distributing traffic across backend servers.

A load balancer distributes incoming traffic across backend servers so no single machine becomes a bottleneck. Below we cover common balancing strategies, health checks, warm-up behavior, an NGINX example, and practical considerations for production systems.

## Problem statement

Suppose you have four backend servers: A, B, C, and D. How should the load balancer decide where to send each incoming request so traffic is distributed evenly and services remain responsive?

## Round-robin (simple pointer)

Round-robin is the simplest approach. The balancer keeps an ordered list of servers and a single index that points to the next server. For each request it forwards the request to the server at the current index and then increments the index, wrapping back to zero at the end.

Example state:

```text theme={null}
LOAD BALANCER
list = [ A, B, C, D ]
index = 0  # points to A initially
```

Sequence of requests: A, B, C, D, A, B, ...

Pros:

* Extremely simple to implement
* Predictable distribution when requests are uniform

Cons:

* Blind to per-request work or latency. If some requests are long-running (e.g., payment processing) a server can be overloaded while others idle.

## Least-connections strategy

Least-connections is more adaptive: send each new request to the server currently handling the fewest active connections or requests. The balancer tracks an active count for each backend; it increments when it assigns a request and decrements when the request completes.

Important nuance: with multiplexed protocols (HTTP/2, gRPC) a single connection may carry many concurrent requests. Some balancers therefore count active requests instead of connections, or combine counts with metrics like CPU usage and request latency.

When using HTTP/2 or similar multiplexed transports, prefer metrics that reflect concurrent work (active requests, CPU, latency) rather than raw TCP connection counts.

![A stylized "Least Connections" diagram showing a load balancer receiving client requests and distributing them to four backend servers labeled A, B, C, and D. Server A shows 6 connections while B, C, and D each show 1 connection.](https://mintcdn.com/kodekloud-c4ac6d9a/2h0o-_DtLcLu6HM7/images/DevOps-Interview-Questions-and-Answers-Scenario-Based-Prep/System-Design/Designing-a-Load-Balancer/least-connections-lb-a6-bcd1.jpg?fit=max\&auto=format\&n=2h0o-_DtLcLu6HM7\&q=85\&s=bc2e3b1629acdce5f48496cbedce7466)

Benefits:

* Adapts to heterogeneous request durations
* Helps prevent long-running requests from concentrating on a single server

Trade-offs:

* Requires accurate accounting of active work
* Slightly more complexity than round-robin

## Health checks (detecting dead backends)

Detecting and removing unhealthy backends is essential to avoid directing traffic to dead or degraded servers. Common approaches:

* Passive health checks:
  * The balancer observes user traffic. If requests fail or time out to a backend, the balancer temporarily stops sending new requests to it and probes later.
  * Pro: No extra probes. Con: Detection occurs only after real requests fail.

* Active health checks:
  * The balancer periodically sends lightweight probe requests (for example, every 2 seconds). If a backend fails several probes in a row (commonly 3), it is marked down and removed from rotation.
  * Pro: Faster detection. Con: Extra probe traffic.

Health check considerations:

* Probe endpoint should be lightweight and representative of app health (for example, `GET /healthz`).
* Balance sensitivity and noise (probe interval, failure threshold) to avoid false positives during transient spikes.

## NGINX example

NGINX (open-source) uses round-robin by default. Switching to least-connections requires a single directive in the `upstream` block:

```nginx theme={null}
upstream backend {
    least_conn;
    server a;
    server b;
    server c;
    server d;
}
```

Active health checks (and advanced features like slow-start/warmup) are available in NGINX Plus. The open-source NGINX supports passive checks and several basic load-balancing modes.

## Warm-up / slow-start after a backend returns

When a backend recovers, it typically has zero active connections. A plain least-connections balancer might immediately send many new requests to it, which can overwhelm caches, warmed-up services, or background initialization logic.

To avoid this, use a warm-up or "slow-start" behavior: gradually increase the share of traffic to a returning backend over a configured interval so it can build caches and stabilize.

![A stylized NGINX load‑balancing diagram with users at the top sending traffic into an NGINX box that forwards requests to four backend instances labeled A, B, C, and D (showing counts 4, 0, 3, 5). Backend B is depicted as broken or failed while the others are active.](https://mintcdn.com/kodekloud-c4ac6d9a/2h0o-_DtLcLu6HM7/images/DevOps-Interview-Questions-and-Answers-Scenario-Based-Prep/System-Design/Designing-a-Load-Balancer/nginx-loadbalancer-backends-b-failed.jpg?fit=max\&auto=format\&n=2h0o-_DtLcLu6HM7\&q=85\&s=0f2e5bf5c4a0294a8545cb391dbfdecb)

## Quick comparison

| Strategy | How it works | Pros | Cons | Example |
| - | -: | - | - | - |
| Round‑robin | Cycle through servers sequentially | Simple, low-overhead | Ignores request duration | Default in NGINX |
| Least‑connections | Route to backend with fewest active connections/requests | Adapts to variable request costs | Requires accurate metrics | `least_conn` in NGINX |
| Weighted balancing | Assign weights to backends and use weighted round‑robin or least‑conn | Useful for heterogeneous server capacity | Requires tuning of weights | `server app1 weight=2;` |
| Hashing / sticky sessions | Use client IP or cookie to route to same backend | Required for session-local data | Reduces flexibility for scaling | `ip_hash` in NGINX |

## Additional considerations

* Sticky sessions: If your app stores session state locally, sticky sessions (cookie-based or IP-hash) ensure subsequent requests hit the same backend. Use with caution — it reduces the balancer’s flexibility.

Relying on sticky sessions can make scaling and failover harder. Prefer stateless services or externalize session state (Redis, database) where possible.

* Weights: Use when backends have different capacity (e.g., larger machines get higher weights).
* Observability: Track active requests, request duration histograms, CPU, memory, and error rates to make informed balancing decisions.
* Autoscaling integration: Combine health checks and metrics with autoscaling to add/remove capacity automatically.
* Use proven software or cloud load balancers rather than implementing complex logic from scratch (NGINX, HAProxy, Envoy, AWS/Cloud Load Balancers).

## Summary

* Round-robin is simple but blind to server load and request duration.
* Least-connections routes to the backend with the fewest active connections or requests and adapts to heterogeneous request costs.
* Health checks can be passive (observe failures) or active (periodic probes); active checks detect failures faster.
* Warm-up / slow-start prevents sudden traffic spikes to recovering servers.
* Prefer mature load balancer implementations and externalized session/state management rather than building custom balancers from scratch.

## Links and references

* [NGINX Load Balancing](https://docs.nginx.com/nginx/admin-guide/load-balancer/http-load-balancer/)
* [HAProxy Documentation](https://www.haproxy.org/)
* [Kubernetes Services and Ingress](https://kubernetes.io/docs/concepts/services-networking/service/)

> [card] [Watch Video](https://learn.kodekloud.com/user/courses/devops-interview-prep/module/ef53ec43-96e9-4d1b-8a6e-e6eb97b0d0dc/lesson/b9f3005f-e6cc-4c83-a33f-bfd38d6eb3ff)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.