🌍 Networking

Load Balancing

Load Balancing

A technique that distributes network traffic across multiple servers to achieve high availability and performance. It operates at L4 (transport layer) and L7 (application layer) of the OSI model and supports various distribution algorithms such as Round Robin and Least Connection.

📖 Detailed Explanation

Load Balancing is a technology that distributes incoming network traffic across multiple backend servers to prevent overload on a single server and improve service availability and response speed. Working on the same principle as distributing customers across multiple counters in a restaurant, it is an essential infrastructure component in large-scale web services.

Load balancers are classified into L4 (transport layer) and L7 (application layer) according to the layer of the OSI 7-layer model at which they operate. An L4 load balancer distributes traffic quickly using only IP addresses and TCP/UDP port information, while an L7 load balancer can perform more fine-grained routing based on application-level information such as HTTP headers, URLs, and cookies.

Health Check is a core feature of load balancing that periodically checks the status of backend servers and does not send traffic to servers where a failure has occurred. It supports various methods such as TCP connection checks, HTTP response code verification, and custom health check endpoints, which makes uninterrupted service possible.

In modern cloud environments, managed services such as AWS ELB (ALB/NLB), GCP Cloud Load Balancing, and Azure Load Balancer are widely used. In on-premises environments, HAProxy, Nginx, and F5 BIG-IP are representative solutions. In microservices architectures, Kubernetes Ingress and Service Mesh (Istio, Linkerd) handle internal load balancing.

⚖️ L4 vs L7 Load Balancers

Category L4 Load Balancer L7 Load Balancer
Operating Layer Transport Layer (TCP/UDP) Application Layer (HTTP/HTTPS)
Distribution Criteria IP, Port information URL, Header, Cookie, Host
Speed Very fast (packet level) Relatively slower (parsing required)
SSL Handling Passthrough (handled by the backend) SSL Termination supported
Use Cases DB, game servers, TCP-based services Web services, API Gateway, MSA
AWS Service NLB (Network Load Balancer) ALB (Application Load Balancer)

🔄 Load Balancing Algorithms

Round Robin

Distributes requests to servers sequentially. The simplest and most widely used. Effective when server performance is identical.

Weighted Round Robin

Distributes requests by assigning a weight to each server. Useful when mixing servers with different performance. (e.g., 3:1 ratio)

Least Connections

Distributes to the server with the fewest current connections. Effective when request processing times vary.

IP Hash

Connects to the same server using a hash based on the client IP. Used for session persistence (Sticky Session).

Least Response Time

Distributes to the server with the fastest response time. Requires real-time performance monitoring.

Random

Selects a server at random. Simple to implement, and the load tends to be distributed evenly.

💻 Code Example

# /etc/nginx/nginx.conf - Nginx 로드 밸런서 설정

http {
    # 백엔드 서버 그룹 정의 (upstream)
    upstream backend_servers {
        # 분산 알고리즘 (기본: Round Robin)
        # least_conn;           # Least Connections
        # ip_hash;              # IP Hash (Sticky Session)
        # random two least_conn; # 무작위 + Least Conn 혼합

        # 서버 목록 (weight: 가중치, max_fails: 실패 허용 횟수)
        server 10.0.0.1:8080 weight=3;
        server 10.0.0.2:8080 weight=2;
        server 10.0.0.3:8080 weight=1 backup;  # 백업 서버

        # Health Check 설정
        # max_fails=3: 3번 실패 시 비활성화
        # fail_timeout=30s: 30초 후 재시도
        server 10.0.0.4:8080 max_fails=3 fail_timeout=30s;

        # 연결 유지 (Keep-Alive)
        keepalive 32;
    }

    server {
        listen 80;
        server_name api.example.com;

        location / {
            proxy_pass http://backend_servers;
            proxy_http_version 1.1;
            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_connect_timeout 5s;
            proxy_send_timeout 60s;
            proxy_read_timeout 60s;
        }

        # L7 라우팅: URL 기반 분산
        location /api/v2/ {
            proxy_pass http://api_v2_servers;
        }
    }
}
# /etc/haproxy/haproxy.cfg - HAProxy 설정

global
    log /dev/log local0
    maxconn 4096
    user haproxy
    group haproxy
    daemon

defaults
    mode http
    log global
    option httplog
    option dontlognull
    timeout connect 5s
    timeout client 30s
    timeout server 30s
    retries 3

# 프론트엔드: 클라이언트 요청 수신
frontend http_front
    bind *:80
    bind *:443 ssl crt /etc/ssl/certs/server.pem

    # ACL 기반 라우팅
    acl is_api path_beg /api
    acl is_static path_end .css .js .png .jpg

    use_backend api_servers if is_api
    use_backend static_servers if is_static
    default_backend web_servers

# 백엔드: 실제 서버 그룹
backend web_servers
    balance roundrobin           # 알고리즘: roundrobin, leastconn, source
    option httpchk GET /health   # HTTP Health Check
    http-check expect status 200

    server web1 10.0.0.1:8080 check weight 3
    server web2 10.0.0.2:8080 check weight 2
    server web3 10.0.0.3:8080 check backup   # 백업 서버

