Amazon DynamoDB Tutorial 0/30 lessons ~6 min read Lesson 24

    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.

    Course progress0%
    Focus
    11 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    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:

    • TransactWriteItems supports Put, Update, Delete, and ConditionCheck actions — up to 100 actions and 4 MB per transaction.
    • TransactGetItems reads 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).
    • ClientRequestToken makes 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 TransactionCanceledException and a CancellationReasons list in action order.

    Informative example

    Unique email on sign-up: the customer item and an email-uniqueness item are created together:

    ts
    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 taken
    if (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.

    ts
    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 (TransactionConflict cancellation reasons).

    Best practices

    • Use transactions only for cross-item invariants; single-item conditional writes are cheaper.
    • Always pass a ClientRequestToken for 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.

    3 questions
    1IntermediateQuestionHow do you enforce a unique attribute such as email in DynamoDB?+

    Answer

    Create a separate item keyed by the unique value (PK = EMAIL#value) with attribute_not_exists(PK), in the same transaction as the main item. A GSI alone cannot enforce uniqueness because it is eventually consistent.
    2AdvancedQuestionWhat does ClientRequestToken do?+

    Answer

    It makes TransactWriteItems idempotent. If a request with the same token is repeated within 10 minutes, DynamoDB returns success without applying the writes again (and rejects the token if the request parameters differ).
    3IntermediateQuestionWhat do transactions cost?+

    Answer

    Transactional writes consume twice the write capacity of standard writes, and transactional reads consume twice the capacity of strongly consistent reads, because DynamoDB performs a prepare and a commit for each item.

    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.

    Ready to mark this lesson complete?Track your journey across the entire course.