🧠
Mechanism Depth - How It Works
💡 This level explains internal workings, trade-offs, and practical considerations expected in product company interviews. It helps you understand why and when to use each algorithm.
Intuition
Load balancers use different algorithms to optimize request distribution based on server load, session affinity, and fault tolerance requirements.
Explanation
Round Robin assigns each incoming request to the next server in a fixed order, which is simple but does not account for server load or capacity differences. Least Connections dynamically tracks the number of active connections per server and routes new requests to the server with the fewest active connections, improving load distribution especially when requests vary in duration. IP Hash computes a hash of the client's IP address to consistently route requests from the same client to the same server, enabling session persistence without shared session storage. However, IP Hash can cause uneven load if many clients share an IP (e.g., behind NAT). Health checks are critical in all algorithms to detect and exclude unhealthy servers, ensuring reliability. Trade-offs include complexity, session stickiness, and handling server failures gracefully.
Memory Hook
💡 Imagine a traffic cop directing cars: Round Robin sends cars down each lane in turn, Least Connections sends cars to the emptiest lane, and IP Hash sends cars based on their license plate number to the same lane every time.
Illustrative Code
class LoadBalancerDetailed:
def __init__(self, servers):
self.servers = servers
self.index = 0
self.connections = {server: 0 for server in servers}
self.healthy = {server: True for server in servers}
def health_check(self, server, status):
self.healthy[server] = status
def round_robin(self):
n = len(self.servers)
for _ in range(n):
server = self.servers[self.index]
self.index = (self.index + 1) % n
if self.healthy[server]:
return server
return None # No healthy servers
def least_connections(self):
healthy_servers = {s: c for s, c in self.connections.items() if self.healthy[s]}
if not healthy_servers:
return None
return min(healthy_servers, key=healthy_servers.get)
def ip_hash(self, client_ip):
n = len(self.servers)
for i in range(n):
idx = (hash(client_ip) + i) % n
server = self.servers[idx]
if self.healthy[server]:
return server
return None