Home CS Fundamentals Load Balancers: Algorithms, Types, and Deployment Guide
Intermediate 5 min · July 13, 2026

Load Balancers: Algorithms, Types, and Deployment Guide

Learn how load balancers distribute traffic, prevent downtime, and scale applications.

N
Naren Founder & Principal Engineer

20+ years shipping production systems from the metal up. Written from production experience, not tutorials.

Follow
Production
production tested
July 13, 2026
last updated
2,165
articles · all by Naren
Before you start⏱ 15-20 min read
  • Basic understanding of networking (IP, TCP/UDP, HTTP)
  • Familiarity with web servers (e.g., Nginx, Apache)
  • Experience with command line and configuration files
 ● Production Incident 🔎 Debug Guide ⚙ Triage Commands
Quick Answer
  • Load balancers distribute incoming traffic across multiple servers to ensure high availability and reliability.
  • Common algorithms include Round Robin, Least Connections, IP Hash, and Weighted variants.
  • Types: Hardware, Software (e.g., HAProxy, Nginx), and Cloud-based (e.g., AWS ELB).
  • Deployment can be in front of web servers, databases, or microservices.
  • Health checks and session persistence are critical for production use.
✦ Definition~90s read
What is Load Balancers?

A load balancer is a device or software that distributes incoming network traffic across multiple servers to ensure high availability, reliability, and scalability.

Imagine a busy restaurant with one waiter.
Plain-English First

Imagine a busy restaurant with one waiter. Customers wait a long time. Now add three waiters and a host who assigns each new customer to the least busy waiter. That host is a load balancer. It ensures no waiter is overwhelmed and customers get served faster.

Imagine your web application goes viral overnight. Thousands of users flood your site, but your single server can't handle the load. The site slows to a crawl, then crashes. Your business loses revenue and user trust. This is where load balancers come in. A load balancer acts as a traffic cop, sitting between users and your servers, distributing requests across multiple servers. It prevents any single server from becoming a bottleneck, ensures high availability, and allows you to scale horizontally by adding more servers. In this tutorial, you'll learn the core algorithms that decide where traffic goes, the different types of load balancers (hardware, software, cloud), and how to deploy them in real-world scenarios. We'll cover practical examples using HAProxy and Nginx, and discuss production pitfalls like session persistence and health checks. By the end, you'll be able to design a resilient system that handles millions of requests.

What is a Load Balancer?

A load balancer is a device or software that distributes network traffic across multiple servers. Its primary goals are to ensure high availability, improve responsiveness, and prevent any single server from becoming overloaded. Load balancers operate at different layers of the OSI model: Layer 4 (transport) balances based on IP and TCP/UDP ports, while Layer 7 (application) can inspect HTTP headers, cookies, and URLs. For example, a Layer 7 load balancer can route requests for /api to a cluster of API servers and /static to a CDN. In modern architectures, load balancers are essential for scaling applications horizontally. They also perform health checks to detect server failures and automatically reroute traffic to healthy servers. Common implementations include hardware appliances (F5, Citrix), software (HAProxy, Nginx), and cloud services (AWS ELB, Google Cloud Load Balancing).

haproxy-basic.cfgBASH
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
global
    daemon
    maxconn 256

defaults
    mode http
    timeout connect 5000ms
    timeout client 50000ms
    timeout server 50000ms

frontend http-in
    bind *:80
    default_backend servers

backend servers
    balance roundrobin
    server server1 192.168.1.10:80 check
    server server2 192.168.1.11:80 check
    server server3 192.168.1.12:80 check
🔥Layer 4 vs Layer 7
📊 Production Insight
In production, always configure health checks. Without them, a load balancer may send traffic to a dead server, causing errors.
🎯 Key Takeaway
Load balancers distribute traffic across servers to improve availability and performance. Choose between Layer 4 and Layer 7 based on your needs.

Load Balancing Algorithms

