Skip to content

DynamoDB Architecture ​

Code JavaScript trong các mục DynamoDB dùng AWS SDK v3 (@aws-sdk/client-dynamodb, @aws-sdk/lib-dynamodb, gọi client.send(new XxxCommand(params))). SDK v2 (aws-sdk, .promise()) hết hỗ trợ 09/2025.

Tình huống: Vừa ghi xong đơn hàng, truy vấn qua GSI không thấy đơn đó; hoặc bảng 1 000 WCU vẫn báo throttle khi một key nhận quá nhiều ghi. Hai triệu chứng đều đến từ cách DynamoDB chia dữ liệu theo partition key và đồng bộ index bất đồng bộ; xem hai mục GOTCHA bên dưới.

Client dùng chung cho mọi khối JavaScript trong phần DynamoDB (các khối khác ghi "chạy sau khối tạo client"):

javascript
// Node.js: tạo client dùng chung (biến dynamodb)
import { DynamoDBClient } from '@aws-sdk/client-dynamodb'
import { DynamoDBDocumentClient } from '@aws-sdk/lib-dynamodb'

const client = new DynamoDBClient({ region: 'us-east-1' })
// DynamoDB Local: thêm endpoint: 'http://localhost:8000' và credentials: { accessKeyId: 'x', secretAccessKey: 'x' }
const dynamodb = DynamoDBDocumentClient.from(client)

DynamoDB là gì? ​

DynamoDB là cơ sở dữ liệu NoSQL do AWS quản lý hoàn toàn, serverless, hỗ trợ cả key-value lẫn document, độ trễ thường ở mức vài mili-giây.

Đặc điểm chính:

  • ✅ Serverless: không quản lý máy chủ, có auto scaling
  • ✅ Hiệu năng ổn định: thường vài ms (không có SLA về độ trễ; SLA chỉ cam kết khả dụng 99,99% / 99,999%)
  • ✅ Scale ngang: doc quota ghi "no practical limit on a table's size"; trần nằm ở mỗi partition (xem mục Hot Partition)
  • ✅ Giao dịch ACID: transaction nhiều item (từ 2018)
  • ✅ Global tables: nhiều region, active-active
  • ✅ Hướng sự kiện: DynamoDB Streams (CDC)

Core Concepts ​

Bảng (Tables)

  • Không cố định schema (giống collection của MongoDB)
  • Bắt buộc có primary key (chỉ partition key, hoặc partition key + sort key)

Item (dòng)

  • Tối đa 400 KB mỗi item
  • Mỗi item có thể có tập attribute khác nhau

Attribute (cột)

  • Kiểu dữ liệu: String, Number, Binary, Boolean, Null, List, Map, Set

Primary Key (REQUIRED)

Option 1: Partition Key only (simple primary key)

text
PK (Partition Key)
─────────────────
USER#12345         → Distributes data across partitions

Option 2: Partition Key + Sort Key (composite primary key)

text
PK (Partition Key)    SK (Sort Key)
──────────────────    ──────────────
USER#12345            METADATA
USER#12345            ORDER#2024-01-01
USER#12345            ORDER#2024-01-05

DynamoDB Data Model Example ​

javascript
// Node.js, minh hoạ hình dạng item (không chạy độc lập; ghi bằng PutCommand, Item: {...})
// Users table
{
  PK: "USER#12345",                    // Partition key (required)
  SK: "METADATA",                      // Sort key (optional)
  email: "john@example.com",
  name: "John Doe",
  createdAt: "2024-01-01T00:00:00Z",
  subscription: {                      // Nested object (document model)
    plan: "premium",
    expiresAt: "2025-01-01T00:00:00Z"
  },
  tags: ["verified", "premium"]        // List
}

// Orders for same user (same partition key)
{
  PK: "USER#12345",
  SK: "ORDER#2024-01-01#001",
  orderId: "001",
  total: 99.99,
  status: "completed"
}

Single-Table Design (Advanced Pattern) ​

Traditional multi-table approach (SQL-style):

text
Users table
Orders table
Products table
→ 3 tables, 3 queries

DynamoDB single-table approach:

text
Main table (all entities in one table)
PK                    SK                        Type      Data
────────────────────────────────────────────────────────────────
USER#123              METADATA                  User      {name, email}
USER#123              ORDER#001                 Order     {total, status}
USER#123              ORDER#002                 Order     {total, status}
PRODUCT#456           METADATA                  Product   {name, price}
ORDER#001             PRODUCT#456               OrderItem {quantity}

Lợi ích:

  • ✅ 1 query lấy được user cùng các order (thay vì 2 query)
  • ✅ Giao dịch nguyên tử xuyên nhiều loại entity
  • ✅ Ít bảng phải quản lý hơn
  • ❌ Phải thiết kế trước các access pattern

Indexes ​

1. Primary Key (required) (SQL: PRIMARY KEY = Partition Key + Sort Key)

  • Partition key (PK): quyết định item nằm ở partition nào
  • Sort key (SK): tuỳ chọn, cho phép truy vấn theo khoảng trong cùng partition key

2. Global Secondary Index (GSI) (SQL: tương tự Composite Index nhưng eventually consistent)

  • Partition key và/hoặc sort key khác bảng gốc
  • Eventually consistent (replication bất đồng bộ)
  • Có WCU/RCU riêng (tốn thêm chi phí)
  • Tối đa 20 mỗi bảng (mặc định 20, có thể xin tăng)

⚠️ GOTCHA: Độ trễ lan truyền GSI (ghi thành công nhưng truy vấn GSI trả dữ liệu cũ)

When you write to a DynamoDB table, the write is acknowledged IMMEDIATELY, but the Global Secondary Index (GSI) is updated asynchronously. GSI queries can return stale/old data for seconds (or even minutes during high load), even though the write succeeded.

Vì sao xảy ra:

  • GSI là eventually consistent (không có strongly consistent read)
  • DynamoDB replicate ghi sang GSI bất đồng bộ (lưu trữ riêng)
  • Tải bình thường: thường chỉ một phần giây (không đảm bảo)
  • Tải ghi cao hoặc GSI bị throttle: trễ từ vài giây đến vài phút
  • Nếu GSI provision thiếu WCU: ghi vào BẢNG GỐC bị throttle (back-pressure)

Real-world bug:

javascript
// Node.js
import { CreateTableCommand } from '@aws-sdk/client-dynamodb'
import { PutCommand, QueryCommand } from '@aws-sdk/lib-dynamodb'
// chạy sau khối tạo client (biến client, dynamodb) ở đầu mục DynamoDB Architecture

// 0. Tạo bảng Orders với GSI UserIdIndex (userId HASH, createdAt RANGE)
await client.send(new CreateTableCommand({
  TableName: 'Orders',
  BillingMode: 'PAY_PER_REQUEST',
  AttributeDefinitions: [
    { AttributeName: 'orderId', AttributeType: 'S' },
    { AttributeName: 'userId', AttributeType: 'S' },
    { AttributeName: 'createdAt', AttributeType: 'N' }
  ],
  KeySchema: [{ AttributeName: 'orderId', KeyType: 'HASH' }],
  GlobalSecondaryIndexes: [{
    IndexName: 'UserIdIndex',
    KeySchema: [
      { AttributeName: 'userId', KeyType: 'HASH' },
      { AttributeName: 'createdAt', KeyType: 'RANGE' }
    ],
    Projection: { ProjectionType: 'ALL' }
  }]
}))

// 1. Create new order
await dynamodb.send(new PutCommand({
  TableName: 'Orders',
  Item: {
    orderId: 'ORDER#123',
    userId: 'USER#456',
    status: 'pending',
    createdAt: Date.now()
  }
}))
// ✅ Write acknowledged

// 2. Immediately query orders by userId using GSI
const result = await dynamodb.send(new QueryCommand({
  TableName: 'Orders',
  IndexName: 'UserIdIndex',  // GSI: userId (PK), createdAt (SK)
  KeyConditionExpression: 'userId = :uid',
  ExpressionAttributeValues: { ':uid': 'USER#456' }
}))

