DynamoDB Transactions
Syntax
{
"TransactItems": [
<operations>
],
"ReturnConsumedCapacity": "TOTAL",
"ReturnItemCollectionMetrics": "SIZE"
}
Example
{
"TransactItems": [{
"Update": {
"TableName": "Table1",
"Key": {
"id": { "S": "123" }
},
"UpdateExpression": "SET #item = :val",
"ExpressionAttributeNames": {
"#item": "attribute1"
},
"ExpressionAttributeValues": {
":val": { "S": "value1" }
}
}
},
{
"Get": {
"TableName": "Table2",
"Key": {
"id": { "S": "456" }
}
}
}]
}
Output
{
"Responses": [
{
"Update": {}
},
{
"Get": {
"attribute1": { "S": "value2" },
"attribute2": { "N": "1234" }
}
}
],
"ConsumedCapacity": [
{
"TableName": "Table1",
"CapacityUnits": 1
},
{
"TableName": "Table2",
"CapacityUnits": 0.5
}
],
"ItemCollectionMetrics": [
{
"ItemCollectionKey": { "id": { "S": "123" } },
"SizeEstimateRangeGB": [0.5, 1]
},
{
"ItemCollectionKey": { "id": { "S": "456" } },
"SizeEstimateRangeGB": [0, 0.5]
}
]
}
Explanation
DynamoDB Transactions allow developers to group operations so that they either all succeed, or all fail. This guarantees the atomicity of operations, which means that either all updates will be made or none at all, avoiding situations where some operations succeed and others fail, causing data inconsistencies.
The syntax for a DynamoDB transaction includes an array of operations, where each operation is either a Put, Update, Delete, or Get command. The transaction will only succeed if all operations in the array succeed.
In the above example, a transaction includes an Update operation on Table1 and a Get operation on Table2. If both operations succeed, the transaction as a whole will succeed and the response will include the new value for attribute1 in Table1 and the attributes for the item in Table2.
Use
DynamoDB Transactions are useful in situations where multiple pieces of data need to be updated simultaneously, while maintaining data consistency. For example:
- A shopping cart application where updating the inventory of different products and the cost of the order needs to be atomic.
- A banking application where transferring money from one account to another needs to be atomic.
Important Points
- DynamoDB Transactions work on a maximum of 10 items across 10 tables
- The operations in a transaction must use a consistent read, which means that they will read the latest state of the item, rather than a cached state
- Transactions are billed on the total number of operations in the transaction, even if some operations fail
Summary
DynamoDB Transactions allow developers to group operations into an atomic unit, ensuring that they all either succeed or fail together. This is useful in situations where data consistency is critical, and multiple updates need to happen simultaneously. DynamoDB Transactions support Put, Update, Delete, and Get operations, using a consistent read to ensure the latest data is used. Transactions are billed on the total number of operations, and support a maximum of 10 items across 10 tables.