devHọc Dev
EN
Bài học

Tuần 1 - Ngày 2: Ôn nền tảng VPC, EC2/Auto Scaling và S3

Tuần 1 – Ngày 2

Bài này gộp 3 chủ đề: VPC Fundamentals Review, EC2 và Auto Scaling Review, S3 và Storage Review.

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

  • Ôn tập các khái niệm cơ bản của VPC
  • Hiểu rõ về Subnets, Route Tables, Gateways
  • Nắm vững Security Groups và NACLs
  • Ô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
  • Ôn tập S3 storage classes và lifecycle policies
  • Hiểu S3 security và encryption
  • Nắm vững S3 performance optimization

Phần 1: VPC Fundamentals Review

1. VPC Overview

Định nghĩa

VPC (Virtual Private Cloud) là một mạng ảo riêng biệt trong AWS cloud, nơi bạn có toàn quyền kiểm soát:

  • IP address range (CIDR block)
  • Subnets
  • Route tables
  • Network gateways
  • Security settings

VPC CIDR Block

Allowed range: /16 (65,536 IPs) to /28 (16 IPs)

Ví dụ:
10.0.0.0/16    →  10.0.0.0 - 10.0.255.255 (65,536 IPs)
172.16.0.0/16  →  172.16.0.0 - 172.16.255.255
192.168.0.0/16 →  192.168.0.0 - 192.168.255.255

Reserved IPs trong mỗi Subnet

Subnet: 10.0.1.0/24 (256 IPs total, 251 usable)

10.0.1.0   - Network address
10.0.1.1   - VPC Router
10.0.1.2   - DNS Server
10.0.1.3   - Reserved for future use
10.0.1.255 - Broadcast address (không dùng trong VPC)

2. Subnet Architecture

Public vs Private Subnet

┌─────────────────────────────────────────────────────────┐│VPC││┌─────────────────────┐┌─────────────────────────┐│││PublicSubnet││PrivateSubnet││││││││││┌─────────────┐││┌─────────────────┐│││││WebServer││││Database││││││(PublicIP)││││(PrivateIP)│││││└─────────────┘││└─────────────────┘││││││││││││▼││▼││││Route:0.0.0.0/0││Route:0.0.0.0/0││││→InternetGW││→NATGateway│││└─────────────────────┘└─────────────────────────┘││││││▼▼││┌──────────────┐┌──────────────┐│││InternetGW││NATGateway│││└──────────────┘└──────────────┘│└─────────────────────────────────────────────────────────┘

Điều kiện để Subnet là Public

  1. Có route đến Internet Gateway
  2. Instances có Public IP hoặc Elastic IP

3. Route Tables

Cấu trúc Route Table

Destination     Target          Status    Propagated
-----------     ------          ------    ----------
10.0.0.0/16     local           Active    No
0.0.0.0/0       igw-xxxxx       Active    No

Route Priority

  • Most specific route wins (longest prefix match)
  • 10.0.1.0/24 ưu tiên hơn 10.0.0.0/16

Các loại Targets

TargetMô tả
localTraffic trong VPC
igw-xxxInternet Gateway
nat-xxxNAT Gateway
vgw-xxxVirtual Private Gateway
tgw-xxxTransit Gateway
pcx-xxxVPC Peering Connection
vpce-xxxVPC Endpoint

4. Internet Gateway (IGW)

Đặc điểm

  • Horizontally scaled, redundant, highly available
  • Một VPC chỉ attach được 1 IGW
  • Perform NAT cho instances có public IP

Các bước để internet access

  1. Attach IGW vào VPC
  2. Thêm route 0.0.0.0/0 → IGW trong route table
  3. Associate route table với subnet
  4. Instances cần public IP

5. NAT Gateway vs NAT Instance

So sánh

FeatureNAT GatewayNAT Instance
AvailabilityHighly available trong AZTự manage
BandwidthUp to 100 GbpsPhụ thuộc instance type
MaintenanceManaged by AWSTự manage
Security GroupsKhông hỗ trợHỗ trợ
Bastion hostKhôngCó thể
CostTheo giờ + dataInstance cost