// Trên AWS thật có thể THIẾU ORDER#123: GSI còn đang đồng bộ, query trả dữ liệu cũ
// (DynamoDB Local trả đủ ngay vì không mô phỏng độ trễ GSI)
// User sees "No orders" even though order just created

How to detect:

javascript
// Node.js, minh hoạ, không chạy độc lập: `...` là placeholder; chạy sau khối tạo client và bảng Orders ở trên
import { GetCommand, QueryCommand } from '@aws-sdk/lib-dynamodb'

// Monitor GSI propagation lag (CloudWatch metric)
// No direct GSI propagation-lag metric; watch WriteThrottleEvents on the GSI (GlobalSecondaryIndexName dimension)
// OnlineIndexPercentageProgress only tracks new-index backfill

// Check for missing items after write
const tableResult = await dynamodb.send(new GetCommand({
  TableName: 'Orders',
  Key: { orderId: 'ORDER#123' }
}))
// Item exists in table

const gsiResult = await dynamodb.send(new QueryCommand({
  IndexName: 'UserIdIndex',
  KeyConditionExpression: 'userId = :uid',
  ...
}))
// Item missing in GSI → propagation lag!

Prevention:

  1. Query bảng gốc sau khi ghi (không qua GSI) để đọc-sau-ghi:
    javascript

// Node.js import { GetCommand, PutCommand } from '@aws-sdk/lib-dynamodb'

await dynamodb.send(new PutCommand({...}))

// Use GetItem on base table (strongly consistent) const result = await dynamodb.send(new GetCommand({ TableName: 'Orders', Key: { orderId: 'ORDER#123' }, ConsistentRead: true // ✓ Always latest data }))


2. **Provision đủ WCU cho GSI** khớp tải ghi của bảng gốc:
```javascript
// Node.js
// Base table: 1000 WCU
// GSI needs WCU ≥ projected writes it receives (auto-scale it too, with matching settings)
  1. Thêm timestamp và lọc phía client:
    javascript

// Node.js import { GetCommand, QueryCommand } from '@aws-sdk/lib-dynamodb'

// Query GSI but filter out stale results const result = await dynamodb.send(new QueryCommand({...})) const recentOrders = result.Items.filter(order => Date.now() - order.createdAt < 60000 // Only orders in last 60s )

// If just created order missing, fallback to GetItem if (!recentOrders.find(o => o.orderId === 'ORDER#123')) { const order = await dynamodb.send(new GetCommand({ TableName: 'Orders', Key: { orderId: 'ORDER#123' } })) if (order.Item) recentOrders.push(order.Item) }


4. **Dùng DynamoDB Streams + Lambda** để đảm bảo nhất quán ở downstream:
```javascript
// Node.js
// Write to table → Stream event → Lambda processes → Update cache
// Streams: each record appears exactly once, ordered per item (not globally); 24h retention

→ See also: DynamoDB Auto-Scaling, DynamoDB Anti-Patterns

3. Local Secondary Index (LSI) (SQL: Composite Index với cùng prefix column)

  • Same partition key, different sort key
  • Query/Scan dùng được cả eventually consistent lẫn strongly consistent read (tham số ConsistentRead); dùng chung capacity của bảng; mỗi item collection tối đa 10 GB
  • Phải tạo lúc tạo bảng (không thêm sau được)
  • Max 5 per table

Example:

javascript
// Node.js, minh hoạ, không chạy độc lập: chỉ là tham số, gửi bằng GetCommand / QueryCommand (bảng Users + GSI1 + GSI2 đã tạo và query OK trên dynamodb-local)
// Table: Users
// Primary key: email (PK)
// GSI1: userId (PK), createdAt (SK)  → Query by userId
// GSI2: country (PK), email (SK)     → Query users by country
// LSI not possible: table has a simple primary key (email only); use a GSI or add a sort key at creation

// Query by email (primary key)
const params = {
  TableName: 'Users',
  Key: { email: 'john@example.com' }
}

// Query by userId (GSI1)
const params = {
  TableName: 'Users',
  IndexName: 'GSI1',
  KeyConditionExpression: 'userId = :uid',
  ExpressionAttributeValues: { ':uid': '12345' }
}

Read/Write Capacity Modes ​

1. On-Demand (Serverless)

  • Trả theo từng request, không cần khai báo capacity trước
  • Hấp thụ ngay tới 2 lần đỉnh lưu lượng trước đó; tăng vọt hơn thế có thể bị throttle
  • Hợp với: lưu lượng khó đoán, ứng dụng mới, dev/test
  • Cost: $0.625 mỗi triệu write request unit, $0.125 mỗi triệu read request unit (us-east-1, bảng Standard; kiểm 2026-11-20 tại bảng giá on-demand; giá đổi theo region)

2. Provisioned Capacity

  • Provision trước RCU (đọc) và WCU (ghi)
  • Có auto-scaling
  • Phù hợp: traffic dự đoán được, tối ưu chi phí
  • Cost: $0.00065 mỗi WCU/giờ, $0.00013 mỗi RCU/giờ (us-east-1, bảng Standard; kiểm 2026-11-20 tại bảng giá provisioned)

Capacity units:

  • 1 RCU = 1 strongly consistent read/giây (tối đa 4KB)
  • 1 RCU = 2 eventually consistent read/giây (tối đa 4KB)
  • 1 WCU = 1 write/giây (tối đa 1KB)
  • Giao dịch (TransactWriteItems/TransactGetItems): mỗi item tốn gấp đôi (một lần chuẩn bị, một lần xác nhận)

Example calculation:

text
Query: Read 100 items/sec, 10KB each, eventually consistent

RCU needed:
- 10KB / 4KB = 2.5 → round up to 3 read units per item
- Eventually consistent = 3 / 2 = 1.5 RCU per item
- 100 items/sec × 1.5 = 150 RCU

Cost:
- On-demand: 150 RRU/sec × 3,600 × 730 × $0.125 / 1M ≈ $49.28/month
- Provisioned: 150 RCU × $0.00013/hr × 730 hr = $14.24/month (rẻ hơn ≈3,5 lần khi tải đều 24/7: 49,28 / 14,235)

⚠️ GOTCHA: Hot partition vẫn bị throttle dù capacity cấp bảng đủ

Adaptive capacity shifts throughput to hot partitions automatically, but each partition is still hard-capped at 3,000 RCU and 1,000 WCU. If one partition key receives more traffic than its allocated capacity (hot partition), DynamoDB throttles requests to that partition EVEN IF your table-level capacity is sufficient.

Why it happens:

  • Mỗi partition có trần cứng 3 000 read unit/s và 1 000 write unit/s, bất kể bảng có bao nhiêu capacity
  • Adaptive capacity dồn throughput sang partition nóng nhưng KHÔNG vượt trần partition
  • Một partition (một item đơn, hoặc item collection không tách được như bảng có LSI) nhận hơn 1 000 write unit/s thì bị throttle dù bảng provisioned 5 000 WCU còn rảnh; bảng có sort key và không LSI thì adaptive capacity có thể tách item collection, không bảo đảm
  • Doc: "Every partition in a DynamoDB table is designed to deliver a maximum capacity of 3,000 read units per second and 1,000 write units per second."

Real-world throttling (chạy sau khối tạo client; bảng Events: eventType HASH, userId RANGE; DynamoDB Local không mô phỏng throttle nên khối này chưa chạy được ra lỗi, chỉ chạy được phần ghi):

javascript
// Node.js
import { CreateTableCommand } from '@aws-sdk/client-dynamodb'
import { PutCommand } from '@aws-sdk/lib-dynamodb'

// Tạo bảng Events (provisioned 5000 WCU, partition key eventType, sort key userId; không có LSI)
await client.send(new CreateTableCommand({
  TableName: 'Events',
  BillingMode: 'PROVISIONED',
  ProvisionedThroughput: { ReadCapacityUnits: 100, WriteCapacityUnits: 5000 },
  AttributeDefinitions: [
    { AttributeName: 'eventType', AttributeType: 'S' },
    { AttributeName: 'userId', AttributeType: 'S' }
  ],
  KeySchema: [
    { AttributeName: 'eventType', KeyType: 'HASH' },
    { AttributeName: 'userId', KeyType: 'RANGE' }
  ]
}))

