AWS Documentation · Tiếng Việt

Elastic Load Balancing

Phân phối lưu lượng truy cập tự động trên AWS — ALB, NLB, GWLB từ kiến trúc đến vận hành thực chiến

Cập nhật 04/2026
Networking · Load Balancing
AWS Core Service
01 · Tổng quan

ELB là gì?

Elastic Load Balancing (ELB) là dịch vụ phân phối lưu lượng truy cập (traffic) tự động của AWS, giúp phân tán request đến nhiều target (EC2, container, IP, Lambda) trên một hoặc nhiều Availability Zone. ELB tự động scale theo lưu lượng, đảm bảo high availabilityfault tolerance cho ứng dụng.

⚖️
Phân phối tự động
Tự động chia đều traffic đến các target healthy, loại bỏ target unhealthy.
📈
Auto Scaling
ELB tự scale capacity theo lưu lượng. Không cần provision trước.
🛡️
High Availability
Hoạt động trên nhiều AZ, tự động failover khi một AZ gặp sự cố.
🔒
SSL/TLS Offloading
Terminate SSL tại LB, giảm tải cho backend. Tích hợp ACM miễn phí.
🔗
Tích hợp sâu
Kết nối Auto Scaling Group, ECS, EKS, Lambda, CloudWatch, WAF, Route 53.
🌍
Managed Service
AWS quản lý hoàn toàn — patching, scaling, HA. Bạn chỉ cần cấu hình.

Tại sao cần Load Balancer?

  • Phân tải: Chia đều request đến nhiều server, tránh quá tải một instance
  • High Availability: Nếu một server chết, LB tự động chuyển traffic sang server khác
  • Health Check: Liên tục kiểm tra sức khỏe backend, chỉ gửi traffic đến target healthy
  • SSL Termination: Xử lý mã hóa/giải mã SSL tại LB, giảm CPU cho backend
  • Single DNS endpoint: Client chỉ cần biết 1 DNS name, không cần biết IP từng server
  • Enforce stickiness: Giữ session của user trên cùng một backend server

Các loại Load Balancer trên AWS

AWS cung cấp 4 loại ELB, mỗi loại phục vụ use case khác nhau:

Tiêu chí ALB NLB GWLB CLB (Legacy)
Layer Layer 7 Layer 4 Layer 3 Layer 4/7
Protocol HTTP, HTTPS, gRPC TCP, UDP, TLS IP (GENEVE) HTTP, HTTPS, TCP, SSL
Static IP Không (dùng DNS) (1 IP/AZ, Elastic IP) Không Không
Latency ~400ms ~100μs (ultra-low) ~ms ~ms
Target types Instance, IP, Lambda Instance, IP, ALB Instance, IP Instance
Path/Host routing ✓ Có Không Không Không
WebSocket ✓ Có ✓ Có Không Không
SNI (Multi-cert) ✓ Có ✓ Có Không Không
Use case chính Web app, microservices, API Gaming, IoT, real-time, TCP Firewall, IDS/IPS, DPI Legacy (không nên dùng mới)
💡 Ghi nhớ cho SAA Exam
ALB = Layer 7 (HTTP/HTTPS), NLB = Layer 4 (TCP/UDP) với static IP và ultra-low latency, GWLB = Layer 3 cho third-party virtual appliances. CLB đã deprecated — AWS khuyến nghị migrate sang ALB/NLB.

Kiến trúc tổng quan ELB

🌐 Internet / Client Elastic Load Balancer ALB / NLB / GWLB Availability Zone 1 🖥 EC2 Instance 1 🖥 EC2 Instance 2 🐳 ECS Task Availability Zone 2 🖥 EC2 Instance 3 🖥 EC2 Instance 4 λ Lambda Function Availability Zone 3 🖥 EC2 Instance 5 🖥 EC2 Instance 6 📦 IP Target
02 · Application Load Balancer

Application Load Balancer (ALB)

ALB hoạt động ở Layer 7 (HTTP/HTTPS), là lựa chọn tốt nhất cho web application, microservices và container-based architecture. ALB hiểu nội dung HTTP request và có thể routing dựa trên path, host, header, query string, source IP.

