0
0
DynamoDBquery~5 mins

Transaction conditions in DynamoDB

Choose your learning style9 modes available
Introduction

Transaction conditions help make sure changes happen only if certain rules are true. This keeps your data safe and correct.

You want to update a user's balance only if they have enough money.
You want to add a new item only if it doesn't already exist.
You want to delete a record only if it matches a specific status.
You want to change multiple items together but only if all conditions are met.
You want to avoid conflicts when many people change data at the same time.
Syntax
DynamoDB
TransactWriteItems {
  TransactItems: [
    {
      Put: {
        TableName: "TableName",
        Item: { ... },
        ConditionExpression: "condition_expression"
      }
    },
    {
      Update: {
        TableName: "TableName",
        Key: { ... },
        UpdateExpression: "update_expression",
        ConditionExpression: "condition_expression"
      }
    }
    // More actions
  ]
}

ConditionExpression is a string that defines the rule to check before the action.

If any condition fails, the whole transaction stops and no changes happen.

Examples
This adds a new user only if the UserId does not already exist.
DynamoDB
TransactWriteItems {
  TransactItems: [
    {
      Put: {
        TableName: "Users",
        Item: { "UserId": "123", "Name": "Alice" },
        ConditionExpression: "attribute_not_exists(UserId)"
      }
    }
  ]
}
This subtracts 100 from Balance only if Balance is at least 100.
DynamoDB
TransactWriteItems {
  TransactItems: [
    {
      Update: {
        TableName: "Accounts",
        Key: { "AccountId": "abc" },
        UpdateExpression: "SET Balance = Balance - :amount",
        ConditionExpression: "Balance >= :amount",
        ExpressionAttributeValues: { ":amount": { "N": "100" } }
      }
    }
  ]
}
Sample Program

This transaction tries to add a new product p1 only if it doesn't exist, and reduce stock of product p2 by 5 only if it has enough stock.

DynamoDB
TransactWriteItems {
  TransactItems: [
    {
      Put: {
        TableName: "Inventory",
        Item: { "ProductId": "p1", "Stock": { "N": "10" } },
        ConditionExpression: "attribute_not_exists(ProductId)"
      }
    },
    {
      Update: {
        TableName: "Inventory",
        Key: { "ProductId": "p2" },
        UpdateExpression: "SET Stock = Stock - :qty",
        ConditionExpression: "Stock >= :qty",
        ExpressionAttributeValues: { ":qty": { "N": "5" } }
      }
    }
  ]
}
OutputSuccess
Important Notes

All actions in a transaction succeed or fail together.

Use ConditionExpression to prevent unwanted changes.

Remember to provide ExpressionAttributeValues when using placeholders like :qty.

Summary

Transaction conditions check rules before changing data.

If any condition fails, no changes happen.

This helps keep your data safe and consistent.