// Item 1 KB (1 write = 1 WCU)
// Partition key: eventType, 90% ghi vào eventType = "user_login" (hot key)

// 1 500 ghi/s vào MỘT partition key: có thể vượt trần 1 000 WCU của partition (bảng có sort key, không LSI: adaptive capacity có thể tách, không bảo đảm)
const promises = []
for (let i = 0; i < 1500; i++) {
  promises.push(
    dynamodb.send(new PutCommand({
      TableName: 'Events',
      Item: {
        eventType: 'user_login',  // Hot partition!
        userId: `USER#${i}`,
        timestamp: Date.now()
      }
    }))
  )
}

try {
  await Promise.all(promises)
} catch (err) {
  // ProvisionedThroughputExceededException trên AWS thật:
  // bảng còn nhiều WCU rảnh nhưng key "user_login" có thể vượt trần 1 000 WCU của partition
}

How to detect:

bash
# Throttle do trần partition: WriteKeyRangeThroughputThrottleEvents / ReadKeyRangeThroughputThrottleEvents
# Tổng request bị throttle: ThrottledRequests; key nóng: bật CloudWatch Contributor Insights cho bảng
# UserErrors KHÔNG chứa throttle (doc: throttle chỉ nằm ở ThrottledRequests)
aws cloudwatch get-metric-statistics \
  --namespace AWS/DynamoDB \
  --metric-name WriteKeyRangeThroughputThrottleEvents \
  --dimensions Name=TableName,Value=Events \
  --statistics Sum \
  --start-time 2025-01-01T00:00:00Z \
  --end-time 2025-01-01T01:00:00Z \
  --period 60

# Sum > 0 trong khi ConsumedWriteCapacityUnits thấp hơn provisioned: nghi hot key, kiểm phân bố partition key

Prevention:

  1. Thêm yếu tố ngẫu nhiên vào partition key (hậu tố shard):
    javascript

// Node.js // BAD: All "user_login" events go to same partition

// GOOD: Add random suffix (0-9) to distribute across 10 partitions const shard = Math.floor(Math.random() * 10) { eventType: user_login#${shard}, // user_login#0 to user_login#9 userId: 'USER#123', ... }

// Query requires scanning all shards (10 queries), but writes distributed!


2. **Dùng composite partition key** (cardinality cao):
```javascript
// Node.js
// Combine eventType + date (YYYY-MM-DD)
{
  eventType_date: 'user_login#2025-01-10',  // Different partition per day
  userId: 'USER#123',
  ...
}
// Distributes load across time, prevents single hot partition
  1. Dùng write sharding + aggregation:
    javascript

// Node.js import { GetCommand, UpdateCommand } from '@aws-sdk/lib-dynamodb'

// Write to multiple shard items const shard = Math.floor(Math.random() * 10) await dynamodb.send(new UpdateCommand({ TableName: 'EventCounts', Key: { eventType: user_login#shard_${shard} }, UpdateExpression: 'ADD #count :val', ExpressionAttributeNames: { '#count': 'count' }, // count is a reserved word ExpressionAttributeValues: { ':val': 1 } }))

// Aggregate shards on read const totalCount = await Promise.all( Array.from({ length: 10 }, (_, i) => dynamodb.send(new GetCommand({ TableName: 'EventCounts', Key: { eventType: user_login#shard_${i} } })) ) ).then(results => results.reduce((sum, r) => sum + (r.Item?.count || 0), 0) )


4. **On-Demand mode cũng KHÔNG bỏ trần partition** (3 000 RCU / 1 000 WCU mỗi partition vẫn áp dụng): on-demand chỉ bỏ việc lập kế hoạch capacity cho bảng, key nóng vẫn bị throttle. Chống bằng cách 1-3 ở trên.
```text
Trần partition: 3 000 RCU và 1 000 WCU, áp cho cả provisioned lẫn on-demand
  1. Dùng burst capacity cho đúng (hiểu cửa sổ 300 giây):
    • DynamoDB cho phép burst ngắn (dùng capacity chưa dùng của 300 giây gần nhất)
    • Đừng trông cậy vào burst cho traffic hot partition kéo dài

→ See also: DynamoDB Auto-Scaling, DynamoDB Anti-Patterns

DynamoDB Capacity Planning Calculator ​

Mục đích: Tính chi phí và nhu cầu capacity (RCU/WCU) của DynamoDB cho cả chế độ provisioned và on-demand, kèm phân tích chi phí GSI.

Cách dùng:

  1. Xác định yêu cầu (item size, QPS, số GSI)
  2. Chạy hàm tính cho cả hai chế độ để so sánh
  3. Chọn chế độ theo mẫu traffic và chi phí
  4. Theo dõi hot partition và chỉnh thiết kế partition key
javascript
// Node.js — giá us-east-1, bảng Standard, kiểm ngày 2026-11-20:
// https://aws.amazon.com/dynamodb/pricing/on-demand/ và https://aws.amazon.com/dynamodb/pricing/provisioned/
// Đổi region/bảng giá thì sửa PRICE trước khi dùng.
const PRICE = {
  onDemandWritePerM: 0.625,   // USD / triệu write request unit
  onDemandReadPerM: 0.125,    // USD / triệu read request unit
  wcuHour: 0.00065,           // USD / WCU / giờ
  rcuHour: 0.00013,           // USD / RCU / giờ
  storageGBMonth: 0.25,       // USD / GB / tháng, 25 GB đầu miễn phí
  freeStorageGB: 25,
}
const HOURS = 730                    // giờ / tháng
const SECONDS = HOURS * 3600         // 2_628_000 giây / tháng

/**
 * Tính capacity và chi phí DynamoDB (giả định GSI project cả item, mỗi ghi đi vào mọi GSI)
 * @param {Object} requirements
 * @returns {Object} capacity và chi phí
 */
function calculateDynamoDBCost(requirements) {
  const {
    itemSize = 1,          // KB trung bình mỗi item
    readsPerSecond = 1000,
    writesPerSecond = 100,
    storageGB = 100,
    consistentRead = false, // false = eventually consistent
    gsiCount = 2,
    mode = 'provisioned',  // 'provisioned' | 'on-demand'
  } = requirements

  // 1 RCU = 1 strongly consistent read tới 4KB/giây; eventually consistent tốn một nửa
  const readUnits = Math.ceil(itemSize / 4)
  const rcu = readsPerSecond * readUnits * (consistentRead ? 1 : 0.5)
  // 1 WCU = 1 write tới 1KB/giây
  const wcu = writesPerSecond * Math.ceil(itemSize)
  const gsiWCU = wcu * gsiCount
  const storageCost = Math.max(0, storageGB - PRICE.freeStorageGB) * PRICE.storageGBMonth

  let readCost, writeCost
  if (mode === 'on-demand') {
    readCost = rcu * SECONDS * PRICE.onDemandReadPerM / 1_000_000
    writeCost = (wcu + gsiWCU) * SECONDS * PRICE.onDemandWritePerM / 1_000_000
  } else {
    readCost = rcu * PRICE.rcuHour * HOURS
    writeCost = (wcu + gsiWCU) * PRICE.wcuHour * HOURS
  }

  return {
    mode: mode === 'on-demand' ? 'On-Demand' : 'Provisioned',
    capacity: {
      rcu: `${rcu.toFixed(0)} RCU`,
      wcu: `${wcu.toFixed(0)} WCU`,
      gsiWCU: `${gsiWCU.toFixed(0)} WCU (${gsiCount} GSIs)`,
    },
    cost: {
      reads: `$${readCost.toFixed(2)}/month`,
      writes: `$${writeCost.toFixed(2)}/month`,
      storage: `$${storageCost.toFixed(2)}/month`,
      total: `$${(readCost + writeCost + storageCost).toFixed(2)}/month`,
    },
    recommendations: [
      gsiCount >= 3 ? `⚠️ ${gsiCount} GSIs = ${1 + gsiCount}x write cost. Consider consolidating GSIs` : null,
      wcu > rcu ? '💡 Write-heavy workload. Check batching and GSI count first' : null,
    ].filter(Boolean)
  }
}

