devHọc Dev
Bài học

Ngày 5: EC2 và Auto Scaling Review

Tuần 1 – Ngày 5

Mục tiêu học tập

  • Ôn tập EC2 instance types và pricing models
  • Hiểu sâu về Auto Scaling Groups
  • Nắm vững các scaling strategies

1. EC2 Instance Types

Naming Convention

m5.xlargeSize:nano,micro,small,medium,large,xlarge,2xlarge...Generation:scàngcaocàngmiFamily:m(general),c(compute),r(memory),etc.

Instance Families

FamilyOptimized forUse Cases
M (General)BalancedWeb servers, app servers
C (Compute)CPUBatch processing, gaming
R (Memory)RAMIn-memory databases, caching
X (Memory)Extreme RAMSAP HANA, large databases
I (Storage)High I/ONoSQL, data warehousing
D (Dense)HDD storageDistributed file systems
G/P (Accelerated)GPUML, graphics rendering
T (Burstable)Burst CPUVariable workloads

T Instance và CPU Credits

T3InstanceCPUCreditSystem:CPUUsage100%BurstSdngcredits20%BaselineEarncredits0%TimeKhihếtcredits:-T3Standard:Bgiihnbaseline-T3Unlimited:Tiếptcburst,trthêmphí

2. EC2 Pricing Models

So sánh các pricing models

ModelDiscountCommitmentBest For
On-Demand0%NoneShort-term, unpredictable
Reserved30-72%1 or 3 yearsSteady-state workloads
Savings Plans30-72%1 or 3 yearsFlexible compute usage
Spot60-90%NoneFault-tolerant, flexible
Dedicated HostVariesPer hostLicensing, compliance

Reserved Instances Types

Standard RI:
- Highest discount (up to 72%)
- Có thể bán trên Marketplace
- Không thể đổi instance family

Convertible RI:
- Lower discount (up to ~54% cho 3-year term)
- Có thể đổi instance family, OS, tenancy
- Không thể bán trên Marketplace

Savings Plans

Compute Savings Plans:
- Áp dụng cho EC2, Lambda, Fargate
- Flexible across regions, instance families
- Up to 66% discount

EC2 Instance Savings Plans:
- Specific to instance family in a Region
- Up to 72% discount
- Less flexible

Spot Instances

Spot Request Types:

1. One-time Request
   - Launched → Running → Terminated when interrupted

2. Persistent Request
   - Automatically re-requests if interrupted
   - Stays valid until canceled

Spot Fleet:
- Collection of Spot + On-Demand instances
- Automatically maintains target capacity
- Diversified allocation strategy

3. EC2 Placement Groups

Ba loại Placement Groups

1.CLUSTER(LowLatency)SameRack,SameAZEC2EC2EC2Use:HPC,Low-latencyapps2.SPREAD(HighAvailability)Rack1Rack2Rack3EC2EC2EC2Max:7instancesperAZUse:Criticalapps3.PARTITION(LargeDistributed)Partition1Partition2Partition3EC2EC2EC2EC2EC2EC2Use:HDFS,Cassandra,Kafka

4. Auto Scaling Groups (ASG)

Components

AutoScalingGroupLaunchTemplateScalingPolicies-AMI-TargetTracking-InstanceType-StepScaling-SecurityGrp-SimpleScaling-UserData-ScheduledCapacitySettings:-Minimum:2-Desired:4-Maximum:10

Launch Template vs Launch Configuration

FeatureLaunch TemplateLaunch Config
VersioningYesNo
Multiple instance typesYesNo
Spot + On-Demand mixYesNo
T2/T3 UnlimitedYesNo
RecommendedYesLegacy

5. Scaling Policies

Target Tracking (Khuyến nghị)

Policy: Keep Average CPU at 50%

CPU = 70% → Scale OUT (add instances)
CPU = 30% → Scale IN (remove instances)
CPU = 50% → No action

Step Scaling

CPU Usage    Action
0-40%        Remove 2 instances
40-60%       No change
60-80%       Add 1 instance
80-100%      Add 3 instances

Scheduled Scaling

{
  "ScheduledActionName": "scale-out-morning",
  "Recurrence": "0 9 * * MON-FRI",
  "MinSize": 5,
  "MaxSize": 20,
  "DesiredCapacity": 10
}

Predictive Scaling

  • Sử dụng ML để dự đoán traffic patterns
  • Proactive scaling trước khi load tăng
  • Kết hợp với dynamic scaling

6. Scaling Cooldowns

ScaleOutEventCooldownAdd2Inst(300sec)ReadyfornextscalePurpose:-Tránhscalequánhanh-Chmetricsnđnh-Default:300seconds

7. Health Checks

Types

