🔄 AWS Elastic Load Balancer (ELB) Complete Guide

📋 Table of Contents

🎯 ELB Overview

AWS Elastic Load Balancer (ELB) automatically distributes incoming application traffic across multiple targets, such as Amazon EC2 instances, containers, IP addresses, Lambda functions, and virtual appliances. ELB provides high availability, fault tolerance, and automatic scaling for your applications.

graph TB A[Internet Users] --> B[Route 53 DNS] B --> C[Application Load Balancer] C --> D[Target Group 1] C --> E[Target Group 2] D --> F[EC2 Instance 1] D --> G[EC2 Instance 2] E --> H[Lambda Function] E --> I[ECS Container] subgraph "Availability Zone A" F H end subgraph "Availability Zone B" G I end style A fill:#e1f5fe style C fill:#f3e5f5 style D fill:#e8f5e8 style E fill:#e8f5e8
High-Level ELB Architecture: This diagram shows how internet traffic flows through Route 53 DNS to an Application Load Balancer, which then distributes requests across different target groups containing various compute resources (EC2, Lambda, ECS) spread across multiple Availability Zones for high availability.

🔀 ELB Types

graph LR A[ELB Types] --> B[Application Load Balancer
ALB - Layer 7] A --> C[Network Load Balancer
NLB - Layer 4] A --> D[Gateway Load Balancer
GWLB - Layer 3] A --> E[Classic Load Balancer
CLB - Legacy] B --> F[HTTP/HTTPS
WebSocket
gRPC] C --> G[TCP/UDP
TLS
High Performance] D --> H[Firewall
IDS/IPS
Deep Packet Inspection] E --> I[EC2-Classic
Deprecated] style B fill:#4CAF50 style C fill:#2196F3 style D fill:#FF9800 style E fill:#f44336
ELB Types Comparison: AWS offers four types of load balancers. ALB operates at Layer 7 (Application) for HTTP/HTTPS traffic with advanced routing. NLB operates at Layer 4 (Transport) for high-performance TCP/UDP traffic. GWLB operates at Layer 3 (Network) for security appliances. CLB is the legacy option being phased out.

🌐 Traffic Flow Diagrams

Application Load Balancer Traffic Flow

sequenceDiagram participant U as User participant DNS as Route 53 participant ALB as Application LB participant TG as Target Group participant EC2 as EC2 Instance participant HCheck as Health Check U->>DNS: 1. DNS Resolution request DNS->>U: 2. ALB IP Address U->>ALB: 3. HTTPS Request ALB->>TG: 4. Check healthy targets TG->>ALB: 5. Return healthy instances ALB->>EC2: 6. Forward request (round-robin) EC2->>ALB: 7. Response ALB->>U: 8. Response to user Note over HCheck: Continuous health monitoring HCheck->>EC2: Health check probe EC2->>HCheck: Health status response
ALB Traffic Flow Sequence: This sequence diagram illustrates the complete request flow from user to backend instances through an Application Load Balancer. The process includes DNS resolution, SSL termination at the ALB, target health verification, request routing using algorithms like round-robin, and response delivery back to the user.

Network Load Balancer Traffic Flow

graph TD A[Client] --> B[NLB Listener] B --> C{Load Balancing
Algorithm} C -->|Flow Hash| D[Target 1
AZ-A] C -->|Flow Hash| E[Target 2
AZ-B] C -->|Flow Hash| F[Target 3
AZ-C] G[Health Check] --> D G --> E G --> F subgraph "Connection Tracking" H[Source IP:Port] --> I[Dest IP:Port] I --> J[Protocol] J --> K[Hash Result] end K --> C style B fill:#2196F3 style C fill:#FF9800 style D fill:#4CAF50 style E fill:#4CAF50 style F fill:#4CAF50
NLB Flow Hash Routing: Network Load Balancer uses flow hash algorithm based on source IP, source port, destination IP, destination port, and protocol to ensure that packets from the same connection always go to the same target. This maintains connection stickiness and provides ultra-low latency with millions of requests per second capability.

Multi-Tier Application Architecture

