devHọc Dev
EN
Bài học

Tuần 2 - Ngày 3: RDS, Aurora và DynamoDB

Tuần 2 – Ngày 3

Bài này gộp 3 chủ đề: RDS Fundamentals, Amazon Aurora, DynamoDB Basics.

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

  • Hiểu RDS architecture và supported engines
  • Phân biệt Multi-AZ vs Read Replicas
  • Nắm backup, snapshot, encryption
  • Biết khi nào dùng RDS vs DynamoDB vs Aurora
  • Hiểu Aurora architecture đặc biệt (6 copies storage)
  • Phân biệt Aurora Provisioned vs Serverless v2
  • Nắm Aurora Global Database
  • Biết Aurora endpoints và replication
  • Hiểu DynamoDB data model: table, item, attribute
  • Phân biệt Partition Key vs Composite Key
  • Nắm Provisioned vs On-Demand capacity
  • Hiểu Global Tables, DAX, Streams

Phần 1: RDS Fundamentals

1. Tổng quan RDS

Amazon RDS (Relational Database Service) = managed relational database service.

Supported Engines

  • MySQL
  • PostgreSQL
  • MariaDB
  • Oracle
  • SQL Server
  • Amazon Aurora (MySQL/PostgreSQL-compatible, AWS proprietary — chi tiết ngày mai)
  • IBM Db2 (added 2023)

RDS managed features

  • Automated provisioning, patching, backup
  • Monitoring (CloudWatch)
  • Multi-AZ high availability
  • Read replicas
  • Encryption at rest (KMS), in transit (TLS)
  • Maintenance windows
  • Không SSH vào underlying EC2 (managed)

2. RDS Architecture

Single-AZ deployment

┌────VPC────────────┐│││┌────AZ-a────┐│││││││RDS││││(Primary)││││││││Storage││││(EBS)│││└──────────────┘│└──────────────────────┘
  • NOT HA — nếu AZ fail, DB down
  • Dev/test environments

Multi-AZ deployment

┌────VPC────────────────────────────┐│││┌────AZ-a────┐┌────AZ-b────┐│││││││││Primary◄──┼──►Standby││││(Active)││(Syncrepl)││││││││││EBS││EBS│││└──────────────┘└───────────────┘│└───────────────────────────────────────┘
  • Synchronous replication từ primary sang standby
  • Automatic failover khi primary fail (~1-2 phút)
  • DNS endpoint không đổi, app tự reconnect
  • Standby không serve read traffic (chỉ HA backup)
  • Cost gấp đôi (2 instances chạy)

Multi-AZ DB Cluster (mới 2022, MySQL & PostgreSQL)

  • 1 writer + 2 reader instances ở 3 AZs
  • Readers có thể serve read traffic (khác Multi-AZ thường)
  • Failover nhanh hơn (~35s vs 1-2 phút Multi-AZ thường)
  • Higher cost (3 instances)

3. Read Replicas

Định nghĩa

Read Replica = bản copy read-only của primary DB, scale read workload.

Đặc điểm

  • Asynchronous replication từ primary
  • Có lag (vài giây thường, có thể tăng nếu primary busy)
  • Tối đa 15 read replicas per primary (MySQL/MariaDB/PostgreSQL/SQL Server — từ 10/2022; Oracle: 5; Aurora: 15)
  • Có thể promote thành standalone DB (break replication)
  • Có thể cross-region (CRR cho RDS)
  • Có thể cross-account (qua snapshot copy)

Use cases

  • Scale read workload (reporting, analytics)
  • DR scenario (cross-region read replica → promote)
  • Migration (test new region với replica before cutover)

Multi-AZ vs Read Replica

Multi-AZRead Replica
PurposeHAScale reads
ReplicationSynchronousAsynchronous
Serve readsNo (standby idle)Yes
FailoverAutoManual promote
AZDifferent AZSame/different AZ or Region
Cost impact2x+1x per replica

Cross-Region Read Replica

  • Replicate sang Region khác
  • Cross-region data transfer charges apply
  • Use case: DR, regional read scaling

4. RDS Storage

Volume types

  • gp3 (mặc định mới): General SSD
  • gp2 (legacy): General SSD tied to size
  • io1: Provisioned IOPS SSD
  • Magnetic (legacy, deprecated)

Storage scaling

  • Storage Autoscaling: tự động grow khi cần (max threshold do bạn set)
  • Modify storage: increase manually anytime (no downtime)
  • Không thể decrease (cần dump + restore vào DB mới)

