High Availability & Load Balancing
One server is a ticking clock—sooner or later, a power supply dies, a disk fills up, or an update needs a reboot. Learn how production engineers eliminate Single Points of Failure, split traffic across clusters, and keep websites online 99.999% of the time.
Start Module 15 ↓01 Eliminating Single Points of Failure (SPOF) & The "Five Nines" Uptime Math
Define: A Single Point of Failure (SPOF) is any single component in your infrastructure whose failure brings down the entire service. High Availability (HA) is the practice of designing systems with redundant components so that if one part fails, traffic automatically continues with little or no downtime.
Understand: Think of a town connected to a hospital by one single bridge. If a truck breaks down on that bridge, nobody can cross. Even if the hospital has 100 doctors inside, the bridge is a SPOF. High Availability builds a second bridge—and ensures there is more than one power line, more than one water pipe, and more than one road.
🚨 The Hidden SPOF Trap
Many beginners put two web servers behind one load balancer and celebrate: "We are highly available!" Actually, they just moved the SPOF from the web server to the load balancer. True HA requires eliminating SPOFs at every layer: power, network switches, load balancers, web servers, and databases.
Know: The "Nines" of Availability Math
In Service Level Agreements (SLAs), uptime is measured in "nines." Every extra nine cuts your allowed yearly downtime by 10×—and increases cost and complexity dramatically.
| Availability | Nickname | Downtime / Year | Downtime / Month | Real-World Target |
|---|---|---|---|---|
| 99% | Two Nines | 3.65 days | 7.3 hours | Internal hobby tools |
| 99.9% | Three Nines | 8.76 hours | 43.8 minutes | Standard small business apps |
| 99.99% | Four Nines | 52.6 minutes | 4.38 minutes | E-commerce, SaaS platforms |
| 99.999% | Five Nines | 5.26 minutes | 26.3 seconds | Banking, healthcare, telecom |
🧠 Memory Trick: "5 Nines = 5 Minutes"
Forget complex formulas in an interview! Just remember: 99.999% (Five Nines) = ~5 minutes of downtime per year (5.26 min). Every nine you remove multiplies downtime by 10: Four Nines = ~50 minutes/year, Three Nines = ~9 hours/year.
When & Execute: Before buying expensive hardware, draw your architecture on a whiteboard and play the "What if I unplug this?" game. Point at every box—firewall, switch, load balancer, app server, database, power strip—and ask: "If this dies right now, do users get an error?" If the answer is yes, you found a SPOF.
02 Active-Passive vs Active-Active Clustering
Define: A server cluster is a group of two or more servers working together so they appear as one reliable system to users. Clusters are built in two main styles: Active-Passive (failover) and Active-Active (load-shared).
Understand (Spare Tire vs. Twin Engines Analogy):
- Active-Passive (The Spare Tire): Your car drives on 4 tires while the 5th spare tire sits quietly in the trunk. It does zero work during normal driving—until one tire pops. Then you swap it in and keep moving. In servers, Node A handles 100% of traffic while Node B sits idle, watching Node A's heartbeat.
- Active-Active (Twin Jet Engines): A commercial airplane flies with both left and right engines running at the same time. Both share the workload, making the plane faster and more efficient. If one engine fails mid-flight, the other engine keeps the plane safely in the air. In servers, both Node A and Node B serve users simultaneously.
Know & When: Choosing the Right Cluster Mode
| Feature | Active-Passive | Active-Active |
|---|---|---|
| Hardware Utilization | 50% (backup sits idle) | Up to 100% (all nodes work) |
| Failover Time | 1–10 seconds (VIP move / promotion) | Near-instant (healthy nodes absorb load) |
| Complexity | Low — easy to reason about | Higher — needs shared/synced state |
| Best For | SQL Databases (PostgreSQL), Firewalls, Keepalived VIPs | Stateless Web/API servers, Microservices, Containers |
⚠️ The "50% Capacity Rule" for Active-Active
If you run 2 Active-Active web servers at 80% CPU each and one crashes, the surviving server suddenly gets 160% of its capacity and crashes too (a cascading failure). Always size Active-Active clusters so the surviving nodes can handle 100% of peak traffic!
03 Load Balancers: Round Robin, Least Connections, Health Checks (HAProxy / Nginx)
Define: A Load Balancer (LB) is a reverse proxy that sits in front of your backend servers, receives all incoming user requests, and distributes them across healthy nodes using a routing algorithm. Two of the most popular open-source load balancers on Linux servers are HAProxy and Nginx.
Understand (The Restaurant Host Analogy): Imagine a busy restaurant with 3 waiters. Instead of letting 50 hungry guests rush into the kitchen, a Host stands at the front door. The Host greets each guest, checks which waiter isn't overwhelmed, and seats the guest at a table. If Waiter #3 calls in sick, the Host stops assigning tables to Waiter #3 until they return.
Know: Core Algorithms & Health Checks
Round Robin
Sends requests in strict rotation: Server 1 → Server 2 → Server 3 → Server 1. Best when all servers have identical hardware and requests take similar time.
Least Connections
Sends the next request to whichever server currently has the fewest active connections. Ideal for long-lived requests (video, file downloads, heavy API queries).
Active Health Checks
The LB pings /healthz every few seconds. If a server returns HTTP 500 or times out
3 times in a row, it is marked DOWN and removed from rotation.
Execute: Real HAProxy & Nginx Snippets
Notice how clean both configs are—just a few lines give you automatic health checks and load balancing:
# /etc/haproxy/haproxy.cfg — Least Connections + HTTP Health Check
backend app_servers
mode http
balance leastconn
option httpchk GET /healthz
http-check expect status 200
server app01 10.0.1.11:8080 check inter 3s fall 3 rise 2
server app02 10.0.1.12:8080 check inter 3s fall 3 rise 2
server app03 10.0.1.13:8080 check inter 3s fall 3 rise 2
# /etc/nginx/conf.d/loadbalancer.conf — Nginx Upstream Block
upstream app_pool {
least_conn;
server 10.0.1.11:8080 max_fails=3 fail_timeout=15s;
server 10.0.1.12:8080 max_fails=3 fail_timeout=15s;
server 10.0.1.13:8080 max_fails=3 fail_timeout=15s;
}
server {
listen 80;
location / {
proxy_pass http://app_pool;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
04 Virtual IP (VIP), VRRP / Keepalived & Avoiding Split-Brain
Define: A Virtual IP (VIP) is a floating IP address that is not permanently tied to a single physical server—it can move between servers in milliseconds. VRRP (Virtual Router Redundancy Protocol), implemented on Linux by Keepalived, is the protocol that decides which server currently holds that VIP.
Understand (The Relay Baton Analogy): Imagine two runners (LB-1 and
LB-2) holding a single glowing baton (the VIP, e.g.,
10.0.1.100). Users only ever call the baton's number. While LB-1 is healthy, it sends a
tiny heartbeat packet ("I'm alive!") to LB-2 every second. If LB-1 crashes and misses 3 heartbeats,
LB-2 grabs the baton, broadcasts a Gratuitous ARP to the network switch saying
"10.0.1.100 is now at MY MAC address!", and traffic keeps flowing.
Know: What Is Split-Brain & How Do We Prevent It?
Split-Brain happens when the heartbeat network cable between Node 1 and Node 2 gets unplugged or blocked by a firewall—while both servers are actually still alive. Node 2 thinks Node 1 died, so it promotes itself to MASTER. Now both servers claim the same VIP (or worse, both write conflicting data to a database).
🛡️ 3 Rules to Prevent Split-Brain
- Odd-Number Quorum (3, 5, 7 nodes): A node can only become Master if it can talk to a majority (e.g., 2 out of 3). A single isolated node cannot form a majority.
- Dedicated Heartbeat + Redundant Links: Never rely on a single network interface for VRRP/cluster heartbeats.
- STONITH ("Shoot The Other Node In The Head"): Hardware power fencing (via IPMI/iDRAC) that forcibly powers off a misbehaving node before another node takes over.
# /etc/keepalived/keepalived.conf (on LB-1: state MASTER, priority 101)
vrrp_instance VI_1 {
state MASTER
interface eth0
virtual_router_id 51
priority 101
advert_int 1
authentication {
auth_type PASS
auth_pass S3cr3tHA
}
virtual_ipaddress {
10.0.1.100/24
}
}
05 Practical Zero-Downtime Rolling Updates & Failover Testing
Define: A Rolling Update upgrades a cluster one node at a time while the remaining nodes continue serving live user traffic—achieving zero downtime during OS patching or app deployments.
Understand (The Pit Crew Analogy): You don't shut down an entire highway to repaint one lane. You put cones on Lane 1, let cars flow smoothly through Lanes 2 and 3, finish Lane 1, open it back up, and then move the cones to Lane 2.
Execute: The 5-Step Rolling Update Playbook
- Drain Connections: Tell the load balancer to mark
Node 1asDRAIN(finish existing requests, send zero new ones). - Verify Zero Active Traffic: Confirm active connections on
Node 1hit 0. - Patch & Reboot: Upgrade packages or deploy the new app version on
Node 1. - Smoke Test Locally: Curl
http://10.0.1.11:8080/healthzdirectly to verify HTTP 200 OK. - Re-enable & Repeat: Put
Node 1back into rotation, then repeat forNode 2andNode 3.
# 1. Drain a backend server gracefully in HAProxy (via runtime socket)
echo "set server app_servers/app01 state drain" | socat stdio /run/haproxy/admin.sock
# 2. Patch & reboot app01 safely while app02 & app03 serve users
ssh [email protected] "sudo apt update && sudo apt upgrade -y && sudo systemctl restart myapp"
# 3. Verify health before re-enabling
curl -f http://10.0.1.11:8080/healthz && \
echo "set server app_servers/app01 state ready" | socat stdio /run/haproxy/admin.sock
# 4. Chaos / Failover Test: Watch zero dropped requests while stopping Keepalived on LB-1
while true; do curl -s -o /dev/null -w "%{http_code} %{time_total}s\n" https://app.example.com/healthz; sleep 0.5; done
🎯 HA Readiness Checkpoint
- Every layer (LB, App, DB, Network) has at least 2 redundant paths—zero SPOFs.
- Active-Active nodes run below 50% peak load so one survivor can handle 100%.
- Health checks test real app readiness (
/healthz), not just TCP port open. - Failover is tested on purpose during business hours, not discovered at 3 AM.
🧪 Practice Scenario: Troubleshoot a Broken Failover
You have 2 HAProxy load balancers (LB-1 and LB-2) sharing VIP
10.0.1.100 via Keepalived. You power off LB-1 for testing, and
LB-2 immediately logs Entering MASTER STATE—yet users still cannot
reach the website for 60 seconds. What most likely went wrong?
Show Solution
Likely Cause: Either (1) Gratuitous ARP packets were
blocked or cached by the upstream switch/cloud VPC (common in cloud environments where
VRRP multicast isn't supported without unicast/floating-IP APIs), or (2)
LB-2's local firewall (ufw/nftables) is blocking
ports 80/443 or VRRP protocol 112.
Fix: Verify ip addr show eth0 on
LB-2 has 10.0.1.100, check firewall rules for protocol vrrp
(IP protocol 112), and test with arping -I eth0 -c 3 10.0.1.100.