0
0
DynamoDBquery~5 mins

TransactWriteItems in DynamoDB

Choose your learning style9 modes available
Introduction

TransactWriteItems lets you make multiple changes to your database at once. It makes sure all changes happen together or none at all, so your data stays correct.

You want to update several related items and keep them in sync.
You need to add a new order and reduce stock at the same time.
You want to delete an item only if another item meets a condition.
You want to make sure no partial updates happen if something fails.
Syntax
DynamoDB
TransactWriteItems {
  TransactItems: [
    {
      Put: { TableName, Item },
      Update: { TableName, Key, UpdateExpression, ExpressionAttributeValues },
      Delete: { TableName, Key },
      ConditionCheck: { TableName, Key, ConditionExpression }
    },
    ...
  ]
}

You include an array of actions inside TransactItems.

Each action can be a Put, Update, Delete, or ConditionCheck.

Examples
This example adds a new user and decreases stock for a product in one transaction.
DynamoDB
TransactWriteItems {
  TransactItems: [
    { Put: { TableName: "Users", Item: { UserId: "123", Name: "Alice" } } },
    { Update: { TableName: "Inventory", Key: { ProductId: "A1" }, UpdateExpression: "SET Stock = Stock - :dec", ExpressionAttributeValues: { ":dec": { "N": "1" } } } }
  ]
}
This deletes a session only if the user exists.
DynamoDB
TransactWriteItems {
  TransactItems: [
    { Delete: { TableName: "Sessions", Key: { SessionId: "abc" } } },
    { ConditionCheck: { TableName: "Users", Key: { UserId: "123" }, ConditionExpression: "attribute_exists(UserId)" } }
  ]
}
Sample Program

This transaction adds a new order and reduces the stock of the product by 2. Both happen together or not at all.

DynamoDB
TransactWriteItems {
  TransactItems: [
    {
      Put: {
        TableName: "Orders",
        Item: { OrderId: "order123", ProductId: "prod456", Quantity: { "N": "2" } }
      }
    },
    {
      Update: {
        TableName: "Inventory",
        Key: { ProductId: "prod456" },
        UpdateExpression: "SET Stock = Stock - :qty",
        ExpressionAttributeValues: { ":qty": { "N": "2" } }
      }
    }
  ]
}
OutputSuccess
Important Notes

All actions in TransactWriteItems succeed or fail together.

Use ConditionCheck to prevent unwanted changes.

Maximum 100 actions per transaction.

Summary

TransactWriteItems lets you group multiple writes into one safe transaction.

It helps keep your data consistent by applying all changes together.

You can use Put, Update, Delete, and ConditionCheck actions inside it.