Đặc điểm chính của ALB

  • Content-based routing: Route dựa trên URL path, hostname, HTTP header, query string, source IP
  • Host-based routing: api.example.com → Target Group A, web.example.com → Target Group B
  • Path-based routing: /api/* → Backend API, /images/* → Image Service
  • HTTP/2 & gRPC: Hỗ trợ native HTTP/2 và gRPC protocol
  • WebSocket: Hỗ trợ WebSocket connections
  • Redirect & Fixed Response: Trả về redirect 301/302 hoặc fixed response trực tiếp tại ALB
  • Authentication: Tích hợp Cognito hoặc OIDC provider để authenticate user tại ALB
  • WAF Integration: Gắn AWS WAF để bảo vệ khỏi SQL injection, XSS, DDoS

Kiến trúc ALB

ALB gồm 3 thành phần chính: ListenerRuleTarget Group

🌐 Client HTTPS ALB Listener :443 Rule: /api/* Rule: /web/* Target Group: API 🖥 EC2-api-1 🖥 EC2-api-2 🖥 EC2-api-3 Target Group: Web 🐳 ECS-web-1 🐳 ECS-web-2 🐳 ECS-web-3 EC2 :8080 EC2 :8080 EC2 :8080 Container :3000 Container :3000 Container :3000

Routing Conditions của ALB

ConditionMô tảVí dụ
Host headerRoute theo domain nameapi.example.com
Path patternRoute theo URL path/api/v1/*
HTTP headerRoute theo custom headerX-Custom-Header: mobile
Query stringRoute theo query parameter?platform=mobile
HTTP methodRoute theo HTTP methodGET, POST, PUT
Source IPRoute theo IP nguồn10.0.0.0/8
✅ Tip thực chiến
ALB rất phù hợp cho kiến trúc microservices: mỗi service có Target Group riêng, ALB route traffic dựa trên path hoặc hostname. Kết hợp với ECS/EKS để dynamic port mapping.

X-Forwarded Headers

Vì ALB terminate connection từ client, backend sẽ thấy IP của ALB thay vì IP client. ALB thêm các header sau:

  • X-Forwarded-For — IP gốc của client
  • X-Forwarded-Proto — Protocol gốc (http/https)
  • X-Forwarded-Port — Port gốc của request
03 · Network Load Balancer

Network Load Balancer (NLB)

NLB hoạt động ở Layer 4 (TCP/UDP/TLS), được thiết kế cho workload cần ultra-low latency (~100 microseconds) và khả năng xử lý hàng triệu request/giây. NLB cung cấp static IP cho mỗi AZ và hỗ trợ Elastic IP.

Đặc điểm chính của NLB

  • Ultra-low latency: ~100 microseconds — nhanh nhất trong các loại ELB
  • Static IP: Mỗi AZ có 1 static IP, có thể gán Elastic IP → whitelist firewall dễ dàng
  • Millions of RPS: Xử lý hàng triệu request/giây mà không cần warm-up
  • TCP/UDP/TLS: Hỗ trợ TCP, UDP, TLS (TCP với encryption)
  • Preserve source IP: Backend thấy IP gốc của client (không cần X-Forwarded-For)
  • TLS Termination: Có thể terminate TLS tại NLB hoặc pass-through đến backend
  • Target: ALB: NLB có thể forward traffic đến ALB (NLB → ALB pattern)
  • PrivateLink: NLB là thành phần bắt buộc để tạo VPC Endpoint Service (PrivateLink)
✅ Khi nào dùng NLB
  • Cần static IP hoặc Elastic IP
  • Workload TCP/UDP (không phải HTTP)
  • Cần ultra-low latency (gaming, trading)
  • Hàng triệu concurrent connections
  • Cần expose service qua PrivateLink
  • Cần preserve source IP cho backend
❌ Không nên dùng NLB khi
  • Cần routing theo URL path, host header
  • Cần authentication tại LB (Cognito/OIDC)
  • Cần gắn WAF (WAF chỉ hỗ trợ ALB/CloudFront)
  • Cần redirect HTTP → HTTPS tại LB
  • Cần fixed response tại LB
  • Web app thuần HTTP/HTTPS

NLB + Elastic IP

Mỗi NLB có thể gán 1 Elastic IP cho mỗi AZ. Điều này rất hữu ích khi partner/client cần whitelist IP cố định trong firewall:

NLB với Elastic IP
# Tạo NLB với Elastic IP cho mỗi AZ
aws elbv2 create-load-balancer \
  --name my-nlb \
  --type network \
  --subnet-mappings \
    SubnetId=subnet-aaa,AllocationId=eipalloc-111 \
    SubnetId=subnet-bbb,AllocationId=eipalloc-222

# Kết quả: NLB có 2 static IP cố định
# AZ-a: 52.10.20.30 (Elastic IP)
# AZ-b: 52.10.20.31 (Elastic IP)

NLB → ALB Pattern

Khi cần kết hợp static IP (NLB) với content-based routing (ALB), bạn có thể chain NLB → ALB:

  • NLB cung cấp static IP / Elastic IP cho client whitelist
  • NLB forward traffic đến ALB (ALB là target của NLB)
  • ALB thực hiện path/host routing đến các Target Group
⚠️ Lưu ý quan trọng
NLB không có Security Group mặc định (trước đây). Từ 2023, NLB đã hỗ trợ Security Group. Tuy nhiên, nếu không gán SG, NLB sẽ cho phép tất cả traffic đi qua — hãy luôn gán Security Group cho NLB.

TLS Termination trên NLB

NLB hỗ trợ TLS listener để terminate TLS tại load balancer:

  • Sử dụng certificate từ ACM (AWS Certificate Manager)
  • Hỗ trợ SNI (Server Name Indication) — nhiều certificate trên 1 listener
  • Hoặc TLS pass-through — NLB forward encrypted traffic trực tiếp đến backend
04 · Gateway Load Balancer

Gateway Load Balancer (GWLB)

GWLB hoạt động ở Layer 3 (Network layer), kết hợp vai trò transparent network gatewayload balancer. GWLB được thiết kế để deploy, scale và quản lý các third-party virtual appliances như firewall, IDS/IPS, deep packet inspection.

Đặc điểm chính của GWLB

  • Transparent gateway: Hoạt động như single entry/exit point cho tất cả traffic
  • GENEVE protocol: Sử dụng GENEVE encapsulation (port 6081) để forward traffic đến appliances
  • Layer 3: Xử lý tất cả IP packets — không giới hạn protocol
  • Bump-in-the-wire: Traffic đi qua appliance rồi quay lại GWLB trước khi đến destination
  • Cross-AZ: Phân phối traffic đến appliances trên nhiều AZ
  • Gateway Load Balancer Endpoint (GWLBe): VPC endpoint để route traffic từ VPC đến GWLB
🌐 Internet Gateway VPC — Application 📋 Route Table GWLBe (Endpoint) Application Subnet 🖥 App Server 1 🖥 App Server 2 🖥 App Server 3 VPC — Security Appliances Gateway Load Balancer GENEVE :6081 🔥 Firewall 1 Palo Alto 🔥 Firewall 2 Fortinet 🛡️ IDS/IPS Suricata ↩ Traffic quay lại GWLB → GWLBe → App

Luồng traffic qua GWLB

  1. Traffic từ Internet đi vào Internet Gateway
  2. Route table chuyển traffic đến GWLBe (Gateway LB Endpoint) trong Application VPC
  3. GWLBe forward traffic đến GWLB trong Security VPC
  4. GWLB phân phối traffic đến các security appliances (firewall, IDS/IPS)
  5. Appliance inspect/filter traffic rồi gửi lại GWLB
  6. GWLB trả traffic về GWLBe → đến Application Server
💡 GENEVE Protocol
GWLB sử dụng GENEVE (Generic Network Virtualization Encapsulation) trên port UDP 6081. Appliance phải hỗ trợ GENEVE để nhận và trả traffic. Các vendor lớn như Palo Alto, Fortinet, Check Point đều hỗ trợ.
05 · Thành phần

Target Groups

Target Group là nhóm các target (đích) mà Load Balancer sẽ forward traffic đến. Mỗi target group có cấu hình health check riêng và thuộc về một hoặc nhiều listener rule.

Các loại Target

Target TypeMô tảHỗ trợ bởiUse case
Instance EC2 instance ID (traffic gửi đến primary private IP) ALB NLB GWLB EC2 truyền thống, Auto Scaling Group
IP Private IP address (có thể ngoài VPC) ALB NLB GWLB On-premises server, peered VPC, container với awsvpc
Lambda Lambda function ARN ALB Serverless backend, API endpoint
ALB Application Load Balancer ARN NLB NLB → ALB pattern (static IP + L7 routing)

Health Check Configuration

Health check xác định target nào healthy để nhận traffic. Cấu hình bao gồm:

Tham sốMô tảMặc định
ProtocolHTTP, HTTPS, TCP, gRPCHTTP (ALB), TCP (NLB)
PathURL path cho HTTP/HTTPS health check/
PortPort kiểm tra (traffic port hoặc override)traffic-port
Healthy thresholdSố lần check thành công liên tiếp → healthy5 (ALB), 3 (NLB)
Unhealthy thresholdSố lần check thất bại liên tiếp → unhealthy2
IntervalKhoảng thời gian giữa các lần check30s (ALB), 30s (NLB)
TimeoutThời gian chờ response5s (ALB), 10s (NLB)
Success codesHTTP status code coi là healthy200
⚠️ NLB Health Check
NLB health check chỉ hỗ trợ TCP, HTTP, HTTPS (không hỗ trợ gRPC). Với TCP health check, NLB chỉ kiểm tra kết nối TCP thành công — không kiểm tra nội dung response. Nên dùng HTTP health check nếu có thể.

Deregistration Delay (Connection Draining)

Khi target bị remove khỏi target group (scale-in, unhealthy), ELB sẽ chờ một khoảng thời gian để hoàn thành các request đang xử lý trước khi ngắt kết nối:

  • Mặc định: 300 giây (5 phút)
  • Range: 0 – 3600 giây
  • Đặt 0: Ngắt kết nối ngay lập tức (không khuyến nghị)
  • Khuyến nghị: Đặt bằng thời gian xử lý request dài nhất của ứng dụng
Tạo Target Group với Health Check
# Tạo target group cho ALB
aws elbv2 create-target-group \
  --name my-api-targets \
  --protocol HTTP \
  --port 8080 \
  --vpc-id vpc-0123456789abcdef0 \
  --target-type instance \
  --health-check-protocol HTTP \
  --health-check-path /health \
  --health-check-interval-seconds 15 \
  --healthy-threshold-count 3 \
  --unhealthy-threshold-count 2 \
  --matcher HttpCode=200

# Đăng ký target
aws elbv2 register-targets \
  --target-group-arn arn:aws:elasticloadbalancing:... \
  --targets Id=i-0abcd1234efgh5678 Id=i-0ijkl9012mnop3456

# Cấu hình deregistration delay
aws elbv2 modify-target-group-attributes \
  --target-group-arn arn:aws:elasticloadbalancing:... \
  --attributes Key=deregistration_delay.timeout_seconds,Value=120
06 · Thành phần

Listeners & Rules

Listener là process lắng nghe connection request trên một protocol và port cụ thể. Mỗi listener có một hoặc nhiều rules để xác định cách route traffic đến target group.

Listener Configuration

LB TypeProtocols hỗ trợPort range
ALBHTTP (80), HTTPS (443)1 – 65535
NLBTCP, UDP, TLS, TCP_UDP1 – 65535
GWLBGENEVE (6081)6081 (cố định)

Rule Components (ALB)

Mỗi rule gồm: Priority + Conditions + Actions

Conditions (Điều kiện)

  • host-header — Match domain name: *.example.com
  • path-pattern — Match URL path: /api/*
  • http-header — Match custom header: X-Device: mobile
  • query-string — Match query param: version=v2
  • http-request-method — Match HTTP method: POST
  • source-ip — Match source IP CIDR: 10.0.0.0/8

Actions (Hành động)

ActionMô tảVí dụ
forward Forward đến 1 hoặc nhiều target group (weighted) 80% → TG-v2, 20% → TG-v1
redirect Redirect HTTP → HTTPS hoặc URL khác (301/302) HTTP :80 → HTTPS :443
fixed-response Trả về response cố định (status code + body) 503 "Service Maintenance"
authenticate-cognito Authenticate qua Amazon Cognito User Pool Login trước khi truy cập app
authenticate-oidc Authenticate qua OIDC provider (Google, Okta...) SSO với corporate IdP

Priority (Độ ưu tiên)

Rules được đánh giá theo thứ tự priority (số nhỏ = ưu tiên cao). Rule đầu tiên match sẽ được thực thi. Mỗi listener có 1 default rule (priority thấp nhất) — xử lý traffic không match rule nào.

Ví dụ: Cấu hình Listener Rules
# Rule 1 (Priority 10): /api/* → API Target Group
aws elbv2 create-rule \
  --listener-arn arn:aws:elasticloadbalancing:...:listener/app/my-alb/... \
  --priority 10 \
  --conditions Field=path-pattern,Values='/api/*' \
  --actions Type=forward,TargetGroupArn=arn:aws:...tg-api

# Rule 2 (Priority 20): Redirect HTTP → HTTPS
aws elbv2 create-rule \
  --listener-arn arn:aws:elasticloadbalancing:...:listener/app/my-alb/... \
  --priority 20 \
  --conditions Field=path-pattern,Values='/*' \
  --actions Type=redirect,RedirectConfig='{Protocol=HTTPS,Port=443,StatusCode=HTTP_301}'

# Rule 3: Fixed response cho maintenance
aws elbv2 create-rule \
  --listener-arn arn:aws:elasticloadbalancing:...:listener/app/my-alb/... \
  --priority 5 \
  --conditions Field=path-pattern,Values='/maintenance' \
  --actions Type=fixed-response,FixedResponseConfig='{StatusCode=503,ContentType=text/html,MessageBody="<h1>Bảo trì hệ thống</h1>"}'

# Weighted Target Group (Blue/Green, Canary)
aws elbv2 create-rule \
  --listener-arn arn:aws:elasticloadbalancing:...:listener/app/my-alb/... \
  --priority 15 \
  --conditions Field=path-pattern,Values='/app/*' \
  --actions Type=forward,ForwardConfig='{
    TargetGroups=[
      {TargetGroupArn=arn:aws:...tg-blue,Weight=90},
      {TargetGroupArn=arn:aws:...tg-green,Weight=10}
    ]
  }'
✅ Weighted Target Groups
Sử dụng weighted forward để triển khai Blue/Green deployment hoặc Canary release. Ví dụ: 90% traffic → version cũ, 10% → version mới. Dần dần tăng weight cho version mới.
07 · Bảo mật

SSL/TLS Termination

SSL/TLS Termination (hay SSL Offloading) là quá trình giải mã traffic HTTPS tại Load Balancer, giúp backend không phải xử lý mã hóa/giải mã — giảm CPU overhead đáng kể.

Cách hoạt động

  1. Client gửi HTTPS request đến Load Balancer
  2. LB thực hiện TLS handshake, giải mã traffic
  3. LB forward HTTP (plaintext) hoặc HTTPS (re-encrypt) đến backend
  4. Backend xử lý request và trả response

ACM Integration

AWS Certificate Manager (ACM) cung cấp SSL/TLS certificate miễn phí cho ELB:

  • Miễn phí: ACM public certificate hoàn toàn miễn phí
  • Auto-renew: ACM tự động gia hạn certificate trước khi hết hạn
  • Wildcard: Hỗ trợ wildcard certificate (*.example.com)
  • Multi-domain: Hỗ trợ SAN (Subject Alternative Name) cho nhiều domain

SNI — Server Name Indication

SNI cho phép host nhiều SSL certificate trên cùng một listener (cùng IP:port). Client gửi hostname trong TLS handshake, LB chọn certificate phù hợp.

LB TypeSNI SupportSố certificate tối đa
ALB✓ Có25 (default, có thể tăng)
NLB✓ Có25 (default, có thể tăng)
CLB✗ Không1 certificate / CLB
💡 SNI cho SAA Exam
Câu hỏi thường gặp: "Cần host nhiều website HTTPS trên cùng một LB" → Đáp án: ALB hoặc NLB với SNI. CLB không hỗ trợ SNI — mỗi CLB chỉ có 1 certificate.

Security Policies

Security Policy xác định TLS protocol versions và cipher suites mà LB sử dụng:

  • ELBSecurityPolicy-TLS13-1-2-2021-06: TLS 1.3 + TLS 1.2 (khuyến nghị)
  • ELBSecurityPolicy-2016-08: TLS 1.0+ (legacy, không khuyến nghị)
  • ELBSecurityPolicy-TLS-1-2-2017-01: Chỉ TLS 1.2+ (bảo mật cao)
  • ELBSecurityPolicy-FS-1-2-Res-2020-10: Forward Secrecy + TLS 1.2 (restrictive)

Backend Encryption (End-to-End)

Nếu cần mã hóa end-to-end, cấu hình LB forward HTTPS đến backend:

  • ALB: Target group protocol = HTTPS → ALB re-encrypt traffic đến backend
  • NLB: Sử dụng TCP listener (TLS pass-through) → backend tự xử lý TLS
Cấu hình HTTPS Listener với ACM
# Tạo HTTPS listener trên ALB
aws elbv2 create-listener \
  --load-balancer-arn arn:aws:elasticloadbalancing:...:loadbalancer/app/my-alb/... \
  --protocol HTTPS \
  --port 443 \
  --ssl-policy ELBSecurityPolicy-TLS13-1-2-2021-06 \
  --certificates CertificateArn=arn:aws:acm:ap-southeast-1:123456789012:certificate/abc-123 \
  --default-actions Type=forward,TargetGroupArn=arn:aws:...tg-web

# Thêm certificate cho SNI
aws elbv2 add-listener-certificates \
  --listener-arn arn:aws:elasticloadbalancing:...:listener/app/my-alb/... \
  --certificates CertificateArn=arn:aws:acm:...:certificate/def-456

# Redirect HTTP → HTTPS
aws elbv2 create-listener \
  --load-balancer-arn arn:aws:elasticloadbalancing:...:loadbalancer/app/my-alb/... \
  --protocol HTTP \
  --port 80 \
  --default-actions Type=redirect,RedirectConfig='{Protocol=HTTPS,Port=443,StatusCode=HTTP_301}'
08 · Tính năng

Sticky Sessions (Session Affinity)

Sticky Sessions đảm bảo tất cả request từ cùng một client được gửi đến cùng một target trong target group. Điều này cần thiết khi ứng dụng lưu session state trên server (không phải stateless).

Hai loại Sticky Sessions

🕐 Duration-based Stickiness
  • Cookie do ELB tạo
  • Cookie name: AWSALB (ALB), AWSELB (CLB)
  • Cấu hình thời gian sống (1s – 7 ngày)
  • Hết thời gian → LB có thể route đến target khác
  • Phù hợp khi không cần kiểm soát cookie
🍪 Application-based Stickiness
  • Cookie do ứng dụng tạo
  • Custom cookie name (do bạn đặt)
  • Không được dùng: AWSALB, AWSALBAPP, AWSALBTG
  • LB tạo thêm cookie AWSALBAPP để track
  • Phù hợp khi app cần kiểm soát session
Tiêu chíDuration-basedApplication-based
Cookie tạo bởiELBApplication + ELB
Cookie nameAWSALBCustom + AWSALBAPP
ExpirationCấu hình durationDo application quyết định
Hỗ trợALB, CLBALB
Use caseSession đơn giảnApp cần custom session logic
⚠️ Nhược điểm của Sticky Sessions
  • Có thể gây imbalanced load — một số target nhận nhiều traffic hơn
  • Nếu target chết, session bị mất (trừ khi dùng external session store)
  • Best practice: Dùng external session store (ElastiCache Redis, DynamoDB) thay vì sticky sessions
Bật Sticky Sessions
# Duration-based stickiness (3600 giây = 1 giờ)
aws elbv2 modify-target-group-attributes \
  --target-group-arn arn:aws:elasticloadbalancing:... \
  --attributes \
    Key=stickiness.enabled,Value=true \
    Key=stickiness.type,Value=lb_cookie \
    Key=stickiness.lb_cookie.duration_seconds,Value=3600

# Application-based stickiness
aws elbv2 modify-target-group-attributes \
  --target-group-arn arn:aws:elasticloadbalancing:... \
  --attributes \
    Key=stickiness.enabled,Value=true \
    Key=stickiness.type,Value=app_cookie \
    Key=stickiness.app_cookie.cookie_name,Value=MY_SESSION_ID \
    Key=stickiness.app_cookie.duration_seconds,Value=86400
09 · Tính năng

Cross-Zone Load Balancing

Cross-Zone Load Balancing cho phép LB phân phối traffic đều đến tất cả registered targets trên tất cả AZ, thay vì chỉ phân phối đều giữa các AZ.

Có Cross-Zone vs Không Cross-Zone

❌ Không Cross-Zone Load Balancer 50% 50% AZ-a (2 targets) EC2-1: 25% EC2-2: 25% AZ-b (4 targets) EC2-3: 12.5% EC2-4: 12.5% EC2-5: 12.5% EC2-6: 12.5% ✅ Có Cross-Zone Load Balancer AZ-a (2 targets) EC2-1: 16.7% EC2-2: 16.7% AZ-b (4 targets) EC2-3: 16.7% EC2-4: 16.7% EC2-5: 16.7% EC2-6: 16.7%

Mặc định & Chi phí

LB TypeCross-Zone mặc địnhPhí data transfer cross-AZ
ALBBật (luôn bật, không tắt được ở LB level)Miễn phí
NLBTắt (mặc định)Có phí nếu bật
GWLBTắt (mặc định)Có phí nếu bật
CLBTắt (mặc định)Miễn phí nếu bật
💡 Ghi nhớ cho SAA Exam
ALB luôn bật cross-zone (miễn phí). NLB mặc định tắt (có phí nếu bật). Đây là câu hỏi thường gặp trong đề thi SAA.
10 · Tính năng

Connection Draining / Deregistration Delay

Connection Draining (CLB) hay Deregistration Delay (ALB/NLB) là cơ chế cho phép LB hoàn thành các request đang xử lý (in-flight requests) trước khi ngắt kết nối với target bị deregister hoặc unhealthy.

Cách hoạt động

  1. Target bị đánh dấu draining (do scale-in, unhealthy, manual deregister)
  2. LB ngừng gửi request mới đến target đó
  3. LB chờ các in-flight request hoàn thành trong thời gian deregistration delay
  4. Sau khi hết thời gian hoặc tất cả request hoàn thành → LB ngắt kết nối

Cấu hình

Tham sốGiá trị
Mặc định300 giây (5 phút)
Range0 – 3600 giây (0 = tắt, ngắt ngay)
Khuyến nghịBằng thời gian xử lý request dài nhất
✅ Nên đặt giá trị phù hợp
  • API nhanh (< 5s): đặt 30-60 giây
  • Upload file lớn: đặt 300-600 giây
  • Long-polling/WebSocket: đặt 3600 giây
  • Batch processing: đặt theo thời gian batch
❌ Tránh
  • Đặt 0: Request bị ngắt đột ngột → lỗi 502
  • Đặt quá cao: Scale-in chậm, tốn tiền EC2
  • Không cấu hình: Mặc định 300s có thể quá dài
  • Quên cấu hình khi dùng Auto Scaling
Cấu hình Deregistration Delay
# Đặt deregistration delay = 120 giây
aws elbv2 modify-target-group-attributes \
  --target-group-arn arn:aws:elasticloadbalancing:... \
  --attributes Key=deregistration_delay.timeout_seconds,Value=120

# Kiểm tra giá trị hiện tại
aws elbv2 describe-target-group-attributes \
  --target-group-arn arn:aws:elasticloadbalancing:...
✅ Best Practice
Khi dùng với Auto Scaling Group, đặt deregistration delay ngắn hơn cooldown period của ASG. Ví dụ: deregistration delay = 60s, ASG cooldown = 120s. Điều này đảm bảo request hoàn thành trước khi instance bị terminate.
11 · Giám sát

ELB Access Logs & Monitoring

ELB cung cấp nhiều công cụ giám sát: CloudWatch Metrics cho real-time monitoring, Access Logs cho phân tích chi tiết, và Request Tracing cho debugging.

CloudWatch Metrics quan trọng

MetricMô tảÁp dụngAlarm khi
RequestCount Tổng số request đã xử lý ALB Spike bất thường
ActiveConnectionCount Số connection đang active ALB, NLB Vượt capacity
HealthyHostCount Số target healthy trong TG ALB, NLB < số target mong muốn
UnHealthyHostCount Số target unhealthy ALB, NLB > 0
TargetResponseTime Thời gian backend xử lý request ALB > SLA threshold
HTTPCode_ELB_5XX_Count Số lỗi 5xx từ ELB ALB > 0 (liên tục)
HTTPCode_Target_5XX_Count Số lỗi 5xx từ backend ALB > threshold
SurgeQueueLength Số request đang chờ trong queue CLB > 0 (liên tục)
SpilloverCount Số request bị reject do queue đầy CLB > 0
ConsumedLCUs Số Load Balancer Capacity Units tiêu thụ ALB, NLB Theo dõi chi phí

Access Logs

ELB Access Logs ghi lại chi tiết mỗi request và được lưu vào S3 bucket:

  • Thông tin ghi lại: Timestamp, client IP:port, target IP:port, request processing time, target processing time, response processing time, ELB status code, target status code, bytes received/sent, request URL, user agent, SSL cipher, SSL protocol
  • Tần suất: Mỗi 5 phút (hoặc 60 phút cho NLB)
  • Format: Gzip compressed log files trong S3
  • Chi phí: Không tính phí cho access logs, chỉ trả phí S3 storage
⚠️ S3 Bucket Policy cho Access Logs
S3 bucket phải có bucket policy cho phép ELB service account ghi log. AWS cung cấp account ID cho mỗi region (ví dụ: 127311923021 cho us-east-1). Nếu thiếu policy này, access logs sẽ không hoạt động.
Bật Access Logs cho ALB
# Bật access logs
aws elbv2 modify-load-balancer-attributes \
  --load-balancer-arn arn:aws:elasticloadbalancing:... \
  --attributes \
    Key=access_logs.s3.enabled,Value=true \
    Key=access_logs.s3.bucket,Value=my-elb-logs-bucket \
    Key=access_logs.s3.prefix,Value=alb-logs

# S3 Bucket Policy (cần thiết)
{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Principal": {
      "AWS": "arn:aws:iam::127311923021:root"
    },
    "Action": "s3:PutObject",
    "Resource": "arn:aws:s3:::my-elb-logs-bucket/alb-logs/AWSLogs/123456789012/*"
  }]
}

Request Tracing (ALB)

ALB thêm header X-Amzn-Trace-Id vào mỗi request, giúp trace request từ client → ALB → backend → response. Kết hợp với AWS X-Ray để distributed tracing.

Connection Logs (ALB)

Từ 2023, ALB hỗ trợ Connection Logs — ghi lại thông tin TLS connection (cipher, protocol version, client certificate) vào S3. Hữu ích cho security audit và compliance.

12 · Vận hành

Các lỗi thường gặp & Best Practices

HTTP Error Codes từ ELB

ErrorNguyên nhânCách xử lý
400 Bad Request Request header malformed, quá lớn Kiểm tra client request, giảm header size
403 Forbidden WAF block request Kiểm tra WAF rules, whitelist IP nếu cần
460 Client Closed Client đóng connection trước khi LB respond Kiểm tra client timeout, network issues
502 Bad Gateway Target trả response không hợp lệ, target đóng connection, target không phản hồi Kiểm tra backend health, security group, application logs
503 Service Unavailable Không có target healthy nào trong target group Kiểm tra health check, đảm bảo có target healthy
504 Gateway Timeout Target không respond trong thời gian idle timeout (mặc định 60s) Tăng idle timeout, tối ưu backend, kiểm tra database
561 Unauthorized Lỗi authentication (Cognito/OIDC) tại ALB Kiểm tra IdP configuration, token expiry

Troubleshooting 502 Bad Gateway

Lỗi 502 là lỗi phổ biến nhất. Checklist xử lý:

  1. Security Group: SG của target có cho phép traffic từ LB không?
  2. Health Check: Target có healthy không? Kiểm tra health check path và port
  3. Application: App có đang chạy và listen đúng port không?
  4. Keep-alive: Backend keep-alive timeout phải > ALB idle timeout (60s)
  5. Response format: Backend có trả HTTP response hợp lệ không?
  6. Target deregistered: Target có bị deregister trong quá trình xử lý request?
🔥 Lỗi 502 do Keep-Alive
Nguyên nhân phổ biến nhất của 502: Backend đóng keep-alive connection trước ALB. Giải pháp: Đặt backend keep-alive timeout (ví dụ Nginx: keepalive_timeout 65s) lớn hơn ALB idle timeout (mặc định 60s).

Best Practices

🏗️ Kiến trúc

  • Luôn deploy LB trên ít nhất 2 AZ để đảm bảo HA
  • Sử dụng ALB cho HTTP/HTTPS workload, NLB cho TCP/UDP
  • Không dùng CLB cho project mới — migrate sang ALB/NLB
  • Dùng internal LB cho communication giữa các tier (web → app → db)
  • Kết hợp Auto Scaling Group với target group để tự động scale

🔒 Bảo mật

  • Luôn redirect HTTP → HTTPS tại ALB
  • Sử dụng ACM certificate (miễn phí, auto-renew)
  • Chọn security policy TLS 1.2+ (tối thiểu)
  • Gắn AWS WAF vào ALB để chống SQL injection, XSS
  • Cấu hình Security Group chặt chẽ: LB chỉ nhận traffic từ internet, backend chỉ nhận từ LB
  • Bật deletion protection cho production LB

📊 Monitoring

  • Bật access logs và lưu vào S3 cho audit
  • Tạo CloudWatch Alarms cho: UnHealthyHostCount > 0, HTTPCode_ELB_5XX > threshold, TargetResponseTime > SLA
  • Sử dụng CloudWatch Dashboard để visualize metrics
  • Kết hợp X-Ray cho distributed tracing

⚡ Performance

  • Bật cross-zone load balancing cho NLB nếu target không đều giữa các AZ
  • Cấu hình deregistration delay phù hợp với ứng dụng
  • Sử dụng connection pooling ở backend
  • Tăng idle timeout cho long-running request (WebSocket, file upload)
  • Pre-warm ALB bằng cách liên hệ AWS Support nếu expect traffic spike lớn
✅ Security Group Chain
Internet → ALB SG: Allow inbound 80/443 from 0.0.0.0/0
ALB → EC2 SG: Allow inbound app port from ALB Security Group ID
Cách này đảm bảo EC2 chỉ nhận traffic từ ALB, không trực tiếp từ internet.
13 · Tham khảo

AWS CLI Cheat Sheet

Tổng hợp các lệnh AWS CLI thường dùng nhất cho Elastic Load Balancing. Tất cả lệnh sử dụng aws elbv2 (cho ALB, NLB, GWLB).

Quản lý Load Balancer

Load Balancer CRUD
# ── Tạo ALB ──
aws elbv2 create-load-balancer \
  --name my-alb \
  --type application \
  --subnets subnet-aaa subnet-bbb \
  --security-groups sg-12345678 \
  --scheme internet-facing \
  --ip-address-type ipv4

# ── Tạo NLB ──
aws elbv2 create-load-balancer \
  --name my-nlb \
  --type network \
  --subnets subnet-aaa subnet-bbb

# ── Tạo NLB với Elastic IP ──
aws elbv2 create-load-balancer \
  --name my-nlb-eip \
  --type network \
  --subnet-mappings \
    SubnetId=subnet-aaa,AllocationId=eipalloc-111 \
    SubnetId=subnet-bbb,AllocationId=eipalloc-222

# ── Tạo Internal LB ──
aws elbv2 create-load-balancer \
  --name my-internal-alb \
  --type application \
  --scheme internal \
  --subnets subnet-private-a subnet-private-b \
  --security-groups sg-internal

# ── Liệt kê tất cả LB ──
aws elbv2 describe-load-balancers

# ── Xem chi tiết 1 LB ──
aws elbv2 describe-load-balancers \
  --names my-alb

# ── Bật deletion protection ──
aws elbv2 modify-load-balancer-attributes \
  --load-balancer-arn arn:aws:elasticloadbalancing:... \
  --attributes Key=deletion_protection.enabled,Value=true

# ── Xóa LB ──
aws elbv2 delete-load-balancer \
  --load-balancer-arn arn:aws:elasticloadbalancing:...

Target Groups

Target Group Operations
# ── Tạo Target Group ──
aws elbv2 create-target-group \
  --name my-tg \
  --protocol HTTP \
  --port 80 \
  --vpc-id vpc-123 \
  --target-type instance \
  --health-check-path /health \
  --health-check-interval-seconds 15 \
  --healthy-threshold-count 3 \
  --unhealthy-threshold-count 2

# ── Tạo TG cho Lambda ──
aws elbv2 create-target-group \
  --name my-lambda-tg \
  --target-type lambda

# ── Tạo TG cho IP targets ──
aws elbv2 create-target-group \
  --name my-ip-tg \
  --protocol HTTP \
  --port 8080 \
  --vpc-id vpc-123 \
  --target-type ip

# ── Đăng ký targets ──
aws elbv2 register-targets \
  --target-group-arn arn:aws:elasticloadbalancing:... \
  --targets Id=i-111 Id=i-222

# ── Đăng ký IP targets ──
aws elbv2 register-targets \
  --target-group-arn arn:aws:elasticloadbalancing:... \
  --targets Id=10.0.1.50,Port=8080 Id=10.0.2.60,Port=8080

# ── Hủy đăng ký target ──
aws elbv2 deregister-targets \
  --target-group-arn arn:aws:elasticloadbalancing:... \
  --targets Id=i-111

# ── Kiểm tra health status ──
aws elbv2 describe-target-health \
  --target-group-arn arn:aws:elasticloadbalancing:...

# ── Liệt kê tất cả TG ──
aws elbv2 describe-target-groups

Listeners & Rules

Listener & Rule Operations
# ── Tạo HTTP Listener ──
aws elbv2 create-listener \
  --load-balancer-arn arn:aws:elasticloadbalancing:... \
  --protocol HTTP \
  --port 80 \
  --default-actions Type=forward,TargetGroupArn=arn:aws:...

# ── Tạo HTTPS Listener ──
aws elbv2 create-listener \
  --load-balancer-arn arn:aws:elasticloadbalancing:... \
  --protocol HTTPS \
  --port 443 \
  --ssl-policy ELBSecurityPolicy-TLS13-1-2-2021-06 \
  --certificates CertificateArn=arn:aws:acm:...:certificate/abc \
  --default-actions Type=forward,TargetGroupArn=arn:aws:...

# ── HTTP → HTTPS Redirect Listener ──
aws elbv2 create-listener \
  --load-balancer-arn arn:aws:elasticloadbalancing:... \
  --protocol HTTP \
  --port 80 \
  --default-actions \
    Type=redirect,RedirectConfig='{Protocol=HTTPS,Port=443,StatusCode=HTTP_301}'

# ── Tạo Rule với path routing ──
aws elbv2 create-rule \
  --listener-arn arn:aws:elasticloadbalancing:...:listener/... \
  --priority 10 \
  --conditions Field=path-pattern,Values='/api/*' \
  --actions Type=forward,TargetGroupArn=arn:aws:...tg-api

# ── Tạo Rule với host routing ──
aws elbv2 create-rule \
  --listener-arn arn:aws:elasticloadbalancing:...:listener/... \
  --priority 20 \
  --conditions Field=host-header,Values='api.example.com' \
  --actions Type=forward,TargetGroupArn=arn:aws:...tg-api

# ── Liệt kê rules ──
aws elbv2 describe-rules \
  --listener-arn arn:aws:elasticloadbalancing:...:listener/...

# ── Thêm certificate (SNI) ──
aws elbv2 add-listener-certificates \
  --listener-arn arn:aws:elasticloadbalancing:...:listener/... \
  --certificates CertificateArn=arn:aws:acm:...:certificate/def

Monitoring & Attributes

Monitoring & Configuration
# ── Bật Access Logs ──
aws elbv2 modify-load-balancer-attributes \
  --load-balancer-arn arn:aws:elasticloadbalancing:... \
  --attributes \
    Key=access_logs.s3.enabled,Value=true \
    Key=access_logs.s3.bucket,Value=my-logs-bucket \
    Key=access_logs.s3.prefix,Value=elb

# ── Cấu hình Idle Timeout ──
aws elbv2 modify-load-balancer-attributes \
  --load-balancer-arn arn:aws:elasticloadbalancing:... \
  --attributes Key=idle_timeout.timeout_seconds,Value=120

# ── Bật Sticky Sessions ──
aws elbv2 modify-target-group-attributes \
  --target-group-arn arn:aws:elasticloadbalancing:... \
  --attributes \
    Key=stickiness.enabled,Value=true \
    Key=stickiness.type,Value=lb_cookie \
    Key=stickiness.lb_cookie.duration_seconds,Value=3600

# ── Cấu hình Deregistration Delay ──
aws elbv2 modify-target-group-attributes \
  --target-group-arn arn:aws:elasticloadbalancing:... \
  --attributes Key=deregistration_delay.timeout_seconds,Value=120

# ── Xem LB attributes ──
aws elbv2 describe-load-balancer-attributes \
  --load-balancer-arn arn:aws:elasticloadbalancing:...

# ── Xem TG attributes ──
aws elbv2 describe-target-group-attributes \
  --target-group-arn arn:aws:elasticloadbalancing:...

# ── CloudWatch: Lấy UnHealthyHostCount ──
aws cloudwatch get-metric-statistics \
  --namespace AWS/ApplicationELB \
  --metric-name UnHealthyHostCount \
  --dimensions \
    Name=TargetGroup,Value=targetgroup/my-tg/abc123 \
    Name=LoadBalancer,Value=app/my-alb/def456 \
  --start-time 2026-01-01T00:00:00Z \
  --end-time 2026-01-01T01:00:00Z \
  --period 300 \
  --statistics Maximum

# ── Tạo CloudWatch Alarm ──
aws cloudwatch put-metric-alarm \
  --alarm-name elb-unhealthy-hosts \
  --namespace AWS/ApplicationELB \
  --metric-name UnHealthyHostCount \
  --dimensions \
    Name=TargetGroup,Value=targetgroup/my-tg/abc123 \
    Name=LoadBalancer,Value=app/my-alb/def456 \
  --statistic Maximum \
  --period 60 \
  --evaluation-periods 2 \
  --threshold 1 \
  --comparison-operator GreaterThanOrEqualToThreshold \
  --alarm-actions arn:aws:sns:...:my-alerts
💡 Mẹo CLI
  • Dùng --query để filter output: --query 'LoadBalancers[].DNSName'
  • Dùng --output table để hiển thị dạng bảng dễ đọc
  • Dùng jq để parse JSON: aws elbv2 describe-load-balancers | jq '.LoadBalancers[].DNSName'
  • Lệnh CLB cũ dùng aws elb (không có "v2")