ACID Transactions with TransactWriteItems
DynamoDB transactions apply up to 100 actions across one or more tables in the same account and Region as a single all-or-nothing operation.
Introduction
DynamoDB transactions apply up to 100 actions across one or more tables in the same account and Region as a single all-or-nothing operation. They are the right tool for invariants that span items: unique emails, inventory reservation with order creation, or moving money between accounts.
Purpose of this lesson
You will enforce a unique email with a transaction, reserve inventory atomically, make transactions idempotent, and decode cancellation reasons.
Understanding the topic
Transaction rules:
TransactWriteItemssupportsPut,Update,Delete, andConditionCheckactions — up to 100 actions and 4 MB per transaction.TransactGetItemsreads up to 100 items as a consistent snapshot.- One transaction cannot include two actions on the same item.
- Transactional writes cost twice the standard write capacity (and transactional reads twice the strongly consistent read cost).
ClientRequestTokenmakes a transaction idempotent: retries with the same token within 10 minutes do not apply it twice.- If any condition fails, the whole transaction is cancelled with
TransactionCanceledExceptionand aCancellationReasonslist in action order.
Informative example
Unique email on sign-up: the customer item and an email-uniqueness item are created together:
import { TransactWriteCommand } from "@aws-sdk/lib-dynamodb";import { TransactionCanceledException } from "@aws-sdk/client-dynamodb";import { ddb, TABLE } from "./ddb";export async function registerCustomer(customerId: string, email: string, requestId: string) {const normalized = email.trim().toLowerCase();try {await ddb.send(new TransactWriteCommand({ClientRequestToken: requestId,TransactItems: [{ Put: {TableName: TABLE,Item: { PK: `CUSTOMER#${customerId}`, SK: "PROFILE", entityType: "Customer", email: normalized },ConditionExpression: "attribute_not_exists(PK)",} },{ Put: {TableName: TABLE,Item: { PK: `EMAIL#${normalized}`, SK: "EMAIL", entityType: "EmailClaim", customerId },ConditionExpression: "attribute_not_exists(PK)",} },],}));return "created";} catch (err) {if (err instanceof TransactionCanceledException) {const codes = err.CancellationReasons?.map((r) => r.Code);// e.g. [ 'None', 'ConditionalCheckFailed' ] -> email already takenif (codes?.[1] === "ConditionalCheckFailed") return "email-taken";if (codes?.[0] === "ConditionalCheckFailed") return "customer-exists";}throw err;}}
Useful templates
Reserve stock and create the order atomically
If stock is too low, neither the decrement nor the order is written.
await ddb.send(new TransactWriteCommand({TransactItems: [{ Update: {TableName: TABLE,Key: { PK: "PRODUCT#p9", SK: "PRODUCT" },UpdateExpression: "SET stock = stock - :qty",ConditionExpression: "stock >= :qty",ExpressionAttributeValues: { ":qty": 2 },} },{ Put: {TableName: TABLE,Item: { PK: "ORDER#o7", SK: "HEADER", entityType: "Order", status: "PLACED", sku: "p9", qty: 2 },ConditionExpression: "attribute_not_exists(PK)",} },],}));
Trade-offs
- Strong invariants vs. double write cost and higher latency.
- Transactions are scoped to one Region; with global tables, other Regions see the changes through normal replication and conflict resolution.
- Large transactions touching hot items increase conflicts (
TransactionConflictcancellation reasons).
Best practices
- Use transactions only for cross-item invariants; single-item conditional writes are cheaper.
- Always pass a
ClientRequestTokenfor operations that clients may retry. - Map cancellation reasons to user-facing errors by action index.
Common mistakes
- Using transactions for bulk loads — use batch writes instead.
- Including the same item twice in one transaction (validation error).
- Treating a uniqueness GSI as a uniqueness guarantee — GSIs are eventually consistent and allow duplicates.
Advanced interview questions
Interview Prep
Practice concise answers, then expand each card for the explanation.
1IntermediateQuestionHow do you enforce a unique attribute such as email in DynamoDB?+
Answer
2AdvancedQuestionWhat does ClientRequestToken do?+
Answer
3IntermediateQuestionWhat do transactions cost?+
Answer
Hands-on exercise
Hands-on: implement changeEmail(customerId, oldEmail, newEmail) as one transaction: update the profile with a condition on the old email, delete the old EMAIL# claim, and put the new claim with attribute_not_exists(PK). Test the 'new email already taken' case.
Summary
Transactions apply up to 100 actions atomically within one Region. Use them for cross-item invariants, make them idempotent with ClientRequestToken, and decode CancellationReasons by action index.