devHọc Dev
EN
Bài học

Tuần 2 - Ngày 4: ElastiCache, Redshift, Database Migration và Aurora Global Database

Tuần 2 – Ngày 4

Bài này gộp 4 chủ đề: Amazon ElastiCache, Amazon Redshift Introduction, Database Migration (DMS & SCT), Aurora Global Database (Deep Dive).

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

  • Phân biệt ElastiCache for Redis vs Memcached
  • Hiểu cluster mode, replication, failover
  • Nắm caching patterns: lazy loading, write-through
  • Biết khi nào dùng ElastiCache vs DAX
  • Hiểu Redshift là data warehouse cho analytics (OLAP)
  • Phân biệt RA3 nodes vs DC2 nodes
  • Nắm Redshift Spectrum và Concurrency Scaling
  • Biết khi nào dùng Redshift vs Athena vs EMR
  • Hiểu AWS DMS (Database Migration Service)
  • Phân biệt Homogeneous vs Heterogeneous migration
  • Nắm SCT (Schema Conversion Tool)
  • Biết các migration strategies
  • Hiểu Aurora Global Database architecture
  • Nắm Write Forwarding và failover process
  • So sánh với cross-region read replica thông thường

Phần 1: Amazon ElastiCache

1. Tổng quan ElastiCache

ElastiCache = managed in-memory data store, hỗ trợ Redis và Memcached.

Use cases

  • Database caching (giảm load DB)
  • Session storage (user session, shopping cart)
  • Leaderboards (gaming)
  • Real-time analytics
  • Message broker (Redis Pub/Sub)
  • Rate limiting

Lý do dùng cache

  • Giảm latency (memory vs disk)
  • Giảm load lên DB (cost optimization)
  • Increase throughput

2. ElastiCache for Redis

Đặc điểm

  • In-memory key-value + data structures: strings, lists, sets, hashes, sorted sets, streams
  • Persistence: snapshots to S3, AOF (append-only file)
  • Replication: read replicas (up to 5)
  • Multi-AZ với automatic failover
  • Encryption in-transit + at-rest
  • Backup automated
  • Pub/Sub messaging

2 deployment modes

Cluster mode disabled (default)
  • 1 primary node + 0-5 read replicas
  • Single shard
  • Multi-AZ failover
Cluster mode enabled
  • Sharding: data split across multiple shards (up to 500)
  • Each shard: 1 primary + 0-5 replicas
  • Total nodes = shards × (1 + replicas)
  • Use case: data > single node memory, need horizontal scale

Architecture (Cluster Mode Disabled)

┌────Region──────────────────────────────┐│││Primary(write+read)│││││├──ReadReplica1││├──ReadReplica2││└──...(upto5)││││Multi-AZfailover:replica→primary│└────────────────────────────────────────────┘

Architecture (Cluster Mode Enabled)

Shard1────Primary+ReplicasHashslots0-5460Shard2────Primary+ReplicasHashslots5461-10922Shard3────Primary+ReplicasHashslots10923-16383

3. ElastiCache for Memcached

Đặc điểm

  • Pure key-value cache (no data structures)
  • Multi-threaded architecture (good for multi-core)
  • Sharding: client-side (no built-in replication)
  • No persistence (data lost on restart)
  • No multi-AZ failover
  • No backup
  • Simpler, less features than Redis

Architecture

Client uses consistent hashing:
Key → hash → Node 1, 2, 3, ...

When to use Memcached

  • Simple cache (no advanced features)
  • Multi-threaded performance critical
  • Cache can be rebuilt (data loss OK)

When to use Redis

  • Data persistence required
  • Need advanced data structures (sorted sets, hashes)
  • Pub/Sub messaging
  • Multi-AZ HA needed
  • Cluster mode for sharding

4. Redis vs Memcached

FeatureRedisMemcached
Data structuresStrings, lists, sets, hashes, sorted sets, streamsString only
PersistenceYes (snapshot + AOF)No
ReplicationMaster-replicaNo (client sharding only)
Multi-AZYes (automatic failover)No
Backup/RestoreYesNo
EncryptionYes (TLS, KMS)Yes (TLS, KMS — 2018+)
Pub/SubYesNo
TransactionsYes (MULTI/EXEC)No
ShardingCluster mode enabledClient-side
Multi-threadedNo (Redis 6 added I/O threads)Yes
Use caseComplex caching, sessions, leaderboardsSimple caching, ephemeral data

2025 trend: Redis được dùng nhiều hơn. Memcached giảm.

5. Caching Patterns

5.1 Lazy Loading (Cache-Aside)

def get_user(user_id):
    # 1. Check cache
    user = cache.get(user_id)
    if user is not None:
        return user        # Cache HIT

    # 2. Cache miss → read from DB
    user = db.get(user_id)

    # 3. Write to cache
    cache.set(user_id, user)

    return user
Pros
  • Only cache requested data (less memory)
  • Cache failure ≠ app failure (read from DB)
Cons
  • Cache miss penalty (3 trips: cache → DB → cache → app)
  • Stale data possible (if DB updated, cache outdated)
  • Cold start slow

5.2 Write-Through

def update_user(user_id, data):
    # 1. Write to DB
    db.update(user_id, data)

    # 2. Write to cache (same time)
    cache.set(user_id, data)