Load balancers use algorithms to decide which server receives each request. The choice of algorithm affects performance, resource utilization, and user experience. Here are the most common algorithms:

  1. Round Robin: Requests are distributed sequentially to each server in turn. Simple and works well when servers have equal capacity. However, it doesn't account for server load or response times.
  2. Least Connections: Sends requests to the server with the fewest active connections. Ideal for long-lived connections (e.g., WebSocket) or varying request processing times.
  3. IP Hash: Uses the client's IP address to determine which server receives the request. This ensures a client always hits the same server (sticky session) without needing cookies. Useful for stateful applications.
  4. Weighted Round Robin: Assigns weights to servers based on capacity. Servers with higher weight receive more requests. Good for heterogeneous server pools.
  5. Least Response Time: Sends requests to the server with the fastest response time. Requires continuous monitoring and can be CPU-intensive.
  6. Random: Picks a server at random. Simple but can lead to uneven distribution.

In practice, you may combine algorithms or use adaptive algorithms that adjust based on real-time metrics.

haproxy-algorithms.cfgBASH
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
backend servers
    # Round Robin (default)
    balance roundrobin

    # Least Connections
    # balance leastconn

    # IP Hash (sticky)
    # balance source

    # Weighted Round Robin
    # balance roundrobin
    # server server1 192.168.1.10:80 weight 3 check
    # server server2 192.168.1.11:80 weight 1 check

    server server1 192.168.1.10:80 check
    server server2 192.168.1.11:80 check
    server server3 192.168.1.12:80 check
💡Choosing the Right Algorithm
📊 Production Insight
Avoid Round Robin for long-lived connections like WebSockets; use Least Connections to prevent connection pile-up.
🎯 Key Takeaway
Select an algorithm based on your application's statefulness and server homogeneity. Test under load to validate distribution.

Types of Load Balancers

Load balancers come in three main types: hardware, software, and cloud-based.

Hardware Load Balancers: Physical appliances like F5 BIG-IP or Citrix ADC. They offer high performance, advanced features (SSL offloading, DDoS protection), and dedicated support. However, they are expensive, require manual scaling, and have vendor lock-in. Suitable for large enterprises with high traffic and compliance needs.

Software Load Balancers: Open-source or commercial software running on commodity hardware. Examples include HAProxy, Nginx, and Apache mod_proxy. They are cost-effective, flexible, and can be deployed on-premises or in the cloud. HAProxy is known for its high performance and extensive configuration options. Nginx also excels as a reverse proxy and load balancer.

Cloud Load Balancers: Managed services provided by cloud providers like AWS Elastic Load Balancer (ELB), Google Cloud Load Balancing, and Azure Load Balancer. They are fully managed, auto-scale, and integrate with other cloud services. They offer features like SSL termination, health checks, and global load balancing. Ideal for cloud-native applications.

Each type has trade-offs. Hardware offers raw performance, software provides control, and cloud simplifies operations.

nginx-load-balancer.confBASH
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
http {
    upstream backend {
        least_conn;
        server 192.168.1.10:80 weight=3;
        server 192.168.1.11:80;
        server 192.168.1.12:80 backup;
    }

    server {
        listen 80;
        location / {
            proxy_pass http://backend;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
        }
    }
}
⚠ Vendor Lock-in
📊 Production Insight
Software load balancers like HAProxy can handle millions of requests per second on modern hardware, making them a popular choice for high-traffic sites.
🎯 Key Takeaway
Choose hardware for maximum performance, software for flexibility, and cloud for ease of management. Many organizations use a combination.

Deployment Strategies

