0
0
DynamoDBquery~5 mins

Transaction error handling in DynamoDB

Choose your learning style9 modes available
Introduction

Transaction error handling helps you manage problems when multiple database actions happen together. It keeps your data safe and correct.

When you want to update several items at once and need all updates to succeed or none at all.
When you want to avoid partial changes that can cause wrong or broken data.
When you want to catch and fix errors like conflicts or missing items during a transaction.
When you want to retry a transaction if it fails due to temporary issues.
When you want to log or alert about problems during database updates.
Syntax
DynamoDB
Use TransactWriteItems API with a try-catch block in your code.

Example in JavaScript:

try {
  await dynamodb.transactWrite(params).promise();
} catch (error) {
  // handle error here
}
Transactions in DynamoDB let you group multiple write operations that succeed or fail together.
Errors can happen due to condition check failures, conflicts, or capacity limits.
Examples
This example tries to add a user and update an account balance together. If either fails, no change happens.
DynamoDB
const params = {
  TransactItems: [
    {
      Put: {
        TableName: 'Users',
        Item: { UserId: '123', Name: 'Alice' }
      }
    },
    {
      Update: {
        TableName: 'Accounts',
        Key: { AccountId: 'abc' },
        UpdateExpression: 'SET Balance = Balance - :amount',
        ExpressionAttributeValues: { ':amount': 100 }
      }
    }
  ]
};

try {
  await dynamodb.transactWrite(params).promise();
  console.log('Transaction succeeded');
} catch (error) {
  console.error('Transaction failed:', error.message);
}
This shows how to check the error type to handle specific transaction errors differently.
DynamoDB
try {
  await dynamodb.transactWrite(params).promise();
} catch (error) {
  if (error.code === 'TransactionCanceledException') {
    console.log('Transaction canceled due to condition failure or conflict');
  } else {
    console.log('Other error:', error.message);
  }
}
Sample Program

This program tries to add a product and reduce inventory stock by 5 in one transaction. If stock is less than 5, the transaction fails and prints a message.

DynamoDB
const AWS = require('aws-sdk');
const dynamodb = new AWS.DynamoDB.DocumentClient();

const params = {
  TransactItems: [
    {
      Put: {
        TableName: 'Products',
        Item: { ProductId: 'p1', Name: 'Pen', Stock: 10 }
      }
    },
    {
      Update: {
        TableName: 'Inventory',
        Key: { ItemId: 'p1' },
        UpdateExpression: 'SET Quantity = Quantity - :qty',
        ConditionExpression: 'Quantity >= :qty',
        ExpressionAttributeValues: { ':qty': 5 }
      }
    }
  ]
};

(async () => {
  try {
    await dynamodb.transactWrite(params).promise();
    console.log('Transaction succeeded');
  } catch (error) {
    if (error.code === 'TransactionCanceledException') {
      console.log('Transaction failed: Not enough stock or condition failed');
    } else {
      console.log('Transaction failed:', error.message);
    }
  }
})();
OutputSuccess
Important Notes

Always check error codes to understand why a transaction failed.

Use ConditionExpression to prevent unwanted updates during transactions.

Remember that all operations in a transaction must be in the same AWS region.

Summary

Transaction error handling keeps your data safe by making sure all changes happen together or not at all.

Use try-catch blocks to catch errors and respond properly.

Check error codes like TransactionCanceledException to know why a transaction failed.