devHọc Dev

Week 1 - Day 3: EBS, Elastic Load Balancing, Auto Scaling and Lambda Basics

Week 1 – Day 3

This lesson combines 4 topics: EC2 Storage and EBS, Elastic Load Balancing (ELB), Auto Scaling, AWS Lambda Basics.

Learning Objectives

  • Understand the storage types for EC2: EBS, Instance Store, EFS
  • Distinguish the 6 EBS volume types and their use cases
  • Master snapshots, encryption, multi-attach
  • Know when to use Instance Store vs EBS
  • Distinguish the 4 ELB types: ALB, NLB, GLB, CLB
  • Understand listeners, target groups, health checks
  • Master sticky sessions, SSL termination, cross-zone load balancing
  • Know when to choose ALB vs NLB
  • Understand the Auto Scaling Group (ASG): launch template, min/max/desired
  • Distinguish the 4 scaling policies
  • Master integrating an ASG with ELB and CloudWatch
  • Know about lifecycle hooks and instance refresh
  • Understand a Lambda function: runtime, handler, IAM role
  • Master the types of triggers (event sources)
  • Distinguish synchronous vs asynchronous invocation
  • Understand cold start, provisioned concurrency, container image

Part 1: EC2 Storage and EBS

1. Storage Options for EC2

┌────────────────────────────────────────────────────────────┐│EC2StorageOptions│├────────────────────────────────────────────────────────────┤│││EBS(ElasticBlockStore)││├──Network-attachedblockstorage││├──Persistent(outlivestheEC2instance)││├──1EBS=1AZ││└──1EBSattachesto1EC2(exceptio1/io2Multi-Attach)││││InstanceStore(NVMeSSD)││├──Physicalstoragetiedtothehost││├──EPHEMERAL—lostonstop/terminate││├──Highestperformance(sub-mslatency)││└──Free(includedintheinstanceprice)││││EFS(ElasticFileSystem)—Networkfilesystem││├──NFSv4,sharedacrossmultipleEC2││├──Multi-AZ││└──Scalesautomatically(noprovisioning)││││FSx(ManagedFS:Windows,Lustre,NetApp,OpenZFS)││││S3(Objectstorage)││└──Notblockstorage,accessedviaAPI/HTTP│└────────────────────────────────────────────────────────────┘

2. EBS Overview

Characteristics

  • Block-level storage, attached to EC2 like an external drive
  • Network-attached (over the AWS internal network)
  • Persistent: outlives the EC2 instance, can be detached/attached
  • AZ-bound: an EBS volume exists in exactly 1 AZ
  • 1:1 attachment: 1 volume → 1 EC2 (except Multi-Attach io1/io2)
  • Supports resize, snapshot, encryption

EBS Lifecycle

Createvolume→AttachtoEC2→Use(mount)→Detach→Re-attach(sameAZ)→Delete│└─→SnapshottoS3(cross-AZ,cross-Region)

3. EBS Volume Types (6 main types)

SSD-based (for transactional workloads, boot volumes)

TypeUse caseSizeIOPS maxThroughput max
gp3General purpose (new default)1 GB - 64 TB80,000 (independent)2,000 MB/s (independent)
gp2General purpose (old)1 GB - 16 TB100-16,000 (tied to size)250 MB/s
io2 Block ExpressHighest performance4 GB - 64 TB256,0004,000 MB/s
io1Legacy high-IOPS4 GB - 16 TB64,0001,000 MB/s

Note on numbers: gp3 used to be capped at 16,000 IOPS / 1,000 MB/s / 16 TB — the exam may still use the old numbers. AWS docs now list only io2 Block Express for io2 (256,000 IOPS requires a Nitro instance; other instances are limited to 64,000 provisioned IOPS).

HDD-based (for throughput, cannot be a boot volume)

TypeUse caseSizeIOPS maxThroughput max
st1Throughput-optimized (big data, log)125 GB - 16 TB500500 MB/s
sc1Cold storage (infrequent access)125 GB - 16 TB250250 MB/s

gp2 vs gp3 (important for the exam)

gp2gp3
IOPS3 IOPS/GB (min 100, max 16,000) — tied to size; volumes < 1,000 GB burst to 3,0003,000 baseline (provision up to 80,000 independently of size; old limit 16,000)
Throughput128-250 MB/s (depends on size)125 MB/s baseline, provision up to 2,000 MB/s (old limit 1,000 MB/s)
Price~20% more expensive than gp3Cheaper
RecommendationLegacyNew default — choose gp3

io1/io2 Multi-Attach

  • Allows 1 volume to attach to up to 16 EC2 instances in the same AZ
  • Use case: Cluster file system (only with a cluster-aware FS such as GFS2)
  • Do NOT use with ext4, XFS (not cluster-aware)

4. EBS Volume Selection Decision Tree

Workload?├──Bootvolume?│└──gp3(default,cheaperthangp2)│├──Transactionaldatabase(Oracle,SQLServer)?│├──≤80,000IOPS→gp3(olderexams:16,000threshold)│└──>80,000IOPS,sub-mslatency,99.999%durability→io2BlockExpress│├──Mission-criticalwithSLA?│└──io2BlockExpress(99.999%durability)│├──Bigdata,logprocessing(sequentialthroughput)?│└──st1(HDD,cheapthroughput)│├──ColdarchiveonEC2?│└──sc1│└──Sharedblockstorage(cluster)?└──io1/io2Multi-Attach

5. EBS Snapshots

Definition

Snapshot = a point-in-time backup of an EBS volume, stored in S3 (managed by AWS, the bucket is not exposed).