NAT Gateway Best Practice

┌─────────────────────────────────────────────┐│VPC││┌──────────────┐┌──────────────┐│││AZ-1a││AZ-1b││││┌──────────┐││┌──────────┐│││││NATGW1││││NATGW2│││││└──────────┘││└──────────┘││││↑││↑││││┌──────────┐││┌──────────┐│││││Private││││Private││││││Subnet││││Subnet│││││└──────────┘││└──────────┘│││└──────────────┘└──────────────┘│└─────────────────────────────────────────────┘→MỗiAZcóNATGatewayriêngđểtăngavailability

6. Security Groups vs NACLs

So sánh chi tiết

FeatureSecurity GroupNACL
LevelInstance (ENI)Subnet
StateStatefulStateless
RulesAllow onlyAllow & Deny
EvaluationAll rulesRules by number
DefaultDeny all inboundAllow all

Stateful vs Stateless

Security Group (Stateful):
Request:  Inbound port 80 ALLOWED → Response auto allowed
Response: Outbound auto allowed

NACL (Stateless):
Request:  Inbound port 80 ALLOWED
Response: Outbound ephemeral ports MUST be explicitly allowed

Ephemeral Ports

Linux: 32768-65535
Windows: 49152-65535
NAT Gateway: 1024-65535

7. VPC Flow Logs

Các level capture

  1. VPC level: Tất cả ENIs trong VPC
  2. Subnet level: Tất cả ENIs trong subnet
  3. ENI level: Specific ENI

Destinations

  • CloudWatch Logs
  • S3 bucket
  • Amazon Data Firehose (cũ: Kinesis Data Firehose)

Flow Log Record Format

<version> <account-id> <interface-id> <srcaddr> <dstaddr>
<srcport> <dstport> <protocol> <packets> <bytes>
<start> <end> <action> <log-status>

Phần 2: EC2 và Auto Scaling Review

1. EC2 Instance Types

Naming Convention

m5.xlarge│││││└──Size:nano,micro,small,medium,large,xlarge,2xlarge...│└──────Generation:sốcàngcaocàngmới└────────Family: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%├────────────────┐│Burst│←Sửdụngcredits20%├────────────────┼──────────────│Baseline│←Earncredits0%└────────────────┴──────────────→TimeKhihếtcredits:-T3Standard:Bịgiớihạnởbaseline-T3Unlimited:Tiếptụcburst,trảthêmphí

2. EC2 Pricing Models

So sánh các pricing models

ModelDiscountCommitmentBest For
On-Demand0%NoneShort-term, unpredictable
Reserved1yr tới ~40%, 3yr tới ~72%1 or 3 yearsSteady-state workloads
Savings PlansCompute tới 66%, EC2 Instance tới 72%1 or 3 yearsFlexible compute usage
Spottới 90%NoneFault-tolerant, flexible
Dedicated HostVariesPer hostLicensing, compliance

Bộ số discount dùng thống nhất trong khoá: Standard RI 3yr tới 72%, Convertible RI 3yr tới 66%, Compute Savings Plans tới 66%, EC2 Instance Savings Plans tới 72%, Spot tới 90%. Chi tiết purchase options và Spot allocation ở Tuần 3 Ngày 1 (Phần 1).

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 66% 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,SameAZ││┌───┐┌───┐┌───┐│││EC2││EC2││EC2│││└───┘└───┘└───┘│└─────────────────────────┘Use:HPC,Low-latencyapps2.SPREAD(HighAvailability)┌─────┐┌─────┐┌─────┐│Rack1││Rack2││Rack3││┌───┐││┌───┐││┌───┐│││EC2││││EC2││││EC2│││└───┘││└───┘││└───┘│└─────┘└─────┘└─────┘Max:7instancesperAZUse:Criticalapps3.PARTITION(LargeDistributed)┌──────────┬──────────┬──────────┐│Partition1│Partition2│Partition3││┌───┐│┌───┐│┌───┐│││EC2│││EC2│││EC2││││EC2│││EC2│││EC2│││└───┘│└───┘│└───┘│└──────────┴──────────┴──────────┘Use:HDFS,Cassandra,Kafka

