Load Balancing & Auto Scaling

Elastic Load Balancing and EC2 Auto Scaling — ALB vs NLB vs Gateway Load Balancer, listeners, target groups and health checks, path and host routing, TLS termination, cross-zone balancing, connection draining, Auto Scaling groups, scaling policies, lifecycle hooks, instance refresh and a highly available web tier.

Intermediate 6 min readLesson 4 of 19 Interview Q&A

A single instance is a single point of failure with a fixed capacity. The classic AWS answer is a load balancer in front of an Auto Scaling group spread across availability zones: traffic is shared, unhealthy instances are replaced automatically, and capacity follows demand. The general theory is in Load balancing; this lesson is how AWS implements it.

The highly available web tier

AZ aAZ bno trafficreplaceUsersApplication Load Balancernodes in every AZEC2healthyEC2healthyEC2healthyEC2unhealthyAuto Scaling groupmin 2 · desired 4 · max 10

Elastic Load Balancing: three kinds

Application LB (ALB)Network LB (NLB)Gateway LB (GWLB)
Layer7 — HTTP/HTTPS, gRPC, WebSocket4 — TCP, UDP, TLS3 — IP packets
RoutingPath, host, header, query, method, source IPPort and protocolTransparent to appliances
Static IPNo (DNS name only)Yes, one per AZ, or Elastic IPs—
Latency / scaleLow; scales automaticallyUltra-low; millions of requests per second—
ExtrasTLS termination, auth (OIDC/Cognito), WAF, redirects, fixed responsesTLS passthrough or termination, preserves client IPInserts firewalls/IDS inline
Typical useWeb apps, APIs, microservicesNon-HTTP protocols, extreme throughput, fixed IPs, PrivateLink servicesThird-party virtual security appliances

The old Classic Load Balancer is legacy — don't start new work on it.

