Tuần 2 - Ngày 5: Auto Scaling
Mục tiêu học tập
- 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
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
- capacity-optimized (recommended): pool ít bị reclaim nhất
- price-capacity-optimized: cân bằng giá + capacity
- 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
Câu hỏi ôn tập
-
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 (deprecated AWS 2022) — 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:Waittrong 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 signalCONTINUEđể 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.
Bài tập thực hành
- Tạo Launch Template với AMI Amazon Linux 2 + 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
Tài liệu tham khảo chính thức
Tiếp theo: AWS Lambda Basics