graph TB subgraph "Internet Gateway" IG[Internet Gateway] end subgraph "Public Subnet - Load Balancer Tier" ALB[Application Load Balancer] NLB[Network Load Balancer] end subgraph "Private Subnet - Application Tier" APP1[App Server 1] APP2[App Server 2] APP3[App Server 3] end subgraph "Private Subnet - Database Tier" RDS[(RDS Primary)] RDS2[(RDS Standby)] end subgraph "Auto Scaling Group" ASG[Auto Scaling Group] ASG --> APP1 ASG --> APP2 ASG --> APP3 end IG --> ALB IG --> NLB ALB --> APP1 ALB --> APP2 ALB --> APP3 NLB --> APP1 APP1 --> RDS APP2 --> RDS APP3 --> RDS RDS --> RDS2 style IG fill:#ffeb3b style ALB fill:#4caf50 style NLB fill:#2196f3 style APP1 fill:#ff9800 style APP2 fill:#ff9800 style APP3 fill:#ff9800 style RDS fill:#9c27b0 style RDS2 fill:#9c27b0
Multi-Tier Architecture with ELB: This diagram shows a complete three-tier architecture where ELBs sit in public subnets to receive internet traffic, application servers run in private subnets for security, and databases reside in isolated private subnets. Auto Scaling Groups ensure application tier elasticity based on demand.

⚙️ Setup Process Flow

graph TD A[Start ELB Setup] --> B[1. Create VPC & Subnets] B --> C[2. Launch EC2 Instances] C --> D[3. Create Security Groups] D --> E[4. Create Target Group] E --> F[5. Register Targets] F --> G[6. Create Load Balancer] G --> H[7. Create Listener] H --> I[8. Configure Health Checks] I --> J[9. Configure SSL Certificate] J --> K[10. Test & Validate] K --> L[11. Monitor & Scale] style A fill:#e1f5fe style B fill:#f3e5f5 style C fill:#e8f5e8 style D fill:#fff3e0 style E fill:#fce4ec style F fill:#f1f8e9 style G fill:#e0f2f1 style H fill:#e8eaf6 style I fill:#fff8e1 style J fill:#fafafa style K fill:#e3f2fd style L fill:#f9fbe7
ELB Setup Process Flow: This flowchart outlines the sequential steps required to set up an ELB from infrastructure preparation to monitoring. Each step builds upon the previous one, starting with network infrastructure (VPC, subnets) and progressing through compute resources, security, load balancing configuration, and finally monitoring setup.

💻 AWS CLI Commands

Step 1: VPC and Network Setup

STEP 1

Create VPC

aws ec2 create-vpc \
    --cidr-block 10.0.0.0/16 \
    --tag-specifications 'ResourceType=vpc,Tags=[{Key=Name,Value=MyELBVPC}]'
Parameters Explained:
  • --cidr-block: Defines the IP address range for the VPC (10.0.0.0/16 provides ~65,000 IP addresses)
  • --tag-specifications: Adds metadata tags for resource identification and management
What this does: Creates the foundational network infrastructure where all ELB components will reside. The VPC acts as a virtual data center in the cloud.
Next Step: Create subnets within this VPC for different tiers (public for ELB, private for instances).

Create Public Subnets (for Load Balancer)

aws ec2 create-subnet \
    --vpc-id vpc-12345678 \
    --cidr-block 10.0.1.0/24 \
    --availability-zone us-west-2a \
    --tag-specifications 'ResourceType=subnet,Tags=[{Key=Name,Value=PublicSubnet1}]'

aws ec2 create-subnet \
    --vpc-id vpc-12345678 \
    --cidr-block 10.0.2.0/24 \
    --availability-zone us-west-2b \
    --tag-specifications 'ResourceType=subnet,Tags=[{Key=Name,Value=PublicSubnet2}]'
Parameters Explained:
  • --vpc-id: References the VPC created in previous step
  • --cidr-block: Subnet IP range (10.0.1.0/24 provides 254 usable IP addresses)
  • --availability-zone: Specific AZ for high availability across multiple zones
What this does: Creates public subnets in different AZs where the load balancer nodes will be deployed. ELBs require at least 2 AZs for high availability.
Next Step: Create private subnets for backend instances and configure route tables.

Step 2: Security Groups

STEP 2

Create Load Balancer Security Group

aws ec2 create-security-group \
    --group-name ELB-SecurityGroup \
    --description "Security group for Application Load Balancer" \
    --vpc-id vpc-12345678
Parameters Explained:
  • --group-name: Unique identifier for the security group
  • --description: Human-readable description of the security group's purpose
  • --vpc-id: Associates security group with specific VPC
What this does: Creates a firewall ruleset that will control traffic to/from the load balancer. By default, it allows all outbound traffic and denies all inbound traffic.
Next Step: Add inbound rules to allow HTTP/HTTPS traffic from the internet.