Characteristics

  • Incremental: later snapshots store only changed blocks
  • Stored cross-AZ within the same Region (a snapshot survives an AZ failure)
  • Copy cross-Region for DR
  • Share cross-account (an encrypted snapshot requires sharing the KMS key)
  • Restore a volume from a snapshot into any AZ in the Region

Snapshot lifecycle with DLM (Data Lifecycle Manager)

  • Automatically creates snapshots on a schedule
  • Automatic retention (keep the N most recent snapshots)
  • Tag-based: snapshots resources with specific tags

EBS Snapshot Archive (2021+)

  • A cheaper tier for long-term snapshots (75% cheaper than standard)
  • Minimum retention 90 days
  • Restoring from archive takes 24-72 hours
  • Use case: Compliance, archive

Recycle Bin for EBS Snapshots

  • "Undo delete" for snapshots
  • Set retention of 1-365 days
  • Protects against accidental/malicious deletion

6. EBS Encryption

Characteristics

  • Encryption at-rest and in-transit between EC2 ↔ EBS
  • Uses KMS (Customer Managed Key or AWS managed)
  • Create an encrypted volume: enable it in the console or as the default for the region

How to encrypt an unencrypted volume

  1. Create a snapshot of the volume
  2. Copy the snapshot with the option Encrypted=true (choose a KMS key)
  3. Create a new volume from the encrypted snapshot
  4. Detach the old volume, attach the new one

EBS Encryption by Default

  • A region-level setting: all new EBS volumes will be encrypted
  • Recommended to enable from the start for new accounts

7. EBS Performance

Burst (gp2)

  • gp2 accumulates I/O credits while idle
  • Bursts up to 3,000 IOPS when needed
  • Out of credits → drops back to baseline

gp3 / io2 — no burst, baseline always guaranteed

EBS-Optimized Instance

  • Most new instances (m5, c5, r5...) are EBS-optimized by default
  • Dedicated bandwidth between EC2 ↔ EBS, not shared with other network traffic

8. Instance Store

Definition

Instance Store is physical storage (NVMe SSD) attached to the physical host of the EC2 instance.

Characteristics

  • Ephemeral: data is LOST when:
    • The instance stops (starting again moves it to another host)
    • The instance terminates
    • Hardware failure
  • PERSISTENT across reboot (same host)
  • Extremely high performance: sub-ms latency, millions of IOPS
  • Free: included in the instance price
  • Cannot be snapshotted

Use case

  • Cache (Redis, Memcached) — data can be rebuilt
  • Temporary storage (scratch space)
  • Buffer for HPC workloads
  • NoSQL with replication (Cassandra, clustered NoSQL)

Instance Store-supported families

  • I-family (i3, i4i): storage optimized with large NVMe SSDs
  • D-family (d2, d3): HDD instance store
  • Some general purpose: m5d, m5ad, c5d, r5d

9. EFS Brief (details in Week 1 Day 5, Part 2)

Definition

EFS (Elastic File System) = a managed NFSv4 file system, shared among multiple EC2 instances and across AZs.

Quick comparison of EBS vs EFS vs Instance Store

EBSEFSInstance Store
TypeBlockFile (NFS)Block
Shared1:1 (Multi-Attach: 16)Many EC21:1
Multi-AZNo (per AZ)YesNo
PersistenceYesYesNo (ephemeral)
Performancegp3: 80k IOPSMulti-GB/sMillions of IOPS
Use caseDB, boot volumeShared file storageCache, scratch

10. EBS Multi-Attach (io1/io2 only)

Definition

1 io1/io2 volume attaches to up to 16 EC2 instances in the same AZ, letting you build shared block storage.

Requirements

  • io1 or io2 volume
  • Same Availability Zone
  • Same VPC (Nitro-based instances)
  • The filesystem must be cluster-aware (GFS2, OCFS2) — do NOT use ext4/XFS

Use case

  • Cluster databases with shared storage
  • Active-active HA applications
  • Rarely used — usually replaced by EFS or database replication

Part 2: Elastic Load Balancing (ELB)

1. ELB Overview

ELB (Elastic Load Balancer) is a managed service that distributes traffic to multiple targets (EC2, IP, Lambda, container).

Why use ELB

  • High availability: spread traffic across AZs
  • Health check: automatically removes unhealthy instances
  • SSL termination: offloads SSL from the backend
  • Scalability: scales automatically with traffic
  • Single endpoint: clients only call the LB's single DNS name

2. 4 types of ELB

TypeLayerProtocolUse case
Application Load Balancer (ALB)7HTTP, HTTPS, gRPC, WebSocketMicroservices, container, path-based routing
Network Load Balancer (NLB)4TCP, UDP, TLSHigh performance, static IP, < 1ms latency
Gateway Load Balancer (GLB)3 (gateway)IP packetsThird-party virtual appliances (firewall, IDS)
Classic Load Balancer (CLB)4 & 7HTTP, HTTPS, TCP, SSLLegacy — do not use for new designs

CLB is deprecated for EC2-Classic; it still exists for VPC, but AWS recommends ALB/NLB.

3. Application Load Balancer (ALB)

