devHọc Dev
EN
Bài học

Tuần 3 - Ngày 3: Database & Analytics (lựa chọn database, RDS/Aurora, DynamoDB, Analytics)

Tuần 3 – Ngày 3

Bài này gộp 4 chủ đề: Database Options, RDS & Aurora Deep Dive, DynamoDB Deep Dive, Data Analytics Services.

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

  • So sánh các database services
  • Hiểu khi nào dùng database nào
  • Nắm vững database scaling patterns
  • Phân biệt RDS Multi-AZ (HA) với Read Replicas (scale/DR) và biết giới hạn từng engine
  • Hiểu khi nào cần RDS Proxy (connection pooling cho Lambda/serverless)
  • Nắm Aurora Serverless v2, Aurora Cloning và các thông số cập nhật 2024–2025
  • Chọn đúng capacity mode (Provisioned vs On-Demand) theo traffic pattern và chi phí
  • Phân biệt GSI vs LSI và hiểu tác động throttling
  • Nắm DAX, Transactions, TTL và single-table design pattern ở mức Professional
  • Nắm pipeline analytics chuẩn (Collect → Store → Process → Analyze → Visualize) và service tương ứng
  • Phân biệt Kinesis Data Streams vs Data Firehose vs Managed Service for Apache Flink
  • Hiểu Redshift, Glue, Athena, Lake Formation ở mức chọn-đúng-service theo scenario

Phần 1: Database Options

1. Database Decision Tree

┌─────────────────────────────────────────────────────────┐│DATABASESELECTION││││Relational+ACID?││├──Yes→RDS,Aurora,AuroraDSQL│││├──MySQL/PostgreSQLcompatible→Aurora│││├──Oracle/SQLServer→RDS│││├──Multi-regionwrites(single-region││││primary,asyncreplica)→AuroraGlobal│││└──DistributedSQLmulti-regionACIDwrites│││(active-active,99.999%multi-region)│││→AuroraDSQL│││││Key-Value+Extremescale?││└──Yes→DynamoDB││├──Needstrongconsistency→DynamoDB││└──Needcaching→DAX││││Document?││└──Yes→DocumentDB(MongoDBcompatible)││││Graph?││└──Yes→Neptune││││In-memory?││└──Yes→ElastiCache(Redis/Memcached)││││Time-series?││└──Yes→TimestreamforInfluxDB││(LiveAnalyticsđóngkháchmớitừ06/2025)││││Ledger/Immutable?││└──Yes→AuroraPostgreSQL(ledgerpattern)││(QLDBđãEOL31/07/2025—trongoption││đềthimớichỉcònlàdistractor)││││Datawarehouse?││└──Yes→Redshift│└─────────────────────────────────────────────────────────┘

2. Aurora Advanced

Aurora Global Database

┌─────────────────────────────────────────────────────────┐│AURORAGLOBALDATABASE││││PrimaryRegion(us-east-1):││┌─────────────────────────────────────────────────┐│││PrimaryCluster││││├──WriterInstance││││└──ReaderInstances│││└─────────────────────────────────────────────────┘│││││AsyncReplication││(<1secondlag)│││││SecondaryRegion(eu-west-1):││┌─────────────────────────────────────────────────┐│││SecondaryCluster(Read-only)││││└──ReaderInstances││││││││Failover:<1minute(promotedtoprimary)│││└─────────────────────────────────────────────────┘││││WriteForwarding:Enablewritesinsecondary│└─────────────────────────────────────────────────────────┘

Aurora Serverless v2

Scaling: 0 ACU to 256 ACU
- Max 256 ACU (từ 10/2024; trước đó 128)
- Min 0 ACU với auto-pause (từ 11/2024;
  trước đó min 0.5 ACU)
- Auto-scales in seconds
- Pay per ACU-hour used

Use cases:
- Variable workloads
- Development/Test
- Multi-tenant applications

Lưu ý: Aurora Serverless v1 đã EOL 31/12/2024
— mọi scenario serverless Aurora giờ là v2.

Aurora DSQL (GA May 2025)

Aurora DSQL là distributed SQL serverless database PostgreSQL-compatible — khác hẳn Aurora Global Database thông thường ở chỗ hỗ trợ active-active multi-region writes với ACID đảm bảo.

┌──────────────────────────────────────────────────────────────┐│AURORADSQL││││Architecture:││-Serverless,noinstancetomanage││-Storagevàcomputedecoupledhoàntoàn││-PostgreSQLwire-protocolcompatible││││Multi-region:││-Active-activewrites(mỗiregionacceptwrite)││-Strongconsistency(ACIDtransactionscross-region)││-99.999%availabilitymulti-regionSLA││-Automaticconflictresolution(snapshotisolation)││││Pricing:││-Perrequest+perstorageGB││-Noinstancecost,noidlecost│└──────────────────────────────────────────────────────────────┘

Aurora DSQL vs Aurora Global Database:

Tiêu chíAurora DSQLAurora Global Database
Write topologyActive-active multi-regionSingle primary, async replicas (hoặc write forwarding)
Consistency cross-regionStrong (ACID)Eventual (~< 1s lag)
Failover RTONear-zero (đã active)< 1 minute
SLA99.999% multi-region99.99% region, 99.95% với failover
Schema/featurePostgreSQL subset (no triggers, FKs có hạn chế)Aurora full PostgreSQL/MySQL
PricingServerless per-requestPer instance + I/O
Use caseMulti-region financial / inventory / global SaaS cần ACIDMulti-region read-heavy + DR

Exam keyword:

  • "Multi-region SQL với active-active writes, strong consistency" → Aurora DSQL
  • "Global app cần ACID transaction cross-region, no downtime failover" → Aurora DSQL
  • "Existing Aurora workload, cần multi-region read replica + failover < 1 min" → Aurora Global Database (write forwarding nếu cần write từ region phụ)
  • "Cần feature PostgreSQL đầy đủ (triggers, extensions, foreign keys phức tạp)" → Aurora Global Database, KHÔNG phải DSQL (DSQL còn giới hạn feature)

3. DynamoDB Advanced

Global Tables

┌─────────────────────────────────────────────────────────┐│DYNAMODBGLOBALTABLES││││Multi-master,multi-region:││││┌──────────┐Active-Active┌──────────┐│││us-east-1│◄─────────────────►│eu-west-1││││(Write)││(Write)│││└──────────┘└──────────┘││▲▲││││││▼▼││┌──────────┐┌──────────┐│││ap-se-1││ap-ne-1││││(Write)││(Write)│││└──────────┘└──────────┘││││-Automaticconflictresolution(last-writer-wins)││-<1secondreplication│└─────────────────────────────────────────────────────────┘

DynamoDB Streams + Lambda

┌─────────────────────────────────────────────────────────┐│DYNAMODBSTREAMS││││DynamoDBTable│││││▼Changes(Insert,Update,Delete)││DynamoDBStream│││││▼EventSourceMapping││LambdaFunction│││││▼Reacttochanges││-UpdateElasticsearch││-Sendnotifications││-Aggregatedata│└─────────────────────────────────────────────────────────┘

4. ElastiCache Strategies

Caching Patterns

1. LAZY LOADING (Cache-Aside):
   - Read: Cache miss → Read DB → Write cache
   - Stale data possible

2. WRITE-THROUGH:
   - Write: Write DB + Write cache
   - Always consistent
   - Higher write latency

3. TTL:
   - Set expiration on cached data
   - Balance freshness vs performance

Valkey vs Redis OSS vs Memcached

FeatureValkeyRedis OSSMemcached
Data structuresYes (lists, sets...)Yes (lists, sets...)No
PersistenceYesYesNo
ReplicationYesYesNo
Multi-AZYesYesNo
Pub/SubYesYesNo
Giá so với Redis OSSThấp hơn 20% (node-based), 33% (Serverless)Mốc so sánhKhác mô hình
Use caseMặc định cho cache tương thích Redis, cost-effectiveWorkload đang chạy Redis OSSSimple caching, multi-threaded

ElastiCache for Valkey (GA 10/2024) là fork mã nguồn mở của Redis, tương thích API Redis OSS. Giá thấp hơn 20% với node-based và 33% với ElastiCache Serverless (tối thiểu lưu trữ 100 MB). Reserved node Redis OSS áp dụng được khi nâng cấp lên Valkey cùng instance family. Keyword đề thi: "most cost-effective cache tương thích Redis" → ElastiCache for Valkey; nâng cấp từ Redis OSS sang Valkey là in-place, không đổi code client.

Phần 2: RDS & Aurora Deep Dive

1. RDS Multi-AZ

┌─────────────────────────────────────────────────────────┐│RDSMULTI-AZ││││┌─────────────────┐┌─────────────────┐│││AZ-a││AZ-b││││┌─────────┐││┌─────────┐│││││Primary│───┼────┼──►│Standby││││││(Active)││Sync││(Passive)│││││└─────────┘│Repl│└─────────┘│││└─────────────────┘└─────────────────┘││││Failovertriggers:││-Primaryinstancefailure││-AZfailure││-Instancetypechange││-Manualfailover(forpatching)││││Failovertime:60-120seconds│└─────────────────────────────────────────────────────────┘

2. RDS Read Replicas

Số read replicas tối đa:
- Aurora: 15
- RDS MySQL/MariaDB/PostgreSQL: 15 (nâng từ 5 lên 15 năm 2022)
- RDS Oracle/SQL Server: 5

Cross-Region Read Replica:
- Async replication
- Different region for DR
- Can be promoted to standalone

Read Replica Use Cases:
1. Read scaling
2. Reporting/Analytics
3. DR (promote if needed)

3. RDS Proxy