Add Inbound Rules to Load Balancer Security Group

# Allow HTTP traffic (port 80)
aws ec2 authorize-security-group-ingress \
    --group-id sg-12345678 \
    --protocol tcp \
    --port 80 \
    --cidr 0.0.0.0/0

# Allow HTTPS traffic (port 443)
aws ec2 authorize-security-group-ingress \
    --group-id sg-12345678 \
    --protocol tcp \
    --port 443 \
    --cidr 0.0.0.0/0
Parameters Explained:
  • --group-id: ID of the security group to modify
  • --protocol: Network protocol (tcp, udp, icmp)
  • --port: Port number or range to allow
  • --cidr: IP address range allowed (0.0.0.0/0 = entire internet)
Alternative Options: Instead of 0.0.0.0/0, you can specify specific IP ranges, security groups, or prefix lists for more restrictive access.
What this does: Opens ports 80 and 443 to receive web traffic from the internet. These are standard ports for HTTP and HTTPS respectively.

Step 3: Target Group Creation

STEP 3

Create Target Group

aws elbv2 create-target-group \
    --name MyTargetGroup \
    --protocol HTTP \
    --port 80 \
    --vpc-id vpc-12345678 \
    --health-check-protocol HTTP \
    --health-check-path /health \
    --health-check-interval-seconds 30 \
    --health-check-timeout-seconds 5 \
    --healthy-threshold-count 2 \
    --unhealthy-threshold-count 3 \
    --target-type instance
Parameters Explained:
  • --name: Unique name for the target group
  • --protocol: Protocol for routing requests to targets (HTTP, HTTPS, TCP, UDP)
  • --port: Port on which targets receive traffic
  • --health-check-path: URL path for health check requests
  • --health-check-interval-seconds: Frequency of health checks (15-300 seconds)
  • --healthy-threshold-count: Consecutive successful checks needed to mark target healthy
  • --target-type: Type of target (instance, ip, lambda, alb)
Alternative Options: Target types include 'ip' for IP addresses, 'lambda' for Lambda functions, and 'alb' for chaining load balancers.
What this does: Creates a logical grouping of targets that will receive traffic from the load balancer. Health checks ensure only healthy targets receive requests.
Next Step: Register actual EC2 instances or other targets with this target group.

Step 4: Load Balancer Creation

STEP 4

Create Application Load Balancer

aws elbv2 create-load-balancer \
    --name MyApplicationLoadBalancer \
    --subnets subnet-12345678 subnet-87654321 \
    --security-groups sg-12345678 \
    --scheme internet-facing \
    --type application \
    --ip-address-type ipv4 \
    --tags Key=Environment,Value=Production Key=Application,Value=WebApp
Parameters Explained:
  • --name: Unique name for the load balancer (max 32 characters)
  • --subnets: List of subnet IDs where LB nodes will be placed (minimum 2 AZs)
  • --security-groups: Security groups controlling traffic to the LB
  • --scheme: internet-facing (public) or internal (private)
  • --type: application, network, or gateway
  • --ip-address-type: ipv4, ipv6, or dualstack
Alternative Options: For internal load balancers, use --scheme internal. For dual-stack support, use --ip-address-type dualstack.
What this does: Creates the actual load balancer infrastructure with nodes deployed across specified subnets. The LB gets a DNS name that clients will use to connect.
Next Step: Create listeners to define how the LB handles incoming requests.

Step 5: Listener Configuration

STEP 5

Create HTTP Listener

aws elbv2 create-listener \
    --load-balancer-arn arn:aws:elasticloadbalancing:us-west-2:123456789012:loadbalancer/app/MyApplicationLoadBalancer/50dc6c495c0c9188 \
    --protocol HTTP \
    --port 80 \
    --default-actions Type=forward,TargetGroupArn=arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/MyTargetGroup/50dc6c495c0c9188
Parameters Explained:
  • --load-balancer-arn: ARN of the load balancer to attach listener to
  • --protocol: Protocol for connections from clients (HTTP, HTTPS, TCP, UDP)
  • --port: Port on which the load balancer listens
  • --default-actions: Default action when request doesn't match any rules
Alternative Actions: Actions include forward, redirect, fixed-response, authenticate-cognito, and authenticate-oidc.
What this does: Creates a listener that defines which port and protocol the load balancer monitors for client connections and how to route those requests.
Next Step: Create HTTPS listener with SSL certificate for secure connections.