Maximum storage

  • MySQL, MariaDB, PostgreSQL, Oracle: up to 64 TiB
  • SQL Server: up to 16 TiB
  • Ghi chú: từ 12/2025, Oracle/SQL Server có thể lên tới 256 TiB với additional storage volumes (chi tiết ngoài phạm vi thi)

5. RDS Backup

Automated Backups

  • Daily full backup + continuous transaction logs
  • Retention 0-35 days (default 7 days)
  • Stored in S3 (managed by AWS)
  • Point-in-Time Recovery (PITR): restore to any second within retention
  • Tự động delete khi DB deleted (trừ khi bạn snapshot manual trước)

Manual Snapshots

  • User-initiated, retain indefinitely until delete
  • Cross-region copy support
  • Cross-account share (qua KMS key sharing nếu encrypted)
  • Use for backup before major change, retain beyond 35 days

Restore process

  • Restore from backup/snapshot = tạo DB instance mới (không restore in-place)
  • Endpoint mới → cần update app
  • Có thể restore vào point-in-time (5-minute granularity)

Database Cloning (Aurora only)

  • Fast clone Aurora cluster (copy-on-write)
  • Use case: test environment với production data

6. RDS Encryption

At Rest

  • KMS encryption (CMK)
  • Apply ở instance creation (KHÔNG enable sau)
  • Bao gồm: storage, backups, snapshots, read replicas

Encrypt unencrypted RDS

  1. Create snapshot
  2. Copy snapshot với encryption enabled
  3. Restore DB from encrypted snapshot
  4. Migrate apps to new endpoint
  5. Delete old DB

In Transit

  • TLS/SSL connection
  • Engines support: MySQL, PostgreSQL, MariaDB, Oracle, SQL Server
  • Download CA cert từ AWS, configure client

Transparent Data Encryption (TDE)

  • Oracle, SQL Server only
  • Database-level encryption (additional layer)

7. RDS Security

Network Isolation

  • Deploy trong VPC, private subnet
  • Security Group control access port (3306, 5432, ...)
  • Không expose public unless absolutely needed

IAM Database Authentication

  • MySQL & PostgreSQL only
  • Use IAM tokens (15-min lifetime) thay password
  • No password management

Database Activity Streams (Oracle, SQL Server, PostgreSQL, MySQL)

  • Real-time stream activity logs to Kinesis
  • Audit trail cho compliance

Audit logs

  • Engine-specific audit logs gửi đến CloudWatch Logs

8. RDS Performance

Performance Insights

  • Visualize DB load và top queries
  • Free (with retention 7 days)
  • Paid (long-term retention)

Enhanced Monitoring

  • OS-level metrics (CPU per process, memory)
  • Granularity 1-60 sec
  • Costs $$ (CloudWatch logs)

Slow Query Logs

  • Engine-specific
  • Identify slow queries
  • Export to CloudWatch Logs

Instance class selection

  • db.t3/t4g: burstable, dev/test
  • db.m5/m6: general-purpose production
  • db.r5/r6: memory-optimized (in-memory cache, complex queries)
  • db.x2: high-memory (SAP HANA, in-memory analytics)

9. RDS Maintenance

Maintenance Window

  • Weekly time slot (30 min) cho AWS apply patch
  • Configurable (e.g., Sunday 3-3:30 AM)
  • Minor version auto-applied; Major version manual

Engine Version Upgrade

  • Minor upgrade: auto during maintenance window (configurable)
  • Major upgrade: manual (e.g., MySQL 5.7 → 8.0)
  • Test in staging first

10. RDS Proxy

Định nghĩa

RDS Proxy = managed connection pooler giữa app và RDS.

Lợi ích

  • Connection pooling: nhiều app connections share fewer DB connections
  • Failover faster: 60-70% giảm failover time
  • Serverless-friendly: Lambda (mỗi cold start mở connection mới) gây load lên DB
  • IAM auth integration

Use case

  • Lambda → RDS (avoid connection storms)
  • App với connection spikes
  • Faster failover for HA

Cost

  • $/vCPU-hour của proxy capacity

11. RDS vs Aurora vs DynamoDB (quick comparison)

