Imagine it is 7:30 PM on a Friday. Thousands of users across India are opening their favourite food delivery app to order dinner. A single standard Node.js or Spring Boot server might comfortably handle 2,000 to 5,000 requests per second (RPS). But during this peak hour, the system is hit with 100,000 RPS. A single server would immediately run out of CPU, memory, or network bandwidth and crash, taking the entire application down with it.
To survive this, we scale horizontally by adding more servers, say 50 of them. But how do the users' mobile apps know which of the 50 servers to talk to? This is where a Load Balancer (LB) comes in.
What is a Load Balancer and why does it matter?
A load balancer is a reverse proxy that sits between your clients (users) and your backend servers. It acts as a traffic cop, receiving all incoming requests and distributing them across your pool of servers.
By ensuring no single server bears too much demand, a load balancer improves overall application responsiveness and availability. If one server crashes, the load balancer simply stops sending traffic to it and redirects those requests to the remaining healthy servers.
How it works
When a user types your website's URL, the DNS resolves the domain name to the IP address of your load balancer, not your actual application servers. The load balancer accepts the connection, decides which backend server should handle the request based on a specific algorithm, forwards the request, and then relays the server's response back to the user.
Load Balancing Algorithms
How exactly does the load balancer choose which server gets the next request? There are several strategies, each with its own trade-offs.
1. Round Robin
Requests are distributed across the group of servers sequentially. If you have three servers (A, B, C), the first request goes to A, the second to B, the third to C, the fourth to A, and so on.
- Best for: Servers with identical hardware specifications and requests that take roughly the same amount of time to process.
- Trade-off: It assumes all requests cost the same. If Server A gets three heavy video-upload requests while B and C get lightweight text requests, Server A might get overloaded.
2. Weighted Round Robin
Similar to Round Robin, but each server is assigned a "weight" based on its capacity. A server with a weight of 2 will receive twice as many requests as a server with a weight of 1.
- Best for: Environments with heterogeneous hardware (e.g., mixing older 4-core machines with newer 16-core machines).
3. Least Connections
The load balancer keeps track of the number of active connections to each server and sends the next request to the server with the fewest active connections.
- Best for: Applications with long-lived connections, such as WebSockets (e.g., designing a WhatsApp chat) or heavy database queries.
4. IP Hash
The load balancer hashes the client's IP address to determine which server receives the request. This ensures that a specific user consistently connects to the same server.
- Best for: Maximizing in-memory cache hits on the server side.
- Trade-off: If a server goes down, the hash ring changes, and users might lose their session data. This is usually mitigated by using Consistent Hashing.
Here is a simplified implementation of a thread-safe Round Robin load balancer to demonstrate the core logic:
import threading
class RoundRobinLB:
def __init__(self, servers):
self.servers = servers
self.index = 0
self.lock = threading.Lock()
def get_server(self):
if not self.servers:
return None
with self.lock:
server = self.servers[self.index]
self.index = (self.index + 1) % len(self.servers)
return serverLayer 4 vs Layer 7 Load Balancing
Load balancers typically operate at one of two levels of the OSI networking model: Layer 4 (Transport) or Layer 7 (Application).
Layer 4 (Transport Layer)
Layer 4 load balancers route traffic based on IP addresses and TCP/UDP ports. They do not inspect the contents of the packets (like the HTTP headers or payload). They simply grab the TCP stream and forward it to a backend server using Network Address Translation (NAT).
- Pros: Extremely fast, low CPU usage, highly secure (since it doesn't decrypt the payload).
- Cons: "Dumb" routing. It cannot route traffic based on the URL path or cookies.
Layer 7 (Application Layer)
Layer 7 load balancers operate at the HTTP/HTTPS level. They terminate the SSL/TLS connection, decrypt the traffic, read the HTTP headers, URL, and cookies, and then make intelligent routing decisions.
- Pros: "Smart" routing. You can route
/api/ordersto the Order Microservice and/api/usersto the User Microservice. - Cons: Slower and more CPU-intensive because it has to decrypt and inspect every single request.
| Feature | Layer 4 (e.g., AWS NLB) | Layer 7 (e.g., AWS ALB) |
|---|---|---|
| Routing basis | IP and Port | URL, HTTP Headers, Cookies |
| Performance | Ultra-fast (millions of RPS) | Slower (requires TLS termination) |
| Microservices | Hard to use for path-based routing | Excellent for path-based routing |
| Caching | No | Yes (can cache HTTP responses) |
Health Checks
A load balancer is only as good as its knowledge of the backend servers. If a server crashes, the load balancer must stop sending traffic to it immediately. It does this using Health Checks.
- Active Health Checks: The load balancer periodically (e.g., every 5 seconds) sends a ping or an HTTP
GET /healthrequest to each server. If the server responds with a200 OK, it remains in the pool. If it times out or returns a5xxerror three times in a row, it is marked as "unhealthy" and removed from rotation. - Passive Health Checks: The load balancer observes the actual user traffic. If it notices that a specific server is consistently returning
502 Bad Gatewayor timing out on real user requests, it temporarily evicts that server from the pool.
Trade-offs and Failure Modes
While load balancers solve the problem of scaling backend servers, they introduce their own set of challenges.
1. Single Point of Failure (SPOF)
If you have 50 backend servers but only one load balancer, what happens if the load balancer crashes? Your entire system goes down.
Solution: Load balancers are deployed in Active-Passive or Active-Active pairs. Two load balancers share a "Virtual IP" (VIP). A daemon like keepalived monitors the active load balancer. If it dies, the passive one instantly takes over the VIP, and traffic continues flowing seamlessly.
2. The Thundering Herd Problem
Imagine a server crashes and is removed from the pool. After a few minutes, it reboots and passes its health check. The load balancer immediately adds it back. If you are using a "Least Connections" algorithm, this new server currently has zero connections. The load balancer will suddenly flood this single server with thousands of requests, instantly crashing it again. Solution: Slow start. The load balancer gradually ramps up the traffic sent to a newly healthy server over a period of a few minutes.
Real-world Systems
In modern architectures, you will encounter load balancers in several forms:
- Cloud Managed: AWS Application Load Balancer (ALB) for L7, Network Load Balancer (NLB) for L4.
- Software Load Balancers: Nginx, HAProxy, and Envoy. These are often deployed as Ingress controllers in Kubernetes clusters.
- Hardware Load Balancers: F5 BIG-IP. These are physical appliances used in on-premise data centers, capable of handling massive throughput via specialized hardware (ASICs).
Interview Questions
Here are the most common questions interviewers ask about load balancing, along with concise model answers.
1. How do you handle user sessions when using a load balancer?
Answer: You have two options. The first is "Sticky Sessions" (Session Affinity), where the load balancer uses a cookie or IP hash to always route a specific user to the same server. However, this breaks down if that server crashes, as the user loses their session. The better, modern approach is to make the application servers completely stateless. The load balancer can route the request to any server, and the server fetches the user's session data from a fast, distributed cache like Redis or Memcached.
2. What happens if the load balancer itself becomes the bottleneck?
Answer: First, ensure you are using the right type of load balancer; an L4 load balancer can handle significantly more throughput than an L7 one. If a single L4 load balancer is still bottlenecking, you can scale out the load balancers themselves using DNS Round Robin. You map multiple load balancer IP addresses to your single domain name. The DNS server will hand out different IPs to different clients, distributing the load across multiple load balancers.
3. Why would you choose Layer 4 over Layer 7 load balancing?
Answer: I would choose Layer 4 if I need ultra-low latency, am handling millions of concurrent connections (like a massive multiplayer game or real-time trading platform), or if I am load balancing non-HTTP traffic like raw TCP/UDP streams or database connections. I would also use L4 if I want to save compute costs, as L4 doesn't require the CPU overhead of decrypting TLS certificates.
4. How does Consistent Hashing improve upon standard IP Hashing?
Answer: In standard IP hashing (hash(IP) % N), if a server is added or removed (N changes), almost all users get remapped to new servers, causing massive cache misses. Consistent Hashing places servers and requests on a virtual ring. If a server goes down, only the requests mapped to that specific server are re-routed to the next server on the ring. The rest of the traffic remains untouched, preserving cache hit rates.
5. How do you load balance WebSocket connections?
Answer: WebSockets are persistent, long-lived TCP connections. A standard Round Robin algorithm is poor here because connection counts can easily become skewed over time. I would use a Least Connections algorithm at Layer 7 (if I need to inspect the initial HTTP upgrade request) or Layer 4. I would also ensure the load balancer's idle timeout is configured to be longer than the WebSocket heartbeat/ping interval, so the LB doesn't aggressively drop quiet connections.
6. What is the difference between a Reverse Proxy and a Load Balancer?
Answer: A reverse proxy accepts requests from clients and forwards them to a server, often providing features like caching, SSL termination, and hiding the backend server's identity. A load balancer is a specific type of reverse proxy that distributes those requests across multiple backend servers to ensure high availability and scalability. All load balancers are reverse proxies, but not all reverse proxies are load balancers (a reverse proxy might just point to a single server).