// Example 1: Gaming leaderboard (provisioned mode)
const leaderboard = calculateDynamoDBCost({
  itemSize: 5,              // 5KB item (userId, score, metadata)
  readsPerSecond: 1000,     // Read queries
  writesPerSecond: 100,     // Score updates
  storageGB: 100,
  consistentRead: false,    // Eventually consistent OK
  gsiCount: 3,              // GSI for score ranking, country ranking, daily ranking
  mode: 'provisioned'
})

console.log(JSON.stringify(leaderboard, null, 2))
/*
Kết quả (đã chạy Node 22, 2026-11-20):
{
  "mode": "Provisioned",
  "capacity": {
    "rcu": "1000 RCU",
    "wcu": "500 WCU",
    "gsiWCU": "1500 WCU (3 GSIs)"
  },
  "cost": {
    "reads": "$94.90/month",
    "writes": "$949.00/month",
    "storage": "$18.75/month",
    "total": "$1062.65/month"
  },
  "recommendations": [
    "⚠️ 3 GSIs = 4x write cost. Consider consolidating GSIs"
  ]
}
*/

Real-world cost examples (chạy sau khối calculateDynamoDBCost ở trên; kết quả đã chạy Node 22, 2026-11-20, giá us-east-1):

Ví dụ 1: Session store (on-demand)

javascript
// Node.js (chạy sau khối calculator ở trên)
calculateDynamoDBCost({
  itemSize: 2,              // 2KB session data
  readsPerSecond: 500,      // Read sessions
  writesPerSecond: 50,      // Update sessions
  storageGB: 10,
  gsiCount: 0,              // No GSIs needed
  mode: 'on-demand'
})
// Result: $246.38/month (reads $82.13, writes $164.25, storage $0.00 vì dưới 25 GB miễn phí)
// Best for: Unpredictable traffic

Example 2: E-commerce orders (provisioned)

javascript
// Node.js (chạy sau khối calculator ở trên)
calculateDynamoDBCost({
  itemSize: 10,             // 10KB order with items
  readsPerSecond: 2000,     // Order lookups
  writesPerSecond: 200,     // New orders
  storageGB: 500,
  consistentRead: true,     // Strong consistency for inventory
  gsiCount: 2,              // GSI for user orders, status
  mode: 'provisioned'
})
// Provisioned: $3,535.15/month (RCU $569.40, WCU + GSI $2,847.00, storage $118.75)
// On-Demand cùng tải: $11,944.75/month (≈3,4 lần đắt hơn)
// ✅ Use provisioned for steady traffic

Example 3: IoT sensor data (write-heavy)

javascript
// Node.js (chạy sau khối calculator ở trên)
calculateDynamoDBCost({
  itemSize: 1,              // 1KB sensor reading
  readsPerSecond: 100,      // Dashboard queries
  writesPerSecond: 5000,    // High write volume
  storageGB: 2000,
  consistentRead: false,
  gsiCount: 1,              // GSI for sensor type
  mode: 'provisioned'
})
// Result: $5,243.49/month (reads $4.75, writes $4,745.00, storage $493.75)
// ⚠️ Write-heavy: giảm GSI và gộp ghi trước; so với DB khác thì đo trên tải thật, không có số so sánh nguồn

Key capacity rules:

  1. Tính RCU: (item size KB / 4) × reads/sec ÷ 2 cho eventually consistent
  2. Tính WCU: (item size KB / 1) × writes/sec
  3. Hệ số GSI: mỗi GSI cộng thêm write unit theo kích thước item được PROJECT (chỉ với item có khoá GSI) (ghi được replicate sang mọi GSI)
  4. Provisioned vs On-Demand:
    • Provisioned: traffic dự đoán được, rẻ hơn khi mức dùng cao và ổn định (so sánh ở mức dùng của bạn sau đợt giảm giá on-demand tháng 11/2024)
    • On-Demand: traffic đột biến, không cần lập kế hoạch capacity
  5. Hot partition: nếu một khoá (hoặc item collection không tách được) vượt trần 1 000 WCU / 3 000 RCU mỗi giây, cân nhắc hậu tố shard; adaptive capacity có thể tách item collection của bảng có sort key và không LSI, nhưng không bảo đảm

Khi nào đổi chế độ:

ModeBest ForCost DriverWhen to Avoid
ProvisionedSteady traffic, cost optimizationRCU/WCU hoursUnpredictable spikes
On-DemandNew apps, spiky traffic, serverlessPer-requestHigh, steady, predictable load

GSI cost optimization:

javascript
// Node.js
// BAD: 5 GSIs for different queries
// GSI1: userId
// GSI2: status
// GSI3: country
// GSI4: category
// GSI5: date
// → mỗi ghi vào bảng + 5 GSI = 6x write unit (500 WCU × 6 = 3000 WCU, trong đó GSI 2500)

// GOOD: Overload 2 GSIs with composite keys
// GSI1: PK=userId, SK=status#date
// GSI2: PK=country#category, SK=date
// → bảng + 2 GSI = 3x write unit (500 WCU × 3 = 1500 WCU, trong đó GSI 1000)
// Giảm 50% tổng write unit (3000 → 1500), phần GSI giảm 60% (2500 → 1000)

→ See also: DynamoDB Single-Table Design, DynamoDB Auto-Scaling

Phải nhớ:

  • GSI cập nhật bất đồng bộ và không hỗ trợ strongly consistent read; đọc ngay sau ghi thì dùng GetItem trên bảng gốc với ConsistentRead: true.
  • Mỗi partition bị chặn 1 000 write unit/s và 3 000 read unit/s dù provisioned hay on-demand (item collection không tách được: bảng không sort key, ghi một item, hoặc có LSI); chống hot key bằng shard hoặc key ghép ngày.
  • Mỗi GSI nhân thêm write unit (bảng + N GSI = (1 + N)x); đo bằng calculator rồi mới thêm GSI.

Tự kiểm: Bảng on-demand, một eventType nhận 1 500 ghi/s item 1 KB, metric WriteKeyRangeThroughputThrottleEvents > 0. Đổi sang provisioned 10 000 WCU có hết throttle không?

Đáp án

Có thể vẫn throttle: nếu bảng chỉ có partition key (hoặc ghi một item, hoặc có LSI) thì một khoá nằm trên một partition với trần 1 000 write unit/s, tăng capacity bảng không nâng trần đó; bảng có sort key và không LSI thì adaptive capacity có thể tách, nhưng không bảo đảm. Thêm hậu tố shard vào partition key để chia ghi ra nhiều partition.

Query vs Scan ​

Triệu chứng: endpoint "đơn của một user" tốn vài RCU, còn endpoint "đơn pending" tốn hàng trăm RCU dù chỉ trả 10 đơn.

Quy tắc: Dùng Query (bắt buộc có khoá phân vùng, sort key tuỳ chọn) cho đường đọc online. Đừng dùng Scan + FilterExpression cho đường đọc online.

Vì sao: Scan đọc từng item theo trang tối đa 1 MB rồi mới lọc; AWS: "a Scan consumes the same amount of read capacity, regardless of whether a filter expression is present."

javascript
// Node.js — chạy độc lập: tạo bảng Orders, nạp 3 000 đơn (mỗi đơn ~1 KB), rồi so Query với Scan
import { DynamoDBClient, CreateTableCommand, waitUntilTableExists } from '@aws-sdk/client-dynamodb'
import { DynamoDBDocumentClient, BatchWriteCommand, QueryCommand, ScanCommand } from '@aws-sdk/lib-dynamodb'

const client = new DynamoDBClient({})
const dynamodb = DynamoDBDocumentClient.from(client)

await client.send(new CreateTableCommand({
  TableName: 'Orders',
  BillingMode: 'PAY_PER_REQUEST',
  AttributeDefinitions: [
    { AttributeName: 'userId', AttributeType: 'S' },
    { AttributeName: 'orderDate', AttributeType: 'S' }
  ],
  KeySchema: [
    { AttributeName: 'userId', KeyType: 'HASH' },
    { AttributeName: 'orderDate', KeyType: 'RANGE' }
  ]
}))
await waitUntilTableExists({ client, maxWaitTime: 60 }, { TableName: 'Orders' })