Pros
  • Cache always fresh
  • No cache miss penalty (data always there)
Cons
  • Write latency higher (2 writes)
  • Cache might contain rarely-read data (wasted memory)

5.3 TTL (Time To Live) + Lazy Loading

  • Set TTL on cached items (e.g., 5 minutes)
  • Auto-expire stale data
  • Combine với lazy loading: TTL expiry → next read pulls fresh from DB

Common pattern: Lazy loading + TTL

  • Best of both worlds
  • Simple to implement
  • Acceptable staleness (5-10 min)

6. Cache Replacement (Eviction)

Redis maxmemory policies

  • noeviction: error when full
  • allkeys-lru: evict least recently used (any key)
  • volatile-lru: evict LRU among keys with TTL set
  • allkeys-random, volatile-random
  • volatile-ttl: evict keys with shortest TTL first
  • allkeys-lfu, volatile-lfu (Redis 4+): least frequently used

Memcached

  • LRU only

7. Redis Cluster Mode

Sharding

  • 16384 hash slots total
  • Distributed across shards
  • Key → CRC16(key) % 16384 → slot → shard

Resharding

  • Add/remove shards → redistribute slots
  • Online operation (no downtime)

Limitations

  • Multi-key operations limited (keys must be in same slot)
  • Use hash tags {tag} to group keys: user:{u-001}:profile, user:{u-001}:orders

8. Security

Encryption in transit (TLS)

  • Enable at cluster creation (cannot change later)

Encryption at rest

  • KMS encryption
  • Snapshots also encrypted

Authentication (Redis)

  • Redis AUTH token
  • Redis IAM (newer): IAM-based authentication
  • Memcached: SASL authentication

Network

  • Deploy in VPC
  • Security Group control access
  • Subnet group selection

9. Backup & Restore (Redis)

Snapshots

  • Automated: daily, retention 0-35 days
  • Manual: on-demand, indefinite retention
  • Stored in S3 (managed)
  • No performance impact (taken from replica)

Restore

  • Restore from snapshot to new cluster
  • Cross-region restore possible

10. DAX vs ElastiCache

DAXElastiCache (Redis)
ForDynamoDB onlyAny data source (RDS, app, etc.)
APIDynamoDB API (transparent)Custom (Redis client)
Caching patternWrite-through automaticallyLazy loading or write-through (manual)
Cache keySame as DynamoDB keyCustom
SetupSimple (DynamoDB drop-in)Custom code needed

Use case

  • DAX: Pure DynamoDB caching, no code change
  • ElastiCache Redis: General cache, advanced data structures, sessions

11. ElastiCache Serverless (2023+)

Đặc điểm

  • Pay per use (no capacity planning)
  • Auto-scale instantly
  • Both Redis và Memcached support
  • Min: ~512 MB cache size
  • Support primary use case của ElastiCache without operational overhead