RDSAuroraDynamoDB
TypeRelationalRelational (MySQL/PG compat)NoSQL (key-value, document)
ManagedYesYes (more so)Yes
Multi-AZStandby (idle)6 copies across 3 AZsAuto multi-AZ
Read scalingRead replicas (15; Oracle 5)Read replicas (15)Auto
PerformanceStandard3-5x MySQLSingle-digit ms
CostLowerHigherPay-per-use or provisioned
Use caseTraditional RDBHigh-perf RDBNoSQL, high-scale

12. RDS Connection Patterns

Pattern 1: Single-AZ with Snapshots

  • Dev/test
  • Daily snapshots
  • Cheap

Pattern 2: Multi-AZ Production

  • HA primary + standby
  • Automated failover
  • Standard production

Pattern 3: Multi-AZ + Read Replicas

  • Write to primary
  • Read traffic to replicas
  • Reporting workload separate

Pattern 4: Cross-Region DR

  • Primary in Region A
  • Cross-region read replica in Region B
  • Promote replica in DR scenario

Phần 2: Amazon Aurora

1. Tổng quan Aurora

Amazon Aurora = relational database AWS proprietary, MySQL & PostgreSQL compatible.

Đặc điểm độc đáo

  • Performance: 5x faster than MySQL, 3x faster than PostgreSQL (theo AWS)
  • Storage: Auto-scaling 10 GB → 128 TB
  • Replication: 6 copies of data across 3 AZs (built-in HA)
  • Failover: < 30 giây (vs 1-2 phút RDS Multi-AZ)
  • 15 read replicas (RDS cũng 15 từ 10/2022, riêng Oracle 5)
  • Continuous backup to S3 (no perf impact)
  • Database cloning (copy-on-write, instant)

Cost

  • ~20% more expensive than RDS standard
  • Trade-off: significantly better performance + features

2. Aurora Storage Architecture

6 copies across 3 AZs

┌───────────AZ-1───────────┐│StorageNode1││StorageNode2│Quorum:4/6forwrite└────────────────────────────┘Quorum:3/6forread▲│syncreplication│┌───────────AZ-2───────────┐│StorageNode3││StorageNode4│└────────────────────────────┘▲│┌───────────AZ-3───────────┐│StorageNode5││StorageNode6│└────────────────────────────┘

Self-healing

  • Continuous scanning, auto-repair corrupted blocks
  • Mất tối đa 2 copies vẫn ghi được (write quorum 4/6); mất tối đa 3 copies vẫn đọc được (read quorum 3/6)
  • AZ failure → no data loss, no write disruption

Storage cluster volume

  • Shared storage volume
  • All compute instances (writer, readers) đọc cùng storage
  • → Failover không cần copy data

3. Aurora Cluster Architecture

┌──────────────────────────┐│AuroraCluster│││Appwrite─►│WriterInstance││(Primary)││││││writes││▼││┌──────────────────┐│││SharedStorage││││(6copies,3AZ)│││└──────────────────┘││▲▲▲│││││││ReaderReaderReader││(R/O)(R/O)(R/O)│└──────────────────────────┘▲│Appreads

Components

  • Writer (Primary) Instance: handle writes
  • Reader Instances: serve reads, up to 15
  • Shared Storage: replicated 6 copies

Failover

  • Auto-promote reader → writer (< 30s)
  • Failover priority: configurable per reader (tier 0-15, lower wins)
  • DNS endpoint updates → app reconnects

4. Aurora Endpoints

4 loại endpoints

EndpointPurpose
Cluster Endpoint (Writer)Always points to primary, for write workload
Reader EndpointLoad-balance reads across all reader instances
Custom EndpointSubset of instances (e.g., reporting subset)
Instance EndpointSpecific instance (rarely used)

Example

my-cluster.cluster-xxx.us-east-1.rds.amazonaws.com           ← Writer
my-cluster.cluster-ro-xxx.us-east-1.rds.amazonaws.com        ← Reader (LB)
my-cluster.cluster-custom-xxx.us-east-1.rds.amazonaws.com    ← Custom
instance-1.xxx.us-east-1.rds.amazonaws.com                   ← Specific

5. Aurora Replication

Read Replicas (within Region)

  • Auto-scale 0-15 replicas
  • Async replication (sub-10ms lag typical)
  • Same shared storage → faster than RDS read replica
  • Reader endpoint load-balances

Aurora Global Database (Cross-region)

  • 1 primary region + up to 10 secondary regions (số cũ: 5 — đề thi có thể còn dùng)
  • Sub-second replication lag (much better than CRR)
  • Read-only replicas in secondary regions
  • Disaster recovery: promote secondary → primary in < 1 minute (RTO)
  • RPO < 1 second