4. Auto Scaling Groups (ASG)

Components

┌─────────────────────────────────────────────────┐│AutoScalingGroup││││┌─────────────────┐┌─────────────────────┐│││LaunchTemplate││ScalingPolicies││││-AMI││-TargetTracking││││-InstanceType││-StepScaling││││-SecurityGrp││-SimpleScaling││││-UserData││-Scheduled│││└─────────────────┘└─────────────────────┘││││CapacitySettings:││-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

ScaleOutEvent│▼┌────────────┐Cooldown┌────────────┐│Add2Inst│────(300sec)─────►│Readyfor│└────────────┘│nextscale│└────────────┘Purpose:-Tránhscalequánhanh-Chờmetricsổnđị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:┌──────────────┐│LoadBalancer││50%50%│←LBnodemỗiAZnhận50%traffic└───┬──────┬───┘┌─────────┘└──────────┐┌────▼─────┐┌──────▼───────────────┐│AZ-1││AZ-2││┌──────┐││┌───┐┌───┐...┌───┐│││EC2││││EC2││EC2││EC2│││└──────┘││└───┘└───┘└───┘││1inst││9instances││=50%!││=50%/9≈5.6%/inst│└──────────┘└──────────────────────┘CÓCross-ZoneLoadBalancing:→Mỗiinstancenhận100%/10=10%,bấtkểAZnà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ếdầntừngbatch,luôngiữ≥9healthy┌─────────────────────────────────────┐│Terminate1(v1)→Launch1(v2)││→chờInstanceWarmup→batchtiếp│└─────────────────────────────────────┘│▼ASG10instances(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.

Phần 3: S3 và Storage Review

1. S3 Storage Classes

So sánh Storage Classes

ClassAvailabilityDurabilityMin DurationUse Case
Standard99.99%99.999999999%NoneFrequently accessed
Express One Zone99.95%99.999999999%1 hourUltra-low latency (single-digit ms), AI/ML training, request-heavy
Intelligent-Tiering99.9%99.999999999%NoneUnknown pattern
Standard-IA99.9%99.999999999%30 daysInfrequent access
One Zone-IA99.5%99.999999999%30 daysNon-critical, infrequent
Glacier Instant99.9%99.999999999%90 daysArchive, instant access
Glacier Flexible99.99%99.999999999%90 daysArchive, minutes-hours
Glacier Deep Archive99.99%99.999999999%180 daysLong-term archive

S3 Express One Zone (GA Nov 2023)

Storage class hiệu năng cực cao, được thiết kế cho workload đòi hỏi truy cập với độ trễ thấp nhất.

Đặc điểm chính:

  • Latency: single-digit millisecond (nhanh hơn S3 Standard 10x)
  • Throughput: hàng triệu request/giây trên mỗi bucket (single-digit ms first-byte latency)
  • Storage: chỉ trong một Availability Zone duy nhất (giảm latency, mất HA cross-AZ)
  • Pricing (sau đợt giảm giá 10/04/2025): storage ~$0.11/GB-tháng (us-east-1), tức khoảng 4.8x S3 Standard ($0.023); request rẻ hơn hẳn Standard — đợt 04/2025 giảm thêm storage 31%, PUT 55%, GET 85% và phí upload/retrieval theo GB 60%. Trade-off: storage đắt hơn nhiều, request rẻ → đáng tiền khi workload request-heavy với object nhỏ, không đáng tiền cho dữ liệu lưu lâu ít truy cập
  • Min storage duration: 1 giờ (so với 30 ngày của Standard-IA)
  • Bucket type: Directory bucket (cấu trúc khác bucket thường, dùng cho high-performance pattern)

Use cases:

  • AI/ML training data với hàng triệu small objects
  • High-frequency trading, real-time analytics
  • Interactive applications cần đọc/ghi tần suất cao
  • Workload có data có thể tái tạo (vì single-AZ → mất AZ = mất data)

Trade-off SAP-C02 hay hỏi:

  • Single-AZ → KHÔNG dùng cho mission-critical data (không có cross-AZ redundancy)
  • Storage cost cao → chỉ dùng khi latency/throughput thực sự quan trọng
  • Không hỗ trợ replication, versioning đầy đủ như S3 Standard
  • Phải dùng Directory bucket, không phải General-purpose bucket

S3 Intelligent-Tiering

┌────────────────────────────────────────────────┐│S3Intelligent-Tiering││││┌──────────────┐│││Frequent│←Objectsaccessed│││AccessTier│within30days││└──────┬───────┘│││Noaccess30days││▼││┌──────────────┐│││Infrequent│←Auto-moved│││AccessTier│(40%costsavings)││└──────┬───────┘│││Noaccess90days(opt-in)││▼││┌──────────────┐│││Archive│←Optionaltier│││AccessTier│(68%costsavings)││└──────┬───────┘│││Noaccess180days(opt-in)││▼││┌──────────────┐│││DeepArchive│←Optionaltier│││AccessTier│(95%costsavings)││└──────────────┘│└────────────────────────────────────────────────┘

Glacier Retrieval Options

TierGlacier FlexibleDeep ArchiveTime
Expedited$$N/A1-5 minutes
Standard$$3-5 hours / 12 hours
Bulk¢¢5-12 hours / 48 hours

2. S3 Lifecycle Policies

Example Policy

{
  "Rules": [
    {
      "ID": "Move to IA after 30 days",
      "Status": "Enabled",
      "Filter": {"Prefix": "logs/"},
      "Transitions": [
        {
          "Days": 30,
          "StorageClass": "STANDARD_IA"
        },
        {
          "Days": 90,
          "StorageClass": "GLACIER"
        }
      ],
      "Expiration": {
        "Days": 365
      }
    }
  ]
}

Lifecycle Flow

Day0Day30Day90Day365││││▼▼▼▼┌────────┐┌────────┐┌────────┐┌────────┐│Standard│────────►│IA│────────►│Glacier│─────────►│DELETE│└────────┘└────────┘└────────┘└────────┘

3. S3 Security

Access Control Methods

┌─────────────────────────────────────────────────┐│S3AccessControl│├─────────────────────────────────────────────────┤│1.BucketPolicies(Resource-based)││-JSONpolicyattachedtobucket││-Cross-accountaccess││││2.IAMPolicies(Identity-based)││-Attachedtousers,groups,roles││-Sameaccountonly││││3.ACLs(Legacy-khôngkhuyếnkhích)││-BucketACL/ObjectACL││││4.AccessPoints││-Simplifiedaccessmanagement││-Eachwithitsownpolicy│└─────────────────────────────────────────────────┘

Block Public Access

Account Level + Bucket Level Settings:
- BlockPublicAcls
- IgnorePublicAcls
- BlockPublicPolicy
- RestrictPublicBuckets

Best Practice: Enable all blocks unless explicitly needed

4. S3 Encryption

Encryption Types

Server-SideEncryption(SSE):┌─────────────────────────────────────────────────┐│SSE-S3(Amazonmanagedkeys)││-AWSmanageskeysentirely││-Header:x-amz-server-side-encryption:AES256│├─────────────────────────────────────────────────┤│SSE-KMS(AWSKMSmanagedkeys)││-Morecontroloverkeys││-AudittrailinCloudTrail││-Header:x-amz-server-side-encryption:aws:kms│├─────────────────────────────────────────────────┤│SSE-C(Customer-providedkeys)││-Customermanageskeys││-MustuseHTTPS││-Providekeywitheachrequest│└─────────────────────────────────────────────────┘Client-SideEncryption:-Encryptbeforeupload-Customermanageskeysentirely

Encryption at rest - Best Practice

Bucket Default Encryption:
{
  "Rules": [{
    "ApplyServerSideEncryptionByDefault": {
      "SSEAlgorithm": "aws:kms",
      "KMSMasterKeyID": "arn:aws:kms:region:account:key/key-id"
    },
    "BucketKeyEnabled": true  ← Giảm KMS API calls
  }]
}

5. S3 Performance

Baseline Performance

  • 3,500 PUT/COPY/POST/DELETE requests per second per prefix
  • 5,500 GET/HEAD requests per second per prefix

Multi-Part Upload

File Size Recommendation:
< 100 MB    → Single PUT
≥ 100 MB    → Multi-Part Upload (recommended)
> 5 GB      → Multi-Part Upload (required)

Benefits:
- Parallel uploads
- Pause and resume
- Begin upload before knowing final size

S3 Transfer Acceleration

WithoutTransferAcceleration:User(Vietnam)──────longdistance────────►S3(us-east-1)WithTransferAcceleration:User(Vietnam)──►EdgeLocation──AWSbackbone──►S3(us-east-1)(Singapore)

S3 Byte-Range Fetches

LargeFile(10GB)┌────┬────┬────┬────┬────┐│1│2│3│4│5│←Parallelbyte-rangerequests└────┴────┴────┴────┴────┘Usecases:-Paralleldownloads-Resumefaileddownloads-Getspecificportions(headersonly)

6. S3 Replication

Types

FeatureSame-Region (SRR)Cross-Region (CRR)
Use CaseLog aggregationCompliance, DR
LatencyLowHigher
RegionsSameDifferent

Requirements

  • Versioning enabled on both buckets
  • IAM permissions for replication
  • Objects mã hoá SSE-S3, SSE-KMS, DSSE-KMS hoặc SSE-C đều replicate được (SSE-KMS/DSSE-KMS phải bật trong replication rule và key policy cho phép replication role)

What's NOT replicated

  • Objects before replication enabled (dùng S3 Batch Replication để replicate object có sẵn)
  • Objects mà bucket owner không có quyền (object do account khác upload không có owner override)
  • Delete markers (optional to replicate)
  • Lifecycle rules actions

7. S3 Event Notifications

Destinations

S3Events───►Lambda├──►SNS├──►SQS└──►EventBridge(recommendedforcomplexrouting)

Event Types

  • s3:ObjectCreated:*
  • s3:ObjectRemoved:*
  • s3:ObjectRestore:*
  • s3:Replication:*

Câu hỏi ôn tập

  1. Một VPC có thể có bao nhiêu Internet Gateway?

    Xem đáp án

    1 IGW per VPC — 1-to-1 relationship. IGW là highly available (horizontally scaled, redundant) — không phải SPOF. Không thể attach 2 IGWs vào 1 VPC, và 1 IGW không thể attach vào 2 VPCs cùng lúc. Để có internet access cho nhiều VPCs, mỗi VPC cần IGW riêng hoặc dùng centralized egress VPC qua Transit Gateway.

  2. Sự khác biệt chính giữa Security Group và NACL là gì?

    Xem đáp án

    Security Group: instance-level (ENI), stateful (response auto-allowed), chỉ có Allow rules, evaluate all rules. NACL: subnet-level, stateless (cần explicit inbound + outbound rules), có cả Allow và Deny rules, rules evaluated theo số thứ tự. SG cho fine-grained instance control; NACL cho subnet-level block (ví dụ: block malicious IP với Deny rule — không thể làm với SG).

  3. Tại sao cần NAT Gateway ở mỗi AZ?

    Xem đáp án

    NAT Gateway là AZ-scoped — chỉ phục vụ instances trong AZ đó. Nếu chỉ có 1 NAT GW ở AZ-a: (1) Traffic từ private instances ở AZ-b phải cross-AZ đến AZ-a → tốn cross-AZ data transfer cost ($0.01/GB), (2) Nếu AZ-a fail → tất cả private instances mất internet. Mỗi AZ có NAT GW riêng = HA + không có cross-AZ cost overhead.

  4. Subnet nào được gọi là public subnet?

    Xem đáp án

    Subnet được gọi là public khi route table của nó có route 0.0.0.0/0 → IGW. Subnet tự nó không public hay private — routing table quyết định. Ngoài ra, instances trong public subnet cần Public IP hoặc Elastic IP để nhận inbound từ internet. Best practice: auto-assign public IP nên tắt, chỉ cấp Elastic IP cho instances thực sự cần.

  5. Flow Logs có thể gửi đến những destinations nào?

    Xem đáp án

    3 destinations: (1) CloudWatch Logs — real-time monitoring, Insights queries, alarms, (2) S3 bucket — long-term storage, Athena queries, rẻ hơn, (3) Amazon Data Firehose (tên cũ: Kinesis Data Firehose) — streaming đến Redshift, OpenSearch, S3. Có thể capture ở VPC level, Subnet level, hoặc ENI level. Một số traffic không capture: DHCP, IMDS, Amazon DNS (169.254.169.253).

  6. 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 (tới 66%), 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.

  7. 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.

  8. 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.

  9. 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.

  10. 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.

  1. 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í.

  1. 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).

  1. Object cần lưu trữ 30 ngày rồi chuyển Glacier, chọn class nào?