┌─────────────────────────────────────────────────────────┐│RDSPROXY││││Problem:ManyLambdafunctions=Manyconnections││││┌──────────┐┌──────────┐┌──────────┐│││Lambda1││Lambda2││LambdaN│││└────┬─────┘└────┬─────┘└────┬─────┘│││││││└─────────────┼─────────────┘││▼││┌─────────────────┐│││RDSProxy│Connectionpooling│││(Managed)│Autofailover││└────────┬────────┘│││Limitedconnections││▼││┌─────────────────┐│││RDS/Aurora│││└─────────────────┘│└─────────────────────────────────────────────────────────┘

4. Aurora Features

Aurora Serverless v2

Scaling:
- Min: 0 ACU (auto-pause, từ 11/2024;
  trước đó min 0.5 ACU)
- Max: 256 ACU (từ 10/2024; trước đó 128)
- Scale in seconds

Pricing:
- Per ACU-hour
- Storage separate

Use cases:
- Variable workloads
- Dev/Test
- Multi-tenant SaaS

Aurora Machine Learning

Integrate with ML services from SQL:
- SageMaker (custom models)
- Comprehend (sentiment)

SELECT
  review,
  aws_comprehend.detect_sentiment(review) as sentiment
FROM reviews;

5. Database Cloning

Aurora Cloning:
- Copy-on-write (instant)
- No storage copied initially
- Independent after creation

Use cases:
- Testing with production data
- Analytics without impacting prod
- Debugging

6. RDS/Aurora IAM Database Authentication

Thay vì lưu password trong ứng dụng, dùng IAM credentials để kết nối database — mỗi lần connect sinh một auth token ngắn hạn từ IAM.

┌─────────────────────────────────────────────────────────┐│IAMDATABASEAUTHENTICATIONFLOW││││┌──────────────┐1.generate-db-auth-token│││App(EC2/│─────────────────────────►IAM│││Lambdarole)│◄─────────────────────────││└──────┬───────┘2.Authtoken(TTL15phút,│││kýbằngSigV4)│││3.Connect:user+tokenthaypassword│││(BẮTBUỘCTLS/SSL)││▼││┌──────────────┐4.RDSverifytokenvớiIAM│││RDS/Aurora│→chophépkếtnối││└──────────────┘│└─────────────────────────────────────────────────────────┘

Điểm chính:

Khía cạnhChi tiết
Engine hỗ trợMySQL, PostgreSQL, MariaDB (cả RDS lẫn Aurora) — Oracle/SQL Server KHÔNG hỗ trợ
TokenSinh từ SDK/CLI: aws rds generate-db-auth-token, hết hạn sau 15 phút, chỉ dùng để mở connection (connection đang mở không bị cắt khi token hết hạn)
TransportBắt buộc TLS/SSL in-transit
IAM policyAction rds-db:connect, resource là db-user ARN: arn:aws:rds-db:region:account:dbuser:DbiResourceId/db_username
DB userVẫn phải tạo user trong database map với IAM: MySQL/MariaDB CREATE USER ... IDENTIFIED WITH AWSAuthenticationPlugin AS 'RDS'; PostgreSQL GRANT rds_iam TO user

Ví dụ IAM policy:

{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Action": "rds-db:connect",
    "Resource": "arn:aws:rds-db:ap-northeast-1:123456789012:dbuser:db-ABCDEFGHIJKL/app_user"
  }]
}

Lợi ích (Professional angle):

  • Không lưu credentials trong code/config — không cần rotate password thủ công
  • Tận dụng IAM: rotation tự động qua role, MFA, centralize access control cho nhiều database qua IAM policy
  • Audit qua CloudTrail

Exam keywords: "avoid storing database passwords", "use IAM credentials to connect to the database" → IAM Database Authentication. Phân biệt: nếu đề nói "rotate credentials automatically" cho engine không hỗ trợ IAM auth (Oracle/SQL Server) hoặc app cần password thật → Secrets Manager rotation.

7. Aurora Custom Endpoints

Aurora có 4 loại endpoint:

EndpointTrỏ tớiUse case
Cluster (writer)Primary instance hiện tạiWrite traffic; tự động chuyển khi failover
ReaderLoad-balance qua TẤT CẢ replicasRead traffic chung
Instance1 instance cụ thểDebug, ít dùng cho app
CustomNhóm CON các instance chỉ địnhTách workload theo nhóm replica

Custom endpoint cho phép chỉ định tập con instance — ví dụ 2 replica cỡ lớn (r6g.8xlarge) dành riêng cho analytics, các replica nhỏ cho app đọc thường — hai workload không ảnh hưởng lẫn nhau:

┌─────────────────────────────────────────────────────────┐│AURORACUSTOMENDPOINTS││││┌──────────┐││Cluster─────►│Writer│││endpoint└──────────┘││││CustomendpointCustomendpoint││"app-read""analytics"││┌─────────────────────┐┌───────────────────┐│││┌─────┐┌─────┐┌────┐││┌───────┐┌───────┐│││││Repl1││Repl2││Rep3││││Repl4││Repl5││││││small││small││smll││││r6g.8xl││r6g.8xl│││││└─────┘└─────┘└────┘││└───────┘└───────┘│││└─────────▲───────────┘└─────────▲─────────┘││││││AppqueriesAnalytics/Reporting││(OLTPreads)(heavyqueries)│└─────────────────────────────────────────────────────────┘