Use case
  • Multi-region applications
  • DR with low RTO/RPO
  • Read scaling globally

Aurora Global Database Architecture

PrimaryRegion(us-east-1):├──Writerinstance──►writes└──Upto15readerinstances││Aurorareplication(sub-second)│▼SecondaryRegion(eu-west-1):└──Upto16read-onlyinstances└──Disaster:promote→becomenewprimary

Write Forwarding (Global Database)

  • Reader instance in secondary region can forward writes to primary
  • App treats secondary as local writer (with latency penalty)
  • Use case: multi-region writes without app complexity

6. Aurora Serverless v2

Định nghĩa

Aurora Serverless v2 = on-demand auto-scaling Aurora, scale instantly từ 0 ACU đến 256 ACU.

Đặc điểm

  • ACU (Aurora Capacity Unit): 2 GiB memory + CPU + networking
  • Min: 0 ACU với auto-pause (từ 11/2024; trước đó min 0.5 ACU, không scale to zero)
  • Max: configurable up to 256 ACU (nâng từ 128 cuối 2024)
  • Scale in seconds (vs minutes cho Provisioned)
  • Pay per ACU-hour consumed

v1 vs v2

Aurora Serverless v1Aurora Serverless v2
ScaleSlow (minutes), pauses to 0Fast (seconds), scale to 0 với auto-pause (từ 11/2024)
EngineMySQL 5.7, PostgreSQL 10MySQL 8, PostgreSQL 13+
Read replicasNoYes (up to 15)
Multi-AZNoYes
StatusDeprecated, removingCurrent (recommended)

Use case Serverless v2

  • Unpredictable workload
  • Intermittent traffic (dev/test, occasional spikes)
  • Multi-tenant apps with variable load
  • New app where size unknown

Use case Provisioned

  • Predictable steady workload
  • Cost-conscious (Reserved Instance discount)

7. Aurora Backup

Automated Backup

  • Continuous backup to S3 (no impact on performance)
  • Retention 1-35 days
  • PITR to any second within retention

Manual Snapshots

  • User-initiated, kept until deleted
  • Cross-region copy
  • Cross-account share

Database Cloning

  • Copy-on-write clone of cluster
  • Instant (no data copy initially)
  • Storage diverges as clones change
  • Use case: dev/test with prod data, what-if analysis
  • Cost: only diverged blocks

8. Aurora Backtrack (MySQL-compatible only)

Định nghĩa

"Undo" cluster to previous point in time without restoring from backup.

Đặc điểm

  • Max backtrack window: 72 hours
  • Fast (no restore involved)
  • In-place operation (no new cluster)
  • Cost: $/hour of backtrack window enabled

Use case

  • "Oops, I dropped wrong table" — backtrack 5 minutes
  • A/B testing rollback
  • Faster than restore from snapshot

9. Aurora Auto Scaling (Read Replicas)

Tính năng

  • Auto-scale number of read replicas based on:
    • Average CPU utilization
    • Average connections
  • Min/Max settings

Setup

Aurora Auto Scaling Policy:
  Target Metric: AverageCPUUtilization
  Target Value: 60%
  Min Replicas: 1
  Max Replicas: 8

10. Aurora Machine Learning Integration

Tính năng

  • Aurora MySQL/PostgreSQL invoke SageMaker hoặc Comprehend from SQL
  • Real-time inference in DB query
  • Use case: fraud detection, sentiment analysis trong query
SELECT product, predict_fraud(product, user_id, amount)
FROM transactions;

11. Cost Comparison Examples

Single-AZ RDS MySQL db.r5.large (16 GB RAM)

  • ~$0.24/hour = $176/month

Aurora MySQL db.r5.large (1 writer + 1 reader Multi-AZ)

  • ~$0.29/hour × 2 = ~$420/month
  • Storage: $0.10/GB-month (vs $0.115 for RDS gp3)

Aurora Serverless v2 (1-4 ACU average)

  • ~$0.12/ACU-hour × 2 avg × 730 hrs = $175/month
  • Pay only what you use

12. RDS vs Aurora Decision