// 100 người dùng x 30 ngày; chỉ USER#7 có 10 đơn pending (ngày 21-30)
const items = []
for (let u = 0; u < 100; u++) {
  for (let d = 1; d <= 30; d++) {
    items.push({
      userId: `USER#${u}`,
      orderDate: `2024-01-${String(d).padStart(2, '0')}`,
      status: u === 7 && d > 20 ? 'pending' : 'shipped',
      note: 'x'.repeat(1000)
    })
  }
}
for (let i = 0; i < items.length; i += 25) {
  // bản production phải thử lại UnprocessedItems
  await dynamodb.send(new BatchWriteCommand({
    RequestItems: { Orders: items.slice(i, i + 25).map((Item) => ({ PutRequest: { Item } })) }
  }))
}

// Query: chỉ đọc item của USER#7 có orderDate > 2024-01-20
const q = await dynamodb.send(new QueryCommand({
  TableName: 'Orders',
  KeyConditionExpression: 'userId = :uid AND orderDate > :date',
  ExpressionAttributeValues: { ':uid': 'USER#7', ':date': '2024-01-20' },
  ReturnConsumedCapacity: 'TOTAL'
}))
console.log('Query', { Count: q.Count, ScannedCount: q.ScannedCount, RCU: q.ConsumedCapacity.CapacityUnits })

// Scan + FilterExpression: đọc cả bảng theo trang, lọc sau khi đọc
// 'status' là từ khoá dành riêng của DynamoDB nên phải đặt bí danh #s
let key
let pages = 0
let scanned = 0
let matched = 0
let rcu = 0
do {
  const s = await dynamodb.send(new ScanCommand({
    TableName: 'Orders',
    FilterExpression: '#s = :s',
    ExpressionAttributeNames: { '#s': 'status' },
    ExpressionAttributeValues: { ':s': 'pending' },
    ExclusiveStartKey: key,
    ReturnConsumedCapacity: 'TOTAL'
  }))
  pages += 1
  scanned += s.ScannedCount
  matched += s.Count
  rcu += s.ConsumedCapacity.CapacityUnits
  key = s.LastEvaluatedKey
} while (key)
console.log('Scan', { pages, ScannedCount: scanned, Count: matched, RCU: rcu })

Kết quả đã chạy (DynamoDB Local, Node 22, SDK v3, 2026-11-20; RCU do Local tính, đổi theo kích thước item):

text
Query { Count: 10, ScannedCount: 10, RCU: 1.5 }
Scan { pages: 3, ScannedCount: 3000, Count: 10, RCU: 385.5 }

Bẫy production:

  • status là từ khoá dành riêng của DynamoDB: FilterExpression: 'status = :status' trả ValidationException. Đặt bí danh #s qua ExpressionAttributeNames (đã chạy: lỗi "Attribute name is a reserved keyword; reserved keyword: status").
  • ScannedCount lớn hơn nhiều Count nghĩa là đang trả tiền cho dữ liệu bị bỏ. Theo dõi bằng ReturnConsumedCapacity và log hai số này.
  • Dùng Query theo khoá phân vùng, hoặc Query trên GSI khi cần khoá khác. Đừng Scan trên đường đọc online; Scan thường chỉ hợp lý cho backfill, export, bảng nhỏ, và chia Segment/TotalSegments khi cần chạy song song.

DynamoDB Streams (Change Data Capture) ​

Triệu chứng: chỉ mục tìm kiếm lệch dữ liệu vì ứng dụng ghi vào hai nơi và lần ghi thứ hai thất bại.

Quy tắc: Bật Streams rồi để consumer (Lambda, KCL) đọc thay đổi, thay vì ghi kép từ ứng dụng.

Vì sao: Streams ghi mọi thay đổi ở cấp item và giữ tối đa 24 giờ; AWS: "stream records appear in the same sequence as the actual modifications to the item."

bash
# Bật stream lúc tạo bảng; NEW_AND_OLD_IMAGES giữ cả ảnh mới và ảnh cũ
aws dynamodb create-table --table-name Users \
  --attribute-definitions AttributeName=PK,AttributeType=S AttributeName=SK,AttributeType=S \
  --key-schema AttributeName=PK,KeyType=HASH AttributeName=SK,KeyType=RANGE \
  --billing-mode PAY_PER_REQUEST \
  --stream-specification StreamEnabled=true,StreamViewType=NEW_AND_OLD_IMAGES \
  --query TableDescription.TableStatus --output text

# Tạo, sửa, xoá một item để sinh INSERT, MODIFY, REMOVE
aws dynamodb put-item --table-name Users --item '{"PK":{"S":"USER#123"},"SK":{"S":"METADATA"},"plan":{"S":"free"}}'
aws dynamodb update-item --table-name Users --key '{"PK":{"S":"USER#123"},"SK":{"S":"METADATA"}}' \
  --update-expression 'SET #p = :p' --expression-attribute-names '{"#p":"plan"}' --expression-attribute-values '{":p":{"S":"pro"}}'
aws dynamodb delete-item --table-name Users --key '{"PK":{"S":"USER#123"},"SK":{"S":"METADATA"}}'

# Đọc stream: DynamoDB Streams có endpoint riêng, lệnh nằm trong nhóm aws dynamodbstreams
STREAM_ARN=$(aws dynamodb describe-table --table-name Users --query Table.LatestStreamArn --output text)
SHARD_ID=$(aws dynamodbstreams describe-stream --stream-arn "$STREAM_ARN" --query 'StreamDescription.Shards[0].ShardId' --output text)
ITERATOR=$(aws dynamodbstreams get-shard-iterator --stream-arn "$STREAM_ARN" --shard-id "$SHARD_ID" \
  --shard-iterator-type TRIM_HORIZON --query ShardIterator --output text)
aws dynamodbstreams get-records --shard-iterator "$ITERATOR" \
  --query 'Records[].[eventName,dynamodb.OldImage.plan.S,dynamodb.NewImage.plan.S]' --output text

Kết quả đã chạy (amazon/dynamodb-local, aws-cli v2, 2026-11-20; cột: eventName, plan cũ, plan mới):

text
INSERT	None	free
MODIFY	free	pro
REMOVE	pro	None

Hình dạng một stream record (rút gọn, dùng định dạng JSON của DynamoDB):

json
{
  "eventName": "MODIFY",
  "dynamodb": {
    "Keys": { "PK": { "S": "USER#123" }, "SK": { "S": "METADATA" } },
    "OldImage": { "plan": { "S": "free" } },
    "NewImage": { "plan": { "S": "pro" } },
    "StreamViewType": "NEW_AND_OLD_IMAGES"
  }
}

Luồng cập nhật chỉ mục tìm kiếm:

text
DynamoDB -> Streams -> Lambda -> Amazon OpenSearch Service
(hoặc DynamoDB -> zero-ETL integration -> OpenSearch Service)

Bẫy production:

  • StreamViewType (KEYS_ONLY, NEW_IMAGE, OLD_IMAGE, NEW_AND_OLD_IMAGES) không sửa được sau khi tạo; muốn đổi thì tắt stream rồi bật stream mới.
  • Consumer chậm quá 24 giờ mất bản ghi: theo dõi IteratorAge của Lambda.
  • PutItem hoặc UpdateItem không đổi dữ liệu thì không sinh bản ghi.
  • Thứ tự được bảo đảm theo từng item, không theo cả partition; bản ghi của cùng một transaction có thể đến lệch lúc, đừng giả định nguyên tử ở consumer.
  • Ví dụ trên chỉ đọc Shards[0] vì DynamoDB Local có một shard; stream thật có nhiều shard, shard có thể tách thành shard con và phải xử lý shard cha trước shard con. Production dùng Lambda event source mapping hoặc KCL (Kinesis Adapter) thay vì tự duyệt shard.

Dùng cho: trigger Lambda, đồng bộ sang tìm kiếm, audit log, kiến trúc hướng sự kiện.