TypeDefaultChecks
EC2YesInstance status
ELBOptionalHTTP health check
CustomOptionalExternal health system

Grace Period

  • Thời gian chờ sau khi instance launch
  • Không terminate instance mới trong grace period
  • Default: 300 seconds

8. Cross-Zone Load Balancing

Vấn đề: instance phân bố lệch giữa các AZ

KHÔNGcóCross-ZoneLoadBalancing:LoadBalancer50%50%LBnodemiAZnhn50%trafficAZ-1AZ-2...EC2EC2EC2EC21inst9instances=50%!=50%/95.6%/instCÓCross-ZoneLoadBalancing:Miinstancenhn100%/10=10%,btkAZnào

Khi số instance giữa các AZ lệch nhau (ví dụ 1 vs 9), nếu không bật cross-zone, mỗi LB node chỉ phân phối cho targets trong AZ của nó → instance đơn độc ở AZ-1 gánh 50% toàn bộ traffic và bị quá tải. Bật cross-zone → mọi LB node phân phối đều cho tất cả targets ở mọi AZ.

So sánh theo loại Load Balancer

ALBNLBGWLB
DefaultLuôn BẬT ở LB levelTẮTTẮT
Tắt/bật được?Tắt được per target groupBật ở LB levelBật ở LB level
Phí data transfer inter-AZMiễn phíTính phí khi bậtTính phí khi bật

Lưu ý Professional:

  • ALB: cross-zone bật sẵn và inter-AZ data transfer miễn phí — hầu như không có lý do tắt, trừ khi cần zonal isolation (kết hợp zonal DNS affinity).
  • NLB: mặc định tắt để tránh phí inter-AZ và giữ zonal isolation; chỉ bật khi chấp nhận phí để cân bằng traffic.
  • Kết hợp ASG: nên cấu hình ASG trải đều instance qua các AZ (balanced AZs) để không phụ thuộc cross-zone.

Exam keyword: "uneven traffic distribution across AZs" / một AZ có ít instance nhưng nhận lượng traffic bằng AZ nhiều instance → bật Cross-Zone Load Balancing (nhớ: NLB mặc định tắt + có phí inter-AZ, ALB mặc định bật + miễn phí).

9. ASG Instance Refresh và EC2 Instance Recovery

ASG Instance Refresh

Rolling replacement toàn bộ instances trong ASG theo launch template mới — dùng khi patch AMI, đổi instance type, sửa user data — không cần terminate thủ công từng instance.

InstanceRefresh(MinHealthyPercentage=90%):ASG10instances(AMIv1)thaythếdntngbatch,luôngi9healthyTerminate1(v1)Launch1(v2)chInstanceWarmupbatchtiếpASG10instances(AMIv2)

Tham số quan trọng:

Tham sốÝ nghĩa
MinHealthyPercentage% capacity tối thiểu phải healthy trong lúc refresh (vd 90% → thay tối đa 10% mỗi lượt)
InstanceWarmupThời gian chờ instance mới "ấm máy" trước khi tính là healthy và thay batch kế
CheckpointsDừng tại các mốc % (vd 25%, 50%) chờ xác nhận — canary-style rollout
Skip matchingBỏ qua instance đã đúng launch template version mới → không thay thừa
Auto rollbackTự rollback về cấu hình cũ nếu refresh fail hoặc CloudWatch alarm trigger

Exam keyword: "update AMI cho toàn bộ instances trong ASG với least operational overhead" → Instance Refresh (KHÔNG phải manually terminate từng instance hay tạo ASG mới).

EC2 Instance Recovery (CloudWatch alarm action)

Tạo CloudWatch alarm trên metric StatusCheckFailed_System với alarm action recover → khi AWS hardware bên dưới lỗi, instance được tự động recover sang host vật lý mới.

Sau recovery, instance giữ nguyên:

  • Instance ID
  • Private IP (private IP vốn giữ nguyên trong VPC suốt vòng đời instance)
  • Elastic IP
  • Instance metadata

(Tương đương một cú stop/start được AWS thực hiện tự động lên host khác — trong VPC, private IP không đổi.)

Điều kiện: instance EBS-backed, không dùng instance store volumes (data instance store sẽ mất, và một số instance type không hỗ trợ recover).

System vs Instance status check

System status checkInstance status check
MetricStatusCheckFailed_SystemStatusCheckFailed_Instance
Lỗi ở đâuAWS hardware/host (power, network của host vật lý)OS level (kernel panic, memory cạn, network config sai trong OS)
Ai xử lýAWS — hoặc bạn dùng alarm action recoverBạn — action recover KHÔNG giúp; cần reboot hoặc fix OS

