Amazon DynamoDB (50 Qs)•Part 2: Intermediate Data Modeling & API Operations (Mid-Level)
How do DynamoDB Transactions (TransactWriteItems / TransactGetItems) work?
mid LevelCode ExampleState ManagementDatabases & SQLDynamoDB
In Simple Words: DynamoDB provides all-or-nothing ACID transactions across multiple items within or across tables in the same AWS account and region:
- TransactWriteItems: Up to 100 items or 4 MB of data in a single transactional batch. If any item fails its condition expression, the entire transaction rolls back.
- Cost: Consumes 2x the capacity units (two-phase commit protocol under the hood).
typescript
import { DynamoDBClient, TransactWriteItemsCommand } from "@aws-sdk/client-dynamodb";
await client.send(new TransactWriteItemsCommand({
TransactItems: [
{
Update: {
TableName: "Accounts",
Key: { id: { S: "acc_A" } },
UpdateExpression: "SET balance = balance - :amt",
ConditionExpression: "balance >= :amt",
ExpressionAttributeValues: { ":amt": { N: "100" } }
}
},
{
Update: {
TableName: "Accounts",
Key: { id: { S: "acc_B" } },
UpdateExpression: "SET balance = balance + :amt",
ExpressionAttributeValues: { ":amt": { N: "100" } }
}
}
]
}));