1.3.2 Database Consistency Models
Database Consistency Models
Strongly Consistent vs Eventually Consistent
| Strongly Consistent | Eventually Consistent |
|---|
| Data | Luôn mới nhất | Có thể stale (~1s) |
| RCU cost | 1 RCU = 4KB | 0.5 RCU = 4KB (rẻ gấp đôi) |
| GSI support | ❌ Không hỗ trợ | ✅ Default |
| LSI support | ✅ Hỗ trợ | ✅ Default |
| Cách dùng | ConsistentRead=true | Default (không cần set) |
Cách hoạt động
Write → Leader node → Replicate to 2 replicas (async)
Eventually Consistent Read: Có thể đọc từ replica chưa cập nhật
Strongly Consistent Read: Luôn đọc từ leader node
Khi nào dùng gì?
| Scenario | Chọn |
|---|
| Hiển thị product catalog | Eventually Consistent (rẻ, chấp nhận stale) |
| Đọc balance sau transaction | Strongly Consistent (cần chính xác) |
| GSI queries | Eventually Consistent (bắt buộc) |
| Real-time inventory count | Strongly Consistent |
DynamoDB Transactions
TransactWriteItems / TransactGetItems- ACID transactions across multiple items/tables
- Cost: 2x WCU/RCU so với standard operations
- Max 100 items per transaction
import boto3
client = boto3.client('dynamodb')
client.transact_write_items(
TransactItems=[
{
'Update': {
'TableName': 'Accounts',
'Key': {'id': {'S': 'acc-1'}},
'UpdateExpression': 'SET balance = balance - :amount',
'ExpressionAttributeValues': {':amount': {'N': '100'}}
}
},
{
'Update': {
'TableName': 'Accounts',
'Key': {'id': {'S': 'acc-2'}},
'UpdateExpression': 'SET balance = balance + :amount',
'ExpressionAttributeValues': {':amount': {'N': '100'}}
}
}
]
)
Exam Tip: Eventually Consistent = default, rẻ hơn 50%. Strongly Consistent = ConsistentRead=true, không dùng được với GSI. Transactions = 2x cost nhưng đảm bảo ACID.