Lưu ý:

  • Sau khi tạo custom endpoint, thường không dùng reader endpoint nữa cho workload đó (reader endpoint vẫn load-balance qua TẤT CẢ replicas, kể cả nhóm analytics)
  • Membership định nghĩa theo static list (danh sách instance) hoặc exclusion list; instance mới thêm vào cluster có thể tự động join tuỳ cấu hình
  • Tối đa 5 custom endpoints/cluster

Exam keyword: "run analytics/reporting queries trên một subset replicas riêng, không ảnh hưởng read traffic của app" → Aurora custom endpoint (không phải reader endpoint, không cần tạo cluster mới).

Phần 3: DynamoDB Deep Dive

1. DynamoDB Capacity Modes

┌─────────────────────────────────────────────────────────┐│CAPACITYMODES││││PROVISIONED:││-DefineRCU/WCUupfront││-AutoScalingavailable││-Reservedcapacitydiscount││-Bestfor:Predictableworkloads││││ON-DEMAND:││-Payperrequest││-Nocapacityplanning││-~3.5xcostofprovisionedatsteadystate││(sauđợtgiảmgiáon-demand50%tháng11/2024)││-Bestfor:Unpredictable,newworkloads││││RCU:1RCU=1stronglyconsistentreadof4KB/sec││or2eventuallyconsistentreads││WCU:1WCU=1writeof1KB/sec│└─────────────────────────────────────────────────────────┘

2. Secondary Indexes

┌─────────────────────────────────────────────────────────┐│GLOBALVSLOCALSECONDARYINDEX││││LOCALSECONDARYINDEX(LSI):││-Samepartitionkey,differentsortkey││-Mustcreateattablecreation││-Max5pertable││-SharesRCU/WCUwithtable││││GLOBALSECONDARYINDEX(GSI):││-Differentpartitionkey(andsortkey)││-Cancreateanytime││-Max20pertable││-SeparateRCU/WCU(canthrottlebasetable!)│└─────────────────────────────────────────────────────────┘

3. DynamoDB Accelerator (DAX)

┌─────────────────────────────────────────────────────────┐│DAX││││Application│││││▼SDKcalls││┌─────────────┐│││DAXCluster│←Microsecondlatency│││(Cache)│││└──────┬──────┘│││Cachemiss││▼││┌─────────────┐│││DynamoDB│←Millisecondlatency││└─────────────┘││││Twocaches:││-Itemcache(GetItem,BatchGetItem)││-Querycache(Query,Scanresults)│└─────────────────────────────────────────────────────────┘

4. DynamoDB Transactions

TransactWriteItems:
- Up to 100 items
- Atomic (all or nothing)
- Consumes 2x WCU

TransactGetItems:
- Up to 100 items
- Consumes 2x RCU

Use cases:
- Financial transactions
- Gaming leaderboards
- Multi-item updates

5. Time To Live (TTL)

Auto-delete expired items:
- No extra cost
- Eventually deleted (within 48 hours)
- Define TTL attribute (epoch timestamp)

Use cases:
- Session data
- Temporary tokens
- Log cleanup

6. Patterns

Single Table Design

PK          | SK              | Data
------------+-----------------+--------
USER#123    | METADATA        | {name, email}
USER#123    | ORDER#001       | {order details}
USER#123    | ORDER#002       | {order details}
PRODUCT#A   | METADATA        | {product info}
ORDER#001   | PRODUCT#A       | {line item}

Benefits:
- Single query for all user data
- Reduced latency
- Cost optimization

Phần 4: Data Analytics Services

1. Analytics Services Overview

┌─────────────────────────────────────────────────────────┐│ANALYTICSPIPELINE││││Collect→Store→Process→Analyze→Visualize││││KinesisS3/EMR/Athena/QuickSight││DataRedshiftGlueRedshift││Firehose│└─────────────────────────────────────────────────────────┘

2. Amazon Kinesis

Kinesis Services

KINESIS DATA STREAMS:
- Real-time data streaming
- 1-365 days retention
- Replay capability
- Consumers: Lambda, Managed Flink, KCL apps

AMAZON DATA FIREHOSE (cũ: Kinesis Data Firehose):
- Load data to destinations
- Near real-time (buffer 0–900 giây; zero buffering hỗ trợ từ Dec 2023)
- Destinations: S3, Redshift, OpenSearch, Splunk
- No data retention (pass-through)
- Lưu ý: AWS đã đổi tên từ "Kinesis Data Firehose" → "Amazon Data Firehose" (2024). Đề thi có thể dùng cả hai tên, kiến thức giữ nguyên.

