Luyện Phỏng Vấn IT — 2000+ Câu Hỏi Phỏng Vấn IT Có Đáp Án 2026
Cloud & AWS
Cloud Computing là mô hình cung cấp tài nguyên công nghệ thông tin (máy chủ, lưu trữ, mạng, phần mềm) qua internet theo mô hình trả-theo-dùng (pay-as-you-go), thay vì tự đầu tư hạ tầng vật lý.
IaaS (Infrastructure as a Service) cung cấp tài nguyên hạ tầng thô như máy ảo, mạng, lưu trữ — ví dụ AWS EC2, Azure VM; người dùng tự quản lý OS và runtime. PaaS (Platform as a Service) cung cấp nền tảng để deploy ứng dụng mà không cần quan tâm đến hạ tầng bên dưới — ví dụ AWS Elastic Beanstalk, Heroku, Google App Engine; developer chỉ cần push code. SaaS (Software as a Service) là phần mềm hoàn chỉnh chạy trên cloud, người dùng chỉ cần sử dụng qua browser — ví dụ Gmail, Salesforce, Jira.
Lựa chọn mô hình phụ thuộc vào mức độ kiểm soát cần thiết: IaaS linh hoạt nhất nhưng tốn công vận hành nhất, SaaS tiện lợi nhất nhưng ít tùy biến nhất.
Amazon EC2 (Elastic Compute Cloud) là dịch vụ cung cấp máy chủ ảo (virtual machines) trên AWS, cho phép khởi chạy, cấu hình và quản lý server với nhiều OS và cấu hình phần cứng khác nhau.
Instance type được nhóm theo họ: T-series (t3, t4g) là burstable general-purpose, phù hợp workload nhẹ, chi phí thấp nhất; M-series (m6i, m7g) là general-purpose cân bằng CPU/RAM, dùng cho web server, app server; C-series (c6i, c7g) tối ưu compute, dùng cho xử lý batch, encoding video; R-series (r6i) tối ưu memory, phù hợp database in-memory, Redis; P/G-series dùng cho GPU workload như ML training.
Pricing model gồm On-Demand (tính theo giây, tối thiểu 60 giây — linh hoạt nhất), Reserved Instances (cam kết 1-3 năm, giảm 30-60%), Spot Instances (dùng capacity dư, giảm đến 90% nhưng có thể bị terminate), và Savings Plans. Best practice: dùng Spot cho batch jobs, Reserved cho production baseline, On-Demand cho traffic spike.
Amazon VPC (Virtual Private Cloud) là mạng ảo riêng biệt, cô lập trong AWS cloud, cho phép bạn kiểm soát hoàn toàn môi trường mạng: chọn IP range (CIDR), tạo subnet, cấu hình route table, gateway.
Public subnet là subnet có route đến Internet Gateway (IGW), các resource trong đó (EC2 với public IP) có thể nhận kết nối từ internet trực tiếp — thường dùng cho load balancer, bastion host, NAT Gateway. Private subnet không có route trực tiếp ra internet; resource muốn ra internet phải đi qua NAT Gateway (một chiều, ra ngoài được nhưng không nhận được kết nối từ ngoài) — thường dùng cho app server, database, Lambda.
Phân tách giúp giảm attack surface: database không bao giờ expose trực tiếp ra internet, chỉ app server trong private subnet mới kết nối được tới DB. Best practice: mỗi AZ có 1 public + 1 private subnet; dùng VPC Flow Logs để audit traffic; dùng VPC Endpoint (PrivateLink) để kết nối AWS services (S3, DynamoDB) mà không cần ra internet.
Amazon Route 53 là dịch vụ DNS (Domain Name System) managed, highly available của AWS với SLA 100% uptime; tên gọi từ cổng DNS TCP/UDP 53.
Các routing policy:
- Simple routing — map domain tới một IP/resource, không có logic
- Weighted routing — phân phối traffic theo tỷ lệ phần trăm (vd: 90% v1, 10% v2 cho canary deployment)
- Latency-based routing — route đến region AWS có latency thấp nhất so với client
- Geolocation routing — route theo quốc gia/châu lục của client (dùng cho content localization, compliance data residency)
- Geoproximity routing — tương tự geolocation nhưng có thể shift traffic theo bias
- Failover routing — primary/secondary, tự động chuyển sang secondary khi health check fail
- Multi-value routing — trả về nhiều IP ngẫu nhiên, client tự chọn (load balancing cơ bản phía DNS)
Health Checks tích hợp cho phép Route 53 detect endpoint unhealthy và tự động failover. Route 53 Resolver cung cấp DNS resolution giữa on-premise và VPC qua Direct Connect/VPN.
Amazon CloudFront là dịch vụ CDN (Content Delivery Network) của AWS với hơn 450 edge locations trên toàn cầu; nó cache content (HTML, CSS, JS, images, video) tại edge gần người dùng, giảm latency và tải cho origin server.
- Cơ chế hoạt động: request đến edge location gần nhất → nếu cache HIT, trả về ngay; nếu cache MISS, fetch từ origin (S3, ALB, EC2, custom server) → cache lại theo TTL → trả về client.
- CloudFront hỗ trợ bảo mật: HTTPS end-to-end (TLS termination tại edge), Origin Access Control (OAC) để chỉ CloudFront mới access được S3 bucket (không expose S3 public), AWS WAF integration để filter request độc hại, Shield Standard miễn phí chống DDoS L3/L4, Shield Advanced cho L7 DDoS protection.
- Signed URLs/Cookies để restrict access cho nội dung premium.
- Cache behavior có thể cấu hình per path pattern (vd:
/api/không cache,/static/cache 1 năm). - CloudFront Functions và Lambda@Edge cho phép chạy code tại edge để modify request/response.
- Pricing dựa trên data transfer và request count.
AWS Lambda là dịch vụ serverless compute cho phép chạy code mà không cần quản lý server; bạn chỉ upload function code, Lambda tự handle provisioning, scaling, và availability.
- Lambda phù hợp cho: event-driven workload (S3 trigger, SQS consumer, API Gateway), task ngắn (<15 phút), traffic không đồng đều hoặc rất thấp, và khi muốn giảm operational overhead.
- Nên dùng EC2 khi cần kiểm soát OS/runtime, workload chạy liên tục 24/7, cần persistent storage local, hoặc cần network configuration phức tạp.
- Cold start xảy ra khi Lambda phải khởi tạo execution environment mới (init container, load code, khởi động runtime) — thường mất 100ms-1s tùy runtime; Java và .NET thường chậm hơn Node.js/Python.
- Giảm cold start bằng: dùng Provisioned Concurrency (giữ sẵn N instances ấm), chọn runtime nhẹ (Node.js, Python), giảm package size, tách cold-path code ra khỏi handler, dùng Lambda SnapStart cho Java.
- Chi phí Lambda tính theo số lần gọi + GB-seconds thực thi, miễn phí 1 triệu request/tháng.
Amazon ECS (Elastic Container Service) là dịch vụ container orchestration native AWS, đơn giản hơn, tích hợp chặt với các dịch vụ AWS khác (IAM, ALB, CloudWatch), phù hợp team không có Kubernetes expertise. Amazon EKS (Elastic Kubernetes Service) là managed Kubernetes, phù hợp khi team đã có K8s knowledge, cần ecosystem K8s (Helm, custom controllers), hoặc cần portability giữa cloud providers.
Fargate là serverless compute engine cho cả ECS và EKS, loại bỏ việc quản lý EC2 node — bạn chỉ định CPU/RAM per task, AWS tự scale; chi phí cao hơn EC2 mode nhưng không cần manage node lifecycle, security patching.
Nên chọn ECS Fargate khi: team nhỏ, muốn đơn giản hóa operations, workload không cần K8s features đặc biệt, và cost không phải ưu tiên hàng đầu. Nên chọn EKS khi: đang migrate từ on-premise K8s, cần stateful workload phức tạp, hoặc cần advanced scheduling (GPU, spot). Với EKS Fargate, không có persistent storage local và không hỗ trợ DaemonSets.
Amazon API Gateway là managed service cho phép tạo, publish, bảo vệ và monitor HTTP/WebSocket API ở scale lớn — cổng kết nối giữa client và backend (Lambda, EC2, hoặc bất kỳ HTTP endpoint).
REST API (v1) là loại cũ hơn, hỗ trợ đầy đủ tính năng: request/response transformation, API keys, usage plans, custom authorizers, caching; phù hợp enterprise API cần nhiều tính năng. HTTP API (v2) ra mắt 2019, đơn giản hơn, nhanh hơn (~60% latency thấp hơn), rẻ hơn (~70%) so với REST API; hỗ trợ JWT authorizer, Lambda proxy integration, CORS — phù hợp microservices hiện đại. WebSocket API cho realtime bidirectional communication.
Tích hợp Lambda: chọn Lambda Proxy Integration để API Gateway forward toàn bộ request (headers, body, query params) vào event object của Lambda; response Lambda phải có format {statusCode, headers, body}.
Bảo mật API bằng: Cognito User Pool authorizer, Lambda custom authorizer (kiểm tra JWT/API key tùy chỉnh), hoặc IAM authorization. Throttling mặc định 10,000 RPS per account, có thể tăng qua request. Pricing: HTTP API ~$1/triệu request, REST API ~$3.5/triệu request.
SG là stateful instance-level firewall; NACL là stateless subnet-level filter.
Security Group (SG) hoạt động ở cấp độ instance (ENI level), là stateful — khi cho phép inbound traffic, outbound response tự động được allow không cần rule riêng; chỉ có allow rules, không có deny rules; áp dụng cho EC2, RDS, Lambda (VPC mode), v.v.
Network ACL (NACL) hoạt động ở cấp độ subnet, là stateless — phải define cả inbound và outbound rules riêng biệt; có cả allow và deny rules; rule được evaluate theo thứ tự số (100, 200...), rule đầu tiên match sẽ áp dụng. Vì stateless, NACL phức tạp hơn để configure đúng — cần cho phép ephemeral ports (1024-65535) cho outbound responses.
Thực tế: Security Group là defense chính, được dùng cho mọi resource; NACL là defense thứ hai ở subnet level, dùng khi cần block toàn bộ subnet hoặc block IP/CIDR range cụ thể (ví dụ chặn IP tấn công DDoS nhanh). Best practice: principle of least privilege cho SG — chỉ mở port cần thiết, chỉ allow source cụ thể (không dùng 0.0.0.0/0 trừ khi cần public access).
ALB cho Layer-7 HTTP routing; NLB cho Layer-4 high-perf TCP/UDP; GWLB cho virtual network appliances.
Application Load Balancer (ALB) hoạt động ở Layer 7 (HTTP/HTTPS), hỗ trợ content-based routing (theo host header, path, query string, HTTP method, headers), WebSocket, HTTP/2, gRPC; tích hợp Cognito authentication, WAF, Lambda target; phù hợp cho web application, microservices, REST API.
Network Load Balancer (NLB) hoạt động ở Layer 4 (TCP/UDP/TLS), cực kỳ high performance (hàng triệu RPS, latency microseconds), static IP hoặc Elastic IP per AZ — quan trọng khi client cần IP cố định (whitelist firewall), preserve source IP; phù hợp cho gaming, IoT, financial trading, TCP-based protocol.
Gateway Load Balancer (GWLB) dùng cho deploy, scale và manage third-party virtual appliances (firewalls, IDS/IPS, deep packet inspection) — traffic đi qua appliance trước khi đến destination. Cross-zone load balancing: ALB bật mặc định (miễn phí), NLB tắt mặc định (tốn phí nếu bật). Sticky sessions: ALB dùng cookie, NLB dùng 5-tuple hash. Health check: ALB check HTTP status code, NLB check TCP/HTTP. Pricing: ALB tính LCU (Load Balancer Capacity Unit), NLB tính NLCU.
S3 có 7 storage class, từ Standard (hot) đến Glacier Deep Archive (cold compliance), mỗi loại tối ưu chi phí cho một access pattern khác nhau — lifecycle policy giúp tự động chuyển đổi và giảm bill.
Các storage class:
- S3 Standard ($0.023/GB) — high durability 11 nines, high availability 99.99%, dùng cho data truy cập thường xuyên
- S3 Intelligent-Tiering — tự động chuyển giữa frequent/infrequent/archive tiers, phù hợp khi không biết trước access pattern
- S3 Standard-IA ($0.0125/GB) — infrequent access, rẻ hơn nhưng có phí retrieval, dùng cho backup, disaster recovery
- S3 One Zone-IA ($0.01/GB) — chỉ lưu 1 AZ, rẻ hơn 20% nhưng rủi ro hơn
- S3 Glacier Instant Retrieval — archival với instant access
- S3 Glacier Flexible Retrieval — retrieval 1-12h
- S3 Glacier Deep Archive ($0.00099/GB) — rẻ nhất, retrieval 12-48h, phù hợp compliance archive
Lifecycle policy tự động transition object giữa storage class hoặc expire/delete theo thời gian — ví dụ: log files chuyển sang IA sau 30 ngày, Glacier sau 90 ngày, delete sau 365 ngày. S3 Object Lock (WORM) ngăn xóa/overwrite object, dùng cho compliance. Versioning bật để protect khỏi xóa nhầm nhưng tăng cost — dùng lifecycle để expire old versions.
Amazon DynamoDB là fully managed NoSQL key-value và document database với single-digit millisecond latency ở mọi scale, serverless (không quản lý server), tự động scale, tích hợp DAX (in-memory cache). DynamoDB phù hợp khi: schema flexible (JSON documents), access pattern đơn giản và predictable (query by partition key ± sort key), cần scale đến hàng triệu RPS, serverless architecture, session store, gaming leaderboard, IoT data.
Amazon RDS hỗ trợ MySQL, PostgreSQL, MariaDB, Oracle, SQL Server — managed service lo patching, backup, multi-AZ. RDS phù hợp khi: cần ACID transactions phức tạp, relationship giữa nhiều entity, ad-hoc query linh hoạt (complex JOINs), reporting, existing SQL expertise. Amazon Aurora là RDS-compatible engine tự xây dựng của AWS: Aurora MySQL/PostgreSQL nhanh gấp 3-5x so với MySQL/PostgreSQL gốc, auto-storage scaling đến 128TB, Aurora Serverless v2 scale theo fractional ACU, Aurora Global Database cho multi-region.
DynamoDB pricing: provisioned capacity (RCU/WCU) hoặc on-demand; RDS pricing theo instance size + storage. Anti-pattern cho DynamoDB: nhiều access pattern phức tạp, cần full-text search, cần reporting.
Amazon ElastiCache là dịch vụ managed in-memory caching, hỗ trợ Redis và Memcached, giúp giảm latency database và tăng throughput ứng dụng.
ElastiCache for Redis hỗ trợ data structures phong phú (strings, hashes, lists, sets, sorted sets, streams), persistence (RDB/AOF snapshots), replication (primary + read replicas), cluster mode (sharding tự động), pub/sub, Lua scripting, transaction; phù hợp cho session store, leaderboard, pub/sub, distributed locking, job queue. ElastiCache for Memcached đơn giản hơn, chỉ key-value string, multi-threaded (tận dụng multi-core tốt hơn), không có persistence hay replication, dễ horizontal scale; phù hợp khi chỉ cần simple object caching và horizontal scaling thuần túy.
Caching patterns:
- Cache-aside (lazy loading) — app check cache trước, miss thì query DB rồi populate cache
- Write-through — ghi vào cache và DB đồng thời, data luôn fresh nhưng write latency cao
- Write-behind (write-back) — ghi vào cache trước, async sync xuống DB, giảm write latency nhưng risk data loss
- Read-through — cache layer tự handle DB read khi miss
TTL đặt phù hợp tránh stale data; Cache Stampede problem giải quyết bằng mutex/probabilistic early expiration. ElastiCache Serverless (2023) tự scale capacity tự động.
Amazon EBS (Elastic Block Store) là block storage gắn vào EC2 instance, như ổ cứng ảo; chỉ gắn được vào 1 EC2 tại một thời điểm (trừ EBS Multi-Attach cho io1/io2), persist sau khi instance terminate (nếu không set DeleteOnTermination), replicated trong cùng AZ.
Loại EBS:
- gp3 (general purpose SSD, mặc định khuyến nghị, 3000 IOPS base, $0.08/GB)
- io2 Block Express (high IOPS cho database production, đến 256,000 IOPS, đắt hơn)
- st1 (throughput-optimized HDD, sequential read/write cho big data)
- sc1 (cold HDD, rẻ nhất, ít dùng)
Amazon EFS (Elastic File System) là managed NFS (Network File System) có thể mount đồng thời vào nhiều EC2 instances, thậm chí across AZ — phù hợp cho shared file storage, content management, home directories; auto-scale, không cần provision trước; Standard và Infrequent Access tiers; đắt hơn EBS (~$0.30/GB vs $0.08/GB).
Instance Store (ephemeral storage) là storage vật lý gắn trực tiếp vào host server, cực nhanh (NVMe SSD), không tốn phí riêng, nhưng mất data khi instance stop/terminate/fail — chỉ dùng cho temporary data, cache, scratch space. EBS snapshot backup lên S3, cross-region copy được.
Amazon Aurora là cloud-native relational database engine do AWS xây dựng từ đầu, tương thích MySQL và PostgreSQL. Architecture Aurora khác biệt: storage layer tách khỏi compute layer — storage tự động scale đến 128TB, replicate 6 copies trên 3 AZ (4/6 write quorum, 3/6 read quorum), healing tự động khi có node fail; điều này cho phép failover nhanh (<30s) và read replicas lag thấp (<100ms).
Throughput Aurora MySQL nhanh gấp 5x MySQL gốc, Aurora PostgreSQL nhanh gấp 3x PostgreSQL gốc nhờ shared storage architecture loại bỏ replication log shipping. Aurora Global Database: 1 primary region + tối đa 5 secondary regions, replication lag <1s, phù hợp disaster recovery và global read scaling — failover cross-region trong <1 phút.
Aurora Serverless v2 (2022) scale compute theo fractional ACU (Aurora Capacity Unit) từ 0.5 đến 128 ACU, scale up trong vài giây, phù hợp workload có spike bất thường, dev/test environment, multi-tenant SaaS. Aurora Serverless v2 không scale về 0 (khác v1); Aurora Serverless v1 có thể scale về 0 nhưng cold start lâu.
Aurora Machine Learning tích hợp SageMaker và Comprehend trực tiếp từ SQL. Backtrack feature cho Aurora MySQL cho phép rewind database về thời điểm bất kỳ trong 72h mà không cần restore snapshot.
Amazon Redshift là petabyte-scale data warehouse dựa trên columnar storage, tối ưu cho OLAP (Online Analytical Processing) — complex queries trên large datasets, reporting, BI. Khác biệt với OLTP (RDS): Redshift lưu data theo cột thay vì hàng, giúp compression tốt hơn và scan nhanh hơn khi chỉ cần một số cột trong query analytic.
Redshift cluster gồm: 1 leader node (parse/plan query, coordinate) + nhiều compute nodes (lưu data, thực thi query); Redshift Serverless tự động scale.
Distribution styles quyết định data phân phối thế nào:
- EVEN — phân phối đều qua tất cả nodes, tốt khi không có JOIN
- KEY — phân phối theo giá trị của column, tốt khi JOIN thường xuyên trên column đó (co-locate related data)
- ALL — copy toàn bộ table vào mọi node, chỉ dùng cho dimension tables nhỏ
- AUTO — Redshift tự chọn
Sort keys giúp range scan hiệu quả (như index trong traditional DB). Redshift Spectrum cho phép query data trực tiếp trên S3 (data lake) mà không cần load vào Redshift — pay per query. Materialized views cho pre-computed aggregation. Redshift phù hợp: business reporting, historical data analysis, data lake queries; không phù hợp: OLTP, nhiều small updates, NoSQL flexible schema.
Amazon SQS (Simple Queue Service) là managed message queue cho point-to-point async messaging: producer gửi message vào queue, consumer poll và xử lý; message tồn tại cho đến khi consumer xóa (đến 14 ngày); hỗ trợ Standard queue (at-least-once, best-effort ordering) và FIFO queue (exactly-once, strict ordering, 300 TPS base; high-throughput mode hỗ trợ đến 30,000 TPS); Dead Letter Queue (DLQ) cho message xử lý thất bại nhiều lần; Visibility Timeout ngăn 2 consumer cùng xử lý một message. Dùng SQS khi: decouple producer/consumer với different speed, buffer traffic spike, retry failed jobs.
Amazon SNS (Simple Notification Service) là pub/sub messaging: publisher gửi message vào topic, SNS fan-out đến nhiều subscribers (SQS queues, Lambda, HTTP endpoint, email, SMS) đồng thời; không lưu trữ message. Dùng SNS khi: broadcast notification, fan-out một event đến nhiều consumers.
Amazon EventBridge là event bus serverless thế hệ mới, hỗ trợ event routing dựa trên content (filter theo pattern JSON), tích hợp 200+ AWS services và SaaS (Salesforce, Datadog), Schema Registry, event replay, pipes; mạnh hơn SNS cho complex routing. Dùng EventBridge khi: event-driven microservices, cross-account event routing, integrate với SaaS, cần content-based routing.
Pattern phổ biến: SNS → SQS fan-out (SNS fan-out đến nhiều SQS queues để nhiều consumer xử lý độc lập).
Amazon Kinesis là family dịch vụ xử lý real-time streaming data.
Kinesis Data Streams (KDS): ingest và store streaming data tạm thời (1-365 ngày), nhiều consumer đọc cùng một stream độc lập (consumer group độc lập), throughput scale bằng shard (1 shard = 1MB/s in, 2MB/s out, 1000 records/s), dùng cho real-time analytics, cần nhiều consumer đọc cùng data, replay events.
Kinesis Firehose (Data Firehose): fully managed, không cần code consumer — tự động load streaming data vào S3, Redshift, OpenSearch, Splunk; transform data bằng Lambda inline; buffer size + interval để batch; không có replay/retention dài; đơn giản nhất khi chỉ cần pipe data vào data store.
Kinesis Data Analytics: chạy SQL hoặc Apache Flink trên streaming data real-time, tính aggregation trong window (tumbling/sliding), anomaly detection; pay per KPU (Kinesis Processing Unit).
Nên dùng Kinesis thay SQS khi: cần nhiều independent consumers đọc cùng stream, cần replay data, ordering quan trọng, real-time analytics, high-volume log ingestion (hàng GB/s). Nên dùng SQS khi: chỉ cần 1 consumer type, task queue pattern, cần exactly-once processing (FIFO), không cần replay. Kinesis đắt hơn SQS, SQS đơn giản hơn để dùng.
AWS Step Functions là serverless workflow orchestration service, cho phép coordinate nhiều Lambda functions và AWS services thành workflows có trạng thái (state machines), với visual diagram, error handling, retry logic, và audit trail tự động. Định nghĩa workflow bằng Amazon States Language (JSON/YAML); các state types: Task (invoke Lambda/service), Choice (conditional branching), Parallel (chạy branches song song), Map (iterate over array), Wait (delay), Pass, Succeed, Fail.
- Standard Workflows: tối đa 1 năm execution duration, exactly-once execution semantics, execution history stored 90 ngày để audit/debug, tính tiền per state transition ($0.025/1000 transitions); phù hợp cho long-running business processes, order fulfillment, human approval flows.
- Express Workflows: tối đa 5 phút, at-least-once semantics, không lưu execution history dài hạn (log vào CloudWatch), giá rẻ hơn ($1/triệu workflow executions + duration); phù hợp cho high-volume, short-duration workflows như IoT data processing, streaming data transformation.
Tích hợp trực tiếp với 200+ AWS services qua SDK integrations (không cần Lambda wrapper cho nhiều tác vụ). So với Lambda orchestration thủ công: Step Functions giải quyết error handling, retry, timeout, saga pattern cho distributed transactions dễ dàng hơn.
AWS CloudFormation là Infrastructure as Code (IaC) service, định nghĩa AWS resources bằng YAML/JSON templates, deploy và manage infrastructure theo stack; hỗ trợ rollback tự động khi deploy fail, drift detection, change sets (preview thay đổi trước khi apply), nested stacks, cross-stack references.
AWS CDK (Cloud Development Kit) là framework cho phép định nghĩa infrastructure bằng ngôn ngữ lập trình quen thuộc (TypeScript, Python, Java, Go, C#); CDK synthesize thành CloudFormation template, sau đó deploy bình thường.
CDK mạnh hơn CloudFormation thuần vì: code abstraction (loops, conditions, functions thay vì repeat YAML), Constructs library cung cấp high-level patterns (L2/L3 constructs như aws-ecs-patterns.ApplicationLoadBalancedFargateService), type safety và IDE autocomplete, unit testing infrastructure code bằng Jest.
Nên dùng CDK khi: team biết lập trình, infrastructure phức tạp cần abstraction, muốn reuse patterns qua constructs, cần generate nhiều tài nguyên tương tự. Nên dùng CloudFormation thuần khi: team không muốn học CDK, template đơn giản, cần maximum transparency. Terraform là alternative multi-cloud (không lock-in AWS), Pulumi tương tự CDK nhưng multi-cloud.
AWS IAM (Identity and Access Management) kiểm soát authentication (ai được phép vào) và authorization (được phép làm gì) trong AWS account.
Các định danh: IAM User — định danh cho người dùng cụ thể hoặc ứng dụng, có credentials dài hạn — không nên dùng cho ứng dụng chạy trên AWS. IAM Group — nhóm chứa Users, áp dụng policy chung cho cả nhóm. IAM Role — định danh không có credentials dài hạn, được assume bởi AWS service (EC2, Lambda), user khác, hoặc external identity (SAML, OIDC); credentials tạm thời qua STS (15 phút đến 12 giờ).
IAM Policy là JSON document định nghĩa permissions; có 2 loại: Identity-based policy (attach vào user/group/role) và Resource-based policy (attach vào resource như S3 bucket, SQS queue — cho phép cross-account access). Policy evaluation: explicit Deny > explicit Allow > implicit Deny.
Best practices:
- Không dùng root account (tạo admin IAM user)
- Bật MFA cho mọi user
- Principle of least privilege
- Dùng Roles thay vì access keys cho EC2/Lambda
- Rotate access keys định kỳ
- Dùng IAM Access Analyzer để phát hiện over-permissive policies
- Dùng Permission Boundary để giới hạn max permissions delegate được
Amazon CloudWatch là observability service tập trung cho monitoring AWS resources và applications.
- CloudWatch Metrics: time-series data points (CPU, memory, request count, latency); AWS services tự động gửi metrics (vd: EC2 CPUUtilization mỗi 5 phút, hoặc 1 phút với detailed monitoring); custom metrics từ ứng dụng qua PutMetricData API hoặc CloudWatch agent ($0.30/metric/month).
- CloudWatch Logs: collect, store và search log data; Log Groups (container) → Log Streams (từng instance/function); Metric Filters extract metrics từ log patterns; Log Insights cho ad-hoc query logs bằng query language; export sang S3 cho long-term retention; Subscription Filters stream logs real-time tới Lambda/Kinesis/OpenSearch.
- CloudWatch Alarms: trigger khi metric vượt threshold; actions: SNS notification, EC2 Auto Scaling, EC2 action (stop/reboot/terminate); Composite Alarms kết hợp nhiều alarms; Anomaly Detection dùng ML để tự động detect anomaly.
- CloudWatch Dashboards: visualize metrics và logs trên single pane; cross-account/cross-region dashboards.
Best practices: enable detailed monitoring cho production EC2, set up alarms cho critical metrics (error rate > 1%, P99 latency > 2s, CPU > 80%), dùng EMF (Embedded Metric Format) để gửi structured metrics từ Lambda logs, tạo custom dashboard cho each service, set log retention policy để kiểm soát cost.
Bảo mật theo layers (defense in depth):
Edge layer — CloudFront với AWS WAF để filter malicious requests (SQL injection, XSS, OWASP Top 10 rules), rate limiting, geo-blocking; Shield Standard (miễn phí, auto) chống DDoS L3/L4, Shield Advanced ($3000/month) cho L7 DDoS mitigation tự động với support team 24/7.
Network layer — VPC với public/private subnets, Security Groups strict, NACLs, VPC Flow Logs để audit traffic; không expose database ra public; dùng AWS Network Firewall cho stateful inspection.
Compute layer — EC2/Lambda trong private subnet, IMDSv2 (Instance Metadata Service v2) bắt buộc để chống SSRF, least privilege IAM roles, SSM Session Manager thay vì SSH (không cần port 22 mở).
Data layer — encrypt at rest bằng KMS (S3, RDS, DynamoDB), encrypt in transit (HTTPS, TLS 1.2+), Secrets Manager cho credentials, S3 Block Public Access account-level.
Identity layer — IAM least privilege, MFA, Cognito cho app authentication, no long-term credentials.
Monitoring — GuardDuty (threat detection ML-based, detect compromised EC2/credentials, crypto mining, unusual API calls), Security Hub (aggregate findings từ GuardDuty, Inspector, Macie, Config thành single dashboard với compliance score), AWS Config (resource configuration compliance, detect drift), CloudTrail (audit log mọi API call). Inspector — vulnerability scanning cho EC2 và Lambda packages tự động.
AWS KMS (Key Management Service) là managed service tạo và quản lý cryptographic keys (CMK — Customer Master Key, nay gọi là KMS Key); keys không bao giờ rời khỏi KMS hardware (FIPS 140-2 validated HSM); tích hợp hầu hết AWS services (S3, EBS, RDS, DynamoDB encryption at rest).
Envelope Encryption: dùng KMS để generate Data Encryption Key (DEK) — DEK encrypt plaintext data, sau đó chính DEK được encrypt bởi KMS Key (encrypted DEK lưu cùng data); khi decrypt, gửi encrypted DEK tới KMS để decrypt → dùng DEK để decrypt data; KMS chỉ decrypt DEK, không handle bulk data — giúp giảm latency và cost.
Key types:
- AWS managed keys: free, managed by AWS.
- Customer managed keys: $1/month/key + $0.03/10,000 API calls.
- Customer managed keys in CloudHSM: dedicated HSM.
AWS Secrets Manager lưu trữ và quản lý secrets (database passwords, API keys, OAuth tokens) có encrypt bằng KMS; tính năng nổi bật: automatic rotation (Lambda function tự đổi password DB theo schedule), versioning, cross-account access, audit via CloudTrail.
- Dùng Secrets Manager khi: cần rotate secrets tự động, cần audit trail, cần chia sẻ secret cross-account.
- Dùng Parameter Store (SSM) khi: lưu config đơn giản (không cần rotation), free tier (Standard parameters miễn phí, Advanced tốn phí).
Không bao giờ hardcode secrets trong code hay environment variables plaintext.
AWS X-Ray là distributed tracing service cho phép trace request path qua toàn bộ microservices architecture, identify performance bottleneck và debug errors trong distributed system.
- Concepts: Trace — toàn bộ journey của 1 request (end-to-end); Segment — công việc của 1 service trong trace; Subsegment — breakdown chi tiết trong segment (downstream call, DB query, external HTTP); Annotation — key-value indexed data để filter traces; Metadata — arbitrary data không indexed; Sampling — chỉ trace một tỷ lệ % requests để kiểm soát cost (mặc định 5% + 1 request/s đầu tiên).
- Instrument Node.js:
npm install aws-xray-sdk-core
// Prefer AWS SDK v3 with captureAWSv3Client:
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb');
const AWSXRay = require('aws-xray-sdk-core');
const ddb = AWSXRay.captureAWSv3Client(new DynamoDBClient({}));
// Capture HTTP outbound:
AWSXRay.captureHTTPsGlobal(require('https'));
// Express middleware:
app.use(AWSXRay.express.openSegment('MyApp'));Lambda tự động tích hợp nếu enable Active Tracing trong function config (Lambda tạo segment, bạn thêm subsegment).
- X-Ray Service Map visualize toàn bộ dependencies, response time, error rate từng node.
- X-Ray Analytics cho filter, compare, build group của traces.
- Tích hợp với CloudWatch ServiceLens để combine metrics, logs và traces trong 1 view.
- OpenTelemetry compatible qua AWS Distro for OpenTelemetry (ADOT) — cho phép switch provider sau.
AWS Well-Architected Framework là tập hợp best practices để thiết kế và vận hành cloud workload, gồm 6 pillars.
(1) Operational Excellence — khả năng vận hành và monitor hệ thống để deliver business value; practices: IaC cho mọi thứ, frequent small reversible changes, refine ops procedures frequently, anticipate failure, learn from all events.
(2) Security — bảo vệ data, systems và assets; practices: implement strong identity foundation (least privilege, MFA), enable traceability (CloudTrail, CloudWatch Logs), apply security at all layers, encrypt data in transit và at rest, prepare for security events.
(3) Reliability — khả năng recover từ failure và scale theo demand; practices: test recovery procedures, scale horizontally, stop guessing capacity (auto-scale), manage change in automation, auto-recover from failure.
(4) Performance Efficiency — dùng resources hiệu quả và maintain hiệu năng khi demand thay đổi; practices: democratize advanced technologies (dùng managed services), go global in minutes, use serverless architectures, experiment more often.
(5) Cost Optimization — tránh chi phí không cần thiết; practices: implement cloud financial management, adopt consumption model (pay-per-use), measure overall efficiency, stop spending money on undifferentiated heavy lifting, analyze and attribute expenditure.
(6) Sustainability — minimize environmental impact; practices: understand impact, establish sustainability goals, maximize utilization, use managed services, reduce downstream impact.
AWS cung cấp Well-Architected Tool (free) để review workload theo framework.
Multi-AZ: deploy resources trên nhiều Availability Zones trong cùng region (thường 2-3 AZ cách nhau vài chục km, latency 1-2ms); AWS RDS Multi-AZ tự động failover khi primary AZ fail (<30s), ALB tự động route traffic qua AZ available, Auto Scaling Group spread instances qua AZs; chi phí thêm ~2x cho redundant resources nhưng vẫn trong region; bảo vệ khỏi AZ failure (datacenter fire, power outage, connectivity).
Multi-Region: deploy trên nhiều AWS regions (cách nhau hàng nghìn km, latency 100-300ms inter-region); bảo vệ khỏi region-level disaster (cực hiếm nhưng xảy ra — us-east-1 có vài incident lớn), giảm latency cho global users, đáp ứng data residency requirements (GDPR — EU data phải ở EU).
Đánh đổi multi-region: phức tạp hơn nhiều (data replication lag, eventual consistency, split-brain), chi phí tăng 2-3x (replicate storage, data transfer cross-region $0.02/GB), operational overhead cao. Strategies: Active-Passive (traffic dồn vào primary region, secondary là warm standby chỉ dùng khi failover), Active-Active (traffic split đều hai region, cả hai phục vụ user).
Services hỗ trợ multi-region: Aurora Global Database, DynamoDB Global Tables, S3 Cross-Region Replication, Route 53 latency/failover routing, CloudFront. RTO/RPO quyết định strategy: multi-AZ đủ cho RTO<5 phút, multi-region cần khi RTO/RPO gần 0.
AWS định nghĩa 4 DR strategies theo thứ tự từ cost thấp/RTO cao đến cost cao/RTO thấp:
(1) Backup & Restore (RTO hours, RPO hours): chỉ backup data lên S3/Glacier, không duy trì environment; khi disaster xảy ra, restore từ backup và rebuild infrastructure — rẻ nhất nhưng downtime lâu nhất; phù hợp non-critical workload.
(2) Pilot Light (RTO 10-30 phút, RPO phút): maintain core components tối thiểu ở DR region luôn chạy (database replicated, AMIs ready) nhưng scale về 0 cho compute; khi fail, provision compute từ AMI, scale up database — nhanh hơn backup/restore nhưng vẫn cần thời gian provision.
(3) Warm Standby (RTO phút, RPO giây): scaled-down version của production environment luôn chạy ở DR region (minimum size Auto Scaling Group, database replica); khi fail, scale up ASG và promote database replica — gần như immediate failover.
(4) Multi-Site Active-Active (RTO near-zero, RPO near-zero): full production capacity chạy ở nhiều region đồng thời, Route 53 hoặc Global Accelerator phân phối traffic; đắt nhất, phức tạp nhất nhưng không downtime.
RTO (Recovery Time Objective) = thời gian từ lúc disaster đến lúc service restored; RPO (Recovery Point Objective) = lượng data tối đa có thể mất (bao lâu backup một lần). DR testing thường xuyên quan trọng như implement — Game Day exercises, chaos engineering.
Serverless architecture tận dụng managed services loại bỏ server management: Lambda (compute), API Gateway (HTTP routing), DynamoDB (database), S3 (storage), SQS/SNS/EventBridge (messaging), Cognito (auth), Step Functions (orchestration).
Pattern 1 — REST API: API Gateway → Lambda → DynamoDB; ưu điểm: không manage server, auto-scale, pay-per-request; nhược: cold start, 29s timeout API Gateway, stateless.
Pattern 2 — Event-driven microservices: services communicate qua EventBridge/SQS/SNS thay vì direct HTTP call; mỗi service là Lambda subscribe event, emit event sau khi xử lý; loosely coupled, independently deployable và scalable; phức tạp debugging (distributed transaction tracking cần X-Ray + correlation IDs).
Pattern 3 — Saga pattern cho distributed transactions: mỗi service local transaction + compensating transaction; Choreography-based saga: mỗi step publish event, next step subscribe và trigger — decentralized nhưng khó monitor; Orchestration-based saga: Step Functions orchestrate toàn bộ flow, mỗi bước có compensating step nếu fail — centralized, dễ debug hơn, preferred trên AWS.
Pattern 4 — BFF (Backend for Frontend): Lambda functions riêng tối ưu cho từng client type (mobile, web, third-party API).
Pattern 5 — CQRS + Event Sourcing: DynamoDB Stream trigger Lambda cập nhật read model.
Anti-patterns serverless: long-running computation (>15 phút), large file processing inline (dùng S3 trigger + async), database connection pooling (dùng RDS Proxy).
Cost optimization là một trong 6 pillars Well-Architected Framework.
Compute optimization:
- Chuyển On-Demand sang Reserved Instances/Savings Plans (tiết kiệm 30-60% cho baseline workload).
- Dùng Spot Instances cho batch/fault-tolerant workload (tiết kiệm đến 90%).
- Right-size instances (dùng Compute Optimizer để suggest instance type phù hợp).
- Tắt non-production environment ngoài giờ làm việc (Lambda + EventBridge scheduler).
Storage optimization:
- S3 Intelligent-Tiering cho data không rõ access pattern.
- Lifecycle policy chuyển sang IA/Glacier/Deep Archive.
- Enable S3 compression.
- Xóa unattached EBS volumes (thường quên tạo snapshot rồi delete instance).
- Xóa old EBS snapshots.
- Dùng gp3 thay gp2 (rẻ hơn 20% và IOPS cao hơn).
Data transfer optimization:
- Data transfer within region miễn phí.
- Cross-AZ $0.01/GB mỗi chiều (đặt DB và app cùng AZ cho non-HA workload).
- CloudFront giảm origin data transfer.
- VPC Endpoint loại bỏ NAT Gateway cost cho S3/DynamoDB access.
Database optimization: Aurora Serverless cho dev/test, DynamoDB on-demand cho sporadic traffic, ElastiCache giảm DB load và RDS cost.
Monitoring cost: AWS Cost Explorer phân tích spending trend, Budget Alerts khi vượt threshold, Cost Allocation Tags track by team/project, Trusted Advisor recommendations. Kiến trúc: serverless loại bỏ idle compute cost, managed services giảm operational labor cost.
AWS Auto Scaling tự động điều chỉnh số lượng instances/containers/Lambda concurrency dựa trên demand. Auto Scaling Group (ASG) cho EC2 có 4 scaling policies:
(1) Target Tracking Scaling — đơn giản nhất, maintain metric ở target value (vd: giữ CPU ở 50%), ASG tự tính toán scale out/in; phù hợp hầu hết use case:
aws autoscaling put-scaling-policy --policy-type TargetTrackingScaling --target-tracking-configuration file://config.json(2) Step Scaling — define steps tùy theo alarm breach magnitude (vd: CPU 60-70% → add 1, 70-80% → add 2, >80% → add 4); linh hoạt hơn nhưng cần tuning.
(3) Scheduled Scaling — scale vào thời điểm biết trước (mỗi sáng thứ 2-6 scale up, cuối ngày scale down); tốt khi traffic pattern predictable theo lịch.
(4) Predictive Scaling — ML phân tích historical pattern, dự báo load và pre-scale trước khi traffic đến — tránh lag của reactive scaling; launch instances 5-6 phút trước dự báo tăng.
Cooldown period tránh thrashing (mặc định 300s). Scale-in protection cho instances đang xử lý long-running jobs. ECS Service Auto Scaling tương tự ASG. Lambda Provisioned Concurrency giải quyết cold start cho Lambda. Application Auto Scaling cover ECS, DynamoDB, Aurora, Kinesis, SageMaker. Luôn test scaling behavior với load testing trước production.
Blue/Green deployment: duy trì hai environment giống nhau (Blue = production hiện tại, Green = version mới); deploy và test Green hoàn toàn, sau đó switch traffic 100% từ Blue sang Green (thường qua Route 53 DNS swap hoặc ALB listener rule update); rollback instant bằng switch lại Blue; Blue environment giữ lại một thời gian rồi mới terminate.
Implement Blue/Green trên AWS:
- EC2 + ALB: tạo Target Group mới cho Green, register instances mới, test qua staging URL, update ALB listener rule để point sang Green TG
- ECS: CodeDeploy blue/green cho ECS — tự động tạo task set mới, shift traffic theo schedule, rollback nếu alarm trigger
- Lambda: Lambda aliases với CodeDeploy, shift traffic theo Linear/Canary/AllAtOnce deployment config
Canary deployment là biến thể của blue/green: thay vì switch 100% ngay, shift dần một tỷ lệ nhỏ traffic sang version mới (5%, 10%, 25%, 50%, 100%) trong khoảng thời gian, monitor metrics/errors ở mỗi bước; nếu metric xấu thì rollback, nếu OK thì tiếp tục tăng. API Gateway có built-in canary release — shift % traffic sang new stage. Route 53 Weighted routing cho canary ở DNS level. CloudWatch alarms trigger automatic rollback khi error rate vượt threshold.
Canary an toàn hơn cho big changes, blue/green nhanh hơn khi confident với version mới.