Verdalia has a stateless application, an optimized and cached catalog, and a calculation that says three application servers are enough for 1,000 users. What is missing is the piece that makes horizontal scaling possible: something that receives the customers' requests and distributes them. In this lesson you will study what a load balancer is, at which layer it can work, which algorithms it distributes with, how it knows a server has stopped working, and why session affinity is best avoided. Verdalia will turn its Nginx into a load balancer, spread the store across three machines, and rehearse its first zero-downtime deployment.
What a Load Balancer Is
A load balancer is a component that receives the customers' requests and distributes them among a group of equivalent servers. The customers only know the load balancer's address.
flowchart LR
customers["Customers"] --> lb["Load balancer"]
lb --> s1["Server 1"]
lb --> s2["Server 2"]
lb --> s3["Server 3, broken down"]
s1 --> data[("Shared data")]
s2 --> data
It solves three problems:
| Problem | How it solves it |
|---|---|
| Distributing | It spreads the requests so that no server gets saturated while others sit idle |
| Hiding failures | It detects servers that do not respond and stops sending them traffic |
| Adding and removing servers | Servers join and leave the group without the customers noticing |
The third is what allows capacity to grow without downtime, as scenario QS-2 requires, and the application to be updated without closing the store, as QS-6 requires.
Layer 4 and Layer 7
Load balancers are classified by the network layer at which they make their decisions. Layer 4 is the transport layer, where TCP connections live. Layer 7 is the application layer, where HTTP lives.
| Aspect | Layer 4, transport | Layer 7, application |
|---|---|---|
| What it sees | IP addresses and ports | The complete HTTP request: URL, headers, and cookies |
| What it distributes | Connections | Requests |
| Possible decisions | Based on the connection's source and destination | Based on the path, the domain, or any header |
| Speed | Maximum: it does not interpret the content | Somewhat lower |
| Can modify the request | No | Yes: add headers, compress, redirect |
| TLS encryption | Passes it through without opening it | Can terminate it |
| Typical use | Databases, queues, non-HTTP traffic | Web applications and APIs |
For a web store, the natural choice is layer 7. It allows, for example, sending the paths that start with /admin to a different server.
Distribution Algorithms
| Algorithm | How it chooses | When to use it |
|---|---|---|
| Round robin | The next one on the list, in order | Equal servers and requests of similar duration |
| Weighted round robin | Round robin, but each server receives a share proportional to its weight | Servers of different capacity |
| Least connections | The one with the fewest requests in progress | Requests of variable duration, or servers that may slow down |
| Least response time | The one that is responding fastest | Servers whose performance varies |
| Client IP hash | Applies a function to the IP: the same client always goes to the same server | When affinity is needed, or for caches |
Hashing and Consistent Hashing
A hash is a function that turns a piece of data, such as an IP address, into a number. The simple way to pick a server is to divide that number by the number of servers and keep the remainder. It works, but it has a flaw: if a server is added or removed, the divisor changes and almost every client moves to a different server.
Consistent hashing avoids that. Imagine a circle on which the servers and the clients are placed, each at the position its hash indicates. Each client is served by the first server it finds moving forward around the circle. If a server disappears, only its clients move to the next one, and the rest stay put. It is the usual technique for distributing data among cache servers, where changing servers means losing the copy.
Health Checks
A load balancer that sends traffic to a broken server turns a breakdown into errors for the customers. Health checks let it know which servers are working.
| Type | How it works | Advantage | Drawback |
|---|---|---|---|
| Active | The load balancer asks each server every few seconds, for example with GET /health |
Detects the failure even when there is no traffic | Generates additional requests |
| Passive | The load balancer watches the real requests and counts the failures | Needs nothing from the server | Some customer suffers the failure before it is detected |
Three parameters have to be decided: how often to check, how many consecutive failures remove a server, and how many successes bring it back into the group. If detection is too fast, a passing hiccup removes healthy servers. If it is too slow, customers receive errors.
What the Health Endpoint Should Check
| Type | What it checks | Risk |
|---|---|---|
| Shallow | That the process responds | A server that responds but cannot work is deemed healthy |
| Deep | That its dependencies, such as the database, respond too | If the database goes down, every server declares itself sick and the load balancer is left with none |
The recommended practice is for the load balancer's check to be shallow. Removing servers does not fix a problem they all share.
Session Affinity
Session affinity, also known as sticky sessions, consists of sending all of a client's requests to the same server. The load balancer achieves it with a cookie or with the IP hash. It is the quick fix when the application keeps sessions in its memory, and it has a price:
| Problem | Consequence |
|---|---|
| The distribution becomes unbalanced | A server with many active clients cannot hand any of them off |
| A failure loses sessions | The customers of the fallen server have to log in again and lose their cart |
| Removing a server is slow | You have to wait for its sessions to end, or cut them off |
| New servers take a while to receive load | Only new clients reach them |
That is why Verdalia moved sessions to Redis in the first lesson of the module. With a stateless application, any server serves any request, and the load balancer can distribute freely.
TLS Termination and Kinds of Load Balancer
TLS Termination
Traffic between the customer and the store travels encrypted with TLS, the protocol behind HTTPS. TLS termination means the load balancer decrypts the requests and sends them to the servers unencrypted, over the internal network. That way, the certificate is installed in a single place and the application servers are spared the work of encrypting. In exchange, internal traffic travels in the clear. Whether that is acceptable depends on the network and the data, and we will assess it in Module 5.
Kinds
| Kind | Examples | Advantage | Drawback |
|---|---|---|---|
| Software | Nginx, HAProxy | Inexpensive and flexible; installs on any machine | It has to be operated, and protected against its own failure |
| Hardware | Dedicated appliances | Very high performance | Expensive; typical of data centers |
| Cloud-managed | The cloud provider's services | No operation; redundant out of the box | Cost per use; dependence on the provider |
There is also DNS load balancing: the store's name is associated with several IP addresses, and each client receives one. It requires no machine, but DNS does not know whether a server has gone down, and clients keep the addresses for minutes or hours. It is used mostly to distribute between data centers.
The Load Balancer as a Single Point of Failure
We have spread out the store so that it does not depend on a single machine, and in front of everything we have placed a single machine. If the load balancer goes down, the store goes down, even if the three servers are working. It is a single point of failure, and we will solve it in the last lesson of the module.
Simulation in Python
The simulation advances in ticks. In each one, three requests arrive, and each server takes a number of ticks to serve its own.
import itertools
class Server:
def __init__(self, name, weight=1, duration=2):
self.name = name
self.weight = weight
self.duration = duration # ticks it takes to serve a request
self.working = True # the machine's real state
self.active = True # the state the load balancer believes
self.consecutive_failures = 0
self.in_progress = [] # tick at which each request in progress finishes
self.served = 0
self.peak = 0 # maximum simultaneous requests
def receive(self, tick):
self.in_progress.append(tick + self.duration)
self.served += 1
self.peak = max(self.peak, len(self.in_progress))
def advance(self, tick):
self.in_progress = [finish for finish in self.in_progress if finish > tick]
def round_robin():
counter = itertools.count()
return lambda active_servers: active_servers[next(counter) % len(active_servers)]
def weighted_round_robin():
counter = itertools.count()
def choose(active_servers):
expanded = [server for server in active_servers for _ in range(server.weight)]
return expanded[next(counter) % len(expanded)]
return choose
def least_connections():
return lambda active_servers: min(active_servers, key=lambda s: len(s.in_progress) / s.weight)
def simulate(title, choose, servers, ticks=600, failure=None, retry=False):
failed = 0
for tick in range(ticks):
if failure and tick == failure[1]:
failure[0].working = False
if tick % 5 == 0: # active health check
for server in servers:
server.consecutive_failures = 0 if server.working else server.consecutive_failures + 1
server.active = server.consecutive_failures < 2
for server in servers:
server.advance(tick)
for _ in range(3): # three requests arrive per tick
active_servers = [s for s in servers if s.active]
chosen = choose(active_servers)
if not chosen.working and retry: # passive check
chosen.active = False
chosen.consecutive_failures = 2
chosen = choose([s for s in servers if s.active])
if chosen.working:
chosen.receive(tick)
else:
failed += 1
print(title)
for server in servers:
print(f" {server.name}: {server.served:4} served, "
f"peak of {server.peak} simultaneous")
print(f" Failed requests: {failed}")
def pool(weight_3=1, duration_3=2):
return [Server("verdalia-app-01"), Server("verdalia-app-02"),
Server("verdalia-app-03", weight=weight_3, duration=duration_3)]
simulate("1. Round robin, with app-03 slow", round_robin(), pool(duration_3=6))
simulate("2. Least connections, with app-03 slow", least_connections(), pool(duration_3=6))
simulate("3. Weighted, with app-03 at weight 2", weighted_round_robin(), pool(weight_3=2))
servers = pool()
simulate("4. app-02 goes down, active check only", round_robin(), servers,
failure=(servers[1], 300))
servers = pool()
simulate("5. app-02 goes down, with retry", round_robin(), servers,
failure=(servers[1], 300), retry=True)Output:
1. Round robin, with app-03 slow verdalia-app-01: 600 served, peak of 2 simultaneous verdalia-app-02: 600 served, peak of 2 simultaneous verdalia-app-03: 600 served, peak of 6 simultaneous Failed requests: 0 2. Least connections, with app-03 slow verdalia-app-01: 800 served, peak of 3 simultaneous verdalia-app-02: 800 served, peak of 3 simultaneous verdalia-app-03: 200 served, peak of 2 simultaneous Failed requests: 0 3. Weighted, with app-03 at weight 2 verdalia-app-01: 450 served, peak of 2 simultaneous verdalia-app-02: 450 served, peak of 2 simultaneous verdalia-app-03: 900 served, peak of 4 simultaneous Failed requests: 0 4. app-02 goes down, active check only verdalia-app-01: 747 served, peak of 3 simultaneous verdalia-app-02: 300 served, peak of 2 simultaneous verdalia-app-03: 748 served, peak of 3 simultaneous Failed requests: 5 5. app-02 goes down, with retry verdalia-app-01: 751 served, peak of 4 simultaneous verdalia-app-02: 300 served, peak of 2 simultaneous verdalia-app-03: 749 served, peak of 3 simultaneous Failed requests: 0
Explanation of the code:
Serverdistinguishes betweenworking, which is reality, andactive, which is what the load balancer believes. Between a server going down and the load balancer finding out there is an interval, and the errors happen in that interval.- Each algorithm is a function that receives the list of active servers and returns the chosen one.
round_robinuses a counter and the remainder of the division.weighted_round_robinrepeats each server in the list as many times as its weight indicates.least_connectionspicks the minimum of requests in progress, divided by the weight. simulateruns an active check every 5 ticks and removes a server that fails 2 times in a row. Withretry=Trueit adds the passive check: if the chosen server does not respond, it removes it and resends the request to another.
Interpretation:
- Cases 1 and 2. Round robin treats a slow server like any other: it sends it the same requests, and 6 pile up on it. Least connections notices without anyone telling it and sends it a quarter.
- Case 3. With weight 2,
verdalia-app-03receives twice as much as the others. - Case 4. The load balancer takes a while to detect the failure, and 5 requests are lost. Afterwards, the two remaining machines share the traffic.
- Case 5. With the retry, none is lost. But you have to be careful about what gets resent: a request that has already started running may run twice. It is the idempotency problem from Module 3.
Verdalia: Nginx as a Load Balancer
The Machines
| Machine | Size | Role | Monthly price |
|---|---|---|---|
verdalia-lb-01 |
S: 2 cores, 4 GB | Nginx: load balancer, TLS termination, and compression | €30 |
verdalia-app-01, -02, and -03 |
M: 4 cores, 8 GB | The store, with 8 worker processes on each one | €60 each |
verdalia-aux-01 |
M | Redis | €60 |
verdalia-prod-01 |
L: 8 cores, 16 GB | PostgreSQL, RabbitMQ, and notification-service |
€120 |
The machines communicate over a private network. The only one with a public address is the load balancer. Scheduled jobs run only on verdalia-app-01. Lucía set up the three application machines by hand, with a 31-step list, and the second one ended up with a different version of one library. She discovered it by comparing the responses from /health.
The Health Endpoint
# verdalia/app.py (excerpt)
import socket
VERSION = "2027.03.02"
@app.route("/health")
def health():
return {"status": "ok", "server": socket.gethostname(), "version": VERSION}, 200It is a shallow check. It returns the machine's name and the deployed version, which make it possible to know which server responded and whether they are all running the same thing.
The Configuration
# /etc/nginx/conf.d/verdalia.conf, on verdalia-lb-01
upstream store {
least_conn;
server 10.0.1.11:8000 weight=1 max_fails=3 fail_timeout=10s; # verdalia-app-01
server 10.0.1.12:8000 weight=1 max_fails=3 fail_timeout=10s; # verdalia-app-02
server 10.0.1.13:8000 weight=1 max_fails=3 fail_timeout=10s; # verdalia-app-03
keepalive 32;
}
server {
listen 80;
server_name www.verdalia.example;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl;
server_name www.verdalia.example;
ssl_certificate /etc/nginx/certs/verdalia.crt;
ssl_certificate_key /etc/nginx/certs/verdalia.key;
gzip on;
gzip_types text/css application/javascript application/json image/svg+xml;
location / {
proxy_pass http://store;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_connect_timeout 2s;
proxy_read_timeout 10s;
proxy_next_upstream error timeout http_502 http_503;
proxy_next_upstream_tries 2;
}
}Explanation, block by block:
| Directive | What it does |
|---|---|
upstream store |
Defines the group of servers to distribute among, with the name store |
least_conn |
Selects the least connections algorithm. Without this line, Nginx distributes round robin |
server 10.0.1.11:8000 |
One server in the group: its address on the private network and the store's port |
weight=1 |
The weight. All three are equal. A bigger machine would carry weight=2 |
max_fails=3 fail_timeout=10s |
Passive check: after 3 failures within 10 seconds, the server is removed for 10 seconds. Then it is tried again |
keepalive 32 |
Keeps up to 32 connections to the servers open, so as not to open one per request |
First server block |
Serves port 80 and redirects to HTTPS with code 301 |
listen 443 ssl and ssl_certificate |
TLS termination: the certificate and its key live only on the load balancer |
gzip |
The compression from the lesson on optimization |
proxy_pass http://store |
Sends the request to the group. It is the line that turns Nginx into a load balancer |
proxy_http_version and Connection "" |
Needed for keepalive to work |
proxy_set_header Host |
Preserves the domain the customer asked for |
X-Forwarded-For |
Adds the customer's IP. Without it, the store would see every request as coming from the load balancer |
X-Forwarded-Proto |
Tells the store that the customer used HTTPS, even though it receives HTTP |
proxy_connect_timeout and proxy_read_timeout |
Timeouts: 2 seconds to connect and 10 to receive the response |
proxy_next_upstream |
If a server fails, the request is resent to another. At most 2 are tried |
Three observations:
- Nginx does not resend
POSTrequests by default. A listing can be requested twice without harm, and confirming an order cannot. And if one day it were resent, the charge's idempotency key protects it. - The free version of Nginx only does passive checks. Active ones belong to its commercial version, and HAProxy includes them in the free one. Verdalia starts with passive checks and the retry, and uses
/healthin deployments. - The
X-Forwarded-Forheader can be forged by a client. The store must only trust it when the request comes from the load balancer. We will come back to that in Module 5.
Zero-Downtime Deployment and the First Test With 1,000 Users
Rolling Deployment
With several servers behind a load balancer, the store can be updated one server at a time. It is the rolling deployment:
verdalia-app-01is markeddownin theupstreamblock and Nginx is reloaded withnginx -s reload, which does not cut open connections.- Wait for that server's requests in progress to finish.
- Install the new version on it and start it.
- Check
/healthand verify that the version is the expected one. - Return it to the group, and repeat with the next one.
There is an important condition: for a few minutes, two versions coexist. Database changes must be compatible with both.
Lucía rehearsed it on Friday, March 5, in the test environment: 0 seconds of interruption and 35 minutes of manual work. It is the first step toward scenario QS-6, but not its fulfillment. The procedure is manual, depends on a single person, and the rollback has not been rehearsed. Automation will come in Module 6.
The Test
The distributed store went into production on Tuesday, March 2, with the last 20-minute downtime. On Thursday, March 4, Lucía ran, in the test environment with the same topology, the first test with 1,000 users:
| Measure | Result | QS-1 target |
|---|---|---|
| 95th percentile of the catalog | 870 ms | Under 800 ms |
| 99th percentile of the catalog | 2.3 s | Under 2 s |
| Requests with errors | 0.4% | |
| CPU usage, application servers | 48% | |
| CPU usage, load balancer | 22% | |
Disk usage, verdalia-prod-01 |
Saturated |
The store withstands 1,000 users without going down, four times more than in January. But scenario QS-1 is not met, by a narrow margin. The application servers have plenty to spare, and the bottleneck has moved to the only place we have not spread out: the database. On verdalia-prod-01, searches and cache misses compete for the disk with the order writes.
Common Mistakes and Tips
- Using session affinity to avoid fixing the application. It hides the state, it does not remove it. The first server that goes down exposes it.
- Deep health checks on the load balancer. A database failure removes every server at once.
- Resending any failed request. Operations that are not idempotent may run twice.
- Sizing without accounting for failure. If three servers work at 80%, the loss of one leaves the other two at 120%. The failure of one causes the failure of all.
- Servers that are not identical. A different version on one machine produces intermittent errors, the hardest to diagnose.
- Forgetting the load balancer itself. It is one more machine, and it fails too.
- Practical tip. Include the version and the server name in the
/healthresponse. It is the cheapest way to answer the question “which server did it happen on?”
Exercises
Exercise 1: Choose the Algorithm
Say which algorithm you would use in each case and why:
- Three identical servers serving pages of similar duration.
- Two 4-core servers and one 8-core server.
- A group of cache servers, to which machines are added and removed frequently.
- Identical servers that handle report generation, which can take between 1 and 40 seconds.
Exercise 2: Does It Survive the Failure?
Verdalia has 3 application servers, with a capacity of 85 requests per second each. With 1,000 users, 120 requests per second arrive. Calculate the utilization of each server with all three running and with one down. What would happen on Mother's Day, with 1,400 users?
Exercise 3: Read the Configuration
A colleague proposes changing max_fails=3 fail_timeout=10s to max_fails=1 fail_timeout=300s “to react sooner.” What effect would it have?
Solutions
Solution to Exercise 1
- Round robin. It is the simplest and, with homogeneous servers and requests, it distributes well.
- Weighted round robin, with weight 2 for the bigger server, or least connections with those same weights.
- Consistent hashing. When the number of servers changes, only the part of the cache that belonged to the affected server is lost.
- Least connections. With such variable durations, round robin can pile several long reports onto the same server.
Solution to Exercise 2
With three servers, each one receives 40 requests per second: 47% utilization. With two, each one receives 60: 71%, below the 75% margin. The failure of one server is tolerated.
With 1,400 users, 168 requests per second arrive. With three servers, 56 each: 66%. With two, 84 each: 99%. The store would work as long as nothing failed, but the loss of one server would saturate the other two. For Mother's Day a fourth server is needed, as we calculated in the first lesson of the module.
Solution to Exercise 3
With max_fails=1, a single failure removes the server, and with fail_timeout=300s, it removes it for 5 minutes. A passing hiccup, such as a timeout on a slow request, would leave the store with two servers for 5 minutes. And three hiccups close together on different servers would leave it with none. Reacting sooner is not reacting better: the parameters must tolerate isolated failures and remove only the servers that fail repeatedly.
Conclusion
In this lesson you have learned what a load balancer is and the three problems it solves: distributing, hiding failures, and letting servers join and leave. You have compared layer 4 and layer 7 load balancing, learned the distribution algorithms, and seen how health checks remove broken servers. You have also understood why session affinity is a remedy best avoided, and what TLS termination is.
At Verdalia, since March 2 the store has run on three application servers, behind Nginx on verdalia-lb-01. It withstands 1,000 users without going down, and Lucía has rehearsed a zero-downtime deployment. Capacity grows by adding one line to the upstream block, although preparing the machine is still manual work.
Two problems remain in plain sight. The load balancer is a single point of failure, and we will deal with it in the last lesson of the module. The other is more urgent: the 95th percentile has stalled at 870 ms because the database has nothing more to give. It is the hardest piece to scale, because it is the one that holds the state we have taken out of all the others. We will take care of it in the next lesson, “Scaling the Data Layer: Replication, Partitioning, and the CAP Theorem.”