Create HTTPS Listener with SSL Certificate

aws elbv2 create-listener \
    --load-balancer-arn arn:aws:elasticloadbalancing:us-west-2:123456789012:loadbalancer/app/MyApplicationLoadBalancer/50dc6c495c0c9188 \
    --protocol HTTPS \
    --port 443 \
    --certificates CertificateArn=arn:aws:acm:us-west-2:123456789012:certificate/12345678-1234-1234-1234-123456789012 \
    --ssl-policy ELBSecurityPolicy-TLS-1-2-2017-01 \
    --default-actions Type=forward,TargetGroupArn=arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/MyTargetGroup/50dc6c495c0c9188
Parameters Explained:
  • --certificates: ARN of SSL certificate from AWS Certificate Manager
  • --ssl-policy: Security policy defining supported SSL protocols and ciphers
SSL Policy Options: ELBSecurityPolicy-TLS-1-2-2017-01 (recommended), ELBSecurityPolicy-TLS-1-2-Ext-2018-06 (extended), ELBSecurityPolicy-FS-2018-06 (forward secrecy).
What this does: Creates a secure HTTPS listener that terminates SSL/TLS encryption at the load balancer level, reducing CPU load on backend instances.

Step 6: Register Targets

STEP 6

Register EC2 Instances with Target Group

aws elbv2 register-targets \
    --target-group-arn arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/MyTargetGroup/50dc6c495c0c9188 \
    --targets Id=i-1234567890abcdef0,Port=80 Id=i-0987654321fedcba0,Port=80
Parameters Explained:
  • --target-group-arn: ARN of the target group to register targets with
  • --targets: List of targets with their IDs and ports
Target Format Options: For IP targets: Id=10.0.1.100,Port=8080. For Lambda: Id=arn:aws:lambda:region:account:function:name.
What this does: Associates specific EC2 instances (or other compute resources) with the target group so they can receive traffic from the load balancer.
Next Step: Monitor target health and configure advanced routing rules if needed.

Step 7: Advanced Configuration

STEP 7

Create Listener Rules for Path-Based Routing

aws elbv2 create-rule \
    --listener-arn arn:aws:elasticloadbalancing:us-west-2:123456789012:listener/app/MyApplicationLoadBalancer/50dc6c495c0c9188/f2f7dc8efc522ab2 \
    --priority 100 \
    --conditions Field=path-pattern,Values="/api/*" \
    --actions Type=forward,TargetGroupArn=arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/APITargetGroup/1234567890123456
Parameters Explained:
  • --listener-arn: ARN of the listener to add the rule to
  • --priority: Rule priority (1-50000, lower number = higher priority)
  • --conditions: Conditions that must be met for rule to apply
  • --actions: Actions to take when conditions are met
Condition Types: path-pattern, host-header, http-header, http-request-method, query-string, source-ip.
What this does: Creates advanced routing rules that direct requests to different target groups based on URL paths, headers, or other criteria. Essential for microservices architectures.

🔧 Configuration Details

Load Balancer Attributes

Configure Load Balancer Attributes

aws elbv2 modify-load-balancer-attributes \
    --load-balancer-arn arn:aws:elasticloadbalancing:us-west-2:123456789012:loadbalancer/app/MyApplicationLoadBalancer/50dc6c495c0c9188 \
    --attributes \
        Key=idle_timeout.timeout_seconds,Value=300 \
        Key=routing.http2.enabled,Value=true \
        Key=access_logs.s3.enabled,Value=true \
        Key=access_logs.s3.bucket,Value=my-elb-access-logs \
        Key=access_logs.s3.prefix,Value=my-app \
        Key=deletion_protection.enabled,Value=true
Key Attributes Explained:
  • idle_timeout.timeout_seconds: Time before idle connections are closed (1-4000 seconds)
  • routing.http2.enabled: Enable HTTP/2 support for better performance
  • access_logs.s3.enabled: Enable detailed access logging to S3
  • deletion_protection.enabled: Prevent accidental deletion of load balancer
Other Useful Attributes: routing.http.desync_mitigation_mode, routing.http.drop_invalid_header_fields.enabled, load_balancing.cross_zone.enabled.
What this does: Fine-tunes load balancer behavior for performance, security, and operational requirements. Access logs are crucial for troubleshooting and compliance.

Target Group Attributes

Configure Target Group Attributes