DynamoDB Transactions ​

Triệu chứng: chuyển tiền giữa hai tài khoản bằng hai UpdateItem rời; lệnh thứ hai lỗi và tiền biến mất.

Quy tắc: Dùng TransactWriteItems khi nhiều item phải cùng đổi hoặc cùng không đổi. Đừng dùng cho nạp dữ liệu hàng loạt (dùng BatchWriteItem).

Vì sao: AWS: "groups up to 100 write actions in a single all-or-nothing operation"; tổng kích thước tối đa 4 MB, cùng tài khoản và cùng Region.

javascript
// Node.js — chạy độc lập: tạo bảng Accounts, nạp 2 tài khoản, chuyển tiền bằng transaction
import { randomUUID } from 'node:crypto'
import { DynamoDBClient, CreateTableCommand, waitUntilTableExists } from '@aws-sdk/client-dynamodb'
import { DynamoDBDocumentClient, PutCommand, GetCommand, TransactWriteCommand } from '@aws-sdk/lib-dynamodb'

const client = new DynamoDBClient({})
const dynamodb = DynamoDBDocumentClient.from(client)

await client.send(new CreateTableCommand({
  TableName: 'Accounts',
  BillingMode: 'PAY_PER_REQUEST',
  AttributeDefinitions: [{ AttributeName: 'accountId', AttributeType: 'S' }],
  KeySchema: [{ AttributeName: 'accountId', KeyType: 'HASH' }]
}))
await waitUntilTableExists({ client, maxWaitTime: 60 }, { TableName: 'Accounts' })
await dynamodb.send(new PutCommand({ TableName: 'Accounts', Item: { accountId: 'A123', balance: 500 } }))
await dynamodb.send(new PutCommand({ TableName: 'Accounts', Item: { accountId: 'B456', balance: 0 } }))

// Chuyển tiền từ A123 sang B456: cả hai Update cùng thành công hoặc cùng không đổi
const transfer = (amount) => dynamodb.send(new TransactWriteCommand({
  ClientRequestToken: randomUUID(), // gửi lại cùng token trong 10 phút không ghi lần hai
  TransactItems: [
    {
      Update: {
        TableName: 'Accounts',
        Key: { accountId: 'A123' },
        UpdateExpression: 'SET balance = balance - :amount',
        ConditionExpression: 'balance >= :amount', // kiểm số dư nguyên tử với lần trừ
        ExpressionAttributeValues: { ':amount': amount }
      }
    },
    {
      Update: {
        TableName: 'Accounts',
        Key: { accountId: 'B456' },
        UpdateExpression: 'SET balance = balance + :amount',
        ExpressionAttributeValues: { ':amount': amount }
      }
    }
  ]
}))

await transfer(100)
const balance = async (id) => (await dynamodb.send(new GetCommand({ TableName: 'Accounts', Key: { accountId: id }, ConsistentRead: true }))).Item.balance
console.log('Sau chuyển 100:', await balance('A123'), await balance('B456'))

try {
  await transfer(1000) // vượt số dư: cả giao dịch bị huỷ
} catch (e) {
  console.log(e.name, e.CancellationReasons.map((r) => r.Code))
}
console.log('Sau chuyển 1000 bị huỷ:', await balance('A123'), await balance('B456'))

Kết quả đã chạy (amazon/dynamodb-local, Node 22, SDK v3, 2026-11-20):

text
Sau chuyển 100: 400 100
TransactionCanceledException [ 'ConditionalCheckFailed', 'None' ]
Sau chuyển 1000 bị huỷ: 400 100

Bẫy production:

  • Mỗi item tốn hai đơn vị (chuẩn bị rồi chốt), tính cả khi giao dịch bị huỷ: giao dịch ghi 3 item tốn 6 WCU (item ≤ 1 KB).
  • Không thao tác trên index, và không hai action trên cùng một item trong một transaction.
  • TransactionCanceledException mang CancellationReasons theo đúng thứ tự TransactItems; SDK không tự thử lại.
  • Global Tables: ACID chỉ trong Region nơi gọi API, Region khác có thể thấy giao dịch dở dang lúc đang sao chép.

Global Tables (Multi-Region) ​

text
us-east-1  <->  eu-west-1  <->  ap-southeast-1
(mọi replica cùng nhận đọc và ghi, không có replica primary)

AWS: "When an application writes data to a replica in one Region, DynamoDB automatically replicates the write to all other replicas in the global table."

  • Active-active: ghi ở Region nào cũng được, đọc cục bộ ở mọi Region.
  • Chế độ mặc định MREC (multi-Region eventual consistency): sao chép bất đồng bộ, xung đột giải bằng last-writer-wins. Đo độ trễ sao chép bằng metric ReplicationLatency (chỉ MREC phát metric này; MRSC không phát), đừng giả định "dưới một giây".
  • Chế độ MRSC (multi-Region strong consistency): chọn lúc tạo, không đổi sau đó; phải đúng ba Region (ba replica, hoặc hai replica và một witness), không hỗ trợ TTL, LSI và transaction.
  • Transaction chỉ nguyên tử trong Region nơi ghi, không xuyên Region.

Dùng khi: ứng dụng toàn cầu cần độ trễ thấp, chịu mất Region, ràng buộc vị trí dữ liệu. Đừng khi: logic cần ghi tuần tự toàn cục (doc nêu xung đột giải theo item bằng timestamp nội bộ của DynamoDB, "last writer wins": bạn không điều khiển được thứ tự). Chưa chạy: dịch vụ quản lý.

DynamoDB Accelerator (DAX) ​

text
Ứng dụng (DAX client) -> cụm DAX (item cache + query cache) -> DynamoDB
  • Hai bộ nhớ đệm độc lập: item cache (cho GetItem, BatchGetItem) và query cache (cho Query, Scan).
  • Ghi qua DAX là write-through cho item cache: DAX ghi DynamoDB trước rồi cập nhật item cache. Ghi KHÔNG làm mất hiệu lực kết quả trong query cache; AWS: "Updates to the item cache, or to the underlying DynamoDB table, do not invalidate or modify the results stored in the query cache."
  • Đọc ConsistentRead: true đi thẳng DynamoDB và không được cache; đọc từ cache luôn là eventually consistent.
  • Ghi thẳng vào DynamoDB (bỏ qua DAX) làm cache lệch tới khi hết TTL.
  • Dùng DAX client thay cho client DynamoDB; AWS khuyên cụm tối thiểu ba nút ở nhiều AZ. Giá theo node-giờ: xem trang giá DynamoDB.

Dùng khi: đọc lặp lại cùng item nóng và chịu được dữ liệu cũ tới hết TTL. Đừng khi: ghi nhiều đọc ít, cần đọc mạnh nhất quán, hoặc nhiều dịch vụ ghi thẳng DynamoDB. Đo độ trễ đọc trước và sau bằng tải thật thay vì tin ngưỡng chung. Chưa chạy: dịch vụ quản lý.

DynamoDB Production War Stories ​

Ba kịch bản minh hoạ về chi phí và hiệu năng DynamoDB (không phải sự cố có nguồn; mỗi kịch bản kết thúc bằng một dòng Bài học)

War Story 1: Scan trên dashboard làm hoá đơn nổ

Kịch bản minh hoạ, không phải sự cố có nguồn. Số liệu là phép tính từ giá on-demand us-east-1 kiểm 2026-11-20 ($0,125 mỗi triệu read request unit, trang giá).

Bảng Users 10 triệu item, mỗi item 2 KB. Dashboard chạy Scan lọc subscriptionStatus = 'premium' mỗi 30 giây.

text
10 triệu item x 2 KB = 20 GB = 5 triệu đơn vị 4 KB
Đọc eventually consistent: 5 triệu / 2 = 2,5 triệu RRU mỗi lần quét
2,5 triệu x $0,125 / 1 triệu = $0,3125 mỗi lần quét
2 880 lần/ngày x 30 ngày = 86 400 lần quét/tháng
86 400 x $0,3125 = $27 000/tháng

