How does DynamoDB handle transactions (TransactWriteItems)?
How DynamoDB TransactWriteItems delivers ACID all-or-nothing writes across tables, with conditions, idempotency, capacity cost and error handling.
Expected Interview Answer
DynamoDB provides ACID transactions through TransactWriteItems and TransactGetItems, which let you group up to 100 write or read actions across one or more tables into a single all-or-nothing operation that either fully succeeds or fully rolls back.
TransactWriteItems can combine Put, Update, Delete and ConditionCheck actions, each optionally guarded by a condition expression. All actions are committed atomically; if any condition fails or a conflict occurs, the whole transaction is cancelled with a TransactionCanceledException listing per-item reasons. Transactions provide isolation using optimistic concurrency — a concurrent conflicting transaction causes a TransactionConflict and is rejected. Each item participating consumes roughly double the capacity of a normal write because DynamoDB does a two-phase prepare/commit.
- All-or-nothing atomicity across multiple items and tables
- Condition checks enforce business rules within the transaction
- Serializable isolation prevents partial or conflicting updates
- Idempotency via a client request token to avoid duplicates
- Coordinates changes without app-level locking
AI Mentor Explanation
Think of a match result only being official when the scorecard, the bowling figures, and the points table are all updated together — if any one entry cannot be signed off, none of them count and the scorers redo it. DynamoDB’s TransactWriteItems is that all-or-nothing sign-off: multiple record changes commit together, and if a single guarded condition fails, the entire set is rolled back so the books never end up half-updated.
Step-by-Step Explanation
Step 1
Group your actions
Assemble up to 100 Put, Update, Delete and ConditionCheck actions across one or more tables into a single TransactWriteItems call.
Step 2
Attach condition expressions
Guard each action with a condition expression (e.g. attribute_not_exists or a balance check) so business rules are enforced atomically.
Step 3
Add an idempotency token
Supply a ClientRequestToken so retries of the same transaction are not applied twice within the ~10-minute idempotency window.
Step 4
Commit atomically
DynamoDB runs a two-phase prepare/commit; all actions succeed together or the whole transaction is cancelled.
Step 5
Handle cancellation
On TransactionCanceledException, inspect the per-item CancellationReasons (e.g. ConditionalCheckFailed, TransactionConflict) and decide whether to retry.
What Interviewer Expects
- Knows TransactWriteItems is all-or-nothing (ACID) across up to 100 actions
- Understands condition expressions guard each action
- Aware transactions cost roughly double the normal capacity per item
- Explains TransactionCanceledException and CancellationReasons
- Mentions ClientRequestToken for idempotency and optimistic concurrency isolation
Common Mistakes
- Thinking transactions can span more than 100 actions or unlimited size
- Ignoring the ~2x capacity cost of transactional operations
- Not handling TransactionCanceledException and its per-item reasons
- Assuming pessimistic locking — DynamoDB uses optimistic concurrency and rejects conflicts
- Omitting ClientRequestToken and getting duplicate effects on retries
Best Answer (HR Friendly)
“DynamoDB transactions let you bundle several database changes so they all happen together or none of them do, which keeps data correct. You can also add rules that must be true for the change to go through, and if any rule fails the whole bundle is cancelled.”
Code Example
import boto3
client = boto3.client('dynamodb')
try:
client.transact_write_items(
ClientRequestToken='transfer-9f2a', # idempotent retries
TransactItems=[
{'Update': {
'TableName': 'Accounts',
'Key': {'id': {'S': 'A'}},
'UpdateExpression': 'SET bal = bal - :amt',
'ConditionExpression': 'bal >= :amt', # must have funds
'ExpressionAttributeValues': {':amt': {'N': '100'}},
}},
{'Update': {
'TableName': 'Accounts',
'Key': {'id': {'S': 'B'}},
'UpdateExpression': 'SET bal = bal + :amt',
'ExpressionAttributeValues': {':amt': {'N': '100'}},
}},
],
)
except client.exceptions.TransactionCanceledException as e:
# Inspect CancellationReasons to see which action failed and why
print('Cancelled:', e.response['CancellationReasons'])Follow-up Questions
- What is the maximum number of actions in a single TransactWriteItems call?
- Why do transactional writes cost roughly twice the capacity of normal writes?
- How does ClientRequestToken provide idempotency?
- What does a TransactionCanceledException tell you and how do you handle it?
- How does DynamoDB’s optimistic concurrency differ from row locking in SQL databases?
MCQ Practice
1. What is the maximum number of actions allowed in one TransactWriteItems call?
A single TransactWriteItems call can include up to 100 action items across one or more tables.
2. Roughly how much capacity does a transactional write consume per item versus a normal write?
Transactions use a two-phase prepare/commit, so each item consumes about twice the capacity of a standard write.
3. What exception is raised when a condition inside a transaction fails?
A failed condition cancels the whole transaction, raising TransactionCanceledException whose CancellationReasons detail each item’s outcome.
Flash Cards
How many actions can TransactWriteItems hold? — Up to 100 Put/Update/Delete/ConditionCheck actions across one or more tables.
What isolation model does DynamoDB use for transactions? — Optimistic concurrency — conflicting concurrent transactions are rejected with TransactionConflict.
What ensures idempotent retries? — A ClientRequestToken, honoured within an ~10-minute window so a retry is not applied twice.
What is the capacity cost of transactions? — Roughly double a normal write per item, due to the two-phase prepare/commit.
Continue Learning
Related Interview Questions
What are the practical limits of DynamoDB transactions, and how do you handle a cancelled transaction?
hard
What is the difference between eventually consistent and strongly consistent reads in DynamoDB?
medium
What is optimistic locking in DynamoDB and how do conditional writes work?
medium
How do you make DynamoDB writes idempotent using condition expressions?
medium