🌍 Networking

Load Balancer

Load Balancer

A device that distributes traffic across multiple servers. Classified by L4 (TCP) and L7 (HTTP) level. Key to high availability.

📖 Detailed Explanation

A load balancer is a device or software that efficiently distributes incoming network traffic across multiple servers. When a single server cannot handle all requests, a load balancer splits traffic across multiple servers to increase the throughput of the entire system and reduce response time. Large-scale services such as Netflix, Amazon, and Google handle millions of requests per second through load balancers.

Load balancers are broadly divided into L4 (Layer 4) and L7 (Layer 7). An L4 load balancer operates at the TCP/UDP layer and distributes traffic based on IP addresses and port numbers. Because it does not inspect packet contents, it is fast and resource-efficient. An L7 load balancer operates at the HTTP/HTTPS layer and enables more sophisticated routing based on application-level information such as URLs, cookies, and HTTP headers.

Health Check is a core feature of a load balancer. It periodically checks the status of backend servers and does not send traffic to servers that have failed. It monitors server status in various ways, such as TCP port checks and HTTP endpoint calls. This allows users to use the service normally without noticing server failures.

In cloud environments, AWS's ELB (Elastic Load Balancer) product family is widely used. ALB (Application Load Balancer) is L7-based and optimized for HTTP/HTTPS traffic, while NLB (Network Load Balancer) is L4-based and suited to cases requiring ultra-low latency and ultra-high performance. In on-premises environments, software load balancers such as Nginx and HAProxy and hardware appliances such as F5 BIG-IP are used.

⚖️ L4 vs L7 Load Balancer Comparison

Category L4 Load Balancer L7 Load Balancer
Operating Layer Transport Layer (TCP/UDP) Application Layer (HTTP/HTTPS)
Routing Criteria IP address, port number URL, cookie, HTTP header, hostname
Performance Ultra-low latency, high throughput Relative delay due to packet analysis
SSL Handling Passthrough or separate handling Supports SSL Termination
AWS Product NLB (Network Load Balancer) ALB (Application Load Balancer)
Suitable Scenarios Game servers, real-time streaming, IoT Web services, API Gateway, microservices

🔄 Load Balancing Algorithms

Round Robin

Distributes requests to servers sequentially. It is the simplest and most widely used method, and is effective when all servers have the same performance.

Suitable for: server groups with identical specs

Weighted Round Robin

Sets a weight for each server and distributes more traffic to higher-performing servers. Useful when server specs differ.

Suitable for: heterogeneous server environments

Least Connections

Forwards new requests to the server with the fewest current connections. Distributes load evenly when request processing times vary.

Suitable for: long-lived connection services

IP Hash

Hashes the client IP address to always route to the same server. Used when session persistence is required.

Suitable for: when session stickiness is required

Least Response Time

Forwards requests to the server with the fastest response time. Requires real-time performance monitoring but provides the best user experience.

Suitable for: latency-sensitive services

Random

Selects a server at random. It is simple to implement and provides statistically even distribution in large-scale systems.

Suitable for: large groups of homogeneous servers

💻 Code Example

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

http {
    # 백엔드 서버 그룹 정의
    upstream backend_servers {
        # 로드 밸런싱 알고리즘 (기본: round robin)
        # least_conn;           # 최소 연결
        # ip_hash;              # IP 해시 (세션 스티키니스)
        # random two least_conn; # 랜덤 + 최소 연결

        # 서버 목록 (가중치 설정 가능)
        server 10.0.1.10:8080 weight=5;   # 가중치 5
        server 10.0.1.11:8080 weight=3;   # 가중치 3
        server 10.0.1.12:8080 weight=2;   # 가중치 2

        # 백업 서버 (다른 서버 장애시 사용)
        server 10.0.1.20:8080 backup;

        # Health Check 설정
        # max_fails: 실패 허용 횟수
        # fail_timeout: 서버 제외 시간
        server 10.0.1.10:8080 max_fails=3 fail_timeout=30s;

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

    # API 서버 그룹 (URL 기반 라우팅용)
    upstream api_servers {
        least_conn;
        server 10.0.2.10:3000;
        server 10.0.2.11:3000;
    }

    server {
        listen 80;
        listen 443 ssl;
        server_name example.com;

        # SSL 설정 (L7 SSL Termination)
        ssl_certificate /etc/ssl/certs/example.com.crt;
        ssl_certificate_key /etc/ssl/private/example.com.key;

        # 기본 요청 → 웹 서버
        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_set_header X-Forwarded-Proto $scheme;

            # 타임아웃 설정
            proxy_connect_timeout 5s;
            proxy_read_timeout 60s;
        }

        # /api 요청 → API 서버 (L7 라우팅)
        location /api {
            proxy_pass http://api_servers;
            proxy_set_header Host $host;
        }

        # Health Check 엔드포인트
        location /health {
            access_log off;
            return 200 "healthy\n";
            add_header Content-Type text/plain;
        }
    }
}
# /etc/haproxy/haproxy.cfg - HAProxy 로드 밸런서 설정