Xem đáp án

Standard cho 30 ngày đầu (không có minimum duration), sau đó transition sang Glacier Instant Retrieval hoặc Glacier Flexible Retrieval (minimum 90 ngày). Nếu biết trước pattern này, cấu hình S3 Lifecycle rule: STANDARD → GLACIER sau 30 ngày. Lưu ý: Standard-IA có minimum 30 ngày — không tiết kiệm nếu object < 30 ngày.

  1. Sự khác biệt giữa SSE-S3 và SSE-KMS?
Xem đáp án

SSE-S3: AWS quản lý keys hoàn toàn, không có audit trail riêng, miễn phí, không thể control key rotation. SSE-KMS: dùng KMS key loại customer managed key, mỗi operation tạo CloudTrail entry (audit trail), có thể set key rotation policy, có thể revoke key (block access ngay lập tức), có phí KMS API calls. Compliance environments cần SSE-KMS cho data access audit trail.

  1. Khi nào nên dùng S3 Transfer Acceleration?
Xem đáp án

Khi upload từ địa lý xa bucket Region — ví dụ upload từ Vietnam lên us-east-1. Transfer Acceleration route qua Edge Location gần nhất → AWS backbone network → bucket, thay vì đi toàn bộ qua public internet. Hiệu quả nhất cho: uploads > 1 GB từ distance > 1,000 km, mobile apps global, content ingestion từ nhiều continents. Tốc độ test tại: s3-accelerate-speedtest.s3-accelerate.amazonaws.com.

  1. S3 Replication có replicate delete markers không?