AMAZON MANAGED SERVICE FOR APACHE FLINK
(tên cũ: Kinesis Data Analytics, đổi tên 08/2023):
- Apache Flink on streaming data
- Real-time analytics
- Lưu ý: loại SQL application cũ đã bị ngừng
  (không tạo mới từ 10/2023; EOL đầu 2026) —
  đáp án hiện hành cho stream processing là Flink

KINESIS VIDEO STREAMS:
- Stream video from devices
- ML integration

Kinesis Shards

1 Shard capacity:
- Read: 2 MB/s, 5 transactions/s
- Write: 1 MB/s, 1000 records/s

Scaling:
- Shard splitting (scale up)
- Shard merging (scale down)

3. Amazon Redshift

┌─────────────────────────────────────────────────────────┐│REDSHIFT││││ClusterTypes:││├──Provisioned:RA3,DC2nodes││└──Serverless:Auto-scaling││││Features:││-Columnarstorage││-MPP(MassivelyParallelProcessing)││-Upto16PB││-RedshiftSpectrum(queryS3directly)││-FederatedQuery(RDS,Aurora)││-MLwithCREATEMODEL││││DistributionStyles:││-AUTO(recommended)││-EVEN(round-robin)││-KEY(bycolumnvalue)││-ALL(fullcopyoneachnode)│└─────────────────────────────────────────────────────────┘

4. AWS Glue

┌─────────────────────────────────────────────────────────┐│AWSGLUE││││Components:││├──GlueDataCatalog│││└──Metadatarepository│││││├──GlueCrawlers│││└──Auto-discoverschema│││││├──GlueETLJobs│││├──Spark(Python/Scala)│││└──PythonShell│││││├──GlueDataBrew│││└──Visualdatapreparation│││││└──GlueStudio││└──VisualETL│└─────────────────────────────────────────────────────────┘

5. Amazon Athena

Serverless SQL on S3:
- Pay per query ($5/TB scanned)
- Standard SQL (Presto)
- Integrates with Glue Data Catalog

Cost Optimization:
- Use columnar formats (Parquet, ORC)
- Partition data
- Compress data

Federated Query:
- Query across data sources
- RDS, DynamoDB, Redshift, on-prem

6. Lake Formation

┌─────────────────────────────────────────────────────────┐│LAKEFORMATION││││Centralizeddatalakemanagement:││││1.Ingestdatafromsources││2.StoreinS3(withformatting)││3.CatalogwithGlue││4.Securewithfine-grainedpermissions││5.Discoverandanalyze││││Security:││-Column-levelsecurity││-Row-levelsecurity││-Cell-levelsecurity││-Tag-basedaccesscontrol│└─────────────────────────────────────────────────────────┘

7. AWS Batch

Managed batch computing: submit job dạng container, Batch tự lo provisioning, scheduling và scaling — không quản lý cluster tay.

Thành phần chính

┌─────────────────────────────────────────────────────────┐│AWSBATCH││││├──JobDefinition│││└──Containerimage,vCPU/memory,IAMrole,│││retrystrategy(tốiđa10attempts)│││││├──JobQueue│││└──Priority—queueprioritycaođược│││scheduletrước;1queuemapnhiềuCE│││││└──ComputeEnvironment(CE)││├──Managed:Batchtựchọninstancetype+│││scaletheoqueuedepth││├──Unmanaged:tựquảnlýECScluster││└──Loạicapacity:EC2On-Demand/EC2Spot/││Fargate/FargateSpot│└─────────────────────────────────────────────────────────┘

Tính năng Professional-level

- Array jobs: fan-out 1 job definition thành hàng nghìn
  child job (tối đa 10,000) — mỗi child nhận index riêng
  (AWS_BATCH_JOB_ARRAY_INDEX), hợp xử lý per-file/per-shard
- Job dependencies: job B chạy sau khi job A SUCCEEDED
  (dựng DAG đơn giản không cần Step Functions)
- Multi-node parallel jobs: 1 job trải nhiều EC2 instance
  (HPC, distributed ML training) — không hỗ trợ Fargate/Spot
- Spot integration: CE dùng Spot (allocation strategy
  SPOT_CAPACITY_OPTIMIZED) + retry strategy tự resubmit
  khi bị reclaim → giảm ~70-90% chi phí batch
- Fargate: job nhỏ, khởi động nhanh, không quản lý AMI/EC2

Batch vs Lambda (vs EMR)

Tiêu chíLambdaAWS Batch
Thời gian chạyTối đa 15 phútKhông giới hạn
MemoryTối đa 10 GBTheo instance (hàng trăm GB+)
RuntimeRuntime hạn chế (hoặc container ≤10GB)Container bất kỳ
GPU / EBSKhôngCó (GPU instance, EBS volume)
Mô hìnhServerless hoàn toàn, event-drivenManaged infra, chạy trên EC2/Fargate
Chi phíPer-invocationEC2/Fargate (Spot rất rẻ)
  • So với EMR: EMR = managed big data framework (Spark/Hadoop/Hive) cho xử lý dữ liệu phân tán; Batch = chạy batch job container tuỳ ý không gắn framework nào.