global
    log /dev/log local0
    maxconn 50000
    daemon

defaults
    log     global
    mode    http
    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/example.pem

    # ACL 정의 (L7 라우팅 규칙)
    acl is_api path_beg /api
    acl is_static path_beg /static
    acl is_websocket hdr(Upgrade) -i websocket

    # ACL 기반 백엔드 라우팅
    use_backend api_backend if is_api
    use_backend static_backend if is_static
    use_backend websocket_backend if is_websocket
    default_backend web_backend

# 웹 백엔드 (Round Robin)
backend web_backend
    balance roundrobin
    option httpchk GET /health HTTP/1.1\r\nHost:\ localhost

    # Health Check: 2초 간격, 3번 실패시 제외
    server web1 10.0.1.10:8080 check inter 2s fall 3 rise 2 weight 5
    server web2 10.0.1.11:8080 check inter 2s fall 3 rise 2 weight 3
    server web3 10.0.1.12:8080 check inter 2s fall 3 rise 2 weight 2

# API 백엔드 (Least Connections)
backend api_backend
    balance leastconn
    option httpchk GET /api/health

    # 쿠키 기반 세션 스티키니스
    cookie SERVERID insert indirect nocache
    server api1 10.0.2.10:3000 check cookie api1
    server api2 10.0.2.11:3000 check cookie api2

# 정적 파일 백엔드
backend static_backend
    balance roundrobin
    server static1 10.0.3.10:80 check
    server static2 10.0.3.11:80 check

# WebSocket 백엔드
backend websocket_backend
    balance source
    timeout tunnel 3600s
    server ws1 10.0.4.10:8080 check
    server ws2 10.0.4.11:8080 check

# 모니터링 페이지
listen stats
    bind *:8404
    stats enable
    stats uri /stats
    stats auth admin:password123
// AWS CDK - ALB + NLB 로드 밸런서 설정
import * as cdk from 'aws-cdk-lib';
import * as ec2 from 'aws-cdk-lib/aws-ec2';
import * as ecs from 'aws-cdk-lib/aws-ecs';
import * as elbv2 from 'aws-cdk-lib/aws-elasticloadbalancingv2';

