Architecture
Load Balancers Explained: Layer 4 vs Layer 7, Algorithms and Health Checks
By NileVPS Team · Published · 5 min read
اقرأ المقال بالعربيA single server has limits: it can only handle so many requests, and when it goes down for maintenance or a crash, your site goes with it. A load balancer sits in front of several servers and spreads incoming traffic across them, so you gain capacity and the ability to lose one server without users noticing. This article explains what load balancers actually do, the difference between Layer 4 and Layer 7 balancing, the common algorithms, and how to build a simple, working setup with nginx on a few VPS instances.
What a load balancer does
At its core, a load balancer accepts connections on a public address and forwards each one to a backend from a pool. Around that core, most load balancers also:
- Run health checks and stop sending traffic to unhealthy backends.
- Terminate TLS, so certificates live in one place.
- Add headers such as
X-Forwarded-Forso backends know the client IP. - Enforce timeouts, connection limits and sometimes rate limits.
- Allow draining a backend for maintenance without dropping active requests.
Layer 4 vs Layer 7
The "layer" refers to the OSI model.
Layer 4 (transport) load balancers work with TCP or UDP connections. They see IP addresses and ports, not HTTP. They are fast, protocol-agnostic and can balance anything: databases, mail, game servers, raw TLS.
Layer 7 (application) load balancers understand HTTP. They can route by host name, path, header or cookie, rewrite requests, cache, compress and retry a failed request on another backend.
| Aspect | Layer 4 | Layer 7 |
|---|---|---|
| Sees | IPs, ports, TCP/UDP | HTTP methods, paths, headers, cookies |
| Routing options | By connection | By host, path, header, cookie |
| TLS | Usually passed through | Usually terminated |
| Overhead | Very low | Higher, parses every request |
| Use cases | Databases, TCP services, high throughput | Websites, APIs, microservices |
| Examples | nginx stream, HAProxy mode tcp, LVS | nginx http, HAProxy mode http, Envoy |
Balancing algorithms
- Round robin: each new request goes to the next backend in turn. Simple and effective when backends are similar.
- Weighted round robin: stronger servers get a larger share, useful when mixing plan sizes.
- Least connections: send to the backend with the fewest active connections. Good when request durations vary a lot.
- IP hash: the client IP determines the backend, so a client usually reaches the same server. A crude form of sticky sessions.
- Consistent hashing: maps keys (such as a URL or user ID) so that adding or removing a backend moves only a small portion of traffic. Useful in front of caches.
- Random with two choices: pick two backends at random and use the less loaded one; scales well across many load balancers.
Health checks
Passive checks watch real traffic: if requests to a backend fail several times, it is marked down for a while. Open source nginx does this with max_fails and fail_timeout. Active checks send their own probes, such as GET /health every few seconds, and mark a backend up or down based on the response. HAProxy supports active checks out of the box.
A good health endpoint is cheap, does not require authentication, and checks only what the instance truly needs to serve traffic. Avoid making it depend on every downstream service, or one slow dependency will mark the whole pool unhealthy at once.
Example: nginx in front of two app servers
Assume two backends on a private network, 10.0.0.11 and 10.0.0.12, each serving the app on port 8080.
upstream app {
least_conn;
server 10.0.0.11:8080 max_fails=3 fail_timeout=30s;
server 10.0.0.12:8080 max_fails=3 fail_timeout=30s;
keepalive 32;
}
server {
listen 443 ssl;
http2 on;
server_name example.com;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
location / {
proxy_pass http://app;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_connect_timeout 3s;
proxy_read_timeout 30s;
proxy_next_upstream error timeout http_502 http_503;
}
}The http2 on; directive needs nginx 1.25.1 or newer; on older versions write listen 443 ssl http2; instead. Test and reload with:
sudo nginx -t && sudo systemctl reload nginxTo take a backend out for maintenance, add down to its server line and reload. Remember to restrict the backends' firewall so port 8080 only accepts connections from the load balancer's private IP.
The load balancer is now a single point of failure
Putting one load balancer in front of two servers moves the weak spot rather than removing it. Common ways to address this:
- Run two load balancers with a floating IP that moves to the standby (for example using keepalived with VRRP, or a provider-managed floating IP).
- Use DNS with multiple A records and short TTLs, accepting that clients cache DNS unpredictably.
- Use a managed load balancer from your infrastructure provider.
Checklist before going live
- Backends are stateless or sessions are shared; see stateful vs stateless apps.
- Backends log the real client IP from
X-Forwarded-Foror the PROXY protocol, trusting it only from the load balancer. - Timeouts are set on the load balancer and are longer than normal response times.
- A health endpoint exists and is monitored.
- Deploys roll through backends one at a time.
- The load balancer itself has a failover plan.
You can start with three small VPS instances, one balancer and two app servers, and grow from there. Compare options on the pricing page.
FAQ
Do I need a load balancer for a single server?
Not for distribution, but a reverse proxy in front of your app still helps with TLS, caching and zero-downtime deploys. Adding a second backend later is then a small configuration change.
Is nginx or HAProxy better for load balancing?
Both are mature and fast. nginx is convenient when it also serves static files and terminates TLS for your sites. HAProxy offers active health checks, detailed statistics and richer balancing features in its open source edition. Choose the one your team can operate confidently.
How do backends see the real visitor IP?
The load balancer adds the client address to X-Forwarded-For or sends it with the PROXY protocol. Configure the backend to trust that information only from the load balancer's IP, for example with nginx's set_real_ip_from and real_ip_header.