Workload?│├──Heavyreadscaling(>5replicasneeded)│└──Aurora(upto15)│├──Need<30sfailover│└──Aurora│├──Multi-regionwithsub-secondRPO│└──AuroraGlobalDatabase│├──Variable/unpredictableload│└──AuroraServerlessv2│├──NeedMySQL/PostgreSQLspecifically(notOracle,SQLServer)│└──Aurora(compatible+faster)│├──NeedOracle/SQLServer│└──RDS(Aurorakhôngsupport)│├──Cost-sensitive,lowworkload│└──RDSSingle-AZ│└──Standardproduction,predictable└──RDSMulti-AZhoặcAurora(dependson$)

Phần 3: DynamoDB Basics

1. Tổng quan DynamoDB

Amazon DynamoDB = fully managed NoSQL key-value & document database.

Đặc điểm

  • Serverless: no servers to manage
  • Single-digit ms latency at any scale
  • Auto-scaling: handle millions of requests/sec
  • Multi-AZ replication built-in (3 copies)
  • NoSQL: no schema, flexible structure
  • HTTP API (no JDBC/connection-based)
  • Encryption at rest by default

Use cases

  • High-traffic web/mobile apps
  • Gaming leaderboards
  • IoT data ingestion
  • Real-time bidding
  • Shopping carts
  • Session storage
  • User profiles

Not for

  • Complex JOIN queries (NoSQL)
  • Strong relational integrity needs
  • Ad-hoc queries (need to design access patterns upfront)
  • BI / analytics (use Redshift)

2. Data Model

Hierarchy

Table├──Item(=rowinSQL)│├──Attribute(=column)││├──Name││└──Value(scalar,list,map,set)│└──...└──...

Example

Table: Users

Item 1:
{
  "UserId": "u-001",       // Partition Key
  "Name": "Alice",
  "Email": "alice@example.com",
  "Age": 30,
  "Interests": ["coding", "music"]    // List attribute
}

Item 2:
{
  "UserId": "u-002",
  "Name": "Bob",
  "Email": "bob@example.com",
  "Age": 25
  // Note: no "Interests" — schema-less!
}

Attribute types

  • Scalar: String, Number, Binary, Boolean, Null
  • Set: String Set, Number Set, Binary Set
  • Document: List, Map (nested structure)

Max sizes

  • Item size: 400 KB
  • Attribute name: 64 KB
  • Partition key: 2048 bytes (string), 38 bytes (number)
  • Sort key: 1024 bytes

3. Primary Key

2 loại

Simple Primary Key (Partition Key only)
  • 1 attribute uniquely identifies item
  • Hash function distributes items across partitions
PrimaryKey:UserId└──u-001└──u-002└──u-003
Composite Primary Key (Partition Key + Sort Key)
  • Partition Key + Sort Key combination must be unique
  • Items với same PK grouped together, sorted by SK
PrimaryKey:UserId+OrderIdItems:├──(u-001,order-100)├──(u-001,order-101)←Sameuser,differentorder├──(u-001,order-102)├──(u-002,order-200)└──(u-002,order-201)

Partition Key best practice

  • High cardinality (many distinct values) → spread evenly
  • Avoid hot partitions: don't use timestamp/sequential as PK
  • Common patterns: UserId, ProductId, SessionId, UUID

4. Read/Write Capacity Modes

Provisioned Capacity

  • Specify RCU (Read Capacity Units) và WCU (Write Capacity Units)
  • Pay for capacity reserved
  • Auto-scaling available (scale RCU/WCU based on utilization target)
Capacity calculation
  • 1 WCU = 1 write/sec for item up to 1 KB
    • Transactional write: 2 WCU per write
  • 1 RCU = 1 strongly-consistent read/sec for item up to 4 KB
    • Eventually consistent: 2 reads/sec per RCU
    • Transactional read: 2 RCU per read
Use case
  • Predictable traffic
  • Cost-optimization (Reserved Capacity option)

On-Demand Capacity

  • Pay per request ($/million reads, $/million writes)
  • No capacity planning — auto-handle any traffic
  • More expensive per request than provisioned
  • Instant scale (no need to provision)
Use case
  • Unpredictable traffic
  • New apps where traffic unknown
  • Spiky traffic (0 → millions in seconds)

Switching between modes

  • Provisioned → On-Demand: up to 4 times per rolling 24 hours; On-Demand → Provisioned: any time (tài liệu cũ: once every 24 hours)

5. Read Consistency Models

Eventually Consistent (default)

  • Read might return stale data (latest update not propagated yet)
  • Faster, cheaper
  • Lag typically < 1 second

Strongly Consistent

  • Read returns latest data (after writes)
  • Slower (higher latency)
  • 2x cost in RCU