Exam keyword: "automatically recover instance khi underlying hardware fails, giữ nguyên instance ID/IP" → CloudWatch alarm StatusCheckFailed_System + action recover.

10. Câu hỏi ôn tập

  1. Sự khác biệt giữa Standard và Convertible Reserved Instances?

    Xem đáp án

    Standard RI: discount cao hơn (~72%), không đổi instance family/OS/tenancy trong thời hạn, có thể bán trên RI Marketplace. Convertible RI: discount thấp hơn (~54%), có thể exchange sang RI khác cùng hoặc cao hơn giá trị (đổi family, OS, tenancy, Region), không bán được. Chọn Standard khi workload ổn định rõ ràng; Convertible khi cần flexibility vì technology roadmap chưa chắc.

  2. Khi nào nên dùng Spot Instances?

    Xem đáp án

    Spot phù hợp cho fault-tolerant, stateless workloads: batch processing, data analytics (Spark/Hadoop), ML training, CI/CD workers, image/video rendering, genomics. Key requirements: (1) App có thể checkpoint và resume, (2) Không cần guaranteed uptime, (3) Có thể handle 2-phút interruption warning. Không dùng cho: production databases, stateful web servers (không có fallback), real-time customer-facing APIs.

  3. Ba loại Placement Groups là gì và use cases của chúng?

    Xem đáp án

    (1) Cluster: cùng rack trong 1 AZ, low-latency 10+ Gbps network — cho HPC, ML training, big data (Hadoop). (2) Spread: mỗi instance trên hardware riêng biệt, cross-AZ, max 7 instances/AZ — cho critical apps cần max HA (tránh correlated hardware failures). (3) Partition: groups of instances, mỗi partition cách nhau về hardware — cho distributed databases (Cassandra, HDFS, HBase) cần topology-aware replication.

  4. Tại sao nên dùng Launch Template thay vì Launch Configuration?

    Xem đáp án

    Launch Template hỗ trợ: versioning (rollback về version cũ), multiple instance types (Mixed Instances Policy), Spot + On-Demand trong cùng ASG, T2/T3 unlimited, tất cả EC2 features mới. Launch Configuration là legacy (deprecated 2022) — không có versioning, chỉ 1 instance type, không tương thích nhiều features mới. AWS không cho phép tạo Launch Configuration mới.

  5. Target Tracking Scaling policy hoạt động như thế nào?

    Xem đáp án

    Target Tracking maintain một metric tại target value bạn set — ASG tự động scale out/in để giữ metric gần target. Ví dụ: target CPU = 50% → khi CPU > 50%, ASG thêm instances; khi CPU < 50%, ASG giảm instances (sau cooldown). Đơn giản nhất trong 4 scaling policies — không cần define thresholds phức tạp. AWS recommend dùng CPU, ALB Request Count per Target, hoặc custom metric từ CloudWatch.

  6. Một NLB có 2 AZ: AZ-1 chạy 1 instance, AZ-2 chạy 9 instances. Instance ở AZ-1 liên tục quá tải. Nguyên nhân và cách khắc phục?

    Xem đáp án

    NLB mặc định TẮT Cross-Zone Load Balancing → mỗi LB node chỉ phân phối cho targets trong AZ của nó: AZ-1 nhận 50% traffic dồn hết vào 1 instance. Khắc phục: (1) Bật cross-zone ở NLB level — mỗi instance nhận đều 10%, nhưng phát sinh phí data transfer inter-AZ, hoặc (2) Cân bằng lại số instance giữa các AZ (ASG với balanced AZs). Lưu ý: với ALB thì không gặp vấn đề này vì cross-zone luôn bật sẵn và inter-AZ traffic miễn phí.

  7. Bạn cần cập nhật AMI mới (đã patch) cho toàn bộ 50 instances trong một ASG với least operational overhead và không downtime. Giải pháp?

    Xem đáp án

    Tạo launch template version mới với AMI đã patch, rồi chạy ASG Instance Refresh — rolling replacement tự động toàn bộ instances. Set MinHealthyPercentage (vd 90%) để giữ capacity trong lúc refresh, InstanceWarmup cho instance mới ổn định trước khi thay batch kế, bật auto rollback kèm CloudWatch alarm để tự quay về version cũ nếu deployment lỗi. Có thể dùng checkpoints cho canary-style rollout. Đây là đáp án đúng thay vì manually terminate từng instance hoặc tạo ASG/blue-green mới (nhiều operational overhead hơn).

11. Bài tập thực hành

  • Tạo Launch Template với User Data
  • Tạo Auto Scaling Group với Target Tracking policy
  • Test scaling bằng cách tạo CPU load
  • Xem scaling activities trong console

Tài liệu tham khảo chính thức


Ngày tiếp theo: S3 và Storage Review