0
0
DynamodbHow-ToBeginner · 4 min read

How to Use TransactWriteItems in DynamoDB for Atomic Writes

Use TransactWriteItems in DynamoDB to perform multiple write operations (put, update, delete) atomically in a single request. This ensures all operations succeed or none are applied, maintaining data consistency. You provide an array of actions in the TransactItems parameter to execute them together.
📐

Syntax

The TransactWriteItems API accepts a list of write operations inside TransactItems. Each item can be a Put, Update, Delete, or ConditionCheck. All operations run atomically.

  • TransactItems: Array of write actions.
  • Put: Adds a new item.
  • Update: Modifies attributes of an existing item.
  • Delete: Removes an item.
  • ConditionCheck: Checks a condition before proceeding.
json
TransactWriteItems({
  TransactItems: [
    { Put: { TableName: 'Table1', Item: { /* item attributes */ } } },
    { Update: { TableName: 'Table2', Key: { /* key attributes */ }, UpdateExpression: 'set #a = :val', ExpressionAttributeNames: { '#a': 'attr' }, ExpressionAttributeValues: { ':val': 'value' } } },
    { Delete: { TableName: 'Table3', Key: { /* key attributes */ } } },
    { ConditionCheck: { TableName: 'Table4', Key: { /* key attributes */ }, ConditionExpression: 'attribute_exists(#k)', ExpressionAttributeNames: { '#k': 'key' } } }
  ]
})
💻

Example

This example shows how to use TransactWriteItems with AWS SDK for JavaScript v3 to put a new item and update another item atomically.

javascript
import { DynamoDBClient, TransactWriteItemsCommand } from "@aws-sdk/client-dynamodb";

const client = new DynamoDBClient({ region: "us-east-1" });

async function run() {
  const params = {
    TransactItems: [
      {
        Put: {
          TableName: "Users",
          Item: {
            UserId: { S: "user123" },
            Name: { S: "Alice" },
            Age: { N: "30" }
          }
        }
      },
      {
        Update: {
          TableName: "Accounts",
          Key: { AccountId: { S: "acc456" } },
          UpdateExpression: "SET Balance = Balance + :inc",
          ExpressionAttributeValues: { ":inc": { N: "100" } }
        }
      }
    ]
  };

  try {
    const data = await client.send(new TransactWriteItemsCommand(params));
    console.log("Transaction succeeded.");
  } catch (err) {
    console.error("Transaction failed:", err);
  }
}

run();
Output
Transaction succeeded.
⚠️

Common Pitfalls

Common mistakes when using TransactWriteItems include:

  • Exceeding the maximum of 25 operations per transaction.
  • Not handling transaction failures properly, which roll back all operations.
  • Using inconsistent data types in keys or attributes.
  • Ignoring conditional checks that can cause the transaction to fail.
  • Not setting proper IAM permissions for transactional operations.
javascript
/* Wrong: More than 25 operations causes error */
const params = {
  TransactItems: new Array(26).fill({
    Put: {
      TableName: "MyTable",
      Item: { Id: { S: "1" } }
    }
  })
};

/* Right: Limit to 25 or fewer operations */
const validParams = {
  TransactItems: new Array(25).fill({
    Put: {
      TableName: "MyTable",
      Item: { Id: { S: "1" } }
    }
  })
};
📊

Quick Reference

ParameterDescription
TransactItemsArray of write operations to perform atomically.
PutAdds a new item to a table.
UpdateUpdates attributes of an existing item.
DeleteDeletes an item from a table.
ConditionCheckChecks a condition before executing the transaction.
Max OperationsMaximum 25 operations per transaction.
AtomicityAll operations succeed or none are applied.

Key Takeaways

Use TransactWriteItems to perform multiple writes atomically in DynamoDB.
You can include Put, Update, Delete, and ConditionCheck operations in one transaction.
Transactions fail entirely if any operation's condition is not met or an error occurs.
Limit your transaction to 25 operations or fewer.
Handle errors properly to maintain data consistency.