When to use Strongly Consistent

  • Read after write must see update (e.g., post-payment check)
  • Financial transactions
# boto3 example
table.get_item(
    Key={'UserId': 'u-001'},
    ConsistentRead=True   # ← strongly consistent
)

6. Indexes

Local Secondary Index (LSI)

  • Same partition key as base table, different sort key
  • Created at table creation, cannot add later
  • Max 5 LSIs per table
  • Uses base table's capacity
Use case
  • Different sort orders for same PK
  • E.g., Orders sorted by date, by amount

Global Secondary Index (GSI)

  • Different partition key (và optional different sort key)
  • Can create anytime (no downtime)
  • Max 20 GSIs per table
  • Own provisioned capacity (separate RCU/WCU)
  • Eventually consistent only
Use case
  • Query by non-PK attribute
  • E.g., Users by Email (PK is UserId)

Example

Base Table:
PK: UserId, SK: OrderId

LSI:
PK: UserId, SK: OrderDate   ← same PK, different SK

GSI:
PK: ProductId, SK: OrderId  ← different PK

7. DynamoDB Streams

Định nghĩa

Streams = ordered log of item changes (insert, modify, delete) in table.

Đặc điểm

  • 24-hour retention
  • Near real-time (< 1 sec lag)
  • Enable per table
  • Compatible với Kinesis Data Streams (newer)

View types

  • KEYS_ONLY: only key attributes
  • NEW_IMAGE: entire new item
  • OLD_IMAGE: entire old item
  • NEW_AND_OLD_IMAGES: both

Use cases

  • Trigger Lambda on changes (CDC pattern)
  • Replicate to other databases
  • Audit trail
  • Aggregations / analytics
  • Notifications (SNS on item change)

8. DAX (DynamoDB Accelerator)

Định nghĩa

DAX = fully managed in-memory cache for DynamoDB, microsecond latency for reads.

Đặc điểm

  • Write-through cache: writes go through DAX to DynamoDB
  • 10x performance for cached reads
  • Compatible với DynamoDB API (no code change)
  • Multi-AZ cluster
  • TTL configurable (5 min default)

When to use DAX

  • Read-heavy workload (>80% reads)
  • Repeated reads of same items
  • Need sub-millisecond response

When NOT to use DAX

  • Write-heavy
  • Eventually consistent reads OK với regular DynamoDB
  • Strongly-consistent reads (DAX is eventually consistent)

Cost

  • DAX cluster (1 primary + readers): ~$0.04/hour per node

9. Global Tables

Định nghĩa

Global Tables = multi-region, multi-active replication for DynamoDB.

Đặc điểm

  • Active-active: write to ANY region, replicated to all others
  • Sub-second replication lag (typical)
  • Conflict resolution: last writer wins (based on timestamp)
  • Requires Streams enabled
  • Cost: charged per region capacity + cross-region data transfer

Use case

  • Multi-region apps with low-latency for global users
  • DR (any region can become primary)
  • Compliance (data in multiple regions)

Architecture

RegionA(us-east-1)◄────►RegionB(eu-west-1)││└────►RegionC(ap-southeast-1)(writetoany,replicatetoall)

10. DynamoDB Backups

Continuous Backup (PITR - Point in Time Recovery)

  • Enable per table
  • Restore to any second in last 35 days
  • No performance impact
  • Cost: $0.20/GB-month

On-Demand Backup

  • User-initiated full backup
  • Retain indefinitely
  • No performance impact
  • Used for compliance, long-term archive

Restore

  • Always restore to new table (cannot in-place)
  • Includes indexes (LSI, GSI), provisioned capacity, encryption settings

11. DynamoDB Transactions

ACID transactions

  • Up to 100 actions per transaction
  • Up to 4 MB data
  • Works across multiple tables in same region
  • 2x RCU/WCU cost vs regular reads/writes

Operations

  • TransactWriteItems: atomic write to 1+ items
  • TransactGetItems: atomic read of 1+ items

Use case

  • Financial transfers (debit + credit atomically)
  • Order processing (inventory + payment + confirmation)
  • Anything requiring "all or nothing"

12. TTL (Time to Live)

Định nghĩa

TTL = auto-delete items at specified expiry time.

Setup

  • Designate an attribute (e.g., ExpiresAt = epoch timestamp)
  • DynamoDB checks periodically (within 48 hours of expiry)
  • Free operation (no WCU charge)

