🌍 Networking

Load Balancer

Load Balancer

Distributes traffic across multiple servers. L4 (TCP), L7 (HTTP). Key to high availability.

📖 Detailed Explanation

A load balancer is a core infrastructure component that distributes incoming network traffic evenly across multiple backend servers to improve the availability and performance of a service. When a single server handles all requests, a bottleneck occurs and the entire service goes down if it fails, but distributing traffic through a load balancer enables horizontal scaling (Scale-out) and makes zero-downtime service possible.

Load balancers are divided into L4 and L7 according to the OSI layer at which they operate. An L4 (Transport Layer) load balancer routes using only TCP/UDP port information, so it is fast but simple. AWS NLB is a representative example. An L7 (Application Layer) load balancer analyzes application-level information such as HTTP headers, URL paths, and cookies, enabling more sophisticated routing. AWS ALB, Nginx, and HAProxy are representative examples.

There are several types of traffic distribution algorithms. Round Robin is the simplest method, distributing requests to servers in order. Least Connections sends requests to the server with the fewest current connections to balance the load. IP Hash always connects a client to the same server based on the client IP, and is used when session persistence is needed. The Weighted method assigns weights according to server performance so that higher-performance servers handle more requests.

Health Check is a core feature of a load balancer that periodically checks the status of backend servers. It determines whether a server is healthy through an HTTP 200 response, a TCP port connection, a custom script, and so on, and a failed server is automatically removed from the traffic pool. Sticky Session (session pinning) sends requests from the same user to the same server to maintain session data consistency, and is implemented based on cookies or source IP.

💻 Code Example

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

http {
    # 업스트림 서버 그룹 정의
    upstream backend_servers {
        # 로드 밸런싱 알고리즘 (기본: Round Robin)
        # least_conn;        # 최소 연결 방식
        # ip_hash;           # IP 해시 (Sticky Session)

        # 백엔드 서버 목록 (weight로 가중치 설정)
        server 10.0.1.10:8080 weight=3;  # 높은 성능 서버
        server 10.0.1.11:8080 weight=2;
        server 10.0.1.12:8080 weight=1;
        server 10.0.1.13:8080 backup;    # 백업 서버 (다른 서버 장애 시 사용)

        # Health Check 설정
        keepalive 32;  # 업스트림 연결 유지
    }

    # API 서버용 별도 업스트림
    upstream api_servers {
        least_conn;  # API는 최소 연결 방식 적합
        server 10.0.2.10:3000;
        server 10.0.2.11:3000;
    }

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

        # SSL 설정
        ssl_certificate /etc/nginx/ssl/cert.pem;
        ssl_certificate_key /etc/nginx/ssl/key.pem;

        # L7 라우팅: URL 경로별 분기
        location / {
            proxy_pass http://backend_servers;
            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;
        }

        location /api/ {
            proxy_pass http://api_servers;
            proxy_http_version 1.1;
            proxy_set_header Connection "";
        }

        # Health Check 엔드포인트
        location /health {
            access_log off;
            return 200 "OK";
        }
    }
}
# /etc/haproxy/haproxy.cfg - HAProxy 고급 설정

global
    maxconn 50000
    log stdout format raw local0
    stats socket /var/run/haproxy.sock mode 660

defaults
    mode http
    log global
    option httplog
    option dontlognull
    option http-server-close
    option forwardfor
    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

    # HTTP → HTTPS 리다이렉트
    redirect scheme https if !{ ssl_fc }

    # ACL 기반 라우팅 (L7)
    acl is_api path_beg /api
    acl is_static path_beg /static /images /css /js
    acl is_websocket hdr(Upgrade) -i websocket

    # ACL에 따른 백엔드 분기
    use_backend api_backend if is_api
    use_backend static_backend if is_static
    use_backend ws_backend if is_websocket
    default_backend web_backend

# 백엔드: 웹 서버 그룹
backend web_backend
    balance roundrobin
    option httpchk GET /health HTTP/1.1\r\nHost:\ localhost

    # Sticky Session (쿠키 기반)
    cookie SERVERID insert indirect nocache

    server web1 10.0.1.10:8080 check cookie web1 weight 100
    server web2 10.0.1.11:8080 check cookie web2 weight 100
    server web3 10.0.1.12:8080 check cookie web3 weight 50 backup

# 백엔드: API 서버 그룹
backend api_backend
    balance leastconn
    option httpchk GET /api/health
    http-check expect status 200

    server api1 10.0.2.10:3000 check inter 3s fall 3 rise 2
    server api2 10.0.2.11:3000 check inter 3s fall 3 rise 2

# 백엔드: 정적 파일 (캐시 서버)
backend static_backend
    balance uri  # URL 해시로 캐시 효율 극대화
    server cache1 10.0.3.10:80 check
    server cache2 10.0.3.11:80 check