Exam keywords

  • "long-running batch jobs", "jobs > 15 minutes" (Lambda không đủ) → AWS Batch
  • "GPU batch processing" (render, genomics, ML inference hàng loạt) → AWS Batch với GPU instance
  • "cost-effective" cho batch chịu được gián đoạn → Batch + Spot + retry

Pattern điển hình

S3event/EventBridgeschedule│(submitjob)▼┌──────────────┐┌─────────────────────────┐│JobQueue│───▶│ComputeEnvironment││(priority)││Managed—Spotfleet│└──────────────┘│scaletheoqueuedepth│└───────────┬─────────────┘│containerxửlý▼S3(kếtquảoutput)

Câu hỏi ôn tập

  1. Khi nào chọn DynamoDB vs RDS?

    Xem đáp án

    DynamoDB khi: (1) cần millisecond latency at any scale (10M+ req/s), (2) data model là key-value hoặc document, (3) schema không cố định hoặc thay đổi thường xuyên, (4) serverless/global scale, (5) không cần complex SQL joins. RDS khi: (1) cần ACID transactions phức tạp, (2) complex JOINs giữa nhiều tables, (3) reporting/analytics với SQL, (4) existing apps với relational schema, (5) team quen với SQL. Aurora = enhanced RDS cho scale và availability cao hơn.

  2. Aurora Global Database replication lag bao nhiêu?

    Xem đáp án

    Thường dưới 1 giây — Aurora Global Database dùng storage-level replication (không phải binlog) với dedicated replication infrastructure. Thực tế thường < 1 giây, trong tài liệu AWS cam kết thường < 1 giây cho "typical workloads". Failover (promote secondary): < 1 phút (managed failover). Đây là lý do Aurora Global Database phù hợp cho DR với RPO gần 0 và RTO < 1 phút.

  3. DynamoDB Global Tables là active-active hay active-passive?

    Xem đáp án

    Active-active — tất cả Regions đều có thể read và write đồng thời. Khác với nhiều DB replication là active-passive (chỉ primary write). Global Tables dùng last-writer-wins để resolve conflicts. Phù hợp cho: global applications cần low-latency writes từ nhiều continents, gaming leaderboards, user profiles. Design pattern: partition users theo Region (user từ Asia → write Asia table) để tránh conflicts.

  4. Redis vs Memcached khác nhau như thế nào?

    Xem đáp án

    Redis: persistence (RDB + AOF), replication, pub/sub, Sorted Sets, Streams, scripting, Multi-AZ failover — feature-rich. Memcached: đơn giản, multi-threaded (scale CPU cores), horizontal sharding, không có persistence — pure cache. Chọn Redis khi: cần persistence, replication, pub/sub, complex data types, HA. Chọn Memcached khi: pure caching đơn giản, cần multi-threading cho CPU-intensive cache operations, không cần persistence.

  5. Multi-AZ khác Read Replica như thế nào?

    Xem đáp án

    Multi-AZ: mục tiêu là HA — standby sync replication, không nhận read traffic (trừ Multi-AZ DB Cluster 2 readable standbys), failover tự động 60–120s, cùng endpoint. Read Replica: mục tiêu là read scaling / DR — async replication, nhận read traffic, có thể cross-region, promote thủ công thành standalone. Câu hỏi exam hay bẫy: "increase availability" → Multi-AZ; "offload reporting queries" → Read Replica; "DR sang region khác với RPO thấp" → cross-region read replica (hoặc Aurora Global Database).

  6. Số read replicas tối đa của từng engine?

    Xem đáp án

    Aurora: 15 replicas (chung storage volume, lag ~ms, có thể làm failover target theo priority tier). RDS MySQL/MariaDB/PostgreSQL: 15 (nâng từ 5 lên 15 năm 2022 — tài liệu cũ ghi 5 là lỗi thời). RDS Oracle/SQL Server: 5. Read replica RDS dùng engine-level async replication nên lag cao hơn Aurora.

  7. Khi nào cần RDS Proxy?

    Xem đáp án

    Khi có nhiều connection ngắn hạn làm cạn max_connections — điển hình là Lambda scale hàng nghìn concurrent executions cùng mở connection. RDS Proxy làm connection pooling managed, multiplexing, giảm failover time tới ~66% (giữ connection khi failover), hỗ trợ IAM auth + Secrets Manager. Keyword: "Lambda + RDS + too many connections" hoặc "reduce database failover time" → RDS Proxy.

  8. Aurora Cloning hoạt động thế nào và khác restore snapshot ra sao?

    Xem đáp án

    Cloning dùng copy-on-write trên shared storage layer — clone tạo gần như tức thì, không copy dữ liệu ban đầu, chỉ ghi page mới khi clone hoặc source thay đổi. Restore từ snapshot phải copy toàn bộ dữ liệu → chậm và tốn storage hơn. Dùng clone cho test trên production data, analytics ad-hoc, debugging. Giới hạn: clone trong cùng region (cross-account được qua RAM sharing).

  9. Ứng dụng trên EC2 cần kết nối Aurora MySQL mà "không lưu database password". Giải pháp và các bước cấu hình?

    Xem đáp án

    IAM Database Authentication. Các bước: (1) bật IAM DB auth trên cluster; (2) tạo DB user map với IAM: CREATE USER 'app_user' IDENTIFIED WITH AWSAuthenticationPlugin AS 'RDS' (PostgreSQL: GRANT rds_iam); (3) gắn IAM policy cho EC2 instance role với action rds-db:connect trên db-user ARN; (4) app gọi generate-db-auth-token lấy token 15 phút và connect qua TLS với token thay password. Chỉ hỗ trợ MySQL/PostgreSQL/MariaDB. Keyword: "avoid storing database passwords", "use IAM credentials to connect" → IAM DB auth.

  10. Team analytics chạy query nặng trên Aurora làm chậm read traffic của app. Làm sao tách 2 workload mà không tạo cluster mới?