export class LoadBalancerStack extends cdk.Stack {
  constructor(scope: cdk.App, id: string) {
    super(scope, id);

    const vpc = new ec2.Vpc(this, 'VPC', { maxAzs: 3 });

    // ═══════════════════════════════════════
    // ALB (Application Load Balancer) - L7
    // ═══════════════════════════════════════
    const alb = new elbv2.ApplicationLoadBalancer(this, 'ALB', {
      vpc,
      internetFacing: true,
      loadBalancerName: 'my-alb',
    });

    // HTTPS 리스너 (SSL Termination)
    const httpsListener = alb.addListener('HTTPS', {
      port: 443,
      certificates: [certificate],
      sslPolicy: elbv2.SslPolicy.TLS12,
    });

    // 타겟 그룹 (백엔드 서버)
    const webTargetGroup = new elbv2.ApplicationTargetGroup(this, 'WebTG', {
      vpc,
      port: 8080,
      protocol: elbv2.ApplicationProtocol.HTTP,
      targetType: elbv2.TargetType.IP,
      // Health Check 설정
      healthCheck: {
        path: '/health',
        interval: cdk.Duration.seconds(30),
        timeout: cdk.Duration.seconds(5),
        healthyThresholdCount: 2,
        unhealthyThresholdCount: 3,
        healthyHttpCodes: '200-299',
      },
      // 로드 밸런싱 알고리즘
      loadBalancingAlgorithmType:
        elbv2.TargetGroupLoadBalancingAlgorithmType.LEAST_OUTSTANDING_REQUESTS,
      // 스티키 세션 (선택적)
      stickinessCookieDuration: cdk.Duration.hours(1),
    });

    // URL 기반 라우팅 (L7 기능)
    httpsListener.addTargetGroups('Default', {
      targetGroups: [webTargetGroup],
    });

    // /api/* 요청은 API 서버로 라우팅
    httpsListener.addTargetGroups('ApiRouting', {
      priority: 10,
      conditions: [elbv2.ListenerCondition.pathPatterns(['/api/*'])],
      targetGroups: [apiTargetGroup],
    });

    // ═══════════════════════════════════════
    // NLB (Network Load Balancer) - L4
    // ═══════════════════════════════════════
    const nlb = new elbv2.NetworkLoadBalancer(this, 'NLB', {
      vpc,
      internetFacing: true,
      crossZoneEnabled: true, // 교차 영역 로드 밸런싱
    });

    // TCP 리스너 (L4)
    const tcpListener = nlb.addListener('TCP', {
      port: 443,
    });

    // 타겟 그룹 (게임 서버 등)
    const gameTargetGroup = new elbv2.NetworkTargetGroup(this, 'GameTG', {
      vpc,
      port: 7777,
      protocol: elbv2.Protocol.TCP,
      healthCheck: {
        protocol: elbv2.Protocol.TCP,
        interval: cdk.Duration.seconds(10),
      },
      // 클라이언트 IP 보존
      preserveClientIp: true,
    });

    tcpListener.addTargetGroups('GameServers', gameTargetGroup);

    // 출력
    new cdk.CfnOutput(this, 'ALBDnsName', { value: alb.loadBalancerDnsName });
    new cdk.CfnOutput(this, 'NLBDnsName', { value: nlb.loadBalancerDnsName });
  }
}

🗣️ Say It Like This in Practice

💬 In an architecture design meeting
"I think it would be good to use ALB for the microservice API and NLB for the real-time game server. ALB supports URL-based routing, so it can send /users to the User service and /orders to the Order service, and NLB has ultra-low latency, so it can guarantee the real-time nature of the game."
💬 In an Interview
"An L4 load balancer distributes traffic by looking only at the IP and port at the TCP layer, so it is fast, while L7 analyzes even HTTP headers and URLs, enabling more sophisticated routing. For web services I use ALB, and I set the Health Check interval to 30 seconds and the unhealthy threshold to 3, so failed servers were removed within 90 seconds."
💬 In an Incident Response Situation
"In the load balancer Health Check, 2 servers dropped out as unhealthy. Traffic is now concentrating on the 3 remaining healthy servers. I'll urgently trigger Auto Scaling to add 2 more servers, and restart the failed servers after checking the logs."

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

⚠️ Common Mistakes & Cautions

❌
Operating without Health Checks

Without Health Checks, traffic is also forwarded to failed servers, causing errors for users. Be sure to implement a /health endpoint and have the load balancer check it periodically.

❌
Misusing session stickiness

Using IP Hash or cookie-based stickiness can concentrate load on specific servers. Design to be stateless wherever possible, and store sessions in an external store such as Redis.

❌
Deploying to a single AZ only

If the load balancer and backend servers are deployed in only one Availability Zone (AZ), the entire service goes down when that AZ fails. Deploy across at least 2 AZs.

✅
Correct Load Balancer Configuration

Enable Cross-Zone Load Balancing, remove servers safely with Connection Draining (Deregistration Delay) settings, and analyze traffic by enabling access logs. A Health Check interval of 10–30 seconds is appropriate.

🔗 Related Terms

📚 Learn More