Deploying a load balancer involves deciding where to place it in the network and how to configure it for resilience. Common deployment patterns:

  1. Single Load Balancer: Simple but a single point of failure. Use for non-critical apps or development.
  2. Active-Passive: Two load balancers in a failover pair. One handles traffic; the other takes over if the primary fails. Requires a heartbeat mechanism (e.g., Keepalived with VRRP).
  3. Active-Active: Multiple load balancers share traffic, often using DNS round robin or anycast. Provides higher throughput and redundancy.
  4. Global Server Load Balancing (GSLB): Distributes traffic across multiple data centers or cloud regions. Uses DNS-based routing or anycast. Improves latency and disaster recovery.
  5. Microservices and API Gateways: In microservice architectures, load balancers are often combined with API gateways (e.g., Kong, Traefik) that handle routing, authentication, and rate limiting.

When deploying, consider SSL termination at the load balancer to offload encryption from backend servers. Also configure health checks with appropriate intervals and thresholds.

keepalived.confBASH
1
2
3
4
5
6
7
8
9
10
11
12
13
14
vrrp_instance VI_1 {
    state MASTER
    interface eth0
    virtual_router_id 51
    priority 100
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 1234
    }
    virtual_ipaddress {
        192.168.1.100
    }
}
🔥Health Check Best Practices
📊 Production Insight
Always test failover scenarios. A misconfigured heartbeat can cause split-brain, where both load balancers think they are active, leading to traffic loss.
🎯 Key Takeaway
Use active-passive or active-active for high availability. GSLB is essential for multi-region deployments.

Session Persistence (Sticky Sessions)

Session persistence ensures that all requests from a client go to the same backend server. This is crucial for stateful applications that store session data locally (e.g., shopping cart). Methods include:

  1. Source IP Hash: The load balancer hashes the client's IP to select a server. Simple but can cause uneven distribution if many clients share the same IP (e.g., behind a NAT).
  2. Cookie Insertion: The load balancer sets a cookie in the client's browser that identifies the backend server. On subsequent requests, the cookie is read to route to the same server. More granular but requires cookie support.
  3. URL or Parameter Based: The load balancer uses a part of the URL or a query parameter to determine the server. Less common.

While sticky sessions solve session loss, they can lead to server overload if a single client has many requests. A better approach is to use a centralized session store (e.g., Redis, Memcached) so any server can handle any request. This makes the application stateless and more scalable.

haproxy-sticky.cfgBASH
1
2
3
4
5
6
7
backend servers
    balance roundrobin
    # Cookie-based persistence
    cookie SERVERID insert indirect nocache
    server server1 192.168.1.10:80 cookie s1 check
    server server2 192.168.1.11:80 cookie s2 check
    server server3 192.168.1.12:80 cookie s3 check
💡Prefer Stateless Design
📊 Production Insight
Cookie-based persistence can break if clients block cookies. Always have a fallback (e.g., IP hash) or use a shared session store.
🎯 Key Takeaway
Sticky sessions are a quick fix for stateful apps, but a centralized session store is more scalable and resilient.

Health Checks and Monitoring

Health checks are essential for maintaining a healthy server pool. The load balancer periodically probes each server to verify it's alive and capable of handling requests. Common health check types:

  • TCP Check: Attempts to open a TCP connection to the server's port. If successful, the server is considered healthy.
  • HTTP Check: Sends an HTTP request (e.g., GET /health) and expects a specific status code (e.g., 200). Can also validate response body.
  • Script Check: Runs an external script that performs deeper checks (e.g., database connectivity).

Configure health check intervals (e.g., every 5 seconds), timeout (e.g., 2 seconds), and failure count (e.g., 3 failures to mark down). Also set a rise count (e.g., 2 successes to mark up) to avoid flapping.

Monitoring the load balancer itself is also critical. Track metrics like request rate, latency, error rates, and server pool health. Tools like Prometheus, Grafana, and ELK stack can provide dashboards and alerts.

haproxy-health-check.cfgBASH
1
2
3
4
5
6
7
8
backend servers
    balance roundrobin
    option httpchk GET /health
    http-check expect status 200
    default-server inter 5s fall 3 rise 2
    server server1 192.168.1.10:80 check
    server server2 192.168.1.11:80 check
    server server3 192.168.1.12:80 check