Xem đáp án

Tạo Aurora custom endpoint: thêm 2 replica cỡ lớn dành riêng cho analytics và gom chúng vào 1 custom endpoint; app đọc qua custom endpoint khác (hoặc reader endpoint nếu đã exclude nhóm analytics — nhưng lưu ý reader endpoint mặc định load-balance qua TẤT CẢ replicas, nên thường tạo 2 custom endpoints và bỏ reader endpoint cho các workload này). Kết quả: query analytics chỉ chạy trên subset replicas chỉ định, không ảnh hưởng OLTP reads. Keyword: "reporting/analytics trên subset replicas riêng" → custom endpoint.

  1. Khi nào chọn On-Demand thay vì Provisioned?
Xem đáp án

On-Demand khi: traffic unpredictable/spiky, workload mới chưa có baseline, hoặc muốn zero capacity planning ("least operational overhead"). Provisioned khi: traffic ổn định/dự báo được — rẻ hơn ~3.5× ở steady state (sau đợt giảm giá on-demand 50% tháng 11/2024; trước đó chênh ~6–7×), có thể mua reserved capacity. Kết hợp Provisioned + Auto Scaling là middle ground cho traffic dao động có pattern.

  1. GSI khác LSI ở những điểm nào và GSI throttle base table khi nào?
Xem đáp án

LSI: cùng partition key, khác sort key; chỉ tạo lúc create table; max 5; share RCU/WCU với table; hỗ trợ strongly consistent read. GSI: partition key khác được; tạo bất kỳ lúc nào; max 20; RCU/WCU riêng; chỉ eventually consistent. Bẫy quan trọng: nếu GSI thiếu WCU, write vào base table bị throttle dù table còn capacity — vì mọi write phải propagate sang GSI. Provision GSI WCU ≥ base table WCU cho attribute được index.

  1. DAX phù hợp use case nào, không phù hợp use case nào?
Xem đáp án

Phù hợp: read-heavy, read-mostly workload cần microsecond latency (item cache cho GetItem, query cache cho Query/Scan), giảm RCU cost khi hot key được đọc lặp lại. Không phù hợp: workload write-heavy, cần strongly consistent reads (DAX chỉ serve eventually consistent), hoặc app không dùng SDK tương thích DAX. Nếu cần cache chung cho nhiều nguồn dữ liệu → ElastiCache thay vì DAX.

  1. TTL có tính phí không và độ trễ xoá là bao lâu?
Xem đáp án

TTL miễn phí (không tiêu WCU khi xoá). Item quá hạn bị xoá eventually — thường trong vòng vài ngày, không tức thì (docs: typically within 48 hours), nên filter expired items trong query nếu app nhạy cảm. Item bị TTL xoá xuất hiện trong DynamoDB Streams (dạng REMOVE với userIdentity là dynamodb.amazonaws.com) — pattern hay: TTL + Streams + Lambda để archive data hết hạn sang S3.

  1. Kinesis Data Streams khác Amazon Data Firehose như thế nào?
Xem đáp án

Data Streams: real-time (~ms), retention 1–365 ngày, replay được, consumer tự viết (Lambda, Managed Flink, KCL), phải quản lý shards (hoặc on-demand mode). Data Firehose: near real-time (buffer 0–900s), không retention (pass-through), fully managed load vào S3/Redshift/OpenSearch/Splunk, có transform bằng Lambda, zero admin. Keyword: "replay/multiple consumers/custom processing" → Streams; "load streaming data vào S3/Redshift với least operational overhead" → Firehose.

  1. Service nào cho real-time stream processing hiện nay và tên cũ của nó?
Xem đáp án

Amazon Managed Service for Apache Flink — tên cũ là Kinesis Data Analytics (đổi tên 08/2023). Chạy Apache Flink application cho windowed aggregation, anomaly detection, streaming ETL. Loại SQL application cũ đã ngừng (không tạo mới từ 10/2023, EOL đầu 2026) — nếu đề bài nói "SQL on streaming data" với option KDA SQL, đó là distractor lỗi thời; đáp án hiện hành là Flink.

  1. Làm sao giảm chi phí Athena?