ALB concepts

  1. A listener accepts connections on a port and protocol (HTTPS :443 with a certificate from ACM).
  2. Rules on the listener match conditions — Host: api.example.com, path /images/*, a header — and pick an action.
  3. The action forwards to a target group (or redirects, or returns a fixed response). Weighted forwarding between two target groups enables blue/green and canary releases.
  4. A target group contains targets — instances, IPs (e.g. ECS tasks), or Lambda functions — and defines health checks.
HTTPS :443  (cert *.example.com from ACM)
  ├─ Host api.example.com, path /v2/*   → tg-api-v2    (weight 90)  + tg-api-v3 (weight 10)
  ├─ Host api.example.com               → tg-api-v2
  ├─ path /static/*                     → redirect to CloudFront
  └─ default                            → tg-web
HTTP :80   → redirect 301 to HTTPS

Health checks

The load balancer probes each target (GET /health every 10–30 s); after N failures the target stops receiving traffic, after M successes it returns. Make the health endpoint cheap and honest: it should fail when this instance can't serve, but shouldn't fail because a shared downstream (the database) is slow — otherwise one database blip marks every instance unhealthy and the load balancer has nowhere to send traffic (ALB then "fails open" to all targets).

Other behaviours worth knowing

  • Cross-zone load balancing: spreads requests evenly across all targets in all AZs (on by default for ALB, off by default for NLB).
  • Deregistration delay (connection draining): when a target is removed, in-flight requests get time to finish (default 300 s — often reduce to 30–60 s for faster deploys).
  • Sticky sessions: pin a client to a target with a cookie — works, but stateless servers with sessions in Redis or DynamoDB scale better.
  • Client IP: the ALB terminates connections, so your app sees the ALB's IP; the original is in X-Forwarded-For.
  • TLS: certificates from AWS Certificate Manager are free and auto-renew (HTTPS and TLS).

Auto Scaling groups

An Auto Scaling group (ASG) keeps a fleet of instances from a launch template between a minimum and maximum, aiming for a desired count, spread across the subnets (AZs) you give it.

It does two jobs:

  1. Self-healing: replaces instances that fail EC2 status checks — or ELB health checks, if you enable that (you should).
  2. Scaling: changes the desired count in response to policies.

Scaling policies

PolicyHow it worksUse
Target tracking"Keep average CPU at 50%" or "1,000 requests per target"; AWS computes the adjustmentsThe default choice
Step scalingAdd 2 instances when CPU is above 70%, 4 when above 85%Fine-grained control
ScheduledDesired = 20 every weekday at 09:00Predictable daily or weekly patterns
PredictiveML forecast from history; scales ahead of the curveRecurring traffic patterns with slow boot times

Scale-out should be fast and scale-in conservative: a cooldown or warm-up period stops the group oscillating. Use request count per target or a queue-depth metric when CPU doesn't reflect load — for example, ApproximateNumberOfMessagesVisible per instance for workers reading SQS.

Making scaling fast

  • Bake software into the AMI so new instances boot in seconds, not minutes.
  • Warm pools keep pre-initialised stopped instances ready to start.
  • Lifecycle hooks pause an instance in Pending:Wait or Terminating:Wait — to register with service discovery, warm caches, or ship logs before shutdown.
  • Mixed instances policy: several instance types and a share of Spot capacity in one group (EC2).

Deploying new versions

  • Instance refresh replaces instances gradually with the new launch template version, keeping a minimum healthy percentage, with checkpoints and automatic rollback.
  • Blue/green: a second ASG and target group, then shift ALB weights.
  • Or let CodeDeploy orchestrate in-place or blue/green deployments.

Design checklist

  • At least two AZs, ideally three; size so the remaining AZs can carry the load if one fails.
  • ALB health checks wired into the ASG, with a sensible grace period for boot time.
  • Stateless instances: sessions, uploads and caches live in managed services.
  • Load balancer in public subnets, instances in private subnets, security group on instances that allows traffic only from the ALB's security group (VPC).
  • Alarms on target 5xx rate, latency (p99) and unhealthy host count (CloudWatch).
Interview questions
QWhen would you choose an NLB over an ALB?medium

When you need layer-4 load balancing: non-HTTP protocols (TCP or UDP — databases, MQTT, gaming, custom protocols), static IP addresses that clients or partners can allow-list, preservation of the client's source IP, extreme throughput with very low latency, TLS passthrough to the backends, or exposing a service to other VPCs through PrivateLink. For HTTP applications that benefit from content-based routing, authentication, WAF integration and redirects, an ALB is the better fit.

QHow does an Auto Scaling group make an application highly available?easy

It spreads instances across multiple availability zones, continuously checks their health (EC2 status checks plus load-balancer health checks), and replaces unhealthy instances automatically to maintain the desired capacity. If an AZ fails, it launches replacements in the remaining zones. Combined with a load balancer that stops routing to unhealthy targets, users see little or no impact from individual instance or zone failures.

QYour app scales on CPU but users still see slowness during spikes. What would you look at?hard

CPU may not be the bottleneck — the app may be I/O-bound or waiting on a database, so scale on request count per target or latency instead. Check how long new instances take to become healthy: slow user data scripts or large downloads delay capacity, so bake AMIs, use warm pools, or add predictive or scheduled scaling ahead of known peaks. Make sure the cooldown and warm-up settings aren't blocking further scale-out, the max size isn't capped too low, and downstream dependencies (database connections, rate-limited APIs) can absorb the extra instances.

Key takeaways
  • ALB is layer 7 with content-based routing; NLB is layer 4 with static IPs and extreme throughput; GWLB inserts network appliances.
  • Listeners, rules and target groups route traffic; weighted target groups enable canary and blue/green releases.
  • Health checks should reflect whether this instance can serve, not the health of shared dependencies.
  • Auto Scaling groups self-heal across AZs and scale with target tracking, step, scheduled or predictive policies.
  • Make scaling fast with baked AMIs, warm pools and the right metric; deploy with instance refresh or blue/green.
  • Put load balancers in public subnets and instances in private subnets behind security-group references.