Use case

  • Variable workload
  • Dev/test
  • New apps (don't know capacity)

12. Common Patterns

Pattern 1: Database cache (lazy loading + TTL)

App → Cache (Redis, lazy load) → RDS
TTL 5 min on cached items

Pattern 2: Session storage

User → ALB (no sticky session) → App tier (any instance)
App reads/writes session in Redis (shared)

Pattern 3: Leaderboard (Redis Sorted Set)

User score event → ZADD leaderboard score user_id
Top 10: ZREVRANGE leaderboard 0 9
Real-time updates với O(log N) performance

Pattern 4: Rate limiting

Redis INCR per user per minute
If count > limit → reject request

Phần 2: Amazon Redshift Introduction

1. Tổng quan Redshift

Amazon Redshift = fully managed petabyte-scale data warehouse cho OLAP (analytics).

Đặc điểm

  • Columnar storage: cột nén tốt, query analytics nhanh
  • MPP (Massively Parallel Processing): query split across nodes
  • SQL-based (PostgreSQL-compatible)
  • Scale: GB → petabyte
  • Performance: 10x faster than traditional DB for analytics

Use cases

  • Business Intelligence (BI) dashboards
  • Reporting (sales, marketing analytics)
  • Log analysis
  • Data lakes (combined với S3 + Spectrum)

NOT for

  • OLTP (transactional) workload — use RDS/Aurora
  • Single-row lookups — use DynamoDB
  • Real-time data ingestion at high frequency — buffer first

2. OLAP vs OLTP

OLTP (RDS, Aurora, DynamoDB)OLAP (Redshift)
WorkloadTransactions (insert, update)Analytics (aggregation)
Query typeFew rows, indexed lookupMany rows, full scan
SchemaNormalizedDenormalized (star/snowflake)
Data sizeGB-TBTB-PB
StorageRow-basedColumn-based
Performance metricLatency (ms)Throughput (GB/sec)

3. Cluster Architecture

Components

┌───RedshiftCluster──────────────────────┐│││┌──────LeaderNode──────┐│││•ReceiveSQLqueries││││•Plan+parallelize││││•Aggregateresults│││└─────────────────────────┘│││││▼││┌──ComputeNode1──┐┌──ComputeNode2──┐...│││Slices(parallel)││Slices││││Storageattached││Storageattached│││└────────────────────┘└────────────────────┘│││└─────────────────────────────────────────────────────────┘

Leader Node

  • Coordinate queries
  • Plan execution
  • Aggregate results from compute nodes

Compute Nodes

  • Actual query execution
  • Data stored on local disk (DC2) hoặc managed storage (RA3)
  • Slices: parallel processing units per node

4. Node Types

  • Managed storage: separate compute from storage
  • Storage scales independently từ compute
  • Use S3-backed managed storage (auto-tier hot data on local SSD)
  • Sizes: ra3.xlplus, ra3.4xlarge, ra3.16xlarge
  • Pay for compute + managed storage

DC2 (Dense Compute)

  • Local SSD storage attached
  • Compute + storage tied together
  • Smaller cluster (< 1 TB)
  • Cheaper for small datasets
  • Sizes: dc2.large, dc2.8xlarge

DS2 (Dense Storage) — Legacy

  • HDD storage
  • Deprecated, migrate to RA3

Recommendation

  • RA3 cho mọi production workload mới
  • DC2 cho small dev/test

5. Redshift Spectrum

Định nghĩa

Spectrum = query data trực tiếp trong S3 từ Redshift, không cần load vào Redshift.

Đặc điểm

  • Run SQL queries against S3 data (Parquet, ORC, CSV, JSON)
  • Combine S3 data với Redshift tables (federated query)
  • Pay per data scanned ($5/TB scanned)
  • Use AWS Glue Data Catalog for schema

Use case

  • Data lake architecture (S3 = storage, Redshift = compute)
  • Query historical data in S3 (without loading)
  • Cost-effective for infrequently accessed data

Example query

-- Query S3 data via Spectrum
SELECT *
FROM redshift_spectrum.s3_logs
WHERE date > '2024-01-01';

-- Join with Redshift table
SELECT u.name, COUNT(*)
FROM users u
JOIN redshift_spectrum.s3_events e ON u.id = e.user_id
GROUP BY u.name;

6. Concurrency Scaling

Định nghĩa

Add transient cluster capacity automatically when concurrent queries spike.

Đặc điểm

  • Auto-scale within seconds
  • Bills per second used (free credits available per cluster)
  • Use case: many concurrent BI users

7. Redshift Data Loading

COPY command (primary method)

COPY my_table
FROM 's3://my-bucket/data/'
IAM_ROLE 'arn:aws:iam::111111111111:role/RedshiftS3Role'
DELIMITER ','
IGNOREHEADER 1;

Sources

  • S3 (most common, parallel load)
  • DynamoDB
  • EMR
  • Remote host (SSH)
  • AWS DMS (from RDS, on-prem DB)
  • Kinesis Data Firehose (streaming)

Best practice

  • Split files into multiple parts (~1 GB each) → parallel load
  • Use Parquet/ORC for compression
  • Compress files (gzip, bzip2)

8. Redshift Backup

Automated snapshots

  • Continuous backup to S3 (managed)
  • Retention: 1-35 days
  • Cross-region copy support

Manual snapshots

  • User-initiated
  • Retain indefinitely

Restore

  • Restore to new cluster from snapshot

9. Redshift Security

Network

  • VPC deployment
  • Enhanced VPC Routing: force traffic through VPC (Spectrum, COPY)
  • Security Group control access

Encryption

  • At rest: KMS or HSM
  • In transit: SSL
  • Enable at cluster launch

Access control

  • IAM for AWS-level (cluster management)
  • Database users for SQL access
  • IAM Database Authentication (token-based)
  • Audit logs: STL_, SVL_ system tables → S3

10. Redshift Serverless

Định nghĩa

Redshift Serverless = on-demand Redshift, no cluster management.

Đặc điểm

  • Pay per RPU-second (Redshift Processing Unit)
  • Auto-pause khi idle (save cost)
  • Auto-scale based on workload
  • Same SQL, same features as provisioned

Use case

  • Sporadic analytics workload
  • Dev/test environments
  • New customer experimentation

Cost

  • Free trial: $300 credits initially
  • Pay-per-use after

11. Redshift vs Athena vs EMR

RedshiftAthenaEMR
TypeData warehouse (cluster)Serverless queryManaged Hadoop/Spark cluster
PerformanceFastest for complex SQL on TBGood for ad-hocVariable, depends on cluster
CostPay for clusterPay per query ($5/TB)Pay for EC2 + EMR fee
LatencySub-sec to secondsSeconds to minutesMinutes
SetupProvision clusterNoneCluster management
Use caseBI dashboards, frequent queriesAd-hoc, infrequent queriesBig data processing (ETL)

Decision

  • Frequent complex queries on TB-PB: Redshift
  • Ad-hoc queries on S3: Athena
  • Custom ETL with Spark/Hive: EMR

12. Modern Data Lake Architecture

┌─────────────┐│S3Data│◄──Raw+processeddata│Lake│(Parquet,DeltaLake)└─────────────┘│┌─────────────────┼─────────────────┐│││┌────────┐┌────────────┐┌─────────┐│Athena││Redshift││EMR││(ad-││Spectrum││(Spark)││hoc)││(BIonS3)││(ETL)│└────────┘└────────────┘└─────────┘│││▼▼▼┌───────────────────────────────────────────┐│QuickSight/Tableau││(Visualization)│└───────────────────────────────────────────┘

Phần 3: Database Migration (DMS & SCT)

1. Tổng quan AWS DMS

AWS Database Migration Service (DMS) = service di chuyển databases lên AWS, hoặc giữa các databases.

Đặc điểm

  • Source → Replication Instance → Target
  • Source vẫn chạy trong khi migration (minimum downtime)
  • Support full load + CDC (Change Data Capture) continuous replication
  • Multi-AZ replication instance for HA

2 loại migration

Homogeneous (cùng engine)
  • MySQL → RDS MySQL
  • PostgreSQL → Aurora PostgreSQL
  • Oracle → RDS Oracle
  • No schema conversion needed (DMS handles)
Heterogeneous (khác engine)
  • Oracle → Aurora PostgreSQL
  • SQL Server → MySQL
  • Cần SCT để convert schema trước
  • DMS migrate data sau

Architecture

SourceDatabaseDMSReplicationInstanceTargetDatabase─────────────────────►────────────────────────────────►─────────────(on-premOracle)(EC2inAWS,runsDMStask)(AuroraPG)│├──Fullload(initial)├──CDC(ongoing)└──Validation

2. DMS Components

Replication Instance

  • EC2 instance runs DMS engine
  • Sizing: t3, c5, r5 (CPU + memory)
  • Multi-AZ option (HA)
  • In VPC, has connectivity to source + target

Endpoints

  • Source endpoint: where data comes from
  • Target endpoint: where data goes to
  • Support 20+ databases (MySQL, PostgreSQL, Oracle, SQL Server, MongoDB, DynamoDB, S3, Aurora, Redshift...)

Migration Task

  • Defines what to migrate (tables, columns, transformations)
  • 3 types:
    • Full load (initial migration)
    • CDC only (continuous replication)
    • Full load + CDC (most common — copy data, then keep in sync)

3. SCT (Schema Conversion Tool)

Định nghĩa

SCT = desktop tool convert source database schema sang target schema (heterogeneous).

Đặc điểm

  • Free tool (download install local)
  • Convert: tables, indexes, views, stored procedures, functions
  • Assessment report: identify issues, manual conversion needed
  • Generate target schema, run on target before DMS

Workflow

1. Install SCT
2. Connect to source DB (Oracle)
3. Convert schema → SQL for target (PostgreSQL)
4. Review assessment report
5. Manually fix complex objects
6. Apply schema to target
7. Run DMS task migrate data

Supported conversions

  • Oracle → PostgreSQL, MySQL, MariaDB
  • SQL Server → PostgreSQL, MySQL, MariaDB
  • MySQL → PostgreSQL
  • Sybase → PostgreSQL, MySQL, MariaDB
  • DB2 → PostgreSQL, MySQL, MariaDB
  • Oracle DW → Redshift
  • Teradata → Redshift

4. DMS vs SCT

DMSSCT
PurposeData migrationSchema conversion
TypeManaged serviceDesktop tool
HomogeneousYes (no SCT needed)Not needed
HeterogeneousNeeds schema in targetYes (convert schema)

Order of operations (heterogeneous)

  1. SCT: Convert schema, apply to target
  2. DMS: Full load + CDC migration of data
  3. Cut over apps to target

5. Migration Strategies (Common)

Strategy 1: Lift-and-Shift (Rehosting)

  • Move on-prem DB to RDS without changing engine
  • DMS homogeneous (Oracle → RDS Oracle)
  • Minimum changes, fastest

Strategy 2: Re-platforming

  • Move + change platform (e.g., Oracle → Aurora PG)
  • DMS heterogeneous + SCT
  • Cost saving (Aurora PG cheaper than Oracle license)

Strategy 3: Refactoring

  • Re-architect (e.g., monolithic SQL → DynamoDB + microservices)
  • More work, more benefit
  • Often involves rewriting app logic

6. DMS Best Practices

Pre-migration

  • Test in non-prod first
  • Assess schema complexity (SCT report)
  • Optimize source DB (vacuum, analyze)
  • Pre-create target schema (indexes after migration for speed)

During migration

  • Disable triggers, indexes on target during full load (faster)
  • Re-enable after full load complete
  • Monitor CloudWatch metrics (CPU, memory, replication lag)
  • Validate data with AWS DMS Data Validation

Cutover

  • Stop writes on source briefly
  • Verify CDC caught up (lag = 0)
  • Switch apps to target endpoint
  • Keep CDC running few hours for safety

7. DMS for Specific Targets

Target: S3

  • Migrate database → S3 in CSV, Parquet, JSON
  • Use case: data lake ingest from RDS
  • Combine with Glue Crawler + Athena

Target: Redshift

  • Migrate OLTP DB → Redshift data warehouse
  • Use case: build analytics from operational data

Target: DynamoDB

  • Migrate from relational to NoSQL
  • Use case: re-architecting for scale

Target: Kinesis / OpenSearch

  • Stream changes via CDC to data pipeline
  • Real-time analytics

8. Other Migration Tools

AWS Application Migration Service (MGN)

  • Lift-and-shift servers (OS + DB if on EC2)
  • Continuous replication of source servers
  • For migrating entire VMs/servers

AWS DataSync

  • Migrate files (NFS, SMB, S3, EFS, FSx)
  • Different from DMS (DMS = databases, DataSync = files)

AWS Snow Family

  • Snowball Edge (không còn nhận khách mới; khách hiện hữu vẫn dùng được — đề thi vẫn có thể hỏi. Khách mới: DataSync hoặc Data Transfer Terminal)
  • Physical device for large data migration (TB-PB, dùng nhiều thiết bị song song cho PB-scale)
  • Use case: limited bandwidth, large dataset
  • Ghi chú 2024: AWS đã ngừng Snowmobile và Snowcone (2024) — đề thi/tài liệu cũ có thể còn nhắc; với PB-scale hiện nay dùng nhiều Snowball Edge hoặc DataSync/Direct Connect

AWS Transfer Family

  • Managed SFTP, FTPS, FTP for file transfer
  • Use case: existing SFTP-based workflows

9. Migration Decision Matrix

Migrating?│├──Databases?│├──Sameengine(homogeneous)││└──DMSonly│└──Differentengine(heterogeneous)│└──SCT+DMS│├──Servers(EC2/VMs)?│└──AWSApplicationMigrationService(MGN)│├──Files?│├──<fewTB,cóbandwidthtốt││└──DataSync│└──TB-PB,bandwidthlimited│└──SnowballEdge(PB-scale:nhiềuthiếtbị│songsong—Snowmobileđãngừng2024)│└──SFTP/FTPfileexchange?└──AWSTransferFamily

10. Cost Considerations

DMS pricing

  • Replication instance: per hour ($)
  • Storage (logs, cache): $/GB
  • Data transfer: standard rates (inbound to AWS free)

Cost optimization

  • Right-size replication instance (start small, scale up if needed)
  • Use Multi-AZ only for production cutover (not pre-test)
  • Delete tasks/instances after migration complete

SCT

  • Free (download tool)

11. Common Migration Scenarios

Scenario 1: Oracle on-prem → Aurora PostgreSQL

  • Why: Reduce Oracle license cost
  • How: SCT convert schema, DMS migrate data with CDC
  • Effort: 1-3 months (depends on schema complexity)

Scenario 2: MySQL on-prem → RDS MySQL

  • Why: Managed service, HA
  • How: DMS homogeneous, optional Aurora upgrade later
  • Effort: 1-4 weeks

Scenario 3: SQL Server on-prem → Aurora PostgreSQL

  • Why: Cost optimization
  • How: SCT + DMS, app changes for SQL dialect
  • Effort: 3-6 months

Scenario 4: On-prem files (100 TB) → S3

  • Why: Cloud storage migration
  • How: Snowball Edge Storage Optimized (~80 TB usable/thiết bị theo đề thi; model mới 210 TB) → 1-2 thiết bị
  • Effort: 2-4 weeks (shipping included)

Phần 4: Aurora Global Database (Deep Dive)

1. Tổng quan Aurora Global Database

Aurora Global Database = Aurora cluster với primary region + up to 10 secondary regions, sub-second replication.

Đặc điểm

  • 1 Primary region + up to 10 Secondary regions (số cũ: 5 — đề thi có thể còn dùng)
  • Replicate via dedicated infrastructure (not standard MySQL/PostgreSQL replication)
  • < 1 second replication lag typical
  • RPO < 1 second
  • RTO < 1 minute (failover)
  • Read-only in secondary regions (or use Write Forwarding)
  • Supports both Aurora MySQL và Aurora PostgreSQL

Limits

  • Up to 10 secondary regions
  • Up to 16 read replicas per secondary region
  • Total: up to 160 read replicas across secondary regions (10 × 16)

2. Architecture

┌───PrimaryRegion(us-east-1)─────────┐│││WriterInstance──►writes│││││├──Reader1(sync)││├──Reader2││└──...upto15││││Storage(shared,6copies,3AZs)│││││▼││AuroraGlobalDatabaseengine││(replicatetosecondaryregions)│└──────────────┬───────────────────────────┘││Replication(dedicatedinfra)│<1seclag│┌──────────────▼────────SecondaryRegion(eu-west-1)─┐│││Read-onlyreplicas(upto16)││└──Localreads(lowlatencyforEUusers)││││Storage(replicatedfromprimary)│└────────────────────────────────────────────────────────┘

3. Use Cases

Disaster Recovery

  • Primary fails → promote secondary → new primary
  • RTO < 1 minute (vs hours for traditional restore)
  • RPO < 1 second (minimal data loss)

Multi-Region Reads

  • Global users get low-latency reads from nearest region
  • e.g., US users → us-east-1, EU users → eu-west-1, Asia → ap-southeast-1

Cross-Region Migration

  • Use Global Database for migration: replicate to new region, then cutover

4. Replication Mechanism

How it works

  • Storage-level replication (not query replication)
  • Dedicated infrastructure between regions
  • Asynchronous BUT very fast (sub-second)
  • No impact on primary performance

vs Standard Cross-Region Read Replica

Aurora Global DatabaseCross-region Read Replica
ReplicationStorage-level (dedicated infra)Query-level (logical)
Lag< 1 secondSeconds to minutes
Performance impact on primaryNoneSome
SetupSingle clickPer replica
Failover time< 1 minute (planned/unplanned)Manual promote, longer

5. Failover Process

Planned Failover

  • Manual switch primary to secondary
  • Use case: scheduled maintenance, region rebalancing
  • ~30-60 seconds RTO

Unplanned Failover (DR)

  • Primary region down
  • Detach secondary from global DB
  • Promote secondary to standalone cluster
  • Update app connection string
  • RTO: < 1 minute

Steps for unplanned failover

1. Detect primary region failure
2. Click "Failover global database" or use API
3. Select secondary region to promote
4. Aurora promotes secondary cluster to standalone
5. Update app to point to new primary endpoint
6. (Optionally) Re-add detached cluster as new secondary

6. Write Forwarding

Định nghĩa

Write Forwarding = secondary region can accept writes, forward to primary.

Đặc điểm

  • App can write to secondary region's endpoint
  • Aurora forwards write to primary, then replicates back
  • Write latency = round-trip to primary + replication
  • Read-after-write consistency options

Use case

  • Multi-region apps where reads dominate but occasional writes
  • Simpler app architecture (single connection logic)

Limitations

  • Yêu cầu version: Aurora MySQL 2.08.1+; Aurora PostgreSQL 14.9/15.4+ (PostgreSQL hỗ trợ từ 11/2023)
  • Higher write latency than direct primary writes
  • Not for write-heavy workloads (use primary directly)

7. Consistency Modes (Write Forwarding)

Eventual Consistency (default)

  • Write returns immediately
  • Read may not see the write yet

Session Consistency

  • Read in same session sees previous writes
  • Other sessions may lag

Global Consistency

  • All sessions in region see write after replication
  • Highest latency

8. Pricing

Components

  • Primary cluster: standard Aurora pricing
  • Secondary cluster: standard Aurora pricing (cheaper if smaller instance)
  • Cross-region replication: $0.20/M I/O operations (or no extra cost for some)
  • Cross-region data transfer

Cost optimization

  • Smaller instances in secondary (read-only workload may be smaller)
  • Aurora Serverless v2 in secondary (auto-scale)

9. Monitoring

CloudWatch metrics

  • AuroraGlobalDBReplicationLag: time lag between regions
  • AuroraGlobalDBProgressLag: log-based lag
  • Per-secondary-region metrics

Alarms

  • Alert when replication lag > threshold (e.g., 1 second)
  • Trigger DR procedures if critical lag

10. Backup Strategy with Global DB

Backups in each region

  • Primary region: automated backups + PITR
  • Secondary region: also has automated backups (independent)
  • → 2x backup storage but additional protection

Manual snapshots

  • Can take from primary
  • Can share/copy across accounts/regions

11. Common Patterns

Pattern 1: Multi-region SaaS

Primary: us-east-1 (writes)
Secondary: eu-west-1, ap-southeast-1, sa-east-1
Each region: ALB → App → local read replica
Writes: all go to primary (acceptable latency)

Pattern 2: DR with auto-failover

Primary: us-east-1
Secondary: us-west-2 (DR)
Route 53 health check on us-east-1 app
If unhealthy → auto-trigger Lambda → Promote Aurora secondary + DNS failover

Pattern 3: Global app with Write Forwarding

AuroraMySQLGlobalDB:├──Primary:us-east-1├──Secondary:eu-west-1(WriteForwardingenabled)└──Secondary:ap-southeast-1(WriteForwardingenabled)Appreads+writesfromlocalregionendpointAuroraforwardswritestoprimarytransparently

12. Aurora Global vs Alternatives

Aurora Global Database

  • RTO < 1 min, RPO < 1 sec
  • Up to 11 regions (1 primary + up to 10 secondaries)
  • Aurora MySQL or PostgreSQL only

DynamoDB Global Tables

  • Multi-master (active-active writes everywhere)
  • Last-write-wins conflict resolution
  • NoSQL only

RDS Cross-Region Read Replica

  • Single replica per region (multiple possible)
  • Slower replication
  • Standard RDS engines (MySQL, PostgreSQL, MariaDB)

Manual replication (DMS)

  • Highest flexibility, more complex
  • For non-Aurora databases

Decision

  • Aurora workload, need fast DR: Aurora Global Database
  • NoSQL multi-region writes: DynamoDB Global Tables
  • RDS non-Aurora: Cross-region read replica
  • Custom logic: DMS

Câu hỏi ôn tập

  1. Redis hỗ trợ persistence, Memcached thì sao?

    Xem đáp án

    Redis: hỗ trợ persistence qua RDB (snapshot) và AOF (append-only file log). Data không mất khi node restart (có thể reload từ disk). Hỗ trợ replication, pub/sub, Sorted Sets, Streams. Memcached: không có persistence — data mất khi node fail hay restart. Pure in-memory, multi-threaded, không có replication. Memcached đơn giản và nhanh hơn cho pure caching use cases.

  2. Lazy loading pattern có nhược điểm gì?

    Xem đáp án

    Cache miss penalty: lần đầu request data (cache miss) phải query DB rồi mới write vào cache — latency cao hơn cho requests đầu tiên. Stale data: nếu DB update nhưng cache không được invalidate, đọc từ cache sẽ nhận data cũ. Giải pháp: TTL (Time-To-Live) để auto-expire, hoặc kết hợp với Write-Through pattern để update cache khi write.

  3. Multi-AZ failover hỗ trợ trong Redis hay Memcached?

    Xem đáp án

    Chỉ Redis hỗ trợ Multi-AZ với automatic failover. Redis có primary + replicas — khi primary fail, replica được promote tự động (failover < 60 giây). Memcached không có replication — nếu node fail, data trong node đó bị mất, không failover. Với Memcached cluster nhiều nodes, chỉ mất data của node fail, không phải toàn bộ.

  4. DAX khác ElastiCache ở điểm gì?

    Xem đáp án

    DAX là DynamoDB-specific cache — transparent, không cần thay đổi code (dùng DAX SDK thay DynamoDB SDK), cache DynamoDB table results trực tiếp, write-through, microsecond latency. ElastiCache là general-purpose cache (Redis/Memcached) — cần code logic để check cache trước DB, linh hoạt hơn (cache bất kỳ gì: SQL query results, session data, computed values).

  5. Redis Cluster Mode dùng để làm gì?

    Xem đáp án

    Redis Cluster Mode cho phép horizontal scaling của dataset bằng cách sharding data qua nhiều shards (mỗi shard = 1 primary + N replicas). Không có Cluster Mode: toàn bộ data trên 1 shard — bị giới hạn bởi memory của single node. Cluster Mode: dataset lớn hơn tổng memory một node, write throughput cao hơn qua parallel shards. Tối đa 500 nodes per cluster.

  6. Redshift dùng cho OLAP hay OLTP?

    Xem đáp án

    OLAP (Online Analytical Processing) — data warehousing, analytics, reporting, BI. Columnar storage tối ưu cho aggregations, scans trên cột cụ thể trong dataset lớn. Không phù hợp cho OLTP (nhiều small transactions, row-level updates). OLTP dùng RDS/Aurora. Redshift được thiết kế cho queries phức tạp trên hàng tỷ rows — data warehouse scale.

  7. Redshift Spectrum query data ở đâu?

    Xem đáp án

    Redshift Spectrum query data trực tiếp từ Amazon S3 — không cần load data vào Redshift cluster. Dùng external tables (schemas trong AWS Glue Data Catalog). Hàng ngàn nodes xử lý S3 data song song. Phù hợp cho "data lake" pattern: cold/historical data trên S3, hot data trong Redshift. Tính phí theo bytes scanned ($5/TB).

  8. RA3 và DC2 khác nhau ở điểm gì?

    Xem đáp án

    DC2: compute-optimized với SSD local storage — storage cố định theo node type, không thể scale storage độc lập với compute. RA3: managed storage trên Redshift Managed Storage (S3-backed) — compute và storage scale độc lập. RA3 phù hợp khi dataset lớn hơn tổng SSD của DC2 nodes. AWS khuyến nghị RA3 cho workloads mới vì linh hoạt hơn.

  9. Khi nào dùng Athena thay vì Redshift?

    Xem đáp án

    Dùng Athena khi: (1) Queries ad-hoc, không thường xuyên trên S3 data, (2) Không muốn quản lý cluster, (3) Dataset thay đổi thường xuyên (schema-on-read), (4) Budget thấp (pay-per-query). Dùng Redshift khi: queries phức tạp, thường xuyên, cần performance cao (seconds vs minutes), data warehousing, BI dashboards cần consistent query time, hoặc cần joins phức tạp.

  10. Redshift Serverless tính phí theo gì?

Xem đáp án

RPU-hours (Redshift Processing Units per hour) — tính theo số RPUs được sử dụng trong thời gian query chạy. Không charge khi không có queries (scale to zero). Minimum 8 RPUs, maximum 512 RPUs. Phù hợp cho sporadic, unpredictable workloads và development/test. Provisioned cluster rẻ hơn cho steady, predictable workloads.

  1. Khi nào cần SCT? Khi nào không?
Xem đáp án

AWS Schema Conversion Tool (SCT) cần khi migrate giữa engines khác nhau (heterogeneous): Oracle → Aurora PostgreSQL, SQL Server → MySQL. SCT convert schema, stored procedures, functions từ source dialect sang target dialect. Không cần SCT khi migrate cùng engine (homogeneous): MySQL → RDS MySQL, Oracle → RDS Oracle — schema tương thích trực tiếp, chỉ cần DMS để migrate data.

  1. DMS hỗ trợ CDC để làm gì?
Xem đáp án

CDC (Change Data Capture) cho phép DMS capture real-time changes từ source database (inserts, updates, deletes) và apply vào target — không chỉ full load một lần. Dùng cho: (1) Zero-downtime migration — full load trước, rồi CDC sync ongoing changes, cutover khi lag gần 0, (2) Ongoing replication — keep target DB synced với source. CDC đọc từ transaction logs (binlog cho MySQL, redo log cho Oracle).

  1. Khác biệt giữa DMS và DataSync?
Xem đáp án

DMS (Database Migration Service): migrate database data — tables, rows, schema. Hỗ trợ SQL databases, NoSQL, data warehouses. Dùng cho database-to-database migration. DataSync: di chuyển file/object data — từ NFS, SMB, HDFS, S3, EFS, FSx. Tối ưu cho large file transfers với validation và scheduling. DataSync không hiểu database schema — nó transfer files như là files.

  1. Khi migrate 200 TB data với bandwidth 100 Mbps, nên dùng gì?
Xem đáp án

AWS Snowball Edge (hoặc Snowball Family). Tính thử: 200 TB = 200 × 8 × 10⁶ Mb = 1.6 × 10⁹ Mb; ÷ 100 Mbps ≈ 1.6 × 10⁷ giây ≈ 185 ngày qua internet — không thực tế. Snowball Edge thiết bị physical lưu đến ~80 TB usable/thiết bị (dùng 3 thiết bị cho 200 TB; model Storage Optimized 210 TB hiện hành thì 1 thiết bị), ship đến AWS datacenter để import vào S3 trong vài ngày. Quy tắc ngón tay cái: nếu transfer > 1 tuần qua internet → dùng Snowball. (Snowmobile trước đây dành cho > 10 PB nhưng đã ngừng cung cấp từ 2024 — PB-scale nay dùng nhiều Snowball Edge song song.)

  1. Replication instance trong DMS chạy ở đâu (managed or self-managed)?
Xem đáp án

AWS managed EC2 instance trong VPC của bạn — AWS quản lý infrastructure, bạn chỉ chọn instance class và cấu hình. DMS tự động patch, monitor, và restart nếu fail. Replication instance cần kết nối được đến cả source và target endpoints. Đặt replication instance cùng Region với target (hoặc giữa source và target) để giảm latency và data transfer cost.

  1. Aurora Global Database max bao nhiêu secondary regions?
Xem đáp án

Tối đa 10 secondary regions (số cũ là 5 — đề thi có thể còn dùng). Mỗi secondary region có Aurora cluster read-only. Tổng cộng: 1 primary + 10 secondary = 11 clusters. Secondary cluster có thể có tối đa 16 read replicas để scale read workload trong region đó. Hữu ích cho global applications cần low-latency reads từ nhiều continents.

  1. RTO và RPO điển hình của Aurora Global Database?
Xem đáp án

RPO < 1 giây (replication lag thường dưới 1 giây — storage-level replication rất nhanh). RTO < 1 phút khi promote secondary region thành primary (managed failover). Unplanned failover khi primary region fails: khoảng 1 phút để detect và promote. Điều này giúp Aurora Global Database đáp ứng RTO/RPO requirements cho tier-1 applications cần DR cross-region.

  1. Write Forwarding hỗ trợ engine nào?
Xem đáp án

Cả Aurora MySQL (2.08.1+) và Aurora PostgreSQL (14.9/15.4+, hỗ trợ từ 11/2023). Write Forwarding cho phép secondary region forward write requests đến primary region thay vì trả lỗi "read-only". Latency tăng thêm round-trip đến primary — không phù hợp cho write-heavy workloads qua long-distance network. Dùng cho applications cần session writes với đa số traffic là reads.

  1. Aurora Global Database replicate ở layer nào (storage vs query)?
Xem đáp án

Storage layer — Aurora Global Database replication xảy ra ở storage engine level, không phải SQL query level. Tất cả storage writes được ghi qua distributed storage và forwarded đến secondary regions qua dedicated replication infrastructure. Đây là lý do replication lag rất thấp (< 1s) và không ảnh hưởng write performance của primary — replication không đi qua database query engine.

  1. Khác biệt với cross-region read replica thông thường?
Xem đáp án

Cross-region read replica (binlog): replication qua binlog ở database layer — lag có thể 5-30 giây, overhead trên primary. Aurora Global Database (storage): storage-level replication với lag < 1s, không ảnh hưởng primary performance, support planned failover với data integrity guarantee. Promote secondary của Global DB nhanh hơn nhiều và ít data loss hơn. Cost cao hơn read replica nhưng cho DR-grade solution.

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

Phần 1: Amazon ElastiCache

  • Tạo ElastiCache Redis cluster (cluster mode disabled), 1 primary + 1 replica
  • Implement lazy loading pattern trong app: read cache, fallback DB
  • Set TTL 60 seconds, observe expiry
  • Tạo Redis Cluster Mode Enabled với 3 shards
  • Test failover: stop primary, observe replica promote
  • So sánh latency: DB direct vs DB + cache hit

Phần 2: Amazon Redshift Introduction

  • Tạo Redshift Serverless workgroup (free trial)
  • Load sample data từ S3 với COPY command
  • Query với SELECT joins
  • Setup Redshift Spectrum query S3 Parquet file
  • Compare query performance: same query trong Athena vs Redshift Spectrum

Phần 3: Database Migration (DMS & SCT)

  • Tạo source MySQL trên EC2, target RDS MySQL
  • Setup DMS replication instance + endpoints
  • Tạo Full Load + CDC task, observe migration
  • Download SCT, connect to demo Oracle, convert to PostgreSQL schema
  • So sánh cost: DataSync vs Snowball cho 50 TB

Phần 4: Aurora Global Database (Deep Dive)

  • Tạo Aurora MySQL cluster
  • Convert sang Global Database, add secondary in another region
  • Test cross-region read latency
  • Practice failover: promote secondary to new primary
  • (Optional) Enable Write Forwarding, test from secondary

Tài liệu tham khảo


Bài tiếp theo →