aws elbv2 modify-target-group-attributes \
    --target-group-arn arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/MyTargetGroup/50dc6c495c0c9188 \
    --attributes \
        Key=deregistration_delay.timeout_seconds,Value=30 \
        Key=stickiness.enabled,Value=true \
        Key=stickiness.type,Value=lb_cookie \
        Key=stickiness.lb_cookie.duration_seconds,Value=86400 \
        Key=load_balancing.algorithm.type,Value=round_robin \
        Key=target_group_health.dns_failover.minimum_healthy_targets.count,Value=1
Key Attributes Explained:
  • deregistration_delay.timeout_seconds: Time to wait before deregistering targets (0-3600 seconds)
  • stickiness.enabled: Enable session stickiness (requests from same client go to same target)
  • stickiness.type: Type of stickiness (lb_cookie for ALB, source_ip for NLB)
  • load_balancing.algorithm.type: Algorithm for distributing requests (round_robin, least_outstanding_requests)
Load Balancing Algorithms: round_robin (default), least_outstanding_requests (better for long-running requests).
What this does: Optimizes traffic distribution and connection handling. Stickiness is important for applications that maintain server-side session state.

📊 Monitoring & Health Checks

graph TD A[Load Balancer] --> B[Health Check Process] B --> C{Target Health Status} C -->|Healthy| D[Route Traffic] C -->|Unhealthy| E[Stop Routing Traffic] C -->|Initial| F[Initial Health Check] G[CloudWatch Metrics] --> H[Request Count] G --> I[Response Time] G --> J[Error Rate] G --> K[Target Health] L[CloudWatch Alarms] --> M[High Latency Alert] L --> N[High Error Rate Alert] L --> O[Unhealthy Target Alert] P[Access Logs] --> Q[S3 Bucket] Q --> R[Log Analysis] R --> S[Performance Insights] style B fill:#4caf50 style G fill:#2196f3 style L fill:#ff9800 style P fill:#9c27b0
ELB Monitoring Ecosystem: This diagram shows the comprehensive monitoring capabilities of ELB. Health checks continuously verify target availability. CloudWatch provides real-time metrics and alerting. Access logs in S3 enable detailed analysis of traffic patterns and performance troubleshooting.

Health Check Configuration

Configure Advanced Health Checks

aws elbv2 modify-target-group \
    --target-group-arn arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/MyTargetGroup/50dc6c495c0c9188 \
    --health-check-protocol HTTP \
    --health-check-port 80 \
    --health-check-path "/health" \
    --health-check-interval-seconds 15 \
    --health-check-timeout-seconds 10 \
    --healthy-threshold-count 2 \
    --unhealthy-threshold-count 3 \
    --matcher HttpCode=200,204
Health Check Parameters:
  • --health-check-interval-seconds: Frequency of health checks (15-300 seconds)
  • --health-check-timeout-seconds: Time to wait for response (2-120 seconds)
  • --healthy-threshold-count: Consecutive successful checks to mark healthy (2-10)
  • --unhealthy-threshold-count: Consecutive failed checks to mark unhealthy (2-10)
  • --matcher: HTTP response codes considered successful
Best Practices: Use dedicated health check endpoints that verify critical dependencies. Keep health check intervals short for faster failure detection.
What this does: Ensures only healthy targets receive traffic by continuously monitoring target availability and responsiveness.
💡 Pro Tips for ELB Success:
⚠️ Important Considerations:

Command Execution Order Summary

graph TD A[1. VPC Creation] --> B[2. Subnet Creation] B --> C[3. Internet Gateway] C --> D[4. Route Tables] D --> E[5. Security Groups] E --> F[6. EC2 Instances] F --> G[7. Target Group] G --> H[8. Load Balancer] H --> I[9. Listeners] I --> J[10. Register Targets] J --> K[11. Health Checks] K --> L[12. SSL Certificates] L --> M[13. Monitoring Setup] style A fill:#ffebee style B fill:#f3e5f5 style C fill:#e8f5e8 style D fill:#e1f5fe style E fill:#fff3e0 style F fill:#fce4ec style G fill:#f1f8e9 style H fill:#e0f2f1 style I fill:#e8eaf6 style J fill:#fff8e1 style K fill:#fafafa style L fill:#e3f2fd style M fill:#f9fbe7
Command Execution Sequence: This flowchart shows the mandatory order for executing AWS CLI commands when setting up ELB infrastructure. Each step depends on resources created in previous steps, forming a dependency chain from basic networking (VPC) to advanced features (monitoring and SSL).