Bài này gộp 4 chủ đề: EC2 Storage và EBS, Elastic Load Balancing (ELB), Auto Scaling, AWS Lambda Basics.
Mục tiêu học tập
- Hiểu các loại storage cho EC2: EBS, Instance Store, EFS
- Phân biệt 6 loại EBS volume types và use case
- Nắm snapshot, encryption, multi-attach
- Biết khi nào dùng Instance Store vs EBS
- Phân biệt 4 loại ELB: ALB, NLB, GLB, CLB
- Hiểu listener, target group, health check
- Nắm sticky session, SSL termination, cross-zone load balancing
- Biết khi nào chọn ALB vs NLB
- Hiểu Auto Scaling Group (ASG): launch template, min/max/desired
- Phân biệt 4 scaling policies
- Nắm cách tích hợp ASG với ELB, CloudWatch
- Biết về lifecycle hooks, instance refresh
- Hiểu Lambda function: runtime, handler, IAM role
- Nắm các loại triggers (event sources)
- Phân biệt synchronous vs asynchronous invocation
- Hiểu cold start, provisioned concurrency, container image
Phần 1: EC2 Storage và EBS
1. Storage Options cho EC2
2. EBS Overview
Đặc điểm
- Block-level storage, attach to EC2 như external drive
- Network-attached (qua AWS internal network)
- Persistent: sống lâu hơn EC2, có thể detach/attach
- AZ-bound: 1 EBS volume tồn tại trong 1 AZ duy nhất
- 1:1 attachment: 1 volume → 1 EC2 (trừ Multi-Attach io1/io2)
- Hỗ trợ resize, snapshot, encryption
EBS Lifecycle
3. EBS Volume Types (6 loại chính)
SSD-based (cho transactional, boot volume)
| Type | Use case | Size | IOPS max | Throughput max |
|---|---|---|---|---|
| gp3 | General purpose (mặc định mới) | 1 GB - 64 TB | 80,000 (independent) | 2,000 MB/s (independent) |
| gp2 | General purpose (cũ) | 1 GB - 16 TB | 100-16,000 (tied to size) | 250 MB/s |
| io2 Block Express | Highest performance | 4 GB - 64 TB | 256,000 | 4,000 MB/s |
| io1 | Legacy high-IOPS | 4 GB - 16 TB | 64,000 | 1,000 MB/s |
Lưu ý số liệu: gp3 trước đây giới hạn 16,000 IOPS / 1,000 MB/s / 16 TB — đề thi có thể còn dùng số cũ. Tài liệu AWS hiện chỉ còn liệt kê io2 Block Express cho io2 (256,000 IOPS cần instance Nitro; instance khác tối đa 64,000 IOPS provisioned).
HDD-based (cho throughput, không dùng boot volume)
| Type | Use case | Size | IOPS max | Throughput max |
|---|---|---|---|---|
| st1 | Throughput-optimized (big data, log) | 125 GB - 16 TB | 500 | 500 MB/s |
| sc1 | Cold storage (infrequent access) | 125 GB - 16 TB | 250 | 250 MB/s |
gp2 vs gp3 (quan trọng cho thi)
| gp2 | gp3 | |
|---|---|---|
| IOPS | 3 IOPS/GB (min 100, max 16,000) — tied to size; volume < 1,000 GB burst tới 3,000 | 3,000 baseline (provision up to 80,000 độc lập với size; số cũ 16,000) |
| Throughput | 128-250 MB/s (theo size) | 125 MB/s baseline, provision up to 2,000 MB/s (số cũ 1,000 MB/s) |
| Giá | Cao hơn gp3 ~20% | Rẻ hơn |
| Khuyến nghị | Legacy | Mặc định mới — chọn gp3 |
io1/io2 Multi-Attach
- Cho phép 1 volume attach vào tối đa 16 EC2 instances trong cùng AZ
- Use case: Cluster file system (chỉ với cluster-aware FS như GFS2)
- KHÔNG dùng cho ext4, XFS (không cluster-aware)
4. EBS Volume Selection Decision Tree
5. EBS Snapshots
Định nghĩa
Snapshot = backup point-in-time của EBS volume, lưu vào S3 (managed bởi AWS, không expose bucket).
Đặc điểm
- Incremental: snapshot sau chỉ lưu block changed
- Lưu cross-AZ trong cùng Region (snapshot survives AZ failure)
- Copy cross-Region để DR
- Share cross-account (encrypted snapshot cần share KMS key)
- Restore volume từ snapshot vào bất kỳ AZ trong Region
Snapshot lifecycle với DLM (Data Lifecycle Manager)
- Tự động tạo snapshot theo lịch
- Tự động retention (giữ N snapshots gần nhất)
- Tag-based: snapshot resources có tag cụ thể
EBS Snapshot Archive (2021+)
- Tier rẻ hơn cho snapshot lưu lâu (75% rẻ hơn standard)
- Minimum retention 90 ngày
- Restore từ archive mất 24-72 hours
- Use case: Compliance, archive
Recycle Bin for EBS Snapshots
- "Undo delete" cho snapshot
- Set retention 1-365 ngày
- Bảo vệ chống xóa nhầm/malicious
6. EBS Encryption
Đặc điểm
- Encryption at-rest và in-transit giữa EC2 ↔ EBS
- Dùng KMS (Customer Managed Key hoặc AWS managed)
- Tạo volume encrypted: enable trong console hoặc default cho region
Cách encrypt unencrypted volume
- Tạo snapshot của volume
- Copy snapshot với option
Encrypted=true(chọn KMS key) - Tạo volume mới từ encrypted snapshot
- Detach old volume, attach new
EBS Encryption by Default
- Setting tại region level: tất cả EBS mới sẽ encrypted
- Khuyến nghị enable ngay từ đầu cho account mới
7. EBS Performance
Burst (gp2)
- gp2 tích lũy I/O credits khi idle
- Burst lên 3,000 IOPS khi cần
- Hết credits → giảm về baseline
gp3 / io2 — không burst, đảm bảo baseline luôn
EBS-Optimized Instance
- Hầu hết instance mới (m5, c5, r5...) đều EBS-optimized by default
- Dedicated bandwidth giữa EC2 ↔ EBS, không bị share với traffic mạng khác
8. Instance Store
Định nghĩa
Instance Store là physical storage (NVMe SSD) gắn liền với physical host của EC2.
Đặc điểm
- Ephemeral: data MẤT khi:
- Instance stop (start lại sang host khác)
- Instance terminate
- Hardware failure
- PERSISTENT qua reboot (cùng host)
- Performance cực cao: sub-ms latency, hàng triệu IOPS
- Free: included trong giá instance
- Không snapshot được
Use case
- Cache (Redis, Memcached) — data có thể rebuild
- Temporary storage (scratch space)
- Buffer cho HPC workload
- NoSQL với replication (Cassandra, NoSQL clustered)
Instance Store-supported families
- I-family (i3, i4i): storage optimized với NVMe SSD lớn
- D-family (d2, d3): HDD instance store
- Một số general purpose: m5d, m5ad, c5d, r5d
9. EFS Brief (chi tiết ở Tuần 1 Ngày 5, Phần 2)
Định nghĩa
EFS (Elastic File System) = managed NFSv4 file system, shared giữa multiple EC2 và across AZs.
So sánh nhanh EBS vs EFS vs Instance Store
| EBS | EFS | Instance Store | |
|---|---|---|---|
| Type | Block | File (NFS) | Block |
| Shared | 1:1 (Multi-Attach: 16) | Many EC2 | 1:1 |
| Multi-AZ | No (per AZ) | Yes | No |
| Persistence | Yes | Yes | No (ephemeral) |
| Performance | gp3: 80k IOPS | Multi-GB/s | Hàng triệu IOPS |
| Use case | DB, boot volume | Shared file storage | Cache, scratch |
10. EBS Multi-Attach (io1/io2 only)
Định nghĩa
1 volume io1/io2 attach vào tối đa 16 EC2 instances trong cùng AZ, giúp build shared block storage.
Điều kiện
- io1 hoặc io2 volume
- Cùng Availability Zone
- Cùng VPC (Nitro-based instances)
- Filesystem phải cluster-aware (GFS2, OCFS2) — KHÔNG dùng ext4/XFS
Use case
- Cluster databases với shared storage
- Active-active HA application
- Hiếm dùng — thường thay bằng EFS hoặc database replication
Phần 2: Elastic Load Balancing (ELB)
1. Tổng quan ELB
ELB (Elastic Load Balancer) là managed service phân phối traffic đến nhiều targets (EC2, IP, Lambda, container).
Lý do dùng ELB
- High availability: spread traffic across AZs
- Health check: tự động loại bỏ unhealthy instance
- SSL termination: offload SSL từ backend
- Scalability: tự động scale theo traffic
- Single endpoint: clients chỉ gọi 1 DNS name của LB
2. 4 loại ELB
| Type | Layer | Protocol | Use case |
|---|---|---|---|
| Application Load Balancer (ALB) | 7 | HTTP, HTTPS, gRPC, WebSocket | Microservices, container, path-based routing |
| Network Load Balancer (NLB) | 4 | TCP, UDP, TLS | High performance, static IP, < 1ms latency |
| Gateway Load Balancer (GLB) | 3 (gateway) | IP packets | Third-party virtual appliances (firewall, IDS) |
| Classic Load Balancer (CLB) | 4 & 7 | HTTP, HTTPS, TCP, SSL | Legacy — không dùng cho thiết kế mới |
CLB đã deprecated cho EC2-Classic, vẫn còn cho VPC nhưng AWS khuyến nghị dùng ALB/NLB.
3. Application Load Balancer (ALB)
Đặc điểm
- Layer 7 (HTTP/HTTPS)
- Route theo:
- 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
- Hỗ trợ WebSocket, HTTP/2, gRPC
- SSL termination + SNI multi-domain
- DNS name thay đổi theo thời gian (KHÔNG dùng static IP)
Targets
- EC2 instances
- IP addresses (on-prem, VPC)
- Lambda functions (ALB invoke Lambda như HTTP backend)
- Containers (ECS, EKS)
Sticky Sessions (Session Affinity)
- Application-based cookie (do app gen) hoặc load balancer-cookie (
AWSALB) - Đảm bảo user request đi về cùng 1 target trong session
- Duration: configurable (1 second - 7 days)
Health Check
- HTTP/HTTPS probe
- Customize: path, port, interval, threshold
- ALB chỉ route traffic đến healthy targets
4. Network Load Balancer (NLB)
Đặc điểm
- Layer 4 (TCP, UDP, TLS)
- Cực kỳ performance: hàng triệu requests/giây, latency < 1ms
- Static IP per AZ (hoặc Elastic IP)
- Source IP preservation: backend thấy IP thật của client (không phải IP của NLB)
- Mặc định không có Security Group (chuyển từ 2023 NLB có thể có SG)
- Hỗ trợ PrivateLink (NLB là backend cho VPC Endpoint Service)
Use cases
- Gaming server (UDP)
- IoT (high connection)
- Streaming media
- Trading platform (low latency)
- Cần static IP cho whitelisting
Sticky Sessions
- Source IP affinity (hash source IP → cùng target)
- Per-flow stickiness, không cookie
SSL/TLS Termination
- NLB có thể terminate TLS (TLS listener)
- Hoặc pass-through TCP (backend tự handle TLS)
5. Gateway Load Balancer (GWLB)
Định nghĩa
GWLB distribute traffic đến third-party virtual appliances (firewall, IDS/IPS, packet inspection) ở Layer 3.
Workflow
Đặc điểm
- Hỗ trợ Palo Alto, Fortinet, Check Point... appliances trên AWS Marketplace
- Single entry point cho all traffic inspection
- Scale horizontal với multiple appliances
Use case
- Centralized security inspection
- DPI (deep packet inspection)
- Compliance traffic logging
6. Listener và Target Group
Listener
- Lắng nghe trên port/protocol cụ thể
- 1 LB có thể có nhiều listeners (HTTP:80, HTTPS:443)
- Forward traffic đến target group dựa trên rules
Target Group
- Tập hợp targets (EC2/IP/Lambda) cùng kiểu
- Có health check riêng
- 1 target group có thể được dùng bởi nhiều LB
- 1 LB listener forward đến 1 hoặc nhiều target groups (weighted)
Architecture
7. ALB Routing Rules
Listener Rules
Mỗi listener có priority list of rules:
Advanced Actions
- Forward to target group(s)
- Redirect (HTTP → HTTPS)
- Fixed response (return static 503, 404...)
- Authenticate với Cognito hoặc OIDC
8. SSL/TLS với ELB
ALB
- Terminate TLS, decrypt, route HTTP đến backend
- SNI (Server Name Indication): nhiều SSL certs trên cùng listener cho multi-domain
- Cert từ AWS Certificate Manager (ACM) — free cho ALB/NLB/CloudFront
NLB
- TLS termination với TLS listener
- Hoặc TCP pass-through (backend tự decrypt)
- Hỗ trợ TLS 1.3
Security Policy
- Predefined cipher suite policies:
ELBSecurityPolicy-TLS13-1-2-2021-06 - Compliance: FIPS-140-2 policies có sẵn
9. Cross-Zone Load Balancing
Định nghĩa
Cross-zone = LB distribute traffic đều giữa tất cả targets across AZs thay vì chỉ trong AZ của LB node.
Ví dụ
Default behavior
| LB type | Default | Cost cross-AZ |
|---|---|---|
| ALB | Enabled, free (không tính cross-AZ data) | Free |
| NLB | Disabled by default (có thể enable, tính phí cross-AZ data) | Cost |
| GWLB | Disabled by default | Cost |
| CLB | Disabled (enable free) | Free |
10. Health Check
Cấu hình
- Protocol: HTTP, HTTPS, TCP
- Port: target port hoặc traffic port
- Path (HTTP):
/health,/healthz - Interval: 5-300s (mặc định 30s)
- Timeout: 2-120s (mặc định 5s)
- Healthy threshold: số lần pass liên tiếp → healthy (mặc định 5)
- Unhealthy threshold: số lần fail liên tiếp → unhealthy (mặc định 2)
- Matcher: HTTP code success (mặc định 200)
Best practice
- Endpoint
/healthriêng, không phải/(vì homepage có thể slow) /healthcheck dependencies (DB connection, cache)- Return 200 nếu healthy, 503 nếu draining
Connection Draining (Deregistration Delay)
- Khi target deregister hoặc unhealthy:
- LB ngừng gửi request mới
- Chờ existing connections complete (default 300s)
- Tránh disconnect đột ngột user đang dùng
11. ALB vs NLB — Khi nào dùng cái nào?
| Yêu cầu | Chọn |
|---|---|
| HTTP routing theo path/host/header | ALB |
| WebSocket, HTTP/2, gRPC | ALB |
| Lambda backend | ALB |
| Cognito/OIDC authentication | ALB |
| TCP/UDP non-HTTP traffic | NLB |
| Static IP cho whitelisting | NLB |
| Hàng triệu req/s, sub-ms latency | NLB |
| Source IP preservation | NLB |
| Private endpoint cho service (PrivateLink) | NLB |
| Inspection firewall appliances | GWLB |
Phần 3: Auto Scaling
1. Tổng quan Auto Scaling
EC2 Auto Scaling tự động:
- Add instances khi traffic tăng (scale out)
- Remove instances khi traffic giảm (scale in)
- Replace instances unhealthy (self-healing)
- Maintain số instance đã chỉ định (desired)
Lợi ích
- High availability: tự động replace instance bị fail
- Cost optimization: chỉ chạy số lượng cần thiết
- Elasticity: ứng phó traffic spike
- Fault tolerance: spread across AZs
ASG FREE — chỉ trả tiền cho EC2 instances chạy.
2. Auto Scaling Group (ASG) Components
3. Launch Template vs Launch Configuration
| Launch Template | Launch Configuration | |
|---|---|---|
| Status | Recommended (modern) | Legacy, đang phase out |
| Versioning | Có (multiple versions) | Không |
| Mixed instance types | Hỗ trợ | Không |
| Spot + On-Demand mix | Hỗ trợ | Hạn chế |
| New EC2 features | Hỗ trợ đầy đủ | Không |
AWS đã ngừng tạo mới Launch Configuration cho account mới từ Dec 2023. Always dùng Launch Template.
Launch Template chứa
- AMI ID
- Instance type
- Key pair
- Security group(s)
- User data script
- IAM instance profile
- Storage (EBS) specs
- Tags
- Network interfaces
4. ASG Sizing
Quy tắc
- Min ≤ Desired ≤ Max
- ASG luôn cố gắng đạt Desired
- Scaling policies thay đổi Desired (không vượt Min/Max)
5. Scaling Policies (4 loại)
5.1 Target Tracking Scaling (Recommended)
- Set target value cho 1 metric (CPU 50%, ALB request count 1000/target)
- ASG tự động tính cần thêm/bớt bao nhiêu instances
- Đơn giản nhất, AWS recommended
Ví dụ: Target CPU = 50%
- Current CPU = 70% → Scale out (thêm instances)
- Current CPU = 30% → Scale in (giảm instances)
5.2 Step Scaling
- Định nghĩa step adjustments dựa trên CloudWatch Alarm
- Mức độ scale phụ thuộc severity
Ví dụ:
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 fixed number)
- Cooldown period giữa scaling actions
- Đã bị thay thế bởi Step Scaling cho hầu hết use case
5.4 Scheduled Scaling
- Scale theo lịch (cron, date)
- Use case: traffic predictable (giờ làm việc, end-of-month)
Ví dụ:
Mon-Fri 8:00 AM → Desired = 10 (giờ làm việc)
Mon-Fri 6:00 PM → Desired = 3 (tối)
Sat-Sun all day → Desired = 2 (cuối tuần)
5.5 Predictive Scaling (Bonus)
- ML phân tích traffic 14 ngày qua, dự báo traffic 48 giờ tới
- Tự động scale trước khi traffic tăng (proactive)
- Use case: Daily/weekly traffic patterns
Tổng hợp
| Policy | Trigger | Use case |
|---|---|---|
| Target Tracking | Metric value | Mặc định, đơn giản |
| Step Scaling | CloudWatch Alarm severity | Granular control |
| Simple Scaling | CloudWatch Alarm | Legacy |
| Scheduled | Time-based | Pattern dự đoán được |
| Predictive | ML forecast | Daily/weekly patterns |
6. Cooldown Period
Định nghĩa
Cooldown = thời gian chờ sau 1 scaling action trước khi cho phép action tiếp theo (mặc định 300 seconds).
Lý do
- Tránh "thrashing" (scale liên tục in/out)
- Cho instance mới đủ thời gian boot và bắt đầu xử lý
Lưu ý
- Target Tracking không dùng cooldown (dùng warm-up time thay thế)
- Step Scaling có "estimated instance warmup" period
7. Health Check
2 loại
- EC2 health check (default): Check EC2 status (running, hardware OK)
- ELB health check: ASG xem target group health (cần enable)
Health check grace period
- Thời gian sau khi launch trước khi check health (mặc định 300s)
- Cho instance time để boot, init app
- Critical: app cần warm-up dài (Java JVM) → tăng grace period
Khi instance fail
- ASG mark instance là Unhealthy
- ASG terminate instance đó
- ASG launch instance mới thay thế (để duy trì Desired)
8. Lifecycle Hooks
Định nghĩa
Lifecycle hooks cho phép custom actions khi instance launching hoặc terminating.
2 events
- EC2_INSTANCE_LAUNCHING: chạy script trước khi instance vào InService
- EC2_INSTANCE_TERMINATING: chạy script trước khi terminate
Workflow
Launching:
[Launching] → [Pending:Wait] → run hook → [Pending:Proceed] → [InService]
Terminating:
[InService] → [Terminating:Wait] → run hook → [Terminating:Proceed] → [Terminated]
Use cases
- Pull configuration / secrets trước khi serve traffic
- Register instance với external system
- Drain connections / flush logs trước khi terminate
- Final backup data từ ephemeral storage
9. Instance Refresh
Định nghĩa
Instance Refresh = update instances trong ASG sang launch template version mới (rolling deployment).
Strategy
- Min healthy percentage (mặc định 90%): luôn giữ % instances healthy
- ASG sẽ terminate batch, launch new, đợi healthy, lặp lại
- Optional: Checkpoints để pause giữa batches
Use case
- Deploy new AMI (security patch)
- Update User Data
- Đổi instance type
Alternative: Blue/Green với 2 ASG + ALB target group weight
10. Termination Policy
Khi ASG cần scale in (terminate), ASG chọn instance theo policy:
Default termination policy
- AllocationStrategy (cho mixed instance types)
- OldestLaunchTemplate (terminate launch template cũ)
- OldestLaunchConfiguration (legacy)
- ClosestToNextInstanceHour (cho instance gần đến giờ tính phí kế)
- OldestInstance hoặc NewestInstance
- Random
Custom policies
DefaultOldestInstance/NewestInstanceOldestLaunchConfiguration/OldestLaunchTemplateClosestToNextInstanceHourAllocationStrategy
Instance Scale-In Protection
- Tag specific instances với "scale-in protection" → ASG không terminate
- Use case: instance đang xử lý long-running job
11. ASG với Mixed Instance Types & Spot
Mixed Instance Policy
- 1 ASG có thể launch nhiều instance types khác nhau
- Mix On-Demand + Spot
Spot Allocation Strategy
- price-capacity-optimized (AWS recommended): cân bằng giá + capacity
- capacity-optimized: pool ít bị reclaim nhất (khi interruption gây tốn kém)
- lowest-price: pool rẻ nhất (rủi ro interrupt cao)
- diversified: spread across nhiều pool
Example
12. ASG tích hợp với ELB
Workflow
Cấu hình quan trọng
- ASG attach to 1 hoặc nhiều target groups
- Enable ELB health check trong ASG (thay vì chỉ EC2 health check)
- Warm-up period đủ dài cho app khởi động trước health check
Phần 4: AWS Lambda Basics
1. Tổng quan Lambda
AWS Lambda = serverless compute service. Chạy code mà không quản lý server.
Đặc điểm
- Event-driven: chạy khi có event trigger
- Pay per execution: tính theo số lần invoke + duration + memory
- Auto-scaling: scale từ 0 đến hàng nghìn concurrent executions
- No infrastructure management: AWS lo mọi thứ
- 15 minutes timeout max per execution
Use case
- API backend (qua API Gateway)
- File processing (S3 trigger)
- Stream processing (Kinesis, DynamoDB Streams)
- Scheduled tasks (EventBridge cron)
- IoT data processing
- Real-time data transformation
Khi KHÔNG dùng Lambda
- Long-running tasks (> 15 min) → ECS, EC2, Batch
- Stateful applications → EC2
- Heavy compute / GPU → EC2 GPU, SageMaker
- Predictable steady traffic 24/7 → có thể dùng EC2 RI rẻ hơn
2. Lambda Function Components
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; runtimego1.xđã deprecated) - .NET 10
- Ruby 3.3, 3.4, 4.0
- Custom Runtime (Bash, Rust, etc. qua Runtime API)
- Container Image (any runtime, up to 10 GB)
Memory & CPU
- Memory: 128 MB → 10,240 MB (10 GB), bước 1 MB
- CPU scale tỷ lệ với memory (không cấu hình riêng)
- Tại ~1769 MB memory = 1 vCPU full
3. Triggers (Event Sources)
200+ AWS services có thể trigger Lambda. Phổ biến:
| Service | Use case |
|---|---|
| API Gateway | HTTP/REST API backend |
| ALB | HTTP backend (alternative to API GW) |
| S3 | File upload → process (thumbnail, virus scan) |
| DynamoDB Streams | React to data change |
| Kinesis Data Streams | Real-time stream processing |
| SQS | Process queue messages |
| SNS | Process pub/sub messages |
| EventBridge | Cron schedule, custom events |
| Cognito | User pool triggers (pre-signup, post-confirmation) |
| CloudFront Lambda@Edge | Modify request/response at edge |
| IoT Core | IoT messages |
4. Invocation Models
4.1 Synchronous (Sync)
- Caller chờ response
- Errors return ngay cho caller (caller phải retry)
Examples:
- API Gateway → Lambda
- ALB → Lambda
- AWS CLI invoke
- Cognito triggers
- Lambda function URL
- Lex, Step Functions
4.2 Asynchronous (Async)
- Caller fire-and-forget
- Lambda queue event internally
- Lambda tự retry: 2 retries (3 total attempts)
- Failed events → Dead Letter Queue (DLQ) (SQS/SNS) hoặc on-failure destination
Examples:
- S3 events
- SNS notifications
- EventBridge events
- CodeCommit, CodePipeline
- CloudWatch Logs subscription
4.3 Event Source Mapping (Polling)
- Lambda poll từ stream/queue
- Batch processing
- Internal Lambda machinery, không cần code
Examples:
- Kinesis Data Streams
- DynamoDB Streams
- SQS (standard và FIFO)
- Amazon MQ
- Self-managed Kafka, MSK
5. Pricing
Tính phí 2 components
1. Request count
- $0.20 per 1M requests
- Free tier: 1M requests/month forever free
2. Duration
- Tính theo GB-seconds (memory × duration)
- $0.0000166667 per GB-second
- Free tier: 400,000 GB-seconds/month (forever free)
Ví dụ
- Function 512 MB chạy 1 second 1M times/month
- = 1M × (512/1024) × 1 = 500,000 GB-seconds
- Trừ 400,000 GB-seconds free, billable = 100,000 GB-seconds = ~$1.67
- Request cost: 1M requests nằm trong free tier = $0 (hết free tier thì $0.20/1M)
- Total ~$1.67/month (không có free tier: ~$8.33 + $0.20 = ~$8.53)
Free tier Lambda rất hào phóng — đa số side project chạy miễn phí.
6. Cold Start vs Warm Start
Cold Start
- Lambda runtime mới được khởi tạo
- Download code, init runtime, run init code
- Lag: 100ms - 5s (Java/.NET chậm hơn Node/Python)
- Xảy ra khi: lần đầu invoke, sau 5-15 phút idle, scale up
Warm Start
- Reuse container đã có sẵn
- Latency rất thấp (< 10ms typically)
Cách giảm Cold Start
Provisioned Concurrency
- Pre-warm N executions, luôn sẵn sàng
- Eliminate cold start cho first N concurrent invocations
- Trả thêm phí $/GB-hour cho provisioned capacity
Lambda SnapStart (Java)
- Snapshot pre-initialized Lambda execution environment
- Cold start giảm từ ~3s xuống ~200ms cho Java
- Free (no extra cost)
Best practices
- Init outside handler (DB connection, SDK clients)
- Minimize package size
- Avoid VPC nếu không cần (VPC + ENI thêm cold start)
- Dùng Node.js / Python (cold start nhỏ hơn Java)
7. Concurrency
Reserved Concurrency
- Đặt giới hạn cho function
- Lambda không vượt giới hạn này
- 2 mục đích:
- Cap: function "đói" không ảnh hưởng function khác (account limit shared)
- Throttle protection: bảo vệ downstream (DB không bị quá tải)
Provisioned Concurrency
- Pre-warmed executions
- Không cold start
- Có thể combine với Reserved Concurrency
Account-level Concurrency Limit
- Default 1,000 concurrent executions per account per region
- Có thể request tăng qua Service Quotas
Scaling Rate (model mới từ 12/2023)
- Mỗi function scale thêm 1,000 concurrent executions mỗi 10 giây, cho đến khi chạm account concurrency limit
- Áp dụng per function (không chia sẻ burst pool giữa các function trong account)
- Lưu ý cho người ôn thi: trước 12/2023 Lambda dùng model cũ "burst 500-3000 tùy region, sau đó +500/phút" — tài liệu/đề thi cũ có thể còn nhắc số này
8. Layers
Định nghĩa
Layer = package chứa shared code/libraries dùng chung cho nhiều functions.
Use cases
- Shared SDK (boto3 custom version)
- Common utilities
- Native binaries (FFmpeg, ImageMagick)
- Custom runtime (chạy Rust, Bash...)
Limits
- 5 layers per function
- Total unzipped size (function + layers): 250 MB
Workflow
# Tạo 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
Đặc điểm
- Đóng gói Lambda dưới dạng Docker image (up to 10 GB)
- Push lên ECR (Elastic Container Registry)
- Lambda pull image khi 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 đã quen Docker workflow
- Container image > 250 MB
10. Lambda Networking
Default (no VPC)
- Lambda chạy trong AWS-managed VPC
- Có internet access mặc định
- Nhanh cold start
- KHÔNG access VPC private resources (RDS private, ElastiCache)
VPC Configuration
- Chỉ định subnet + SG
- Lambda tạo ENI trong subnet (Hyperplane ENI — shared, fast)
- Cần NAT Gateway trong VPC để Lambda access internet (vì subnet là private)
- Cold start slower lần đầu (đã giảm nhiều từ 2019)
Best practice VPC
- Lambda trong private subnet
- Route 0.0.0.0/0 → NAT Gateway (cho internet)
- Dùng VPC Endpoints cho AWS services (S3, DynamoDB) để tránh data transfer cost
11. Lambda Destinations (Async)
Khi async invocation fail (sau 2 retries) hoặc success
Có thể gửi event đến destination:
- SQS queue
- SNS topic
- Lambda function khác
- EventBridge bus
vs DLQ
- Destinations hỗ trợ cả success + failure, nhiều target types
- DLQ chỉ failure, chỉ SQS/SNS
- AWS recommend Destinations thay DLQ
12. Lambda Function URL
Định nghĩa
Function URL = dedicated HTTP(S) endpoint cho Lambda function, không cần API Gateway.
Đặc điểm
- Format:
https://<url-id>.lambda-url.<region>.on.aws/ - Auth: NONE (public) hoặc AWS_IAM
- CORS support built-in
- Không có rate limiting, không có custom domain
Khi nào dùng Function URL vs API Gateway?
- Function URL: Đơn giản, low-cost, ít features
- API Gateway: Cần rate limit, custom domain, authorization complex (Cognito, Lambda authorizer), throttling, caching
Câu hỏi ôn tập
-
Khi EC2 stop, dữ liệu trên Instance Store có còn không?
Xem đáp án
Không. Instance Store là ephemeral storage — data mất khi instance stop, terminate, hoặc host hardware fail. Khi reboot thì data vẫn còn. Instance Store phù hợp cho temporary data, buffer, cache, scratch space. Dữ liệu quan trọng phải lưu trên EBS hoặc S3.
-
Khi nào nên chọn gp3 thay vì gp2?
Xem đáp án
Hầu như luôn chọn gp3 — gp3 cho phép cấu hình IOPS (3,000-80,000) và throughput (125-2,000 MB/s) độc lập với storage size, trong khi gp2 buộc IOPS tỷ lệ với size (3 IOPS/GB). gp3 rẻ hơn gp2 ~20% cho cùng size. Chỉ giữ gp2 nếu đang dùng và không cần thay đổi, hoặc có hệ thống không tương thích.
-
EBS snapshot lưu ở đâu? Cross-AZ hay không?
Xem đáp án
EBS snapshot lưu trong Amazon S3 (AWS-managed, không phải bucket của bạn). Snapshot có phạm vi Region — có thể tạo volume từ snapshot ở bất kỳ AZ nào trong cùng Region. Để copy sang Region khác dùng
aws ec2 copy-snapshot. Điều này cho phép tạo volume ở AZ khác từ snapshot — quan trọng cho DR và migration. -
Encrypt unencrypted EBS volume cần qua bước gì?
Xem đáp án
Không thể encrypt trực tiếp volume đang dùng. Phải: (1) Tạo snapshot của volume unencrypted, (2) Copy snapshot với encryption enabled để tạo encrypted snapshot, (3) Tạo volume mới từ encrypted snapshot, (4) Attach volume mới vào instance. Alternatively: enable "EBS encryption by default" cho account/Region — tất cả volumes/snapshots mới tự động encrypted.
-
EBS volume io2 Multi-Attach có thể dùng với ext4 không?
Xem đáp án
Không. Multi-Attach cho phép attach cùng một io1/io2 volume vào nhiều EC2 instances cùng AZ, nhưng yêu cầu ứng dụng tự quản lý concurrent write access. Standard filesystems như ext4 không hỗ trợ concurrent multi-writer — sẽ bị data corruption. Cần dùng cluster-aware filesystem như GFS2, OCFS2, hoặc ứng dụng tự xử lý coordination (như Oracle RAC).
-
ALB và NLB hoạt động ở Layer nào của OSI?
Xem đáp án
ALB (Application Load Balancer): Layer 7 (HTTP/HTTPS/WebSocket) — hiểu content-based routing (path, header, hostname, query string). NLB (Network Load Balancer): Layer 4 (TCP/UDP/TLS) — routing dựa trên IP + port, không inspect payload. GLB (Gateway LB) hoạt động ở Layer 3/4 dành cho security appliances. CLB (Classic) là legacy, hỗ trợ cả L4 và L7 cơ bản.
-
NLB có static IP, ALB thì sao?
Xem đáp án
NLB cấp static IP cho mỗi AZ (1 IP/AZ) — IP không thay đổi kể cả khi scale. ALB không có static IP — chỉ có DNS name (hostname); IP thay đổi khi AWS scale ALB internally. Nếu cần static IP cho ALB (ví dụ: firewall whitelist), dùng AWS Global Accelerator trước ALB — Global Accelerator cung cấp static anycast IPs.
-
Cross-zone load balancing default behavior khác nhau giữa ALB và NLB?
Xem đáp án
ALB: cross-zone load balancing bật mặc định và không tính phí thêm. NLB: cross-zone load balancing tắt mặc định (chỉ route trong AZ nhận traffic); bật thêm sẽ tính phí data transfer cross-AZ ($0.01/GB). Lý do: NLB thường dùng cho latency-sensitive workloads, cross-AZ adds latency.
-
ALB target type nào có thể được Lambda function?
Xem đáp án
ALB hỗ trợ 3 target types: IP (IP addresses), Instance (EC2 instance IDs), và Lambda (Lambda function ARN). Khi chọn Lambda target type, ALB invoke Lambda synchronously với event chứa HTTP request details. Không cần API Gateway — ALB có thể làm HTTP frontend trực tiếp cho Lambda, rẻ hơn API Gateway cho high-volume traffic.
-
Khi cần WebSocket support, chọn LB nào?
Xem đáp án
ALB hỗ trợ WebSocket (và HTTP/2). ALB duy trì connection lâu dài (long-lived connections) cần cho WebSocket. NLB cũng hỗ trợ WebSocket vì nó hoạt động ở Layer 4 (TCP) — nhưng không có sticky sessions hay content-based routing. Thường chọn ALB cho WebSocket apps cần routing intelligence; NLB cho high-performance TCP WebSocket connections.
- Launch Template có ưu điểm gì so với Launch Configuration?
Xem đáp án
Launch Template hỗ trợ: versioning (có thể tạo nhiều version, rollback), multiple instance types trong một ASG (mixed instances), Spot + On-Demand combination, T2/T3 unlimited CPU credits, và các tính năng EC2 mới hơn. Launch Configuration là legacy — AWS khuyến cáo migrate sang Launch Template (announce từ 2022) và account mới từ Dec 2023 không tạo được Launch Configuration nữa; không có versioning, chỉ một instance type. Luôn dùng Launch Template cho ASG mới.
- ASG có thể spread instances qua nhiều AZ trong cùng Region không?
Xem đáp án
Có. ASG được cấu hình với danh sách subnets — mỗi subnet thuộc một AZ. ASG tự động cân bằng instances qua các AZ (rebalancing). Khi một AZ bị unhealthy hoặc scale event xảy ra, ASG ưu tiên launch trong AZ có ít instances nhất. Đây là cách đạt HA trong một Region — luôn configure ASG với ít nhất 2-3 AZs.
- Khi nào dùng Scheduled Scaling thay vì Target Tracking?
Xem đáp án
Scheduled Scaling khi biết trước thời điểm cụ thể load tăng — ví dụ: "mỗi thứ Hai 8 AM scale up vì đầu tuần, 6 PM scale down". Load pattern predictable và có lịch cố định. Target Tracking cho load tăng/giảm không theo lịch cố định — ví dụ CPU tăng khi có traffic, ASG tự động scale. Có thể kết hợp: dùng Scheduled để pre-warm, Target Tracking để fine-tune realtime.
- Lifecycle hook EC2_INSTANCE_TERMINATING thường dùng để làm gì?
Xem đáp án
Dùng để graceful shutdown trước khi instance bị terminate: drain active connections, deregister từ service discovery, flush logs đến centralized logging, backup in-memory state, send final metrics. Instance ở trạng thái Terminating:Wait trong khoảng thời gian cấu hình (mặc định 1 giờ) — trong lúc này Lambda/SSM Automation thực hiện cleanup tasks rồi signal CONTINUE để tiếp tục terminate.
- Min Healthy Percentage trong Instance Refresh là gì?
Xem đáp án
Phần trăm tối thiểu instances phải healthy trong suốt quá trình Instance Refresh. Ví dụ: ASG có 10 instances, Min Healthy = 90% → tối đa 1 instance bị replace cùng lúc (10% = 1 instance). ASG launch instance mới và chờ healthy trước khi terminate instance cũ — rolling update không downtime. Giá trị thấp hơn = rolling faster nhưng riskier; cao hơn = safer nhưng chậm hơn.
- Lambda timeout tối đa là bao lâu?
Xem đáp án
15 phút (900 giây). Default timeout là 3 giây — cần tăng nếu function cần lâu hơn. Workload vượt 15 phút cần dùng dịch vụ khác: EC2, Fargate, hoặc Step Functions để orchestrate nhiều Lambda invocations. Memory range: 128 MB đến 10,240 MB (10 GB).
- CPU của Lambda được scale theo gì?
Xem đáp án
CPU scale tỷ lệ thuận với memory. Bạn không cấu hình CPU trực tiếp — chỉ cấu hình memory. Tại 1,769 MB, function có 1 full vCPU. Tại 3,538 MB có 2 vCPUs, v.v. Nếu function CPU-bound và cần nhanh hơn, tăng memory (dù không cần RAM) để tăng CPU allocation — chi phí tăng nhưng execution time giảm, tổng chi phí có thể không đổi hoặc rẻ hơn.
- Khi async invoke fail, Lambda retry mấy lần?
Xem đáp án
2 lần retry (tổng 3 lần attempt). Sau lần đầu fail: retry lần 1 sau 1 phút, retry lần 2 sau 2 phút. Sau 3 lần đều fail, event bị discarded (hoặc gửi đến DLQ/EventBridge nếu cấu hình). Synchronous invoke: không retry tự động — caller nhận lỗi và tự quyết định retry. SQS trigger: retry theo SQS visibility timeout và maxReceiveCount.
- Provisioned Concurrency giải quyết vấn đề gì?
Xem đáp án
Giải quyết cold start latency. Khi Lambda function chưa có warm instance, lần invocation đầu phải khởi tạo execution environment (download code, init runtime, run init code) — mất 100ms-1s+. Provisioned Concurrency giữ sẵn N instances warm và initialized, sẵn sàng phục vụ requests ngay lập tức. Chi phí: tính phí cho cả thời gian "provisioned" dù không có request — trade-off cost vs latency.
- Khi nào nên dùng container image thay vì zip cho Lambda?
Xem đáp án
Dùng container image khi: (1) Deployment package lớn hơn 250 MB (zip limit) — container image hỗ trợ đến 10 GB, (2) Cần custom runtime, system libraries, hay binaries không có trong standard Lambda runtimes, (3) Team đã quen với Docker workflow và muốn reuse Dockerfile, (4) Cần test locally với behavior giống production bằng Lambda Runtime Interface Emulator (RIE).
Bài tập thực hành
Phần 1: EC2 Storage và EBS
- Tạo gp3 EBS volume 10 GB, attach vào EC2, format và mount
- Tạo snapshot, sau đó tạo volume mới từ snapshot ở AZ khác
- Enable EBS encryption by default cho region
- Test Instance Store: launch m5d.large, check
/dev/nvme*, write file, stop+start, verify data mất - Setup DLM tự động snapshot hằng ngày, giữ 7 snapshots
Phần 2: Elastic Load Balancing (ELB)
- Tạo ALB với 2 target groups (web và api), route path-based
- Setup health check endpoint
/healthtrả 200, test với 1 instance fail - Enable HTTPS với ACM certificate, redirect HTTP → HTTPS
- Tạo NLB với UDP listener (port 53 simulate DNS)
- Enable cross-zone load balancing cho NLB, observe cost change
Phần 3: Auto Scaling
- Tạo Launch Template với AMI Amazon Linux 2023 + User Data cài Apache
- Tạo ASG với min=2, desired=2, max=5, spread across 3 AZs
- Attach ASG vào Target Group của ALB
- Tạo Target Tracking policy (CPU 50%)
- Stress test 1 instance → quan sát scale out
- Thêm Scheduled Action: scale to 5 instances at 8 AM, scale to 2 at 6 PM
Phần 4: AWS Lambda Basics
- Tạo Lambda function Python "hello world" với memory 256 MB
- Tạo trigger từ S3 bucket → Lambda log filename khi có file upload
- Setup API Gateway → Lambda (REST API endpoint trả JSON)
- Enable Provisioned Concurrency = 1, observe cold start before/after
- Tạo Layer chứa
requestslibrary, attach vào function - Setup EventBridge schedule cron(0/5 * * * ? *) → Lambda chạy mỗi 5 phút
Tài liệu tham khảo
- Amazon EBS Documentation
- EBS Volume Types
- EBS Snapshots
- EBS Encryption
- Instance Store
- Elastic Load Balancing
- Application Load Balancer
- Network Load Balancer
- Gateway Load Balancer
- ALB Listener Rules
- EC2 Auto Scaling User Guide
- Launch Templates
- Scaling Policies
- Lifecycle Hooks
- Instance Refresh
- AWS Lambda Developer Guide
- Lambda Pricing
- Provisioned Concurrency
- Lambda Layers
- Container Image Support