Mỗi lần gọi Scan chỉ trả tối đa 1 MB, nên 20 GB là khoảng 20 000 trang: code chỉ gọi một ScanCommand không lặp theo LastEvaluatedKey sẽ trả thiếu dữ liệu mà không báo lỗi.

Sửa: thêm GSI thưa chỉ chứa người premium rồi Query. Với 100 000 người premium: 100 000 x 2 KB = 200 MB = 50 000 đơn vị 4 KB, chia đôi còn 25 000 RRU, tức $0,003125 mỗi lần, $270/tháng (rẻ hơn khoảng 100 lần). Dựng lại ở quy mô nhỏ:

javascript
// Node.js — dựng lại ở quy mô nhỏ: 5 000 người dùng (~2 KB mỗi người), 1 % là premium
import { DynamoDBClient, CreateTableCommand, waitUntilTableExists } from '@aws-sdk/client-dynamodb'
import { DynamoDBDocumentClient, BatchWriteCommand, ScanCommand, QueryCommand } from '@aws-sdk/lib-dynamodb'

const client = new DynamoDBClient({})
const dynamodb = DynamoDBDocumentClient.from(client)

await client.send(new CreateTableCommand({
  TableName: 'UsersW1',
  BillingMode: 'PAY_PER_REQUEST',
  AttributeDefinitions: [
    { AttributeName: 'PK', AttributeType: 'S' },
    { AttributeName: 'SK', AttributeType: 'S' },
    { AttributeName: 'GSI1PK', AttributeType: 'S' },
    { AttributeName: 'GSI1SK', AttributeType: 'S' }
  ],
  KeySchema: [
    { AttributeName: 'PK', KeyType: 'HASH' },
    { AttributeName: 'SK', KeyType: 'RANGE' }
  ],
  GlobalSecondaryIndexes: [{
    IndexName: 'GSI1',
    KeySchema: [
      { AttributeName: 'GSI1PK', KeyType: 'HASH' },
      { AttributeName: 'GSI1SK', KeyType: 'RANGE' }
    ],
    Projection: { ProjectionType: 'ALL' }
  }]
}))
await waitUntilTableExists({ client, maxWaitTime: 60 }, { TableName: 'UsersW1' })

const items = []
for (let i = 0; i < 5000; i++) {
  const premium = i % 100 === 0
  items.push({
    PK: `USER#${i}`,
    SK: 'METADATA',
    email: `user${i}@example.com`,
    subscriptionStatus: premium ? 'premium' : 'free',
    bio: 'x'.repeat(2000),
    // chỉ người premium mang khoá GSI, nên GSI1 là chỉ mục thưa
    ...(premium ? { GSI1PK: 'STATUS#premium', GSI1SK: '2024-01-01' } : {})
  })
}
for (let i = 0; i < items.length; i += 25) {
  await dynamodb.send(new BatchWriteCommand({
    RequestItems: { UsersW1: items.slice(i, i + 25).map((Item) => ({ PutRequest: { Item } })) }
  }))
}

// Sai: Scan cả bảng rồi lọc, đi hết mọi trang (mỗi trang ≤ 1 MB)
let key
let pages = 0
let scanned = 0
let matched = 0
let rcu = 0
do {
  const s = await dynamodb.send(new ScanCommand({
    TableName: 'UsersW1',
    FilterExpression: 'subscriptionStatus = :s',
    ExpressionAttributeValues: { ':s': 'premium' },
    ExclusiveStartKey: key,
    ReturnConsumedCapacity: 'TOTAL'
  }))
  pages += 1
  scanned += s.ScannedCount
  matched += s.Count
  rcu += s.ConsumedCapacity.CapacityUnits
  key = s.LastEvaluatedKey
} while (key)
console.log('Scan ', { pages, ScannedCount: scanned, Count: matched, RCU: rcu })

// Đúng: Query trên GSI1 chỉ đọc người premium
const q = await dynamodb.send(new QueryCommand({
  TableName: 'UsersW1',
  IndexName: 'GSI1',
  KeyConditionExpression: 'GSI1PK = :s',
  ExpressionAttributeValues: { ':s': 'STATUS#premium' },
  ReturnConsumedCapacity: 'TOTAL'
}))
console.log('Query', { Count: q.Count, ScannedCount: q.ScannedCount, RCU: q.ConsumedCapacity.CapacityUnits })

Kết quả đã chạy (amazon/dynamodb-local, Node 22, SDK v3, 2026-11-20; RCU do Local tính):

text
Scan  { pages: 10, ScannedCount: 5000, Count: 50, RCU: 1267 }
Query { Count: 50, ScannedCount: 50, RCU: 13 }

Theo dõi: log ScannedCount so với Count ở mọi lệnh Scan/Query có lọc, và đặt cảnh báo CloudWatch khi RCU tiêu thụ của bảng vượt mức nền:

bash
# Ngưỡng 300000 chỉ để minh hoạ: đặt bằng 2 lần tổng RCU nền đo được trong 5 phút
aws cloudwatch put-metric-alarm --alarm-name users-read-spike \
  --namespace AWS/DynamoDB --metric-name ConsumedReadCapacityUnits \
  --dimensions Name=TableName,Value=Users \
  --statistic Sum --period 300 --evaluation-periods 2 \
  --threshold 300000 --comparison-operator GreaterThanThreshold

Bài học: Scan + FilterExpression tính tiền theo dữ liệu đã đọc chứ không theo kết quả trả về; đường đọc online cần Query trên khoá hoặc GSI.

War Story 2: Hot partition làm production bị throttle

Kịch bản minh hoạ, không phải sự cố có nguồn.

Bảng Catalog đặt mọi sản phẩm cùng khoá phân vùng PRODUCT (hình dạng dữ liệu, không chạy):

json
{ "PK": "PRODUCT", "SK": "laptop-001", "name": "Gaming Laptop", "price": 1299 }

Ngày sale, 10 000 lượt đọc mỗi giây cùng Query PK = 'PRODUCT'. Trần 3 000 RCU và 1 000 WCU áp cho một partition (item đơn hoặc item collection không tách được); bảng có sort key và không có LSI thì adaptive capacity có thể tách item collection nhưng không bảo đảm. Triệu chứng: ProvisionedThroughputExceededException, metric ReadKeyRangeThroughputThrottleEvents > 0 (throttle không nằm trong UserErrors).

Sửa: chia khoá thành N shard với hậu tố tính từ productId (không random, để GetItem biết đọc shard nào), liệt kê bằng scatter-gather, và cache danh sách ở tầng ứng dụng. Một khoá phân vùng không bằng một partition: 50 category chưa chắc rải trên 50 partition, và một item hot đơn lẻ vẫn chịu trần 3 000 RCU.

javascript
// Node.js — chạy độc lập: bảng Catalog, 100 sản phẩm rải trên 10 shard của khoá phân vùng
import { DynamoDBClient, CreateTableCommand, waitUntilTableExists } from '@aws-sdk/client-dynamodb'
import { DynamoDBDocumentClient, BatchWriteCommand, GetCommand, QueryCommand } from '@aws-sdk/lib-dynamodb'

const client = new DynamoDBClient({})
const dynamodb = DynamoDBDocumentClient.from(client)

await client.send(new CreateTableCommand({
  TableName: 'Catalog',
  BillingMode: 'PAY_PER_REQUEST',
  AttributeDefinitions: [
    { AttributeName: 'PK', AttributeType: 'S' },
    { AttributeName: 'SK', AttributeType: 'S' }
  ],
  KeySchema: [
    { AttributeName: 'PK', KeyType: 'HASH' },
    { AttributeName: 'SK', KeyType: 'RANGE' }
  ]
}))
await waitUntilTableExists({ client, maxWaitTime: 60 }, { TableName: 'Catalog' })

// Hậu tố tính từ productId (không random) để GetItem biết đọc shard nào
const SHARDS = 10
const shardOf = (productId) => [...productId].reduce((h, c) => (h * 31 + c.charCodeAt(0)) % SHARDS, 0)