⚠ Health Check Endpoint
📊 Production Insight
In cloud environments, use instance health checks provided by the cloud provider (e.g., AWS ELB health checks) to integrate with auto-scaling.
🎯 Key Takeaway
Health checks automatically remove failing servers. Configure them carefully to avoid false positives or negatives.

SSL Termination and Security

SSL termination (or TLS termination) is the process of decrypting HTTPS traffic at the load balancer, so backend servers receive plain HTTP. This offloads the CPU-intensive encryption work from backend servers and simplifies certificate management. The load balancer holds the SSL certificate and handles the handshake.

Benefits
  • Reduced backend CPU load.
  • Centralized certificate management.
  • Ability to inspect traffic for security (e.g., WAF).

However, traffic between the load balancer and backend servers is unencrypted, so ensure they are on a trusted network (e.g., private subnet). For end-to-end encryption, use SSL passthrough (Layer 4) where the load balancer forwards encrypted traffic directly to the backend.

Security best practices
  • Use strong ciphers and disable outdated protocols (e.g., TLS 1.0, 1.1).
  • Enable HSTS (HTTP Strict Transport Security).
  • Use a Web Application Firewall (WAF) in front of the load balancer.
  • Regularly update certificates.
nginx-ssl-termination.confBASH
1
2
3
4
5
6
7
8
9
10
11
12
13
14
server {
    listen 443 ssl;
    server_name example.com;

    ssl_certificate /etc/ssl/certs/example.com.crt;
    ssl_certificate_key /etc/ssl/private/example.com.key;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;

    location / {
        proxy_pass http://backend;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}
🔥SSL Passthrough vs Termination
📊 Production Insight
Use Let's Encrypt for free automated certificates. Many load balancers support automatic renewal via ACME protocol.
🎯 Key Takeaway
SSL termination offloads encryption from backends. Ensure backend traffic is secured via network isolation.
● Production incidentPOST-MORTEMseverity: high

The Sticky Session Disaster: How a Misconfigured Load Balancer Caused a Black Friday Outage

Symptom
Users were intermittently logged out and saw empty shopping carts. The site became unresponsive under heavy load.
Assumption
The developer assumed that the load balancer's default Round Robin algorithm would work fine for all traffic.
Root cause
The load balancer was distributing requests without session persistence. User sessions were stored on individual servers, so subsequent requests went to different servers, losing session data. This caused repeated re-authentication and database overload.
Fix
Enabled sticky sessions (IP Hash) and configured a shared session store (Redis). Also added health checks to remove unhealthy servers.
Key lesson
  • Always consider session persistence for stateful applications.
  • Use health checks to automatically remove failing servers.
  • Test load balancer configuration under realistic traffic patterns.
  • Monitor server load and adjust algorithms dynamically.
  • Document your load balancer setup for incident response.
Production debug guideSymptom to Action5 entries
Symptom · 01
Uneven traffic distribution among servers
Fix
Check load balancer algorithm; verify server weights; inspect health check status.
Symptom · 02
Users losing session data
Fix
Enable sticky sessions (IP Hash or cookie-based); implement centralized session store.
Symptom · 03
High latency on some requests
Fix
Check backend server health; review load balancer timeout settings; enable connection pooling.
Symptom · 04
Backend servers overwhelmed
Fix
Scale up servers; adjust algorithm to Least Connections; add rate limiting.
Symptom · 05
SSL/TLS handshake failures
Fix
Verify SSL certificate on load balancer; check cipher compatibility; enable SSL termination.
★ Quick Debug Cheat Sheet for Load BalancersCommon symptoms and immediate actions to diagnose load balancer issues.
Uneven load
Immediate action
Check algorithm and health
Commands
curl -I http://lb.example.com/health
haproxy -c -f /etc/haproxy/haproxy.cfg
Fix now
Switch to Least Connections algorithm
Session lost+
Immediate action
Enable sticky sessions
Commands
curl -c /tmp/cookies.txt http://lb.example.com
curl -b /tmp/cookies.txt http://lb.example.com
Fix now
Configure cookie-based persistence
High latency+
Immediate action
Check backend response times
Commands
time curl http://backend1.example.com
netstat -an | grep :80 | wc -l
Fix now
Increase backend server capacity
Backend down+
Immediate action
Check health check logs
Commands
tail -f /var/log/haproxy.log
systemctl status haproxy
Fix now
Restart backend service or remove from pool
AlgorithmDescriptionBest Use CaseSticky Sessions
Round RobinDistributes requests sequentiallyEqual capacity servers, short-lived requestsNo
Least ConnectionsSends to server with fewest connectionsLong-lived connections, varying loadNo
IP HashHashes client IP to select serverStateful apps, simple stickinessYes (by IP)
Weighted Round RobinAssigns weights to serversHeterogeneous server capacitiesNo
Least Response TimeSends to fastest responding serverPerformance-sensitive appsNo
⚙ Quick Reference
7 commands from this guide
FileCommand / CodePurpose
haproxy-basic.cfgglobalWhat is a Load Balancer?
haproxy-algorithms.cfgbackend serversLoad Balancing Algorithms
nginx-load-balancer.confhttp {Types of Load Balancers
keepalived.confvrrp_instance VI_1 {Deployment Strategies
haproxy-sticky.cfgbackend serversSession Persistence (Sticky Sessions)
haproxy-health-check.cfgbackend serversHealth Checks and Monitoring
nginx-ssl-termination.confserver {SSL Termination and Security

Key takeaways

1
Load balancers distribute traffic across servers to improve availability and performance.
2
Choose the right algorithm based on your application's statefulness and server homogeneity.
3
Health checks are critical for automatically removing failed servers.
4
Prefer stateless designs with centralized session stores over sticky sessions.
5
Test your load balancer configuration under realistic conditions, including failover scenarios.

Common mistakes to avoid

5 patterns
×

Not configuring health checks

×

Using Round Robin for long-lived connections

×

Ignoring session persistence for stateful apps

×

Overlooking SSL termination security

×

Not testing failover scenarios

INTERVIEW PREP · PRACTICE MODE

Interview Questions on This Topic

Q01JUNIOR
Explain the difference between Layer 4 and Layer 7 load balancing.
Q02JUNIOR
Describe the Round Robin algorithm and its limitations.
Q03SENIOR
How would you design a load-balanced system for a global audience?
Q04JUNIOR
What is a 'health check' and why is it important?
Q05SENIOR
Explain the concept of 'sticky sessions' and discuss alternatives.
Q01 of 05JUNIOR

Explain the difference between Layer 4 and Layer 7 load balancing.

ANSWER
Layer 4 load balancing operates at the transport layer (TCP/UDP), making routing decisions based on IP addresses and ports. It is fast but cannot inspect application data. Layer 7 load balancing operates at the application layer (HTTP/HTTPS), allowing content-based routing (e.g., by URL or cookie). It offers more flexibility but with higher overhead.
FAQ · 5 QUESTIONS

Frequently Asked Questions

01
What is the difference between a load balancer and a reverse proxy?
02
Can a load balancer handle WebSocket connections?
03
How do I choose between hardware and software load balancers?
04
What is a 'sticky session' and when should I use it?
05
How do I test my load balancer configuration?
N
Naren Founder & Principal Engineer

20+ years shipping production systems from the metal up. Written from production experience, not tutorials.

Follow
Verified
production tested
July 13, 2026
last updated
2,165
articles · all by Naren
🔥

That's Computer Networks. Mark it forged?

5 min read · try the examples if you haven't

Previous
What Is a Node in Networking? Definition, Types and How They Work
23 / 30 · Computer Networks
Next
API Gateway: Architecture and Patterns