backend api_servers
    balance leastconn
    option httpchk GET /api/health

    # Sticky Session (쿠키 기반)
    cookie SERVERID insert indirect nocache
    server api1 10.0.0.10:8080 check cookie s1
    server api2 10.0.0.11:8080 check cookie s2

# 모니터링 대시보드
listen stats
    bind *:8404
    stats enable
    stats uri /stats
    stats refresh 10s
    stats auth admin:password
# 간단한 로드 밸런서 구현 예제 (Python)
import random
import time
from collections import defaultdict
from typing import List, Optional

class Server:
    def __init__(self, host: str, port: int, weight: int = 1):
        self.host = host
        self.port = port
        self.weight = weight
        self.connections = 0
        self.healthy = True
        self.response_times = []

    @property
    def address(self) -> str:
        return f"{self.host}:{self.port}"

class LoadBalancer:
    def __init__(self, servers: List[Server], algorithm: str = "round_robin"):
        self.servers = servers
        self.algorithm = algorithm
        self.current_index = 0
        self.weighted_index = 0

    def get_healthy_servers(self) -> List[Server]:
        return [s for s in self.servers if s.healthy]

    def round_robin(self) -> Optional[Server]:
        """순차적으로 서버 선택"""
        healthy = self.get_healthy_servers()
        if not healthy:
            return None
        server = healthy[self.current_index % len(healthy)]
        self.current_index += 1
        return server

    def least_connections(self) -> Optional[Server]:
        """연결 수가 가장 적은 서버 선택"""
        healthy = self.get_healthy_servers()
        if not healthy:
            return None
        return min(healthy, key=lambda s: s.connections)

    def ip_hash(self, client_ip: str) -> Optional[Server]:
        """IP 기반 해시로 서버 선택 (Sticky Session)"""
        healthy = self.get_healthy_servers()
        if not healthy:
            return None
        index = hash(client_ip) % len(healthy)
        return healthy[index]

    def weighted_round_robin(self) -> Optional[Server]:
        """가중치 기반 라운드 로빈"""
        healthy = self.get_healthy_servers()
        if not healthy:
            return None

        # 가중치 리스트 생성
        weighted_list = []
        for server in healthy:
            weighted_list.extend([server] * server.weight)

        server = weighted_list[self.weighted_index % len(weighted_list)]
        self.weighted_index += 1
        return server

    def get_server(self, client_ip: str = None) -> Optional[Server]:
        """알고리즘에 따라 서버 반환"""
        if self.algorithm == "round_robin":
            return self.round_robin()
        elif self.algorithm == "least_conn":
            return self.least_connections()
        elif self.algorithm == "ip_hash" and client_ip:
            return self.ip_hash(client_ip)
        elif self.algorithm == "weighted":
            return self.weighted_round_robin()
        return self.round_robin()

# 사용 예제
servers = [
    Server("10.0.0.1", 8080, weight=3),
    Server("10.0.0.2", 8080, weight=2),
    Server("10.0.0.3", 8080, weight=1),
]

lb = LoadBalancer(servers, algorithm="weighted")

# 10번 요청 분산 시뮬레이션
for i in range(10):
    server = lb.get_server()
    print(f"Request {i+1} → {server.address}")

🗣️ Say It Like This in Practice

💬 In an Infrastructure Design Meeting
"We placed an ALB in front of the API servers and set the health check endpoint to /health. With the Unhealthy threshold set to 3, a failed server is automatically removed within about 30 seconds. There are currently 4 servers in the target group, so even if one goes down, traffic only decreases by 75%."
💬 In an Interview
"An L4 load balancer distributes quickly by looking only at the IP and port at the TCP/UDP level, while L7 can parse HTTP headers and URLs for more fine-grained routing. For example, we used an L7 ALB for a blue-green deployment, sending /api/v1 to the legacy server and /api/v2 to the new server."
💬 In an Incident Response Situation
"Right now we're getting 502 errors from the Nginx upstream, and it looks like 2 of the 3 backend servers are down. Because of the max_fails setting, traffic is still going to them. For now, I'll manually remove those servers from the upstream, and since all the traffic will pile onto the remaining 1 server, I'll proceed with scaling out first."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

❌
Operating Without Health Checks

If health checks are not configured, traffic continues to be sent to failed servers. Be sure to create a /health endpoint and implement a comprehensive health check that also verifies the DB connection and external API status.

❌
Session Mismatch (No Sticky Session Configured)

With Round Robin, if the login session is stored in server memory, the user will be logged out when the next request goes to a different server. Use a Redis session store, or configure IP Hash/cookie-based Sticky Session.

❌
Single Load Balancer (SPOF)

The load balancer itself must not become a Single Point of Failure. Configure Active-Standby or Active-Active redundancy, and set up DNS Failover as well.

✅
Correct Load Balancer Configuration

Set the health check interval to 10-30 seconds, the timeout to 5 seconds, and the Unhealthy threshold to 2-3 times. Enable Connection Draining so that existing connections are terminated gracefully when a server is removed. Use a monitoring dashboard to check the number of requests and response time per server in real time.

🔗 Related Terms

📚 Learn More