const ids = Array.from({ length: 100 }, (_, i) => `laptop-${String(i).padStart(3, '0')}`)
for (let i = 0; i < ids.length; i += 25) {
  await dynamodb.send(new BatchWriteCommand({
    RequestItems: {
      Catalog: ids.slice(i, i + 25).map((id) => ({
        PutRequest: { Item: { PK: `PRODUCT#${shardOf(id)}`, SK: id, name: `Laptop ${id}`, price: 1299 } }
      }))
    }
  }))
}

// Đọc một sản phẩm: tính lại shard từ productId
const one = await dynamodb.send(new GetCommand({
  TableName: 'Catalog',
  Key: { PK: `PRODUCT#${shardOf('laptop-042')}`, SK: 'laptop-042' }
}))
console.log('GetItem', one.Item.name)

// Liệt kê tất cả: scatter-gather qua 10 shard
const pages = await Promise.all(Array.from({ length: SHARDS }, (_, i) => dynamodb.send(new QueryCommand({
  TableName: 'Catalog',
  KeyConditionExpression: 'PK = :pk',
  ExpressionAttributeValues: { ':pk': `PRODUCT#${i}` }
}))))
console.log('Scatter-gather', pages.flatMap((p) => p.Items).length, 'sản phẩm,', pages.map((p) => p.Count).join('/'))

Kết quả đã chạy (amazon/dynamodb-local, Node 22, SDK v3, 2026-11-20):

text
GetItem Laptop laptop-042
Scatter-gather 100 sản phẩm, 10/10/10/10/10/10/10/10/10/10

Khoá phân vùng tốt và xấu:

text
Tốt (nhiều giá trị, truy cập đều):
- userId, orderId
- entityId + bucket ngày, ví dụ sensorId#YYYY-MM-DD
- khoá + hậu tố shard tính từ id

Xấu (ít giá trị, dồn truy cập):
- "PRODUCT" (một giá trị)
- status (vài giá trị)
- country (khoảng 200 giá trị)
- ngày không kèm thành phần khác (toàn bộ ghi hôm nay dồn một khoá)

Theo dõi khoá nóng bằng CloudWatch Contributor Insights:

bash
aws dynamodb update-contributor-insights \
  --table-name Catalog \
  --contributor-insights-action ENABLE \
  --contributor-insights-mode THROTTLED_KEYS

aws dynamodb describe-contributor-insights --table-name Catalog

Đặt cảnh báo trên ReadKeyRangeThroughputThrottleEvents và WriteKeyRangeThroughputThrottleEvents lớn hơn 0. Chưa chạy: dịch vụ quản lý (dynamodb-local trả UnknownOperationException cho update-contributor-insights); đối chiếu tham số với trang tham chiếu CLI.

Bài học: một khoá phân vùng bị đọc hoặc ghi vượt trần của một partition sẽ bị throttle dù capacity cả bảng còn dư; chia shard trước khi tải đến, và cache thứ đọc lặp lại.

War Story 3: GSI ghi tốn gấp ba vì chiếu cả item

Kịch bản minh hoạ, không phải sự cố có nguồn.

Bảng Events 1 tỉ item, mỗi item khoảng 2 KB (1 TB mỗi 500 triệu item, tổng khoảng 2 TB). Một GSI thưa trên isPremium (chỉ 5 % item mang thuộc tính, tức 50 triệu item) dùng ProjectionType: ALL, kéo theo userAgent 500 byte và payload 1,5 KB.

Cơ chế (AWS): một GSI chỉ chứa item có thuộc tính khoá của nó, nên chỉ mục thưa chỉ lớn bằng 5 % bảng; dung lượng một item trong chỉ mục là khoá bảng + khoá chỉ mục + thuộc tính được chiếu + 100 byte overhead. Chi phí lệch nằm ở ghi: mỗi lần ghi item premium, GSI tốn WCU theo kích thước phần được chiếu.

javascript
// Node.js — chạy độc lập: so chi phí ghi của GSI ProjectionType ALL với INCLUDE trên cùng một item ~2 KB
import { DynamoDBClient, CreateTableCommand, waitUntilTableExists } from '@aws-sdk/client-dynamodb'
import { DynamoDBDocumentClient, PutCommand } from '@aws-sdk/lib-dynamodb'

const client = new DynamoDBClient({})
const dynamodb = DynamoDBDocumentClient.from(client)

const gsi = (IndexName, Projection) => ({
  IndexName,
  KeySchema: [
    { AttributeName: 'isPremium', KeyType: 'HASH' },
    { AttributeName: 'SK', KeyType: 'RANGE' }
  ],
  Projection
})

await client.send(new CreateTableCommand({
  TableName: 'EventsW3',
  BillingMode: 'PAY_PER_REQUEST',
  AttributeDefinitions: [
    { AttributeName: 'PK', AttributeType: 'S' },
    { AttributeName: 'SK', AttributeType: 'S' },
    { AttributeName: 'isPremium', AttributeType: 'S' }
  ],
  KeySchema: [
    { AttributeName: 'PK', KeyType: 'HASH' },
    { AttributeName: 'SK', KeyType: 'RANGE' }
  ],
  GlobalSecondaryIndexes: [
    gsi('PremiumAllIndex', { ProjectionType: 'ALL' }),
    gsi('PremiumIncludeIndex', { ProjectionType: 'INCLUDE', NonKeyAttributes: ['eventType', 'url'] })
  ]
}))
await waitUntilTableExists({ client, maxWaitTime: 60 }, { TableName: 'EventsW3' })

const r = await dynamodb.send(new PutCommand({
  TableName: 'EventsW3',
  Item: {
    PK: 'USER#123',
    SK: 'EVENT#2024-01-09#12:34:56',
    eventType: 'page_view',
    url: '/products',
    userAgent: 'u'.repeat(500),
    payload: 'p'.repeat(1500),
    isPremium: 'Y'
  },
  ReturnConsumedCapacity: 'INDEXES'
}))
console.log(JSON.stringify(r.ConsumedCapacity))

Kết quả đã chạy (amazon/dynamodb-local, Node 22, SDK v3, 2026-11-20; đơn vị WCU do Local tính):

json
{"TableName":"EventsW3","CapacityUnits":7,"Table":{"CapacityUnits":3},"GlobalSecondaryIndexes":{"PremiumAllIndex":{"CapacityUnits":3},"PremiumIncludeIndex":{"CapacityUnits":1}}}

Chiếu ALL tốn 3 WCU mỗi lần ghi vào chỉ mục, chiếu INCLUDE hai thuộc tính nhỏ tốn 1 WCU. Bẫy riêng của chỉ mục thưa: ghi isPremium = 'N' cho mọi người thì mọi item vào chỉ mục và nó không còn thưa; chỉ đặt thuộc tính khi item thật sự thuộc nhóm.

Chọn kiểu chiếu:

text
KEYS_ONLY  Nhỏ nhất. Dùng khi chỉ cần nhận diện item rồi GetItem trên bảng chính.
INCLUDE    Khoá + thuộc tính chỉ định. Dùng khi biết truy vấn cần trường nào.
ALL        Lớn nhất, nhân đôi cả item. Dùng khi hầu hết truy vấn cần mọi trường.

Ước tính dung lượng GSI (đo bằng dữ liệu thật, đây là ví dụ minh hoạ, giá $0,25/GB-tháng us-east-1, chưa trừ 25 GB miễn phí mỗi tháng của tài khoản):

text
Dung lượng GSI = số item trong GSI x (khoá bảng + khoá GSI + thuộc tính chiếu + 100 byte)
INCLUDE (~100 byte chiếu): 50 triệu x ~200 byte = ~10 GB  -> ~$2,50/tháng
ALL (~2 000 byte):         50 triệu x ~2 100 byte = ~105 GB -> ~$26/tháng

Bài học: kiểu chiếu quyết định cả dung lượng lẫn WCU của mỗi lần ghi; chỉ mục thưa chỉ thưa khi bạn bỏ thuộc tính khoá ở item không thuộc nhóm.

DynamoDB Capacity Planning Calculator (bản trùng): xem DynamoDB Capacity Planning Calculator ở phần trên; bản đó dùng giá us-east-1 kiểm 2026-11-20 và đã chạy lại từng ví dụ.