Use case

  • Session storage (auto-cleanup expired sessions)
  • Temporary data (cache, logs)
  • Compliance (auto-delete old data)

Câu hỏi ôn tập

  1. Multi-AZ standby có serve read traffic không?

    Xem đáp án

    Không — RDS Multi-AZ standby là pure failover target, không serve read traffic. Standby sync synchronously từ primary — đảm bảo zero data loss khi failover. Để scale reads, cần Read Replicas (replicate asynchronously, có thể cross-Region, và có thể promote thành standalone). Failover thường hoàn tất trong 60-120 giây — Route 53 CNAME cập nhật.

  2. Tối đa bao nhiêu read replicas per RDS primary?

    Xem đáp án

    15 read replicas per RDS primary instance cho MySQL, MariaDB, PostgreSQL, SQL Server (nâng từ 5 lên 15 vào 10/2022); riêng Oracle vẫn là 5. Mỗi read replica có thể có thêm read replicas của nó (cascading). Aurora hỗ trợ đến 15 read replicas per cluster. Read Replicas có thể ở cross-Region — hỗ trợ geographic distribution và DR.

  3. Khác biệt giữa automated backup và manual snapshot?

    Xem đáp án

    Automated backup: retention 1-35 ngày, tự động xóa khi hết retention period hoặc khi xóa DB instance, enable point-in-time recovery (PITR). Manual snapshot: retention vĩnh viễn cho đến khi bạn xóa thủ công, ngay cả sau khi xóa DB. Dùng manual snapshot trước khi major upgrade, xóa DB, hoặc khi cần backup lâu dài hơn 35 ngày.

  4. Để encrypt RDS đã chạy unencrypted, cần qua bước gì?

    Xem đáp án

    Không thể encrypt trực tiếp. Phải: (1) Tạo snapshot của instance unencrypted, (2) Copy snapshot với encryption (chọn KMS key), (3) Restore từ encrypted snapshot thành new DB instance, (4) Update connection string của ứng dụng. Optional: xóa DB cũ sau khi verify. Downtime = thời gian restore (có thể dùng read replica để giảm downtime).

  5. RDS Proxy giải quyết vấn đề gì cho Lambda?

    Xem đáp án

    Connection pooling. Lambda functions stateless và scale rapidly — mỗi Lambda invocation có thể mở DB connection mới, gây connection exhaustion khi hàng nghìn Lambda chạy đồng thời (RDS max connections giới hạn). RDS Proxy duy trì connection pool đến DB, Lambda kết nối đến Proxy — Proxy multiplexes nhiều Lambda connections qua ít DB connections thực sự. Cũng cải thiện failover time (failover trong Proxy, Lambda không thấy).

  6. Aurora replicate data thành mấy copies, qua mấy AZ?

    Xem đáp án

    Aurora tự động replicate data thành 6 copies trên 3 AZs (2 copies/AZ). Write chỉ cần 4/6 copies acknowledge; read cần 3/6. Shared storage volume tự heal — nếu mất 2 copies vẫn có thể write, mất 3 copies vẫn có thể read. Đây là lý do Aurora có durability và availability cao hơn standard RDS Multi-AZ.

  7. Aurora Global Database RTO khi failover là bao nhiêu?

    Xem đáp án

    < 1 phút (thường dưới 1 phút, không quá 1 phút). Aurora Global Database replication lag thường < 1 giây. Managed failover (promote secondary region thành primary): dưới 1 phút. Unplanned failover (primary region fail): khoảng 1 phút. So sánh: RDS Multi-AZ failover 60-120s, nhưng trong cùng Region.

  8. Aurora Serverless v2 có scale to zero không?

    Xem đáp án

    Có — từ 11/2024, Aurora Serverless v2 hỗ trợ scale to 0 ACU với auto-pause (set min capacity = 0); resume tự động khi có connection (có cold start vài giây). Trước 11/2024, min là 0.5 ACU và không scale về 0 — đề thi/tài liệu cũ có thể vẫn ghi như vậy. Max hiện là 256 ACU. Aurora Serverless v1 (legacy, đã deprecated) cũng pause được về 0 nhưng scale chậm hơn nhiều.

  9. Aurora Backtrack max window là bao lâu?

    Xem đáp án

    72 giờ (3 ngày) maximum backtrack window. Backtrack cho phép "rewind" Aurora cluster về bất kỳ thời điểm nào trong window đó — không cần restore snapshot (nhanh hơn nhiều, thường vài phút). Chỉ hỗ trợ MySQL-compatible Aurora, không phải PostgreSQL. Hữu ích khi phát hiện data corruption hoặc accidental delete trong vòng 72 giờ.

  10. Khác biệt giữa Cluster Endpoint và Reader Endpoint?

