Chuyển đến nội dung

Bài 27 · Capacity, Consistency and Transactions

Transactions

Group up to 100 DynamoDB actions in an all-or-nothing transaction with TransactWriteItems, learn the limits, costs, idempotency tokens and when to avoid them.

A conditional write protects one item. Many real operations touch several: transfer money between two accounts, create an order and decrement stock, claim a username and create the user. If the second step fails after the first succeeded, your data is wrong. DynamoDB transactions make a group of actions atomic (all succeed or none do) and isolated (other requests never see half of it).

Transactions are two API calls: TransactWriteItems for writes and TransactGetItems for reads. They work across multiple items, across multiple tables in the same Region and account, with serializable isolation.

TransactWriteItems

A transaction holds up to 100 actions (the limit was 25 before 2022) with a combined size limit of 4 MB. Each action is one of:

  • Put, Update, Delete, each with an optional ConditionExpression
  • ConditionCheck: only check a condition on an item you do not write

If any condition fails, the whole transaction is rejected with TransactionCanceledException, which lists a cancellation reason for every action so you can see which one failed. Rules: an item can appear in only one action per transaction, and actions cannot target indexes, only base tables.

Python
# boto3 client (read-only here): create an order and take stock in one transaction
client.transact_write_items(
    ClientRequestToken="order-o21-attempt",
    TransactItems=[
        {"Put": {
            "TableName": "Shop",
            "Item": {"PK": {"S": "ORDER#o21"}, "SK": {"S": "META"}, "status": {"S": "NEW"}},
            "ConditionExpression": "attribute_not_exists(PK)",
        }},
        {"Update": {
            "TableName": "Shop",
            "Key": {"PK": {"S": "PRODUCT#mug"}, "SK": {"S": "STOCK"}},
            "UpdateExpression": "SET stock = stock - :n",
            "ConditionExpression": "stock >= :n",
            "ExpressionAttributeValues": {":n": {"N": "2"}},
        }},
    ],
)

What a transaction gives you

Atomic All actions or none
Isolated Serializable, no half states
Idempotent ClientRequestToken for 10 minutes
Costs double 2 units per KB written or 4 KB read

Use it where consistency matters most.

1 / 2

Try it: all or nothing

The stand-in below applies a list of actions to a dictionary, checking every condition first and only then applying changes. This mirrors the guarantee, though the real service does it across partitions with a two-phase protocol.

Python Transfer between two accounts

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

When the second transfer was refused, neither account changed. That is the point: the credit to b is never applied without the debit from a.

TransactGetItems

TransactGetItems reads up to 100 items as one snapshot, so a set of related items is consistent with each other. It costs two RCU per 4 KB (see capacity modes). Ordinary BatchGetItem is cheaper but may return items from different moments.

Idempotency with ClientRequestToken

Network timeouts leave you unsure whether a transaction ran. Pass a ClientRequestToken (up to 36 characters). Repeating the same request with the same token within 10 minutes returns success without applying it twice; the same token with different parameters raises IdempotentParameterMismatchException. Use a stable ID such as the order ID.

Costs, limits and failures

  • Each item in a transaction costs double write or read units, because DynamoDB does a prepare and a commit phase.
  • Items in a transaction are locked briefly. A concurrent transaction touching the same item fails with TransactionConflictException or is cancelled with TransactionConflict; retry with backoff.
  • Transactions are not supported by a global secondary index and cannot span Regions or accounts. For global tables they are atomic only in the Region where they run.
  • Plain items for which a conditional write is enough should not use a transaction.

Design first for one-item operations. Put data that changes together in the same item or item collection. A single UpdateItem with a condition is atomic and half the price of a two-item transaction.

Transactions versus batches

BatchWriteItem TransactWriteItems
Atomic No: items succeed or fail separately Yes
Conditions None (puts and deletes only) Per action
Max items 25 100
Cost normal units double units
Python Compare a batch with a transaction

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The batch credits b and loses the debit: money appeared from nowhere. The transaction leaves both untouched.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What happens if one condition in a TransactWriteItems call fails?

    Transactions are all-or-nothing. The cancellation reasons tell you which actions failed.
  2. 2. What does ClientRequestToken provide?

    The token lets you safely retry after a timeout. The same token with different parameters is rejected.
  3. 3. How are transactional operations billed compared with standard ones?

    Transactions use a two-phase protocol, so they consume two units per KB written or 4 KB read.
  4. 4. Which is NOT a feature of a transaction?

    Each item may appear in only one action of a transaction. The others are supported.

Summary

  • TransactWriteItems groups up to 100 puts, updates, deletes and condition checks atomically; TransactGetItems reads a consistent snapshot.
  • If any condition fails, nothing is written and the exception lists a reason per action.
  • Use ClientRequestToken to make retries idempotent for 10 minutes.
  • Transactions cost double and can conflict with each other; prefer single-item conditional writes where they suffice.
  • A batch is not atomic and has no conditions.

Next: DynamoDB Streams

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.