0
0
DynamoDBquery~5 mins

Why transactions ensure atomicity in DynamoDB

Choose your learning style9 modes available
Introduction

Transactions make sure that a group of database actions all happen together or not at all. This keeps data correct and safe.

When you want to update multiple items and need all updates to succeed together.
When transferring money between two accounts and both debit and credit must happen together.
When creating an order and reducing stock, both must happen or neither.
When you want to avoid partial changes that can cause errors or confusion.
Syntax
DynamoDB
TransactWriteItems {
  TransactItems: [
    { Put: { TableName: 'TableName', Item: { /* item attributes */ } } },
    { Update: { TableName: 'TableName', Key: { /* key attributes */ }, UpdateExpression: 'string', ExpressionAttributeValues: { /* values */ } } },
    { Delete: { TableName: 'TableName', Key: { /* key attributes */ } } }
  ]
}
All actions inside TransactWriteItems succeed or fail as one unit.
If any action fails, none of the changes are saved.
Examples
This example adds a new user and updates an account balance together.
DynamoDB
TransactWriteItems {
  TransactItems: [
    { Put: { TableName: 'Users', Item: { UserId: '123', Name: 'Alice' } } },
    { Update: { TableName: 'Accounts', Key: { AccountId: 'abc' }, UpdateExpression: 'SET Balance = Balance - :amount', ExpressionAttributeValues: { ':amount': 100 } } }
  ]
}
This example deletes a cart and creates an order in one transaction.
DynamoDB
TransactWriteItems {
  TransactItems: [
    { Delete: { TableName: 'Cart', Key: { CartId: 'cart123' } } },
    { Put: { TableName: 'Orders', Item: { OrderId: 'order456', Status: 'Placed' } } }
  ]
}
Sample Program

This transaction transfers 50 units from account A1 to A2. Both updates happen together or not at all.

DynamoDB
TransactWriteItems {
  TransactItems: [
    { Update: { TableName: 'Bank', Key: { AccountId: 'A1' }, UpdateExpression: 'SET Balance = Balance - :amt', ExpressionAttributeValues: { ':amt': 50 } } },
    { Update: { TableName: 'Bank', Key: { AccountId: 'A2' }, UpdateExpression: 'SET Balance = Balance + :amt', ExpressionAttributeValues: { ':amt': 50 } } }
  ]
}
OutputSuccess
Important Notes

Transactions help avoid partial updates that can cause data errors.

They are useful when multiple related changes must be consistent.

Summary

Transactions group multiple actions to happen all at once.

This ensures data stays correct and safe.

If one action fails, none of the changes happen.