Appearance
DynamoDB Production Setup
Production Checklist
Capacity planning:
javascript
// Node.js (chạy độc lập, không cần AWS; đã chạy: in 5000 / 2000 / 6000 / 2400)
// Calculate required capacity:
// 1. Determine item size (avg)
const itemSize = 2000 // 2KB average
// 2. Calculate reads per second
const readsPerSec = 5000
const stronglyConsistent = true // true = 1 RCU per 4KB, false = 0.5 RCU per 4KB
const rcuPerRead = Math.ceil(itemSize / 4096) // 1 RCU per 4KB
const totalRCU = stronglyConsistent
? readsPerSec * rcuPerRead
: readsPerSec * rcuPerRead * 0.5
console.log(`Required RCU: ${totalRCU}`) // 5000 RCU
// 3. Calculate writes per second
const writesPerSec = 1000
const wcuPerWrite = Math.ceil(itemSize / 1024) // 1 WCU per 1KB
const totalWCU = writesPerSec * wcuPerWrite
console.log(`Required WCU: ${totalWCU}`) // 2000 WCU
// 4. Add 20% buffer for bursts:
const finalRCU = Math.ceil(totalRCU * 1.2) // 6000 RCU
const finalWCU = Math.ceil(totalWCU * 1.2) // 2400 WCUTable configuration:
javascript
// Node.js (minh hoạ: ARN KMS và account ID là placeholder; DynamoDB Local không có KMS)
import { DynamoDBClient, CreateTableCommand } from '@aws-sdk/client-dynamodb' // SDK v3 (ESM: top-level await)
const dynamodb = new DynamoDBClient({})
await dynamodb.send(new CreateTableCommand({
TableName: 'Users',
// Key schema
KeySchema: [
{ AttributeName: 'userId', KeyType: 'HASH' }, // Partition key
{ AttributeName: 'timestamp', KeyType: 'RANGE' } // Sort key
],
AttributeDefinitions: [
{ AttributeName: 'userId', AttributeType: 'S' },
{ AttributeName: 'timestamp', AttributeType: 'N' },
{ AttributeName: 'email', AttributeType: 'S' } // For GSI
],
// Provisioned capacity (production)
BillingMode: 'PROVISIONED',
ProvisionedThroughput: {
ReadCapacityUnits: 6000,
WriteCapacityUnits: 2400 // phải đủ cho ghi ứng dụng cộng ghi nhân bản nếu dùng global tables
},
// Global Secondary Index
GlobalSecondaryIndexes: [{
IndexName: 'email-index',
KeySchema: [
{ AttributeName: 'email', KeyType: 'HASH' }
],
Projection: {
ProjectionType: 'KEYS_ONLY' // Minimize storage cost
},
ProvisionedThroughput: {
ReadCapacityUnits: 1000, // Estimate based on query pattern
WriteCapacityUnits: 2400 // cận trên: GSI chỉ nhận ghi khi item có thuộc tính email hoặc khi thuộc tính khoá/chiếu đổi
}
}],
// Encryption at rest is always on (default: AWS owned key); this sets an AWS managed/customer managed KMS key
SSESpecification: {
Enabled: true,
SSEType: 'KMS', // Use KMS for customer-managed keys
KMSMasterKeyId: 'arn:aws:kms:us-east-1:123456789012:key/...'
},
// Chặn DeleteTable cho tới khi tắt cờ này (nên bật cho bảng production)
DeletionProtectionEnabled: true,
// PITR KHÔNG phải tham số của CreateTable: bật bằng UpdateContinuousBackups
// ngay khi bảng ACTIVE (xem Backup Strategies, mục 2)
// Enable streams for change data capture
StreamSpecification: {
StreamEnabled: true,
StreamViewType: 'NEW_AND_OLD_IMAGES' // Capture before + after
},
// Tags for cost allocation
Tags: [
{ Key: 'Environment', Value: 'production' },
{ Key: 'Team', Value: 'backend' },
{ Key: 'CostCenter', Value: 'engineering' }
]
}))Monitoring Queries
1. Check consumed capacity (detect throttling):
javascript
// Node.js (chưa chạy: dịch vụ quản lý CloudWatch; tham số đối chiếu GetMetricStatistics API reference)
import { CloudWatchClient, GetMetricStatisticsCommand } from '@aws-sdk/client-cloudwatch'
const cloudwatch = new CloudWatchClient({})
// Get read capacity utilization:
const readMetrics = await cloudwatch.send(new GetMetricStatisticsCommand({
Namespace: 'AWS/DynamoDB',
MetricName: 'ConsumedReadCapacityUnits',
Dimensions: [{ Name: 'TableName', Value: 'Users' }],
StartTime: new Date(Date.now() - 3600000), // Last hour
EndTime: new Date(),
Period: 300, // 5-minute intervals
Statistics: ['Sum', 'Maximum']
}))
// Alert if utilization > 80%:
const provisioned = 6000 // Provisioned RCU
readMetrics.Datapoints.forEach(dp => {
const utilization = (dp.Sum / 300) / provisioned // Avg per second
if (utilization > 0.8) {
console.warn(`High read utilization: ${(utilization * 100).toFixed(1)}%`)
}
})2. Check throttling events:
javascript
// Node.js (dùng lại `cloudwatch` ở khối trên; chưa chạy: CloudWatch)
// Get throttled requests:
const throttleMetrics = await cloudwatch.send(new GetMetricStatisticsCommand({
Namespace: 'AWS/DynamoDB',
// WriteThrottleEvents / ReadThrottleEvents chỉ cần dimension TableName.
// ThrottledRequests được xuất với dimension TableName + Operation: chỉ lọc TableName thì không ra điểm dữ liệu.
// Nghi hot partition: Read/WriteKeyRangeThroughputThrottleEvents ("throttled due to partition limits").
MetricName: 'WriteThrottleEvents',
Dimensions: [{ Name: 'TableName', Value: 'Users' }],
StartTime: new Date(Date.now() - 3600000),
EndTime: new Date(),
Period: 300,
Statistics: ['Sum']
}))
// Alert if any throttling:
const totalThrottled = throttleMetrics.Datapoints.reduce((sum, dp) => sum + dp.Sum, 0)
if (totalThrottled > 0) {
console.error(`Throttled requests: ${totalThrottled}`)
}3. Monitor GSI consumption:
javascript
// GSI read capacity:
const gsiMetrics = await cloudwatch.send(new GetMetricStatisticsCommand({
Namespace: 'AWS/DynamoDB',
MetricName: 'ConsumedReadCapacityUnits',
Dimensions: [
{ Name: 'TableName', Value: 'Users' },
{ Name: 'GlobalSecondaryIndexName', Value: 'email-index' }
],
StartTime: new Date(Date.now() - 3600000),
EndTime: new Date(),
Period: 300,
Statistics: ['Sum']
}))4. Check item sizes (detect bloat):
javascript
// Node.js (đã chạy trên DynamoDB Local: bắt được item 150 KB)
// RISK: Scan đọc cả bảng, tiêu tốn RCU toàn bảng và có thể gây throttle trên bảng production.
// Chỉ chạy trên bảng nhỏ, trên bản restore, hoặc dùng Export to S3 thay cho Scan.
// JSON.stringify(item).length là số ký tự, chỉ xấp xỉ kích thước item DynamoDB tính.
// Scan table to find large items:
import { DynamoDBClient } from '@aws-sdk/client-dynamodb'
import { DynamoDBDocumentClient, ScanCommand } from '@aws-sdk/lib-dynamodb'
const docClient = DynamoDBDocumentClient.from(new DynamoDBClient({}))
let largeItems = []
let params = { TableName: 'Users', Limit: 1000 }
do {
const result = await docClient.send(new ScanCommand(params))
result.Items.forEach(item => {
const size = JSON.stringify(item).length
if (size > 100000) { // >100KB
largeItems.push({ userId: item.userId, size })
}
})
params.ExclusiveStartKey = result.LastEvaluatedKey
} while (params.ExclusiveStartKey)
console.log('Items >100KB:', largeItems)
// DynamoDB limit: 400KB per item (alert if >300KB)Backup Strategies
1. On-demand backups:
javascript
// Node.js (chạy sau khối Table configuration ở mục Production Checklist, dùng chung `dynamodb`;
// chưa chạy: DynamoDB Local không hỗ trợ backup, trả UnknownOperationException; ARN là placeholder)
import { CreateBackupCommand, ListBackupsCommand, RestoreTableFromBackupCommand } from '@aws-sdk/client-dynamodb'
// Create backup:
await dynamodb.send(new CreateBackupCommand({
TableName: 'Users',
BackupName: `Users-backup-${Date.now()}`
}))
// List backups:
const backups = await dynamodb.send(new ListBackupsCommand({
TableName: 'Users',
TimeRangeLowerBound: new Date(Date.now() - 30 * 86400000) // Last 30 days
}))
// Restore from backup:
await dynamodb.send(new RestoreTableFromBackupCommand({
TargetTableName: 'Users-restored',
BackupArn: 'arn:aws:dynamodb:us-east-1:123456789012:table/Users/backup/...'
}))2. Point-in-time recovery (PITR):
javascript
// Node.js (chạy sau khối Table configuration; chưa chạy: DynamoDB Local không hỗ trợ PITR, trả UnknownOperationException)
import { RestoreTableToPointInTimeCommand, UpdateContinuousBackupsCommand } from '@aws-sdk/client-dynamodb'
// Enable PITR (covers last 35 days):
await dynamodb.send(new UpdateContinuousBackupsCommand({
TableName: 'Users',
PointInTimeRecoverySpecification: {
PointInTimeRecoveryEnabled: true
}
}))
// Restore to specific timestamp:
await dynamodb.send(new RestoreTableToPointInTimeCommand({
SourceTableName: 'Users',
TargetTableName: 'Users-recovered',
RestoreDateTime: new Date(Date.now() - 3600000), // ví dụ: 1 giờ trước; phải nằm trong cửa sổ PITR (tối đa 35 ngày) và sau lúc bật PITR
UseLatestRestorableTime: false
}))3. Cross-region replication (Global Tables):
javascript
// Node.js (chạy sau khối Table configuration; chưa chạy: DynamoDB Local không hỗ trợ global tables, báo "Nothing to update")
import { UpdateTableCommand } from '@aws-sdk/client-dynamodb'
// Create global table (multi-region):
// Global Tables 2019.11.21 (current): add replicas via UpdateTable ReplicaUpdates: [{ Create: { RegionName: 'eu-west-1' } }]
// Run against the source table in us-east-1; add one replica per call, wait for ACTIVE in between
await dynamodb.send(new UpdateTableCommand({
TableName: 'Users',
ReplicaUpdates: [{ Create: { RegionName: 'eu-west-1' } }]
}))
await dynamodb.send(new UpdateTableCommand({
TableName: 'Users',
ReplicaUpdates: [{ Create: { RegionName: 'ap-southeast-1' } }]
}))
// Benefits:
// - Multi-region redundancy (disaster recovery)
// - Low-latency reads from nearest region
// - Automatic replication (typically <1 second)
// - Chi phí: mỗi region có replica tính rWCU/rWRU (trang giá không nêu đơn giá rWCU/rWRU riêng: đối chiếu trang giá) cho mỗi lần ghi: 3 region như ví dụ trên = ghi 3 lần, cộng storage mỗi region; GSI tính thêmSecurity Hardening
1. IAM policies (least privilege; ${aws:username} chỉ có với IAM user, role và federated user không có biến này nên điều kiện không khớp):
json
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Action": [
"dynamodb:GetItem",
"dynamodb:Query",
"dynamodb:PutItem",
"dynamodb:UpdateItem"
],
"Resource": "arn:aws:dynamodb:us-east-1:123456789012:table/Users",
"Condition": {
"ForAllValues:StringEquals": {
"dynamodb:LeadingKeys": ["${aws:username}"]
}
}
}]
}2. VPC endpoints (private network):
bash
# Create VPC endpoint for DynamoDB (no internet gateway needed):
aws ec2 create-vpc-endpoint \
--vpc-id vpc-12345 \
--service-name com.amazonaws.us-east-1.dynamodb \
--route-table-ids rtb-12345
# Benefits:
# - Traffic stays within AWS network (no internet exposure)
# - Lower latency
# - No data transfer charges3. Encryption:
javascript
// Minh hoạ, không chạy độc lập: đây là phần SSESpecification của CreateTableCommand ở mục Production Checklist
// At rest (KMS):
SSESpecification: {
Enabled: true,
SSEType: 'KMS',
KMSMasterKeyId: 'arn:aws:kms:us-east-1:123456789012:key/...'
}
// In transit (TLS 1.2+):
// Default for all AWS SDK connectionsPhải nhớ (DynamoDB production):
- Bật deletion protection ở CreateTable và PITR bằng
UpdateContinuousBackups(CreateTable không có tham số PITR). - Cảnh báo throttle bằng
Read/WriteThrottleEvents(dimension TableName); nghi hot partition thì xemRead/WriteKeyRangeThroughputThrottleEvents. - Mỗi GSI và mỗi replica global table nhân thêm chi phí ghi.