Xem đáp án

Cluster Endpoint (Writer Endpoint): luôn trỏ đến primary instance — dùng cho write operations. Tự động failover sang primary mới khi có failover event. Reader Endpoint: load balance reads qua tất cả read replicas — dùng cho read-only queries. Không cần biết IP/hostname của từng replica. Aurora cũng cung cấp custom endpoints để route traffic đến subset replicas cho workloads cụ thể.

  1. DynamoDB item size max là bao nhiêu?
Xem đáp án

400 KB per item. Nếu cần lưu data lớn hơn (images, files), lưu trong S3 và chỉ lưu S3 key trong DynamoDB item. Table size không giới hạn, chỉ item size bị giới hạn. Attribute names cũng tính vào item size — dùng tên ngắn để tối ưu storage và RCU/WCU.

  1. GSI và LSI khác nhau ở điểm gì cốt lõi?
Xem đáp án

LSI (Local Secondary Index): dùng cùng Partition Key nhưng Sort Key khác — chỉ tạo được khi create table, không thể thêm sau. Dùng chung throughput với base table. GSI (Global Secondary Index): có Partition Key hoàn toàn khác — có thể tạo/xóa bất kỳ lúc nào. Có throughput riêng (provision riêng hoặc on-demand). Tối đa 5 LSI và 20 GSI per table.

  1. 1 RCU strongly consistent = bao nhiêu reads/sec cho item 4 KB?
Xem đáp án

1 read/second cho item đến 4 KB với strong consistency. Eventually consistent read: 2 reads/sec cho item 4 KB (gấp đôi). Item lớn hơn: 1 RCU strongly consistent = 1 read/4 KB — item 8 KB cần 2 RCUs, item 1 KB cần 0.5 RCU (làm tròn lên = 1 RCU). Transactional reads tiêu tốn 2 RCUs per read.

  1. DAX phù hợp cho read-heavy hay write-heavy?
Xem đáp án

Read-heavy. DAX (DynamoDB Accelerator) là in-memory cache cho DynamoDB — giảm read latency từ milliseconds xuống microseconds và giảm RCU consumption. Không phù hợp cho write-heavy vì write-through DAX vẫn phải write xuống DynamoDB. Cũng không phù hợp khi application cần strongly consistent reads (DAX chỉ eventually consistent) hoặc data thay đổi liên tục (cache hit rate thấp).

  1. Global Tables conflict resolution là gì?
Xem đáp án

DynamoDB Global Tables dùng "last writer wins" (LWW) với timestamp. Nếu cùng item được write ở hai Regions cùng lúc, write với timestamp mới nhất (theo wall clock) sẽ thắng. AWS khuyến nghị thiết kế ứng dụng tránh conflict: assign primary region cho mỗi user/tenant, hoặc dùng conditional writes với version counter. Không có built-in CRDT hay merge logic.

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

Phần 1: RDS Fundamentals

  • Tạo RDS MySQL db.t3.micro Single-AZ, enable backup 7 days
  • Modify → enable Multi-AZ, observe failover behavior (force reboot with failover)
  • Tạo Read Replica trong cùng AZ và cross-region
  • Test PITR: restore DB to 1 hour ago
  • Enable Performance Insights, observe top queries
  • Setup RDS Proxy for Lambda integration

Phần 2: Amazon Aurora

  • Tạo Aurora MySQL cluster với 1 writer + 1 reader
  • Test failover: force reboot writer, observe < 30s failover
  • Tạo Aurora Serverless v2 cluster với 0.5-4 ACU, observe scaling
  • Setup Aurora Global Database (1 primary region + 1 secondary)
  • Test database cloning: clone production cluster, modify clone
  • Backtrack cluster về 5 phút trước

Phần 3: DynamoDB Basics

  • Tạo DynamoDB table với composite PK (UserId + OrderId), On-Demand capacity
  • Insert 100 items, query bằng PK
  • Add GSI cho query by Email
  • Enable Streams, tạo Lambda trigger log thay đổi
  • Enable PITR, test restore to 1 hour ago
  • Enable Global Tables sang 2 regions, test write từ region B

Tài liệu tham khảo


Bài tiếp theo →