Transactions and batches help you work with many items in a database at once. Transactions make sure all changes happen together or not at all. Batches let you do many changes quickly but without full safety.
0
0
Transaction vs batch comparison in DynamoDB
Introduction
When you need to update multiple items and want to be sure all updates succeed or none do.
When you want to read or write many items quickly without needing all-or-nothing safety.
When you want to avoid partial updates that could cause inconsistent data.
When you want to save time by sending many requests in one go.
When you want to handle multiple items but can accept some updates failing.
Syntax
DynamoDB
Transaction example:
TransactWriteItems {
TransactItems: [
{ Put: { TableName, Item } },
{ Update: { TableName, Key, UpdateExpression } },
...
]
}
Batch example:
BatchWriteItem {
RequestItems: {
TableName: [
{ PutRequest: { Item } },
{ DeleteRequest: { Key } },
...
]
}
}Transactions guarantee all operations succeed or none do.
Batches are faster but may partially succeed.
Examples
This transaction adds a user and updates an order status together.
DynamoDB
TransactWriteItems {
TransactItems: [
{ Put: { TableName: "Users", Item: { UserId: "1", Name: "Alice" } } },
{ Update: { TableName: "Orders", Key: { OrderId: "100" }, UpdateExpression: "SET Status = :s", ExpressionAttributeValues: { ":s": "Shipped" } } }
]
}This batch writes a new user and deletes another user quickly.
DynamoDB
BatchWriteItem {
RequestItems: {
"Users": [
{ PutRequest: { Item: { UserId: "2", Name: "Bob" } } },
{ DeleteRequest: { Key: { UserId: "3" } } }
]
}
}Sample Program
This transaction adds a new product and decreases stock of another product together. If one fails, none change.
DynamoDB
TransactWriteItems {
TransactItems: [
{ Put: { TableName: "Products", Item: { ProductId: "p1", Name: "Pen", Stock: 10 } } },
{ Update: { TableName: "Products", Key: { ProductId: "p2" }, UpdateExpression: "SET Stock = Stock - :dec", ExpressionAttributeValues: { ":dec": 1 } } }
]
}OutputSuccess
Important Notes
Transactions are slower because they check all operations before applying.
Batches can process up to 25 items per request.
Use transactions when data consistency is critical.
Summary
Transactions ensure all-or-nothing changes for multiple items.
Batches allow fast processing of many items but may partially succeed.
Choose transactions for safety, batches for speed.