Advanced9 min read

DynamoDB Transactions: All-or-Nothing Writes Across Items

A DynamoDB transaction groups several writes into a single all-or-nothing operation: either every action commits, or none does. It's how you keep two related items from drifting apart when a write half-fails.

Take an append-only audit log for a multi-tenant SaaS: one item per event under the tenant's partition key (PK = TENANT#acme, SK = EVENT#<time>#<id>), plus a COUNTER item per tenant holding eventCount.

Every event you append should also bump that counter. If the event lands but the counter doesn't, or the other way round, the log and the count disagree for good.

Does DynamoDB support transactions?

Yes. TransactWriteItems and TransactGetItems group up to 100 actions, across one or more tables in the same account and Region, into one all-or-nothing request.

  • Up to 100 actions, 4 MB in total. Each action targets a different item.
  • Actions are Put, Update, Delete, and ConditionCheck. A ConditionCheck asserts something about an item the transaction doesn't write.
  • It costs double. Every item is written twice, once to prepare and once to commit, and a canceled transaction still consumes that capacity.
  • Any failure cancels the whole request with a TransactionCanceledException whose CancellationReasons say which action failed and why.

The problem: two writes that must agree

You want each new audit event to also increment the tenant's running count. Done as two separate calls, any failure between them corrupts your data:

  1. PutItem the new EVENT#… item: succeeds.
  2. UpdateItem to ADD eventCount 1: times out.

Now the log has one more row than the counter claims. Retrying step 2 blindly risks double-counting; not retrying leaves them inconsistent. There's no safe recovery because the two writes were never linked.

Coming from SQL, you'd wrap both in BEGIN … COMMIT. DynamoDB's answer is a single transactional request that carries both writes together.

How TransactWriteItems works

Per the AWS Developer Guide, TransactWriteItems "groups up to 100 write actions in a single all-or-nothing operation" targeting up to 100 distinct items, and "the aggregate size of the items in the transaction cannot exceed 4 MB." The actions complete atomically: all succeed or none do.

You can mix four action types in one transaction:

  • Put: create or replace an item.
  • Update: edit attributes (including ADD for our counter).
  • Delete: remove an item by key.
  • ConditionCheck: assert a condition on an item you are not otherwise writing (e.g. "this tenant is still active").

You can't target the same item twice in one transaction, so a ConditionCheck can't sit on the item an Update writes. Put that condition in the Update's own ConditionExpression instead.

Transactions can't run against an index. To change items you find through a GSI, Query the index for their base-table keys, then transact on those keys. Add a condition to each action, because the GSI read was eventually consistent.

On a global table, the all-or-nothing guarantee holds only in the Region where you call it. Other replicas can briefly show part of a transaction while it replicates.

"DynamoDB"App"DynamoDB"Appprepare all,checkconditions"TransactWriteItems [PutEVENT, Update COUNTER,Check PROFILE]""all commit, orTransactionCanceledExcept-ion"

A worked example: append + count, atomically

Back to the audit log. Appending an event for tenant acme, bumping its counter, and checking that the tenant isn't suspended is one transaction with three actions on three different items:

actionitemeffect
PutTENANT#acmeEVENT#2026-06-24T09:14Z#a1write the new audit row
UpdateTENANT#acmeCOUNTERADD eventCount 1
ConditionCheckTENANT#acmePROFILEstatus must be "active"

If any condition fails, the whole request is canceled with a TransactionCanceledException and none of the writes happen. The log and the counter can't disagree.

Each action takes its own ConditionExpression. attribute_not_exists(SK) on the Put stops a retry from writing the event twice. #status = :active on the ConditionCheck asserts the tenant is active; status is a , so it goes through ExpressionAttributeNames.

Here is the whole request as tx.json:

[
  {
    "Put": {
      "TableName": "audit-log",
      "Item": {
        "PK": {"S": "TENANT#acme"},
        "SK": {"S": "EVENT#2026-06-24T09:14Z#a1"},
        "action": {"S": "invoice.export"}
      },
      "ConditionExpression": "attribute_not_exists(SK)"
    }
  },
  {
    "Update": {
      "TableName": "audit-log",
      "Key": {"PK": {"S": "TENANT#acme"}, "SK": {"S": "COUNTER"}},
      "UpdateExpression": "ADD eventCount :one",
      "ExpressionAttributeValues": {":one": {"N": "1"}}
    }
  },
  {
    "ConditionCheck": {
      "TableName": "audit-log",
      "Key": {"PK": {"S": "TENANT#acme"}, "SK": {"S": "PROFILE"}},
      "ConditionExpression": "#status = :active",
      "ExpressionAttributeNames": {"#status": "status"},
      "ExpressionAttributeValues": {":active": {"S": "active"}}
    }
  }
]
aws dynamodb transact-write-items --transact-items file://tx.json \
  --client-request-token evt-acme-a1