Xem đáp án

Tùy cấu hình. Mặc định: replication rules không replicate delete markers (S3 chủ ý không tự động propagate deletes để bảo vệ). Bạn có thể bật "Delete marker replication" trong replication rule configuration để replicate delete markers. Permanent deletes (delete specific version) không bao giờ replicate — designed để bảo vệ destination từ accidental/malicious deletes ở source.

  1. Minimum object size cho Multi-Part Upload recommendation?
Xem đáp án

AWS khuyến nghị 100 MB — objects lớn hơn nên dùng Multipart Upload. Bắt buộc dùng khi object > 5 GB (single PUT limit). Lợi ích của Multipart: (1) Upload parallel (nhanh hơn), (2) Resumable (resume khi mất kết nối), (3) Retry failed parts mà không restart toàn bộ. Nếu upload fail giữa chừng, cần lifecycle rule để abort incomplete multipart uploads tránh tốn storage.

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

Phần 1: VPC Fundamentals Review

  • Tạo VPC với 2 public và 2 private subnets
  • Configure NAT Gateway cho private subnets
  • Tạo Security Group và test connectivity
  • Enable VPC Flow Logs

Phần 2: EC2 và Auto Scaling Review

  • 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

Phần 3: S3 và Storage Review

  • Tạo bucket với lifecycle policy
  • Enable versioning và test delete/restore
  • Configure cross-region replication
  • Test S3 event notifications với Lambda

Tài liệu tham khảo


Bài tiếp theo →