Amazon DynamoDB
NoSQL key-value và document database, Single-digit millisecond latency, Global Tables, DAX
Tổng quan
Amazon DynamoDB là fully managed NoSQL database service cung cấp hiệu suất single-digit millisecond latency ở mọi quy mô. DynamoDB hỗ trợ cả key-value và document data models, phù hợp cho các ứng dụng yêu cầu throughput cao và latency thấp.
Use Cases phổ biến
| Use Case | Mô tả |
|---|---|
| Web/Mobile Apps | Session management, user profiles, shopping carts |
| Gaming | Leaderboards, player state, game data |
| IoT | Device state, sensor data, telemetry |
| E-commerce | Product catalogs, inventory, order processing |
| Real-time Analytics | Clickstream data, metrics, event logging |
| Serverless Apps | Backend cho Lambda functions |
Nguồn: What is Amazon DynamoDB?
EXAM TIP: "LEAST Operational Overhead for ANY Scale"
[!IMPORTANT] Khi exam hỏi: "Which database has the LEAST operational overhead at ANY scale?" → Đáp án luôn là DynamoDB
So sánh Operational Overhead
| Task | DynamoDB | Aurora Serverless | RDS | EC2 + Self-managed |
|---|---|---|---|---|
| Patching | AWS | AWS | AWS | ❌ You |
| Scaling | ✅ Automatic | Automatic | Manual resize | ❌ You |
| Capacity | ✅ On-Demand | Auto pause | Pre-provision | ❌ You |
| HA/Replication | ✅ Built-in | Built-in | Multi-AZ config | ❌ You |
| Backups | ✅ Automatic | Automatic | Configure | ❌ You |
Sample Exam Questions
1. Core Concepts
1.1 Table, Items, Attributes
1.2 Data Types
| Category | Types | Examples |
|---|---|---|
| Scalar | String, Number, Binary, Boolean, Null | "name", 123, true |
| Document | List, Map | ["a", "b"], {"a": 1} |
| Set | String Set, Number Set, Binary Set | SS: ["a", "b"], NS: [1, 2, 3] |
1.3 Read Consistency
RCU là gì? RCU đo lường cái gì?
RCU (Read Capacity Unit) là đơn vị đo lường CAPACITY (năng lực/khả năng xử lý) cho read operations trong DynamoDB.
RCU dùng để đo lường:
- Khả năng đọc data của table trong Provisioned Capacity Mode
- Tương tự như "mã lực" của xe - cho biết table có thể đọc bao nhiêu data mỗi giây
Eventually Consistent vs Strongly Consistent - Khác nhau như thế nào?
Điểm khác biệt CỐT LÕI: Cách DynamoDB đọc data từ các Availability Zones (AZs)
So sánh chi tiết: Eventually vs Strongly Consistent
| Tiêu chí | Eventually Consistent | Strongly Consistent |
|---|---|---|
| Giá tiền | Rẻ (0.5 RCU cho 4KB) | Đắt gấp đôi (1 RCU cho 4KB) |
| Latency | Nhanh (~1-5ms) | Chậm hơn (~5-15ms) |
| Cơ chế | Đọc từ 1 AZ gần nhất | Đọc và đồng bộ tất cả 3 AZs |
| Data mới nhất | Không đảm bảo (có thể stale) | Luôn đảm bảo 100% |
| Thời gian stale | Thường < 1 giây sau write | Không bao giờ stale |
| Use Case | Social feeds, analytics, recommendations | Banking, inventory, auth |
Ví dụ thực tế
Nguồn: DynamoDB Read Consistency
WCU là gì? (Bonus: Write Capacity Unit)
Summary: RCU vs WCU
| Đơn vị | Dùng cho | 1 Unit = | Tính theo |
|---|---|---|---|
| RCU | Read operations | 4 KB item | Per read request |
| WCU | Write operations | 1 KB item | Per write request |
| RRU | Read (On-Demand) | 4 KB item | Pay-per-request |
| WRU | Write (On-Demand) | 1 KB item | Pay-per-request |
2. Primary Key
2.1 Simple Primary Key (Partition Key only)
2.2 Composite Primary Key (Partition Key + Sort Key)
2.3 Partition Key Distribution
Partition Key Distribution là cách DynamoDB phân chia data vào các partitions dựa trên giá trị của Partition Key.
Nguồn: DynamoDB Keys
2.4 Partition Storage & Multi-AZ Replication
3. Capacity Modes
DynamoDB cung cấp hai capacity modes để xử lý read và write throughput:
3.1 On-Demand Capacity Mode
3.2 Provisioned Capacity Mode
3.3 Capacity Mode Comparison
| Feature | On-Demand | Provisioned |
|---|---|---|
| Setup | Zero config | Cần specify RCU/WCU |
| Scaling | Instant, automatic | Auto Scaling policies |
| Billing | Per-request | Per-hour cho capacity |
| Cost | Higher per-request | Lower nếu high utilization |
| Predictability | Variable | Fixed hourly cost |
| Throttling | Không bao giờ | Có thể nếu vượt capacity |
| Reserved Capacity | ❌ | ✅ |
4. Secondary Indexes
4.1 Global Secondary Index (GSI)
4.2 Local Secondary Index (LSI)
4.3 Index Comparison
| Feature | GSI | LSI |
|---|---|---|
| Partition Key | Different from base table | Same as base table |
| Sort Key | Different | Different |
| Created after table creation | ✅ Yes | ❌ No (only at create time) |
| Consistency | Eventually consistent | Strongly consistent available |
| Capacity Units | Separate RCU/WCU | Shares with base table |
| Max per table | 20 | 5 |
| Projected attributes | Any subset | Any subset |
4.4 Index Key Structure
Nguồn: Secondary Indexes
5. Global Tables
Global Tables là gì?
Global Tables = Multi-region replication - 1 table tự động sync giữa nhiều AWS regions.
Đặc điểm Global Tables
| Feature | Giải thích |
|---|---|
| Active-Active | Write được ở BẤT KỲ region nào (không phải chỉ 1 master) |
| Auto sync | Data tự động đồng bộ giữa regions (<1 giây) |
| Conflict resolution | Last Writer Wins (timestamp mới nhất thắng) |
| No downtime | Nếu 1 region chết, traffic tự động chuyển sang region khác |
Khi nào dùng Global Tables?
| ✅ Nên dùng | ❌ Không cần |
|---|---|
| Users ở nhiều regions (US, EU, Asia) | Users chỉ ở 1 region |
| Cần Disaster Recovery tự động | Chấp nhận downtime khi có sự cố |
| Cần low latency cho global users | Latency không quan trọng |
Nguồn: Global Tables
6. DynamoDB Streams
Streams là gì?
DynamoDB Streams = Event log - Ghi lại MỌI thay đổi (INSERT/UPDATE/DELETE) xảy ra trong table.
Stream Record Types
| Type | Nội dung | Use case |
|---|---|---|
| NEW_IMAGE | Data SAU thay đổi | Sync data sang service khác |
| OLD_IMAGE | Data TRƯỚC thay đổi | Audit, rollback |
| NEW_AND_OLD_IMAGES | Cả trước và sau | So sánh thay đổi, analytics |
| KEYS_ONLY | Chỉ primary key | Lightweight triggers |
Khi nào dùng Streams?
| ✅ Nên dùng | ❌ Không cần |
|---|---|
| Cần react khi data thay đổi | Chỉ cần CRUD đơn giản |
| Sync data sang Elasticsearch, S3 | Không cần real-time processing |
| Audit/compliance logging | Không có event-driven workflows |
| Trigger notifications |
Retention: Stream records được giữ 24 giờ
Nguồn: DynamoDB Streams
7. DAX (DynamoDB Accelerator)
DAX là gì?
DAX = In-memory cache đặt giữa App và DynamoDB để tăng tốc đọc.
So sánh có/không có DAX
| Metric | Không có DAX | Có DAX |
|---|---|---|
| Read latency | 5-10ms | Microseconds (~0.001ms) |
| RCU cost | Mỗi request tốn RCU | Cache hit = FREE |
| Hot partition | Dễ bị throttle | Cache giảm tải |
Khi nào dùng DAX?
| ✅ Nên dùng DAX | ❌ Không nên dùng |
|---|---|
| Read-heavy workloads (90%+ reads) | Write-heavy workloads |
| Cùng items được đọc nhiều lần | Mỗi item chỉ đọc 1 lần |
| Cần microsecond latency (gaming, trading) | Milliseconds là đủ |
| Muốn giảm RCU cost | Cần strongly consistent reads |
Lưu ý: DAX chỉ hỗ trợ Eventually Consistent Reads. Nếu cần Strongly Consistent, phải bypass DAX.
Nguồn: DAX
So sánh DAX vs Global Tables vs Streams
[!IMPORTANT] Exam Tip: Phân biệt 3 features quan trọng này!
| Feature | Mục đích | Khi nào dùng |
|---|---|---|
| DAX | Tăng tốc đọc (in-memory cache) | Read-heavy, cần microsecond latency, giảm RCU cost |
| Global Tables | Multi-region sync | Global users, disaster recovery, low latency ở nhiều regions |
| Streams | Capture changes (event log) | Event-driven workflows, audit, sync to other services |
8. Transactions
Nguồn: DynamoDB Transactions
8.1 BatchWriteItem vs TransactWriteItems
8.2 DynamoDB Operators
9. TTL (Time to Live)
Nguồn: DynamoDB TTL
10. Best Practices
10.1 Data Modeling
| Practice | Mô tả |
|---|---|
| Single-Table Design | Một table cho nhiều entity types, sử dụng composite keys |
| Access Patterns First | Thiết kế schema dựa trên cách data sẽ được query |
| Denormalization | Duplicate data để tránh joins, optimize cho read |
| Sparse Indexes | Sử dụng GSI với projected attributes phù hợp |
10.2 Partition Key
| Do ✅ | Don't ❌ |
|---|---|
| Sử dụng UUID hoặc high-cardinality values | Sequential keys (timestamps, auto-increment IDs) |
| Hash của natural keys nếu cần | Low-cardinality (status, category, date) |
| Thêm prefix/suffix để distribute | Monotonically increasing values |
10.3 Read/Write Optimization
| Practice | Benefit |
|---|---|
| Batch Operations | BatchGetItem, BatchWriteItem (tối đa 25 items) |
| Parallel Scan | Phân chia scan workload cho large tables |
| Projection Expressions | Chỉ retrieve cần thiết attributes |
| Pagination | Sử dụng LastEvaluatedKey cho large result sets |
| Conditional Writes | Optimistic locking để tránh conflicts |
10.4 Cost Optimization
| Strategy | Mô tả |
|---|---|
| Use On-Demand cho unpredictable | Không cần capacity planning |
| Use Provisioned cho steady traffic | Reserved capacity giảm cost |
| Enable Auto Scaling | Scale capacity theo demand |
| Use DAX for read-heavy | Giảm read operations cost |
| Table Classes | Standard-IA cho infrequently accessed data |
| TTL | Tự động xóa không cần thiết data |
10.5 Security
| Feature | Implementation |
|---|---|
| Encryption at Rest | AWS owned keys hoặc KMS CMK |
| Encryption in Transit | TLS 1.2+ |
| IAM Policies | Fine-grained access control |
| VPC Endpoints | Private connectivity |
| Point-in-Time Recovery | 35-day backup window |
| Continuous Backups | Cross-region backup |
Nguồn: DynamoDB Best Practices
10.6 Backup & Recovery
Backup & Recovery trong DynamoDB xoay quanh 2 cơ chế cốt lõi:
- Point-in-Time Recovery (PITR): continuous backup, restore theo mốc thời gian bất kỳ
- On-demand Backup: snapshot theo thời điểm bạn chủ động tạo backup
Cả hai đều là non-disruptive đối với workload đang chạy và được dùng để bảo vệ dữ liệu trước accidental delete, accidental write, operational mistakes, hoặc yêu cầu lưu trữ/tuân thủ.
10.6.1 Point-in-Time Recovery (PITR)
PITR là cơ chế backup liên tục của DynamoDB. Khi bật PITR, DynamoDB tự động giữ recovery points trong khoảng thời gian cấu hình được, với độ chi tiết theo từng giây.
Đặc điểm chính:
- Restore về bất kỳ thời điểm nào trong recovery window
- Recovery window tối đa 35 ngày
- Phù hợp cho tình huống cần quay lại trạng thái ngay trước khi sự cố xảy ra
- Không ảnh hưởng performance hoặc API latency của bảng đang hoạt động
Khi nào dùng PITR?
- Lỡ xóa dữ liệu nhầm
- Ứng dụng ghi sai/corrupted data
- Muốn rollback về một thời điểm rất cụ thể
- Cần giảm
RPOcho lỗi vận hành
10.6.2 On-demand Backup
On-demand Backup là snapshot toàn bảng tại một thời điểm xác định. Bạn chủ động tạo backup khi cần, hoặc điều phối qua AWS Backup cho các policy backup tập trung.
Đặc điểm chính:
- Restore về đúng trạng thái tại thời điểm backup được tạo
- Phù hợp cho lưu trữ dài hạn, audit, compliance, hoặc backup trước thay đổi lớn
- Không linh hoạt bằng PITR nếu bạn cần quay lại một mốc rất sát trước thời điểm lỗi
Khi nào dùng On-demand Backup?
- Trước khi migration hoặc release lớn
- Trước khi chạy batch job rủi ro cao
- Yêu cầu giữ snapshot theo policy nội bộ/compliance
- Muốn lưu backup lâu hơn logic continuous rollback thông thường
10.6.3 Restore hoạt động như thế nào?
Khi restore từ PITR hoặc On-demand Backup, DynamoDB sẽ tạo ra một bảng mới thay vì overwrite trực tiếp bảng cũ.
Điều này có nghĩa là:
- Bạn restore ra một destination table mới
- Kiểm tra dữ liệu của bảng đã restore
- Thực hiện cutover ứng dụng sang bảng mới nếu cần
Những thứ thường cần cấu hình lại sau restore:
- Auto Scaling policies
- IAM policies liên quan
- CloudWatch metrics/alarms
- Tags
- Stream settings
- TTL settings
- PITR settings cho bảng mới
10.6.4 AWS Backup và DynamoDB
Ngoài cơ chế native của DynamoDB, bạn có thể dùng AWS Backup để:
- tạo và quản lý on-demand backup theo policy tập trung
- quản lý retention
- sao chép backup cross-account hoặc cross-Region
- áp dụng governance/backup compliance trên nhiều resource AWS
AWS Backup hữu ích khi tổ chức muốn quản lý backup tập trung cho nhiều account hoặc nhiều dịch vụ, thay vì vận hành backup từng bảng rời rạc.
10.6.5 So sánh nhanh các lựa chọn liên quan
| Tính năng | Mục đích chính | Điểm mạnh | Không nên nhầm với |
|---|---|---|---|
| PITR | Restore về một thời điểm cụ thể | Per-second granularity, rollback linh hoạt | Snapshot cố định |
| On-demand Backup | Snapshot tại một mốc xác định | Tốt cho compliance, change freeze, pre-release backup | Continuous rollback |
| DynamoDB Streams | Ghi nhận thay đổi dữ liệu | Event-driven processing, CDC, audit | Backup/restore native |
| Global Tables | Multi-Region active-active replication | HA, low-latency global writes/reads | Cơ chế rollback dữ liệu |
10.6.6 Rule nhớ nhanh
- Cần restore về ngay trước khi lỗi xảy ra → PITR
- Cần backup tại một thời điểm cố định → On-demand Backup
- Cần capture thay đổi dữ liệu để trigger xử lý → Streams
- Cần multi-Region active-active → Global Tables
Nguồn:
11. Pricing
11.1 Core Pricing Components
| Component | On-Demand | Provisioned |
|---|---|---|
| Write | $1.25 per million WRUs | $0.00065 per WCU/hour |
| Read | $0.25 per million RRUs | $0.00013 per RCU/hour |
| Storage | $0.25 per GB/month (Standard) | $0.25 per GB/month |
| Storage IA | $0.10 per GB/month | $0.10 per GB/month |
11.2 Optional Features Pricing
| Feature | Giá |
|---|---|
| DynamoDB Streams | $0.02 per 100,000 read request units |
| Global Tables | Replicated write requests × số regions |
| DAX | EC2 instance cost cho DAX nodes |
| Transactions | 2× regular read/write cost |
| On-Demand Backup | $0.10 per GB |
| Point-in-Time Recovery | $0.20 per GB |
| Data Transfer | AWS standard data transfer rates |
11.3 Free Tier
| Resource | Limit |
|---|---|
| Write Capacity | 200 million WRUs/month |
| Read Capacity | 2.5 million RRUs/month |
| Storage | 25 GB |
| Streams Read | 2.5 million read request units |
11.4 Cost Example
Nguồn: DynamoDB Pricing
Summary
| Feature | Key Point |
|---|---|
| Type | NoSQL key-value và document database |
| Performance | Single-digit millisecond latency ở mọi scale |
| Capacity Modes | On-Demand (pay-per-request) hoặc Provisioned (capacity-based) |
| Primary Key | Simple (Partition Key) hoặc Composite (Partition + Sort Key) |
| Secondary Indexes | GSI (khác partition key) và LSI (cùng partition key) |
| Global Tables | Multi-region active-active replication |
| Streams | Change data capture cho event-driven architectures |
| DAX | In-memory caching (microsecond latency) |
| Transactions | ACID operations trên multiple items/tables |
| TTL | Tự động xóa items theo timestamp |
Đánh dấu [x] trong README.md khi hoàn thành topic này