The client token makes retries safe on a flaky connection: a repeat with the same token within 10 minutes returns success without re-applying the writes (idempotency).

Without a token, a retry of a committed transaction is canceled with ConditionalCheckFailed on the Put. Read that as "already applied".

The DynamoDB Expression Builder builds the , with its names and values maps, for a single Put, Update or Delete. Copy those fields into the matching action of your TransactItems; the ConditionCheck you write by hand.

Handle TransactionCanceledException

AWS SDKs don't retry this exception for you. Its CancellationReasons list has one entry per action, in the order of TransactItems, and each entry's Code tells you what to do (TransactWriteItems errors):

CodeMeaningWhat to do
NoneThis action was fineNothing
ConditionalCheckFailedA condition was falseTreat it as the answer (duplicate, suspended)
TransactionConflictAnother write is in progress on the itemRetry with exponential backoff
ThrottlingError, ProvisionedThroughputExceededNot enough capacityRetry with backoff; see throttling
ValidationErrorThe request can't succeed as writtenFix the request; don't retry
ItemCollectionSizeLimitExceededAn item collection on a table with an LSI hit 10 GBDelete or shrink items under that partition key, or move to a new table without the LSI (an LSI can't be removed); don't retry
try {
  await client.send(new TransactWriteItemsCommand({TransactItems: items}));
} catch (err) {
  if (err.name !== 'TransactionCanceledException') throw err;
  const codes = (err.CancellationReasons ?? []).map((r) => r.Code); // codes[i] is TransactItems[i]
  const retryable = ['TransactionConflict', 'ThrottlingError', 'ProvisionedThroughputExceeded'];
  if (codes.some((c) => retryable.includes(c))) {
    // back off, then send the same request again
  }
}

Do it in DynoTable

When you stage item edits in DynoTable and commit them, it sends them as TransactWriteItems calls with optimistic-locking conditions: an edit applies only if the item still holds the values you started from. A commit of up to 100 edits (and about 4 MB) is one all-or-nothing transaction.

A larger commit goes out as several transactions of up to 100 items each. If one fails, the earlier ones stay applied, the rest stay staged without being attempted, and the failed edits show up as conflicts to resolve. Each transactional write costs double, as above.

So you can stage the new event row and the counter edit together, review the diff, and commit both atomically without writing any SDK code.

Staging the new audit event and the tenant counter edit in DynoTable, then committing both as one all-or-nothing transaction.
Staging the new audit event and the tenant counter edit in DynoTable, then committing both as one all-or-nothing transaction.

Pitfalls and next steps

  • Budget for double capacity. A transactional write bills twice the WCU of a plain write, and canceled attempts are billed too. That's fine for the occasional consistency-critical pair and costly if you wrap every single write in a transaction. Use it where atomicity actually matters.
  • Stream records aren't transaction-aware. A transaction's changes reach DynamoDB Streams gradually, interleaved with others, so consumers can't assume atomicity or order across its items. To see them together, read them with TransactGetItems: all of a commit or none of it.
  • A hot counter has a ceiling. Concurrent transactions on one COUNTER item first cancel each other with TransactionConflict. Then throughput caps: a transactional write under 1 KB costs 2 write units of a partition's 1,000 per second, and the ConditionCheck is billed the same way. The example's three actions (event, counter, profile check) take 6 units, so it peaks near 166 transactions a second per tenant.
  • Above that, take the counter out of the transaction. A stream consumer can sum each batch of events and write the counter once per batch, seconds behind. Or use a plain atomic counter where small drift is acceptable, and shard the key when one tenant outgrows a partition.

Transactions are the tool for "these writes must agree." Once events are landing consistently, the next concern is reacting to them, which is what DynamoDB Streams does.

Download DynoTable to stage multi-item edits and commit them as a single transaction against your own table.

By Dmitriy · Updated