# 통계 대시보드
listen stats
    bind *:8404
    stats enable
    stats uri /stats
    stats refresh 10s
    stats admin if TRUE
# AWS Application Load Balancer (ALB) with Terraform

# ALB 생성
resource "aws_lb" "main" {
  name               = "my-app-alb"
  internal           = false
  load_balancer_type = "application"  # "network" for NLB
  security_groups    = [aws_security_group.alb.id]
  subnets            = var.public_subnet_ids

  enable_deletion_protection = true
  enable_http2              = true

  access_logs {
    bucket  = aws_s3_bucket.alb_logs.id
    prefix  = "alb-logs"
    enabled = true
  }

  tags = { Name = "my-app-alb" }
}

# 타겟 그룹 (백엔드 서버 풀)
resource "aws_lb_target_group" "app" {
  name        = "my-app-tg"
  port        = 8080
  protocol    = "HTTP"
  vpc_id      = var.vpc_id
  target_type = "instance"  # "ip" for Fargate

  # Health Check 설정
  health_check {
    enabled             = true
    path                = "/health"
    port                = "traffic-port"
    protocol            = "HTTP"
    healthy_threshold   = 2
    unhealthy_threshold = 3
    timeout             = 5
    interval            = 30
    matcher             = "200-299"
  }

  # Sticky Session (쿠키 기반)
  stickiness {
    type            = "lb_cookie"
    cookie_duration = 86400  # 1일
    enabled         = true
  }

  # 느린 시작 (새 인스턴스 워밍업)
  slow_start = 60
}

# HTTPS 리스너 (L7)
resource "aws_lb_listener" "https" {
  load_balancer_arn = aws_lb.main.arn
  port              = 443
  protocol          = "HTTPS"
  ssl_policy        = "ELBSecurityPolicy-TLS13-1-2-2021-06"
  certificate_arn   = var.acm_certificate_arn

  default_action {
    type             = "forward"
    target_group_arn = aws_lb_target_group.app.arn
  }
}

# 경로 기반 라우팅 규칙
resource "aws_lb_listener_rule" "api" {
  listener_arn = aws_lb_listener.https.arn
  priority     = 100

  condition {
    path_pattern { values = ["/api/*"] }
  }

  action {
    type             = "forward"
    target_group_arn = aws_lb_target_group.api.arn
  }
}

# HTTP → HTTPS 리다이렉트
resource "aws_lb_listener" "http_redirect" {
  load_balancer_arn = aws_lb.main.arn
  port              = 80
  protocol          = "HTTP"

  default_action {
    type = "redirect"
    redirect {
      port        = "443"
      protocol    = "HTTPS"
      status_code = "HTTP_301"
    }
  }
}

# 출력
output "alb_dns_name" {
  value = aws_lb.main.dns_name
}

🗣️ Say It Like This in Practice

💬 In an architecture design meeting
"Looking at the current traffic pattern, the load is concentrating on the API server. If we separate /api/* into a dedicated target group using path-based routing on the ALB and apply the Least Connections algorithm, we can distribute the load in a way that suits the API's characteristic of having many long-polling requests."
💬 In an Incident Response Situation
"Server 3 was removed from the target group due to a Health Check failure. The ALB is automatically distributing traffic to the remaining servers, so there is no user impact. Since unhealthy_threshold is 3, it was removed after 9 seconds, and once it recovers, with healthy_threshold of 2, it will be put back in after 6 seconds."
💬 In a Performance Optimization Discussion
"If we use session-based authentication, we have to turn on Sticky Session, which reduces load balancing efficiency. If we switch to JWT tokens, it becomes Stateless, so it doesn't matter which server a request goes to. Only then is there no problem even when servers are added by Auto Scaling."

⚠️ Common Mistakes & Cautions

❌
Inadequate Health Check configuration

If you only check the TCP port, the server is considered alive even when the application is dead. Be sure to implement a Health Check that verifies the DB connection and the status of essential services through an HTTP endpoint (/health).

❌
Overuse of Sticky Session

Enabling session pinning concentrates traffic on specific servers, which eliminates the benefit of load balancing. If a server fails, the sessions on that server are also lost. Externalize sessions with Redis/Memcached, or implement a Stateless architecture with JWT.

❌
Placing the load balancer in a single AZ

If the load balancer itself becomes a single point of failure (SPOF), it is pointless. Always deploy AWS ALB/NLB across Multi-AZ, and when building your own, make it redundant with an Active-Standby or Active-Active configuration.

✅
How to operate a load balancer correctly

Set Connection Draining (deregistration_delay) so that, when a server is removed, it waits until existing requests are completed. Use slow_start to gradually increase traffic when a new server is added. Monitoring HealthyHostCount, RequestCount, and TargetResponseTime with CloudWatch is essential.

🔗 Related Terms

📚 Learn More