Characteristics

  • Layer 7 (HTTP/HTTPS)
  • Routes by:
    • Host header (api.example.com vs www.example.com)
    • Path (/api/* vs /static/*)
    • HTTP method (GET, POST)
    • Query string (?version=v2)
    • Source IP
    • HTTP header
  • Supports WebSocket, HTTP/2, gRPC
  • SSL termination + SNI multi-domain
  • The DNS name's IPs change over time (NO static IP)

Targets

  • EC2 instances
  • IP addresses (on-prem, VPC)
  • Lambda functions (ALB invokes Lambda as an HTTP backend)
  • Containers (ECS, EKS)

Sticky Sessions (Session Affinity)

  • Application-based cookie (generated by the app) or load balancer cookie (AWSALB)
  • Ensures a user's requests go to the same target during the session
  • Duration: configurable (1 second - 7 days)

Health Check

  • HTTP/HTTPS probe
  • Customize: path, port, interval, threshold
  • ALB only routes traffic to healthy targets

4. Network Load Balancer (NLB)

Characteristics

  • Layer 4 (TCP, UDP, TLS)
  • Extremely high performance: millions of requests/second, latency < 1ms
  • Static IP per AZ (or Elastic IP)
  • Source IP preservation: the backend sees the client's real IP (not the NLB's IP)
  • By default no Security Group (since 2023 an NLB can have an SG)
  • Supports PrivateLink (NLB is the backend for a VPC Endpoint Service)

Use cases

  • Gaming servers (UDP)
  • IoT (many connections)
  • Streaming media
  • Trading platforms (low latency)
  • Need a static IP for whitelisting

Sticky Sessions

  • Source IP affinity (hash source IP → same target)
  • Per-flow stickiness, no cookie

SSL/TLS Termination

  • NLB can terminate TLS (TLS listener)
  • Or TCP pass-through (the backend handles TLS itself)

5. Gateway Load Balancer (GWLB)

Definition

GWLB distributes traffic to third-party virtual appliances (firewall, IDS/IPS, packet inspection) at Layer 3.

Workflow

Internet─►IGW─►GWLB─►Firewallappliances─►Application│└─UsestheGENEVEprotocol(port6081)

Characteristics

  • Supports Palo Alto, Fortinet, Check Point... appliances on AWS Marketplace
  • Single entry point for all traffic inspection
  • Scales horizontally with multiple appliances

Use case

  • Centralized security inspection
  • DPI (deep packet inspection)
  • Compliance traffic logging

6. Listener and Target Group

Listener

  • Listens on a specific port/protocol
  • 1 LB can have multiple listeners (HTTP:80, HTTPS:443)
  • Forwards traffic to a target group based on rules

Target Group

  • A set of targets (EC2/IP/Lambda) of the same kind
  • Has its own health check
  • 1 target group can be used by multiple LBs
  • 1 LB listener forwards to 1 or more target groups (weighted)

Architecture

┌──Listener:80(HTTP)─►TargetGroup"web"│├──EC2-1ALB───────────────┤├──EC2-2│└──EC2-3│└──Listener:443(HTTPS)─┬─►TG"api"(path/api/*)│├──ECSTask1│└──ECSTask2│└─►TG"static"(path/static/*)└──S3?No—useCloudFront

7. ALB Routing Rules

Listener Rules

Each listener has a priority list of rules:

PriorityConditionAction──────────────────────────────────────────────────────────────1Path=/api/v2/*ForwardtoTG"api-v2"2Host=admin.example.comForwardtoTG"admin"3HTTPMethod=POSTForwardtoTG"writes"4Querystring=version=betaForwardtoTG"beta"Default(catch-all)ForwardtoTG"main"

Advanced Actions

  • Forward to target group(s)
  • Redirect (HTTP → HTTPS)
  • Fixed response (return a static 503, 404...)
  • Authenticate with Cognito or OIDC

8. SSL/TLS with ELB

ALB

  • Terminates TLS, decrypts, routes HTTP to the backend
  • SNI (Server Name Indication): multiple SSL certs on the same listener for multi-domain
  • Certs from AWS Certificate Manager (ACM) — free for ALB/NLB/CloudFront

NLB

  • TLS termination with a TLS listener
  • Or TCP pass-through (the backend decrypts itself)
  • Supports TLS 1.3

Security Policy

  • Predefined cipher suite policies: ELBSecurityPolicy-TLS13-1-2-2021-06
  • Compliance: FIPS-140-2 policies are available

9. Cross-Zone Load Balancing

Definition

Cross-zone = the LB distributes traffic evenly across all targets across AZs instead of only within the AZ of the LB node.

Example

SCENARIO:2AZs,AZ-ahas1target,AZ-bhas4targetsTotal:5targetsWITHOUTcross-zone(NLBdefault):├──50%oftraffictoAZ-a→1targetreceives50%└──50%oftraffictoAZ-b→4targetssplitevenly,12.5%each→Unbalanced!WITHcross-zone(ALBdefault):└──All5targetsreceive20%oftrafficeach→Balanced!

Default behavior

LB typeDefaultCost cross-AZ
ALBEnabled, free (no charge for cross-AZ data)Free
NLBDisabled by default (can be enabled, cross-AZ data is charged)Cost
GWLBDisabled by defaultCost
CLBDisabled (enabling is free)Free

10. Health Check

Configuration

  • Protocol: HTTP, HTTPS, TCP
  • Port: target port or traffic port
  • Path (HTTP): /health, /healthz
  • Interval: 5-300s (default 30s)
  • Timeout: 2-120s (default 5s)
  • Healthy threshold: number of consecutive passes → healthy (default 5)
  • Unhealthy threshold: number of consecutive failures → unhealthy (default 2)
  • Matcher: HTTP success code (default 200)

Best practice

  • A dedicated /health endpoint, not / (the homepage may be slow)
  • /health checks dependencies (DB connection, cache)
  • Return 200 when healthy, 503 when draining

Connection Draining (Deregistration Delay)

  • When a target deregisters or becomes unhealthy:
    • The LB stops sending new requests
    • Waits for existing connections to complete (default 300s)
  • Avoids abruptly disconnecting active users

11. ALB vs NLB — When to use which?

RequirementChoose
HTTP routing by path/host/headerALB
WebSocket, HTTP/2, gRPCALB
Lambda backendALB
Cognito/OIDC authenticationALB
TCP/UDP non-HTTP trafficNLB
Static IP for whitelistingNLB
Millions of req/s, sub-ms latencyNLB
Source IP preservationNLB
Private endpoint for a service (PrivateLink)NLB
Inspection firewall appliancesGWLB

Part 3: Auto Scaling

1. Auto Scaling Overview

EC2 Auto Scaling automatically:

  • Adds instances when traffic rises (scale out)
  • Removes instances when traffic drops (scale in)
  • Replaces unhealthy instances (self-healing)
  • Maintains the specified number of instances (desired)

Benefits

  • High availability: automatically replaces failed instances
  • Cost optimization: only runs the number needed
  • Elasticity: handles traffic spikes
  • Fault tolerance: spread across AZs

ASG is FREE — you only pay for the EC2 instances that run.

2. Auto Scaling Group (ASG) Components

┌─────────────────────────────────────┐│AutoScalingGroup││││LaunchTemplate││├──AMI,Instancetype││├──Keypair,Securitygroup││└──Userdata,IAMrole││││Capacity││├──Min:2││├──Desired:4││└──Max:10││││Subnets:subnet-a,subnet-b,...││││ScalingPolicies││├──Targettracking(CPU50%)││└──...││││HealthCheck:EC2+ELB││││TargetGroup:arn:.../tg/...│└─────────────────────────────────────┘

3. Launch Template vs Launch Configuration

Launch TemplateLaunch Configuration
StatusRecommended (modern)Legacy, being phased out
VersioningYes (multiple versions)No
Mixed instance typesSupportedNo
Spot + On-Demand mixSupportedLimited
New EC2 featuresFully supportedNo

AWS stopped allowing new Launch Configurations for new accounts from Dec 2023. Always use a Launch Template.

A Launch Template contains

  • AMI ID
  • Instance type
  • Key pair
  • Security group(s)
  • User data script
  • IAM instance profile
  • Storage (EBS) specs
  • Tags
  • Network interfaces

4. ASG Sizing

MincapacityDesiredcapacityMaxcapacity2◄───►4◄───►10││││││ASGneverASGtriestostayASGnevergoesbelowatthislevel.Scalingexceedspoliciesadjustdesired±

Rules

  • Min ≤ Desired ≤ Max
  • The ASG always tries to reach Desired
  • Scaling policies change Desired (never beyond Min/Max)

5. Scaling Policies (4 types)

  • Set a target value for 1 metric (CPU 50%, ALB request count 1000/target)
  • The ASG automatically calculates how many instances to add/remove
  • Simplest, AWS recommended
Example: Target CPU = 50%
- Current CPU = 70% → Scale out (add instances)
- Current CPU = 30% → Scale in (remove instances)

5.2 Step Scaling

  • Define step adjustments based on a CloudWatch Alarm
  • How much to scale depends on severity
Example:
CPU > 60% (1 alarm)   → +1 instance
CPU > 80% (2 alarm)   → +3 instances
CPU > 95% (3 alarm)   → +5 instances

5.3 Simple Scaling (Legacy)

  • 1 alarm → 1 action (add/remove a fixed number)
  • Cooldown period between scaling actions
  • Replaced by Step Scaling for most use cases

5.4 Scheduled Scaling

  • Scale on a schedule (cron, date)
  • Use case: predictable traffic (business hours, end-of-month)
Example:
Mon-Fri 8:00 AM  → Desired = 10 (business hours)
Mon-Fri 6:00 PM  → Desired = 3  (evening)
Sat-Sun all day  → Desired = 2  (weekend)

5.5 Predictive Scaling (Bonus)

  • ML analyzes the past 14 days of traffic and forecasts the next 48 hours
  • Automatically scales before traffic rises (proactive)
  • Use case: Daily/weekly traffic patterns

Summary

PolicyTriggerUse case
Target TrackingMetric valueDefault, simple
Step ScalingCloudWatch Alarm severityGranular control
Simple ScalingCloudWatch AlarmLegacy
ScheduledTime-basedPredictable patterns
PredictiveML forecastDaily/weekly patterns

6. Cooldown Period

Definition

Cooldown = the waiting time after a scaling action before the next action is allowed (default 300 seconds).

Why

  • Avoids "thrashing" (continuously scaling in/out)
  • Gives new instances enough time to boot and start processing

Note

  • Target Tracking does not use cooldown (it uses warm-up time instead)
  • Step Scaling has an "estimated instance warmup" period

7. Health Check

2 types

  • EC2 health check (default): checks EC2 status (running, hardware OK)
  • ELB health check: the ASG looks at target group health (must be enabled)

Health check grace period

  • Time after launch before health is checked (default 300s)
  • Gives the instance time to boot and initialize the app
  • Critical: apps needing a long warm-up (Java JVM) → increase the grace period

When an instance fails

  1. The ASG marks the instance as Unhealthy
  2. The ASG terminates that instance
  3. The ASG launches a new instance as a replacement (to maintain Desired)

8. Lifecycle Hooks

Definition

Lifecycle hooks allow custom actions when an instance is launching or terminating.

2 events

  • EC2_INSTANCE_LAUNCHING: run a script before the instance enters InService
  • EC2_INSTANCE_TERMINATING: run a script before termination

Workflow

Launching:
[Launching] → [Pending:Wait] → run hook → [Pending:Proceed] → [InService]

Terminating:
[InService] → [Terminating:Wait] → run hook → [Terminating:Proceed] → [Terminated]

Use cases

  • Pull configuration / secrets before serving traffic
  • Register the instance with an external system
  • Drain connections / flush logs before termination
  • Final backup of data from ephemeral storage

9. Instance Refresh

Definition

Instance Refresh = update the instances in an ASG to a new launch template version (rolling deployment).

Strategy

  • Min healthy percentage (default 90%): always keep this % of instances healthy
  • The ASG terminates a batch, launches new ones, waits for healthy, repeats
  • Optional: Checkpoints to pause between batches

Use case

  • Deploy a new AMI (security patch)
  • Update User Data
  • Change the instance type

Alternative: Blue/Green with 2 ASGs + ALB target group weights

10. Termination Policy

When the ASG needs to scale in (terminate), it chooses the instance according to the policy:

Default termination policy

  1. AllocationStrategy (for mixed instance types)
  2. OldestLaunchTemplate (terminate the old launch template)
  3. OldestLaunchConfiguration (legacy)
  4. ClosestToNextInstanceHour (for the instance closest to its next billing hour)
  5. OldestInstance or NewestInstance
  6. Random

Custom policies

  • Default
  • OldestInstance / NewestInstance
  • OldestLaunchConfiguration / OldestLaunchTemplate
  • ClosestToNextInstanceHour
  • AllocationStrategy

Instance Scale-In Protection

  • Mark specific instances with "scale-in protection" → the ASG will not terminate them
  • Use case: an instance processing a long-running job

11. ASG with Mixed Instance Types & Spot

Mixed Instance Policy

  • 1 ASG can launch several different instance types
  • Mix On-Demand + Spot

Spot Allocation Strategy

  • price-capacity-optimized (AWS recommended): balances price + capacity
  • capacity-optimized: the pool least likely to be reclaimed (when interruptions are costly)
  • lowest-price: the cheapest pool (high interruption risk)
  • diversified: spread across many pools

Example

ASG:├──2On-Demand(baseline)├──8Spot(variable,capacity-optimizedstrategy)└──5instancetypes:m5.large,m5a.large,m5n.large,m4.large,m6i.large

12. ASG integration with ELB

Workflow

1.ALBreceivesarequest│▼2.ALBforwardstotheTargetGroup│▼3.TargetGrouptargets=instancesintheASG│▼4.ASGscalesout→launchesanewinstance→automaticallyregistersitintheTargetGroup│▼5.ALBhealthcheck→ifitpasses,routetraffic

Important configuration

  • Attach the ASG to 1 or more target groups
  • Enable the ELB health check in the ASG (instead of only the EC2 health check)
  • A warm-up period long enough for the app to start before the health check

Part 4: AWS Lambda Basics

1. Lambda Overview

AWS Lambda = a serverless compute service. Run code without managing servers.

Characteristics

  • Event-driven: runs when an event triggers it
  • Pay per execution: billed by number of invocations + duration + memory
  • Auto-scaling: scales from 0 to thousands of concurrent executions
  • No infrastructure management: AWS takes care of everything
  • 15 minutes timeout max per execution

Use case

  • API backend (via API Gateway)
  • File processing (S3 trigger)
  • Stream processing (Kinesis, DynamoDB Streams)
  • Scheduled tasks (EventBridge cron)
  • IoT data processing
  • Real-time data transformation

When NOT to use Lambda

  • Long-running tasks (> 15 min) → ECS, EC2, Batch
  • Stateful applications → EC2
  • Heavy compute / GPU → EC2 GPU, SageMaker
  • Predictable steady traffic 24/7 → EC2 RIs may be cheaper

2. Lambda Function Components

┌─────────────────────────────────────────────────────┐│LambdaFunction│├─────────────────────────────────────────────────────┤│││Runtime:Python3.12,Node.js22,...││Handler:index.handler││Memory:128MB-10,240MB││Timeout:1s-900s(15min)││Code:.zip(50MBdirect,250MBS3)││orcontainerimage(10GB)││Environmentvars:Key-valuepairs││IAMRole:Executionrole││VPCconfig:Optional(subnet+SG)││Layers:Shareddependencies│││└─────────────────────────────────────────────────────┘

Runtimes (11/2026)

  • Node.js 22, 24
  • Python 3.11, 3.12, 3.13, 3.14
  • Java 8, 11, 17, 21, 25
  • Go (OS-only runtime provided.al2023; the go1.x runtime is deprecated)
  • .NET 10
  • Ruby 3.3, 3.4, 4.0
  • Custom Runtime (Bash, Rust, etc. via the Runtime API)
  • Container Image (any runtime, up to 10 GB)

Memory & CPU

  • Memory: 128 MB → 10,240 MB (10 GB), in 1 MB increments
  • CPU scales proportionally with memory (not configured separately)
  • At ~1769 MB memory = 1 full vCPU

3. Triggers (Event Sources)

200+ AWS services can trigger Lambda. Common ones:

ServiceUse case
API GatewayHTTP/REST API backend
ALBHTTP backend (alternative to API GW)
S3File upload → process (thumbnail, virus scan)
DynamoDB StreamsReact to data change
Kinesis Data StreamsReal-time stream processing
SQSProcess queue messages
SNSProcess pub/sub messages
EventBridgeCron schedule, custom events
CognitoUser pool triggers (pre-signup, post-confirmation)
CloudFront Lambda@EdgeModify request/response at edge
IoT CoreIoT messages

4. Invocation Models

4.1 Synchronous (Sync)

  • The caller waits for the response
  • Errors are returned immediately to the caller (the caller must retry)
Examples:
- API Gateway → Lambda
- ALB → Lambda
- AWS CLI invoke
- Cognito triggers
- Lambda function URL
- Lex, Step Functions

4.2 Asynchronous (Async)

  • The caller fires and forgets
  • Lambda queues the event internally
  • Lambda retries automatically: 2 retries (3 total attempts)
  • Failed events → Dead Letter Queue (DLQ) (SQS/SNS) or an on-failure destination
Examples:
- S3 events
- SNS notifications
- EventBridge events
- CodeCommit, CodePipeline
- CloudWatch Logs subscription

4.3 Event Source Mapping (Polling)

  • Lambda polls from a stream/queue
  • Batch processing
  • Internal Lambda machinery, no code needed
Examples:
- Kinesis Data Streams
- DynamoDB Streams
- SQS (standard and FIFO)
- Amazon MQ
- Self-managed Kafka, MSK

5. Pricing

Billed on 2 components

1. Request count
  • $0.20 per 1M requests
  • Free tier: 1M requests/month forever free
2. Duration
  • Billed in GB-seconds (memory × duration)
  • $0.0000166667 per GB-second
  • Free tier: 400,000 GB-seconds/month (forever free)

Example

  • A 512 MB function running 1 second, 1M times/month
  • = 1M × (512/1024) × 1 = 500,000 GB-seconds
  • Since 400,000 are free, billable = 100,000 GB-seconds = ~$1.67
  • Request cost: 1M requests fall within the free tier = $0 ($0.20 per 1M beyond it)
  • Total ~$1.67/month (without the free tier: ~$8.33 + $0.20 = ~$8.53)

The Lambda free tier is very generous — most side projects run for free.

6. Cold Start vs Warm Start

Cold Start

  • A new Lambda runtime is initialized
  • Download code, init runtime, run init code
  • Lag: 100ms - 5s (Java/.NET slower than Node/Python)
  • Happens on: first invoke, after 5-15 minutes idle, scale up

Warm Start

  • Reuses an existing container
  • Very low latency (< 10ms typically)

How to reduce Cold Start

Provisioned Concurrency
  • Pre-warm N executions, always ready
  • Eliminates cold start for the first N concurrent invocations
  • Extra charge in $/GB-hour for provisioned capacity
Lambda SnapStart (Java)
  • Snapshot of a pre-initialized Lambda execution environment
  • Cold start drops from ~3s to ~200ms for Java
  • Free (no extra cost)
Best practices
  • Init outside the handler (DB connection, SDK clients)
  • Minimize package size
  • Avoid VPC if not needed (VPC + ENI adds cold start)
  • Use Node.js / Python (smaller cold start than Java)

7. Concurrency

Reserved Concurrency

  • Sets a limit for a function
  • Lambda never exceeds this limit
  • 2 purposes:
    • Cap: a "hungry" function does not affect other functions (the account limit is shared)
    • Throttle protection: protects downstream (the DB is not overloaded)

Provisioned Concurrency

  • Pre-warmed executions
  • No cold start
  • Can be combined with Reserved Concurrency

Account-level Concurrency Limit

  • Default 1,000 concurrent executions per account per region
  • Can request an increase via Service Quotas

Scaling Rate (new model since 12/2023)

  • Each function scales by 1,000 concurrent executions every 10 seconds, until it reaches the account concurrency limit
  • Applies per function (no burst pool shared among functions in the account)
  • Note for exam takers: before 12/2023 Lambda used the old model "burst 500-3000 depending on region, then +500/minute" — older materials/exams may still mention these numbers

8. Layers

Definition

Layer = a package containing shared code/libraries used by multiple functions.

Use cases

  • Shared SDK (custom boto3 version)
  • Common utilities
  • Native binaries (FFmpeg, ImageMagick)
  • Custom runtime (run Rust, Bash...)

Limits

  • 5 layers per function
  • Total unzipped size (function + layers): 250 MB

Workflow

# Create the layer
zip -r layer.zip python/  # boto3 in python/ folder
aws lambda publish-layer-version \
  --layer-name shared-libs \
  --zip-file fileb://layer.zip \
  --compatible-runtimes python3.12

# Attach layer
aws lambda update-function-configuration \
  --function-name my-function \
  --layers arn:aws:lambda:us-east-1:111111111111:layer:shared-libs:1

9. Container Image Support

Characteristics

  • Package Lambda as a Docker image (up to 10 GB)
  • Push to ECR (Elastic Container Registry)
  • Lambda pulls the image on cold start

Dockerfile Example

FROM public.ecr.aws/lambda/python:3.12
COPY app.py ${LAMBDA_TASK_ROOT}/
COPY requirements.txt .
RUN pip install -r requirements.txt
CMD ["app.handler"]

Use cases

  • Heavy dependencies (ML model, native libraries)
  • CI/CD already used to a Docker workflow
  • Container image > 250 MB

10. Lambda Networking

Default (no VPC)

  • Lambda runs in an AWS-managed VPC
  • Has internet access by default
  • Fast cold start
  • CANNOT access VPC private resources (private RDS, ElastiCache)

VPC Configuration

  • Specify subnet + SG
  • Lambda creates an ENI in the subnet (Hyperplane ENI — shared, fast)
  • Needs a NAT Gateway in the VPC for Lambda to access the internet (because the subnet is private)
  • Slower cold start the first time (much improved since 2019)

VPC best practice

  • Lambda in a private subnet
  • Route 0.0.0.0/0 → NAT Gateway (for internet)
  • Use VPC Endpoints for AWS services (S3, DynamoDB) to avoid data transfer cost

11. Lambda Destinations (Async)

When an async invocation fails (after 2 retries) or succeeds

The event can be sent to a destination:

  • SQS queue
  • SNS topic
  • Another Lambda function
  • EventBridge bus

vs DLQ

  • Destinations support both success + failure, many target types
  • DLQ is failure only, SQS/SNS only
  • AWS recommends Destinations over DLQ

12. Lambda Function URL

Definition

Function URL = a dedicated HTTP(S) endpoint for a Lambda function, no API Gateway needed.

Characteristics

  • Format: https://<url-id>.lambda-url.<region>.on.aws/
  • Auth: NONE (public) or AWS_IAM
  • CORS support built-in
  • No rate limiting, no custom domain

When to use Function URL vs API Gateway?

  • Function URL: Simple, low-cost, few features
  • API Gateway: Need rate limiting, custom domain, complex authorization (Cognito, Lambda authorizer), throttling, caching

Review Questions

  1. When an EC2 instance stops, is the data on the Instance Store still there?

    Show answer

    No. Instance Store is ephemeral storage — data is lost when the instance stops, terminates, or the host hardware fails. On reboot the data remains. Instance Store suits temporary data, buffers, caches, scratch space. Important data must be stored on EBS or S3.

  2. When should you choose gp3 instead of gp2?

    Show answer

    Almost always choose gp3 — gp3 lets you configure IOPS (3,000-80,000) and throughput (125-2,000 MB/s) independently of storage size, while gp2 forces IOPS proportional to size (3 IOPS/GB). gp3 is ~20% cheaper than gp2 for the same size. Only keep gp2 if it is already in use and does not need changing, or if a system is incompatible.

  3. Where are EBS snapshots stored? Cross-AZ or not?

    Show answer

    EBS snapshots are stored in Amazon S3 (AWS-managed, not your bucket). A snapshot is Region-scoped — you can create a volume from it in any AZ in the same Region. To copy to another Region use aws ec2 copy-snapshot. This allows creating a volume in another AZ from a snapshot — important for DR and migration.

  4. What steps are needed to encrypt an unencrypted EBS volume?

    Show answer

    You cannot directly encrypt a volume in use. You must: (1) Create a snapshot of the unencrypted volume, (2) Copy the snapshot with encryption enabled to create an encrypted snapshot, (3) Create a new volume from the encrypted snapshot, (4) Attach the new volume to the instance. Alternatively: enable "EBS encryption by default" for the account/Region — all new volumes/snapshots are automatically encrypted.

  5. Can an io2 Multi-Attach EBS volume be used with ext4?

    Show answer

    No. Multi-Attach lets you attach the same io1/io2 volume to multiple EC2 instances in the same AZ, but requires the application to manage concurrent write access itself. Standard filesystems like ext4 do not support concurrent multi-writers — data corruption will occur. You need a cluster-aware filesystem such as GFS2, OCFS2, or an application that handles coordination itself (such as Oracle RAC).

  6. At which OSI Layer do ALB and NLB operate?

    Show answer

    ALB (Application Load Balancer): Layer 7 (HTTP/HTTPS/WebSocket) — understands content-based routing (path, header, hostname, query string). NLB (Network Load Balancer): Layer 4 (TCP/UDP/TLS) — routing based on IP + port, does not inspect the payload. GLB (Gateway LB) operates at Layer 3/4 for security appliances. CLB (Classic) is legacy, supports basic L4 and L7.

  7. NLB has a static IP, what about ALB?

    Show answer

    NLB provides a static IP per AZ (1 IP/AZ) — the IP does not change even when scaling. ALB has no static IP — only a DNS name (hostname); IPs change when AWS scales the ALB internally. If you need a static IP for an ALB (e.g., firewall whitelist), use AWS Global Accelerator in front of the ALB — Global Accelerator provides static anycast IPs.

  8. How does the default cross-zone load balancing behavior differ between ALB and NLB?

    Show answer

    ALB: cross-zone load balancing is enabled by default at no extra charge. NLB: cross-zone load balancing is disabled by default (only routes within the AZ that receives traffic); enabling it incurs cross-AZ data transfer charges ($0.01/GB). Reason: NLB is usually used for latency-sensitive workloads, and cross-AZ adds latency.

  9. Which ALB target type can be a Lambda function?

    Show answer

    ALB supports 3 target types: IP (IP addresses), Instance (EC2 instance IDs), and Lambda (Lambda function ARN). With the Lambda target type, the ALB invokes Lambda synchronously with an event containing the HTTP request details. No API Gateway is needed — the ALB can be the HTTP frontend directly for Lambda, cheaper than API Gateway for high-volume traffic.

  10. When you need WebSocket support, which LB do you choose?

Show answer

ALB supports WebSocket (and HTTP/2). The ALB maintains the long-lived connections WebSocket needs. NLB also supports WebSocket because it operates at Layer 4 (TCP) — but without sticky sessions or content-based routing. Usually choose ALB for WebSocket apps that need routing intelligence; NLB for high-performance TCP WebSocket connections.

  1. What are the advantages of a Launch Template over a Launch Configuration?
Show answer

Launch Template supports: versioning (create multiple versions, rollback), multiple instance types in one ASG (mixed instances), Spot + On-Demand combination, T2/T3 unlimited CPU credits, and newer EC2 features. Launch Configuration is legacy — AWS recommends migrating to Launch Template (announced in 2022) and new accounts since Dec 2023 can no longer create Launch Configurations; it has no versioning and only one instance type. Always use a Launch Template for new ASGs.

  1. Can an ASG spread instances across multiple AZs in the same Region?
Show answer

Yes. An ASG is configured with a list of subnets — each subnet belongs to one AZ. The ASG automatically balances instances across AZs (rebalancing). When an AZ becomes unhealthy or a scale event occurs, the ASG prefers launching in the AZ with the fewest instances. This is how you achieve HA within a Region — always configure an ASG with at least 2-3 AZs.

  1. When do you use Scheduled Scaling instead of Target Tracking?
Show answer

Scheduled Scaling when you know in advance the specific time load increases — e.g., "every Monday at 8 AM scale up for the start of the week, scale down at 6 PM". The load pattern is predictable and on a fixed schedule. Target Tracking for load that rises/falls without a fixed schedule — e.g., CPU rises when traffic arrives and the ASG scales automatically. You can combine them: use Scheduled to pre-warm and Target Tracking to fine-tune in real time.

  1. What is the EC2_INSTANCE_TERMINATING lifecycle hook usually used for?
Show answer

Used for graceful shutdown before the instance is terminated: drain active connections, deregister from service discovery, flush logs to centralized logging, back up in-memory state, send final metrics. The instance stays in the Terminating:Wait state for the configured time (default 1 hour) — during which Lambda/SSM Automation performs cleanup tasks and then signals CONTINUE to proceed with termination.

  1. What is Min Healthy Percentage in Instance Refresh?
Show answer

The minimum percentage of instances that must be healthy throughout the Instance Refresh. Example: an ASG with 10 instances, Min Healthy = 90% → at most 1 instance is replaced at a time (10% = 1 instance). The ASG launches a new instance and waits for it to be healthy before terminating the old one — a rolling update with no downtime. A lower value = faster rolling but riskier; higher = safer but slower.

  1. What is the maximum Lambda timeout?
Show answer

15 minutes (900 seconds). The default timeout is 3 seconds — increase it if the function needs longer. Workloads exceeding 15 minutes need another service: EC2, Fargate, or Step Functions to orchestrate multiple Lambda invocations. Memory range: 128 MB to 10,240 MB (10 GB).

  1. What does Lambda CPU scale with?
Show answer

CPU scales proportionally with memory. You do not configure CPU directly — only memory. At 1,769 MB, the function has 1 full vCPU. At 3,538 MB it has 2 vCPUs, and so on. If a function is CPU-bound and needs to be faster, increase memory (even if you do not need the RAM) to increase CPU allocation — cost goes up but execution time goes down, so the total cost may stay the same or be cheaper.

  1. When an async invoke fails, how many times does Lambda retry?
Show answer

2 retries (3 attempts in total). After the first failure: retry 1 after 1 minute, retry 2 after 2 minutes. After all 3 attempts fail, the event is discarded (or sent to a DLQ/EventBridge if configured). Synchronous invoke: no automatic retry — the caller receives the error and decides whether to retry. SQS trigger: retries according to the SQS visibility timeout and maxReceiveCount.

  1. What problem does Provisioned Concurrency solve?
Show answer

It solves cold start latency. When a Lambda function has no warm instance, the first invocation must initialize the execution environment (download code, init runtime, run init code) — taking 100ms-1s+. Provisioned Concurrency keeps N instances warm and initialized, ready to serve requests immediately. Cost: you are charged for the whole "provisioned" time even without requests — a cost vs latency trade-off.

  1. When should you use a container image instead of a zip for Lambda?
Show answer

Use a container image when: (1) The deployment package is larger than 250 MB (the zip limit) — container images support up to 10 GB, (2) You need a custom runtime, system libraries, or binaries not available in the standard Lambda runtimes, (3) The team is used to a Docker workflow and wants to reuse a Dockerfile, (4) You need to test locally with production-like behavior using the Lambda Runtime Interface Emulator (RIE).

Hands-on Exercises

Part 1: EC2 Storage and EBS

  • Create a 10 GB gp3 EBS volume, attach it to EC2, format and mount it
  • Create a snapshot, then create a new volume from the snapshot in another AZ
  • Enable EBS encryption by default for the region
  • Test Instance Store: launch m5d.large, check /dev/nvme*, write a file, stop+start, verify the data is lost
  • Set up DLM to snapshot daily automatically, keeping 7 snapshots

Part 2: Elastic Load Balancing (ELB)

  • Create an ALB with 2 target groups (web and api), path-based routing
  • Set up a health check endpoint /health returning 200, test with 1 failing instance
  • Enable HTTPS with an ACM certificate, redirect HTTP → HTTPS
  • Create an NLB with a UDP listener (port 53 to simulate DNS)
  • Enable cross-zone load balancing for the NLB, observe the cost change

Part 3: Auto Scaling

  • Create a Launch Template with an Amazon Linux 2023 AMI + User Data installing Apache
  • Create an ASG with min=2, desired=2, max=5, spread across 3 AZs
  • Attach the ASG to the ALB's Target Group
  • Create a Target Tracking policy (CPU 50%)
  • Stress test 1 instance → observe scale out
  • Add a Scheduled Action: scale to 5 instances at 8 AM, scale to 2 at 6 PM

Part 4: AWS Lambda Basics

  • Create a Python "hello world" Lambda function with 256 MB memory
  • Create a trigger from an S3 bucket → Lambda logs the filename when a file is uploaded
  • Set up API Gateway → Lambda (REST API endpoint returning JSON)
  • Enable Provisioned Concurrency = 1, observe cold start before/after
  • Create a Layer containing the requests library, attach it to the function
  • Set up an EventBridge schedule cron(0/5 * * * ? *) → Lambda runs every 5 minutes

References


Next lesson →