Xem đáp án

Athena tính $5/TB scanned nên giảm lượng data scan: (1) columnar format (Parquet/ORC) — chỉ đọc cột cần, (2) partition theo date/region + partition projection, (3) compress (Snappy/GZIP), (4) SELECT đúng cột thay vì SELECT *, (5) dùng CTAS tạo bảng tối ưu từ raw data. Kết hợp thường giảm 90%+ chi phí — đây là câu "most cost-effective" kinh điển.

  1. Redshift Spectrum khác Athena ở điểm nào?
Xem đáp án

Cả hai đều query S3 trực tiếp qua Glue Data Catalog. Spectrum chạy từ Redshift cluster — JOIN được data S3 với bảng local Redshift, phù hợp khi đã có Redshift và cần mở rộng warehouse ra data lake. Athena serverless hoàn toàn, không cần cluster — phù hợp ad-hoc query, "occasional queries, pay per query". Nếu đề bài không có Redshift sẵn → Athena; có Redshift + cần join local data → Spectrum.

  1. Khi nào chọn AWS Batch thay vì Lambda cho batch processing?
Xem đáp án

Chọn AWS Batch khi job vượt giới hạn Lambda: chạy > 15 phút, cần > 10 GB RAM, cần GPU hoặc EBS volume, hoặc cần container/runtime tuỳ ý. Batch tự provisioning và scale Compute Environment theo queue depth, hỗ trợ array jobs (fan-out hàng nghìn job), job dependencies và Spot với retry tự động khi bị reclaim — "most cost-effective" cho batch chịu được gián đoạn. Lambda thắng khi job ngắn, event-driven, cần serverless hoàn toàn với zero infra. Nếu đề bài là big data với Spark/Hadoop → EMR, không phải Batch.

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

Phần 1: Database Options

  1. Aurora Serverless v2 auto-pause: tạo Aurora PostgreSQL Serverless v2 cluster với capacity range 0–4 ACU (min 0 để bật auto-pause). Để idle ~10 phút, quan sát metric ServerlessDatabaseCapacity về 0, rồi đo thời gian resume khi có connection mới. Ghi lại trade-off resume latency vs chi phí idle.

  2. DynamoDB Global Tables: tạo Global Table 2 regions, write cùng một item từ cả 2 region gần như đồng thời và quan sát last-writer-wins conflict resolution qua item cuối cùng. Rút ra vì sao nên partition user theo region.

  3. Caching pattern với ElastiCache: dựng Redis (Serverless hoặc node nhỏ), implement lazy loading + TTL trước một bảng RDS/DynamoDB; đo latency cache hit vs miss và thảo luận khi nào cần write-through.

Phần 2: RDS & Aurora Deep Dive

  1. Failover Multi-AZ: tạo RDS MySQL Multi-AZ (db.t3.micro), chạy reboot with failover, đo thời gian client mất kết nối và verify endpoint không đổi.

  2. RDS Proxy + Lambda: tạo RDS Proxy trước database trên, trỏ Lambda qua proxy endpoint với IAM auth; chạy 200 invocation đồng thời và so sánh số connection trên DB (SHOW PROCESSLIST) khi đi thẳng vs qua proxy.

  3. Aurora clone: tạo Aurora cluster nhỏ, insert dữ liệu mẫu, tạo clone và đo thời gian tạo; sửa dữ liệu trên clone và verify source không đổi.

Phần 3: DynamoDB Deep Dive

  1. So sánh capacity modes: tạo 2 table giống nhau (1 On-Demand, 1 Provisioned 5 RCU/5 WCU), chạy load test nhỏ vượt provisioned capacity và quan sát ThrottledRequests metric; ước tính chi phí tháng cho cùng workload steady 50 req/s trên cả 2 mode.

  2. GSI throttling: tạo GSI với WCU thấp hơn hẳn base table, ghi dồn dập và quan sát write vào base table bị throttle — xác nhận bẫy "GSI có thể throttle base table".

  3. TTL + Streams archive: bật TTL trên attribute epoch, bật Streams, gắn Lambda ghi item expired sang S3. Verify record REMOVE do TTL có userIdentity đặc trưng.

Phần 4: Data Analytics Services

  1. Firehose → S3 pipeline: tạo Firehose delivery stream đích S3 với dynamic partitioning theo ngày, gửi record mẫu bằng CLI (put-record), xem file đổ về S3 theo buffer interval.

  2. Athena tối ưu chi phí: upload dataset CSV (~100MB) lên S3, query bằng Athena và ghi lại "data scanned"; dùng CTAS convert sang Parquet + partition, chạy lại cùng query và so sánh lượng scan/chi phí.

  3. Glue Crawler + Catalog: chạy Glue Crawler trên bucket dataset ở bài 2, xem schema tự động vào Data Catalog và query qua Athena không cần tạo DDL tay.

Tài liệu tham khảo


Bài tiếp theo →