Appearance
DynamoDB Consistency
Khởi tạo dùng chung cho mục này
javascript
// Node.js (SDK v3) — khối khởi tạo; DynamoDB Local lắng nghe ở http://localhost:8000
import { DynamoDBClient, CreateTableCommand } from '@aws-sdk/client-dynamodb'
import { DynamoDBDocumentClient } from '@aws-sdk/lib-dynamodb'
const client = new DynamoDBClient({
region: 'us-east-1',
endpoint: 'http://localhost:8000', // bỏ dòng này khi chạy với AWS thật
credentials: { accessKeyId: 'local', secretAccessKey: 'local' }
})
const dynamodb = DynamoDBDocumentClient.from(client)
for (const [TableName, keyName] of [['Users', 'userId'], ['UserCache', 'userId'], ['Accounts', 'accountId'], ['Charges', 'chargeId'], ['Orders', 'orderId']]) {
await client.send(new CreateTableCommand({
TableName,
BillingMode: 'PAY_PER_REQUEST',
AttributeDefinitions: [{ AttributeName: keyName, AttributeType: 'S' }],
KeySchema: [{ AttributeName: keyName, KeyType: 'HASH' }]
}))
}Eventually Consistent vs Strongly Consistent Reads
Eventually consistent (mặc định):
javascript
// Node.js (SDK v3) — chạy sau khối khởi tạo `dynamodb` ở đầu mục DynamoDB Consistency
import { GetCommand } from '@aws-sdk/lib-dynamodb'
const result = await dynamodb.send(new GetCommand({
TableName: 'Users',
Key: { userId: 'USER#123' }
// ConsistentRead: false (mặc định)
}))- ✅ Rẻ bằng một nửa strongly consistent (1 RCU cho 8 KB)
- ❌ Có thể không phản ánh ghi vừa xong. Doc: "might not reflect the results of a recently completed write operation"; chạy lại sau một lúc ngắn thì thấy bản mới
Strongly consistent:
javascript
// Node.js (SDK v3) — chạy sau khối khởi tạo `dynamodb` ở đầu mục DynamoDB Consistency
import { GetCommand } from '@aws-sdk/lib-dynamodb'
const result = await dynamodb.send(new GetCommand({
TableName: 'Users',
Key: { userId: 'USER#123' },
ConsistentRead: true // ← bắt buộc đọc bản mới nhất
}))- ✅ Phản ánh mọi ghi đã thành công trước đó
- ❌ Gấp đôi RCU (2 RCU cho 8 KB)
- ❌ Chỉ hỗ trợ bảng và LSI; GSI và Stream luôn eventually consistent (doc: "Strongly consistent reads from a global secondary index or a DynamoDB stream are not supported")
Global Tables có hai chế độ nhất quán giữa các Region: MREC (mặc định, thay đổi đến replica khác "typically within a second", eventually consistent giữa Region) và MRSC (ghi được sao chép đồng bộ sang Region khác trước khi trả về, đọc strongly consistent trên mọi replica luôn thấy bản mới nhất).
Dùng strong consistency khi / Đừng khi:
- ✅ Đọc ngay sau ghi trong cùng luồng, tiền, tồn kho
- ❌ Báo cáo/phân tích, cache (eventual đủ dùng)
⚠️ GOTCHA: Đọc eventually consistent ngay sau khi ghi có thể thấy dữ liệu cũ
Kịch bản minh hoạ, không phải sự cố có nguồn; DynamoDB Local chỉ có một bản sao nên không tái hiện được độ trễ này, cơ chế đối chiếu theo doc.
Một GetItem mặc định (eventually consistent) chạy ngay sau PutItem có thể trả về chưa có item hoặc bản cũ. Doc: "the responses might not reflect the results of a recently completed write operation".
Vì sao xảy ra:
- Ghi đã thành công (HTTP 200 là đã bền), nhưng đọc eventually consistent có thể đến bản sao chưa nhận ghi.
- Chỉ ảnh hưởng chính item đó: việc xoá item ở bảng khác (
UserCache) không liên quan tới kết quả đọcUsers.
Lỗi hay gặp:
javascript
// Node.js (SDK v3) — chạy sau khối khởi tạo `dynamodb` ở đầu mục DynamoDB Consistency
import { GetCommand, PutCommand } from '@aws-sdk/lib-dynamodb'
await dynamodb.send(new PutCommand({
TableName: 'Users',
Item: { userId: 'USER#123', name: 'John', status: 'active' }
}))
// Đọc mặc định ngay sau ghi: có thể chưa thấy item
const user = await dynamodb.send(new GetCommand({
TableName: 'Users',
Key: { userId: 'USER#123' }
}))
if (!user.Item) {
console.error('Chưa thấy item vừa ghi: đọc eventually consistent')
}Cách phát hiện: đếm các lần GetItem trả rỗng cho khoá vừa ghi trong cùng luồng xử lý (log ở ứng dụng); metric CloudWatch UserErrors đếm lỗi 4xx, không đếm đọc rỗng.
Cách phòng:
- Đọc strongly consistent cho read-after-write:javascript
// Node.js (SDK v3) — chạy sau khối khởi tạo `dynamodb` ở đầu mục DynamoDB Consistency import { GetCommand } from '@aws-sdk/lib-dynamodb' const result = await dynamodb.send(new GetCommand({ TableName: 'Users', Key: { userId: 'USER#123' }, ConsistentRead: true // ✓ thấy mọi ghi đã thành công trước đó })) - Dùng giá trị trả về của lệnh ghi (
ReturnValues: 'ALL_NEW'ởUpdateItem) thay vì đọc lại. - Transaction chỉ bảo đảm atomic nhiều item, không sửa độ trễ đọc: đọc sau transaction vẫn cần
ConsistentRead: true.
Bài học: read-after-write cần ConsistentRead: true (hoặc dùng giá trị trả về), không cần dựng cơ chế timestamp.
→ See also: DynamoDB Transactions, DynamoDB Anti-Patterns
DynamoDB Transactions (2018+)
TransactWriteItems (tối đa 100 action, tổng ≤ 4 MB):
javascript
// Node.js (SDK v3) — chạy sau khối khởi tạo `dynamodb` ở đầu mục DynamoDB Consistency
// Cần item A (balance 500) và B (balance 0) ở bảng Accounts; ví dụ ở khối Idempotency bên dưới tạo sẵn
import { TransactWriteCommand } from '@aws-sdk/lib-dynamodb'
const params = {
TransactItems: [
{
Update: {
TableName: 'Accounts',
Key: { accountId: 'A' },
UpdateExpression: 'SET balance = balance - :amount',
ConditionExpression: 'balance >= :amount', // Atomic check
ExpressionAttributeValues: {
':amount': 100
}
}
},
{
Update: {
TableName: 'Accounts',
Key: { accountId: 'B' },
UpdateExpression: 'SET balance = balance + :amount',
ExpressionAttributeValues: {
':amount': 100
}
}
}
]
}
try {
await dynamodb.send(new TransactWriteCommand(params))
console.log('Transaction succeeded')
} catch (err) {
if (err.name === 'TransactionCanceledException') {
console.log('Transaction failed:', err.CancellationReasons)
}
}TransactGetItems (tối đa 100 action):
javascript
// Node.js (SDK v3) — chạy sau khối khởi tạo `dynamodb` ở đầu mục DynamoDB Consistency
// Cần item USER#123 ở bảng Users (tạo ở khối Eventually Consistent) và bảng Orders (có ở khối khởi tạo); item ORDER#456 chưa có thì phần tử tương ứng của Responses là {}
import { TransactGetCommand } from '@aws-sdk/lib-dynamodb'
const params = {
TransactItems: [
{
Get: {
TableName: 'Users',
Key: { userId: 'USER#123' }
}
},
{
Get: {
TableName: 'Orders',
Key: { orderId: 'ORDER#456' }
}
}
]
}
const result = await dynamodb.send(new TransactGetCommand(params))
// All reads from same snapshot (consistent view)Transaction costs:
- Ghi: gấp đôi WCU cho mỗi item (một lần chuẩn bị, một lần xác nhận)
- Đọc: gấp đôi RCU cho mỗi item
- Transaction thất bại vẫn tốn capacity. Doc: "This capacity is consumed even when a transaction does not succeed."
Idempotency:
javascript
// Node.js (SDK v3) — chạy sau khối khởi tạo `dynamodb` ở đầu mục DynamoDB Consistency
import { PutCommand, TransactWriteCommand } from '@aws-sdk/lib-dynamodb'
await dynamodb.send(new PutCommand({ TableName: 'Accounts', Item: { accountId: 'A', balance: 500 } }))
await dynamodb.send(new PutCommand({ TableName: 'Accounts', Item: { accountId: 'B', balance: 0 } }))
const transfer = (amount) => ({
TransactItems: [
{ Update: { TableName: 'Accounts', Key: { accountId: 'A' },
UpdateExpression: 'SET balance = balance - :amount',
ConditionExpression: 'balance >= :amount',
ExpressionAttributeValues: { ':amount': amount } } },
{ Update: { TableName: 'Accounts', Key: { accountId: 'B' },
UpdateExpression: 'SET balance = balance + :amount',
ExpressionAttributeValues: { ':amount': amount } } }
]
})
// ClientRequestToken = khoá idempotency (an toàn khi retry)
await dynamodb.send(new TransactWriteCommand({ ...transfer(100), ClientRequestToken: 'transfer-001' }))
// Cùng token + cùng tham số trong 10 phút: trả kết quả cũ, không ghi lại (A vẫn 400, B vẫn 100)
await dynamodb.send(new TransactWriteCommand({ ...transfer(100), ClientRequestToken: 'transfer-001' }))
try {
// Cùng token nhưng tham số khác: bị từ chối
await dynamodb.send(new TransactWriteCommand({ ...transfer(50), ClientRequestToken: 'transfer-001' }))
} catch (err) {
console.log(err.name) // IdempotentParameterMismatchException
}⚠️ GOTCHA: Oversized Transactions Are Rejected As A Whole (Item > 400KB or Total > 4MB)
DynamoDB transactions have a hard limit of 4MB total size across all items, and each item is still capped at 400KB. An item over 400KB or a transaction over 4MB aggregate is rejected with a ValidationException (or a TransactionCanceledException whose CancellationReasons say which item failed), and nothing is written: transactions are all-or-nothing. The failure is not silent; the risk is code that swallows the error and assumes the write happened.
Why it happens:
- Transaction total size limit: 4MB (all items combined); item limit: 400KB
- Large item (e.g., 500KB document) + 9 other items = exceeds the limits
- The whole request fails; no item in it is applied (no partial write)
- Thông báo lỗi nêu rõ lý do (đã đo trên DynamoDB Local:
Item size has exceeded the maximum allowed sizevàTransaction payload size cannot exceed 4MB), nhưng code nuốt lỗi vẫn mất ghi
Real-world bug (error swallowed):
javascript
// Node.js (SDK v3) — minh hoạ, không chạy độc lập (thiếu bảng Audit và 8 item còn lại)
import { TransactWriteCommand } from '@aws-sdk/lib-dynamodb'
// Attempt to save large user profile in transaction
const userProfile = {
userId: 'USER#123',
name: 'John',
avatar: 'x'.repeat(500 * 1024), // 500KB!
preferences: { /* large nested object */ }
}
try {
await dynamodb.send(new TransactWriteCommand({
TransactItems: [
{
Put: {
TableName: 'Users',
Item: userProfile // 500KB item
}
},
{
Update: {
TableName: 'Audit',
Key: { auditId: 'AUDIT#123' },
UpdateExpression: 'SET lastUpdate = :time',
ExpressionAttributeValues: { ':time': Date.now() }
}
},
// ... 8 more items (total > 4MB)
]
}))
console.log('Profile saved!') // Never reached: the request is rejected
} catch (err) {
// ValidationException / TransactionCanceledException: NOTHING was written
// (neither the profile nor the audit update). Logging and moving on loses the user's change.
console.error('Failed:', err)
}How to detect:
javascript
// Node.js (SDK v3) — minh hoạ, không chạy độc lập (transactItems là mảng của bạn)
import { TransactWriteCommand } from '@aws-sdk/lib-dynamodb'
// Ước lượng thô kích thước transaction trước khi gửi (kích thước tính của DynamoDB khác JSON)
const calculateItemSize = (item) => {
return Buffer.byteLength(JSON.stringify(item)) // xấp xỉ theo byte
}
const transactItems = [] // mảng TransactItems của bạn
const totalSize = transactItems.reduce((sum, t) => {
const item = t.Put?.Item || {} // chỉ Put có Item; Update/Delete/ConditionCheck không có
return sum + calculateItemSize(item)
}, 0)
if (totalSize > 4 * 1024 * 1024) { // 4MB
console.error(`Transaction too large: ${totalSize} bytes`)
}
// Monitor for ValidationException errors
try {
await dynamodb.send(new TransactWriteCommand({...}))
} catch (err) {
if (err.name === 'ValidationException' || err.name === 'TransactionCanceledException') {
// Nothing was written; CancellationReasons (if present) names the failing item
console.error('Transaction rejected (size/validation):', err.message, err.CancellationReasons)
}
}Prevention:
Validate item sizes before transaction:
javascript// Node.js (SDK v3) — minh hoạ, không chạy độc lập (transactItems là mảng của bạn) import { TransactWriteCommand } from '@aws-sdk/lib-dynamodb' const MAX_ITEM_SIZE = 400 * 1024 // 400KB (safe limit per item) const MAX_TRANSACTION_SIZE = 4 * 1024 * 1024 // 4MB total const validateTransaction = (transactItems) => { let totalSize = 0 for (const t of transactItems) { const item = t.Put?.Item || {} // chỉ Put có Item const itemSize = Buffer.byteLength(JSON.stringify(item)) if (itemSize > MAX_ITEM_SIZE) { throw new Error(`Item exceeds 400KB: ${itemSize} bytes`) } totalSize += itemSize if (totalSize > MAX_TRANSACTION_SIZE) { throw new Error(`Transaction exceeds 4MB: ${totalSize} bytes`) } } } validateTransaction(transactItems) await dynamodb.send(new TransactWriteCommand({ TransactItems: transactItems }))Store large data in S3, reference in DynamoDB:
javascript// Node.js (SDK v3) — minh hoạ, không chạy độc lập (cần client s3, userId, avatarBuffer) import { TransactWriteCommand } from '@aws-sdk/lib-dynamodb' import { Upload } from '@aws-sdk/lib-storage' // Save large avatar to S3 const avatarUrl = await new Upload({ client: s3, params: { Bucket: 'user-avatars', Key: `${userId}/avatar.jpg`, Body: avatarBuffer } }).done() // Store only S3 URL in DynamoDB (small!) await dynamodb.send(new TransactWriteCommand({ TransactItems: [ { Put: { TableName: 'Users', Item: { userId: 'USER#123', name: 'John', avatarUrl: avatarUrl.Location, // Just URL, not data! preferences: {...} } } } ] }))Split large transactions into multiple smaller transactions:
javascript// Node.js (SDK v3) — minh hoạ, không chạy độc lập (items là mảng TransactItems của bạn) import { TransactWriteCommand } from '@aws-sdk/lib-dynamodb' const chunkSize = 100 // Max items per transaction (splitting loses atomicity across chunks) const chunks = [] for (let i = 0; i < items.length; i += chunkSize) { chunks.push(items.slice(i, i + chunkSize)) } for (const chunk of chunks) { await dynamodb.send(new TransactWriteCommand({ TransactItems: chunk })) }Compress large text fields:
javascript// Node.js (SDK v3) — chạy sau khối khởi tạo `dynamodb` ở đầu mục DynamoDB Consistency import { PutCommand } from '@aws-sdk/lib-dynamodb' import zlib from 'node:zlib' const largeData = { note: 'x'.repeat(10000) } // Compress before storing const compressed = zlib.gzipSync(JSON.stringify(largeData)) await dynamodb.send(new PutCommand({ TableName: 'Users', Item: { userId: 'USER#123', data: compressed.toString('base64') // Compressed } }))
→ See also: DynamoDB Anti-Patterns, DynamoDB Best Practices
Conditional Writes (Optimistic Locking)
javascript
// Node.js (SDK v3) — chạy sau khối khởi tạo `dynamodb`; tạo trước item { userId: 'USER#123', balance: 0, version: 2 } ở bảng Users
import { UpdateCommand } from '@aws-sdk/lib-dynamodb'
// Prevent lost updates with version field
const params = {
TableName: 'Users',
Key: { userId: 'USER#123' },
UpdateExpression: 'SET balance = :newBalance, version = :newVersion',
ConditionExpression: 'version = :expectedVersion',
ExpressionAttributeValues: {
':newBalance': 500,
':newVersion': 3,
':expectedVersion': 2 // Fail if version changed
}
}
try {
await dynamodb.send(new UpdateCommand(params))
} catch (err) {
if (err.name === 'ConditionalCheckFailedException') {
// Version conflict - read latest and retry
}
}⚠️ GOTCHA: Gửi lại sau timeout có thể bị ConditionalCheckFailedException dù lần đầu đã ghi, hoặc ghi đôi
Kịch bản minh hoạ, không phải sự cố có nguồn; mô phỏng "response bị mất" bằng cách gửi cùng một lệnh hai lần (đã chạy trên DynamoDB Local).
Vì sao xảy ra:
- Lần gửi đầu thành công nhưng client không nhận được response (timeout), nên gửi lại.
UpdateItemkhông cóClientRequestToken: DynamoDB không nhận ra lần gửi lại là trùng (chỉTransactWriteItemscó).- Điều kiện dựa trên
version: lần gửi lại bịConditionalCheckFailedExceptionvì lần đầu đã đổi version, dù thay đổi ĐÃ áp. - Cập nhật không có điều kiện version (
balance = balance - :amount): gửi hai lần thì trừ hai lần.
Lỗi hay gặp:
javascript
// Node.js (SDK v3) — chạy sau khối khởi tạo `dynamodb` ở đầu mục DynamoDB Consistency
import { GetCommand, PutCommand, UpdateCommand } from '@aws-sdk/lib-dynamodb'
await dynamodb.send(new PutCommand({ TableName: 'Accounts', Item: { accountId: 'A', balance: 500, version: 2 } }))
const charge = () => dynamodb.send(new UpdateCommand({
TableName: 'Accounts',
Key: { accountId: 'A' },
UpdateExpression: 'SET balance = balance - :amount, version = :newVersion',
ConditionExpression: 'version = :expectedVersion',
ExpressionAttributeValues: { ':amount': 100, ':newVersion': 3, ':expectedVersion': 2 }
}))
await charge() // lần 1: ghi thành công, giả sử response bị mất
try {
await charge() // lần 2 (retry): ConditionalCheckFailedException
} catch (err) {
console.log(err.name)
}
const { Item } = await dynamodb.send(new GetCommand({ TableName: 'Accounts', Key: { accountId: 'A' }, ConsistentRead: true }))
console.log(Item.balance, Item.version) // 400 3: lần 1 ĐÃ ápCách phát hiện: sau ConditionalCheckFailedException, đọc lại item bằng ConsistentRead: true và so với trạng thái kỳ vọng (ở trên: version === 3).
Cách phòng:
- Đọc lại bằng
ConsistentRead: truesauConditionalCheckFailedException, so version/số dư với giá trị kỳ vọng trước khi coi là thất bại. - Dùng transaction +
ClientRequestToken+ bản ghi đánh dấu để mỗi lần thanh toán chỉ áp một lần:javascript// Node.js (SDK v3) — chạy sau khối khởi tạo `dynamodb`; item A (balance 500) ở bảng Accounts như trên import { TransactWriteCommand } from '@aws-sdk/lib-dynamodb' const chargeOnce = (chargeId, amount) => dynamodb.send(new TransactWriteCommand({ ClientRequestToken: chargeId, // cùng token + cùng tham số trong 10 phút: không ghi lại TransactItems: [ { Update: { TableName: 'Accounts', Key: { accountId: 'A' }, UpdateExpression: 'SET balance = balance - :amount', ConditionExpression: 'balance >= :amount', ExpressionAttributeValues: { ':amount': amount } } }, { Put: { // đánh dấu: chargeId đã tồn tại thì cả transaction bị huỷ (token hết hạn vẫn không trừ lần hai) TableName: 'Charges', Item: { chargeId, amount }, ConditionExpression: 'attribute_not_exists(chargeId)' } } ] })) await chargeOnce('CHARGE#12345', 100) await chargeOnce('CHARGE#12345', 100) // retry: không trừ thêm (A vẫn 400)
Bài học: retry sau timeout phải idempotent (token + bản ghi đánh dấu) hoặc xác minh trạng thái bằng đọc ConsistentRead: true, không coi ConditionalCheckFailedException là "chắc chắn chưa ghi".
Phải nhớ
- Đọc mặc định của DynamoDB là eventually consistent: dùng
ConsistentRead: truecho read-after-write (không áp dụng cho GSI). - Transaction: ≤ 100 action, ≤ 4 MB, tốn gấp đôi capacity; thêm
ClientRequestTokenđể retry an toàn. - Gửi lại sau timeout có thể ghi đôi hoặc báo
ConditionalCheckFailedExceptiondù đã ghi: đọc lại bằngConsistentRead: truehoặc dùng transaction + token.
→ See also: DynamoDB Transactions, DynamoDB Anti-Patterns