Skip to content

DynamoDB Transactions: TransactWriteItems, Limits, Cost, and Single-Table Patterns

A DynamoDB transaction groups reads or writes into one all-or-nothing call. Either every action in it applies, or none does. There are two calls: TransactWriteItems and TransactGetItems.

They cost twice as much as normal operations and cap at 100 items. Use them for the few places where two items must change together. Do not use them as a default.

This post is the reference. For the choice between a transaction and a conditional write, read transactions vs conditional writes.

TransactWriteItems

TransactWriteItems takes a list of actions. Each action is one of four types:

  • Put creates or replaces an item.
  • Update changes attributes of an item.
  • Delete removes an item.
  • ConditionCheck checks a condition on an item and writes nothing.

Every action can carry a condition expression. If any condition fails, the whole transaction is cancelled and nothing is written.

import { DynamoDBClient } from '@aws-sdk/client-dynamodb'
import { DynamoDBDocumentClient, TransactWriteCommand } from '@aws-sdk/lib-dynamodb'

const client = DynamoDBDocumentClient.from(new DynamoDBClient({}))

await client.send(new TransactWriteCommand({
  ClientRequestToken: 'order_01HVMK3P2Q', // see the idempotency section
  TransactItems: [
    {
      Put: {
        TableName,
        Item: { pk: 'ORDER#01HVMK3P2Q', sk: '#METADATA', total: 4200 },
        ConditionExpression: 'attribute_not_exists(pk)',
      },
    },
    {
      Update: {
        TableName,
        Key: { pk: 'PRODUCT#p_01', sk: '#METADATA' },
        UpdateExpression: 'SET stock = stock - :n',
        ConditionExpression: 'stock >= :n',
        ExpressionAttributeValues: { ':n': 1 },
      },
    },
  ],
}))

The order is created and the stock drops by one, or neither happens. Stock can never go below zero.

All writes in a transaction are applied as one unit with serializable isolation. Other readers do not see a half-finished transaction.

TransactGetItems

TransactGetItems reads up to 100 items as one consistent snapshot. Use it when you must read several items and be sure none changed between the reads.

import { TransactGetCommand } from '@aws-sdk/lib-dynamodb'

const { Responses } = await client.send(new TransactGetCommand({
  TransactItems: [
    { Get: { TableName, Key: { pk: 'ACCOUNT#alice', sk: '#METADATA' } } },
    { Get: { TableName, Key: { pk: 'ACCOUNT#bob', sk: '#METADATA' } } },
  ],
}))

It is rarely needed. A single Query over one item collection already returns a consistent view of that collection if you ask for a strongly consistent read. Reach for TransactGetItems only when the items live under different partition keys.

Limits

As of November 2026, from the AWS transactions docs:

  • A transaction holds up to 100 distinct items.
  • The total size of all items in it is up to 4 MB.
  • Two actions in one transaction cannot target the same item.
  • Transactions cannot run on a GSI. They address base table items.
  • A transaction can span tables in the same AWS account and Region.

The “same item twice” rule catches people. You cannot Put an item and Update it in one call. Fold both into one action. A ConditionCheck on an item also uses up that item for the call.

Limits change. Check the docs before you design around 100.

Cost

A transactional write uses two write units per 1 KB of item. A transactional read uses two read units per 4 KB. A normal write uses one and a normal strongly consistent read uses one. That is the 2x. The DynamoDB service does the work in two phases, prepare and commit, and you pay for both.

A few points:

  • Size rounds up per item, the same as a normal write.
  • A ConditionCheck is billed like a write, even though it writes nothing.
  • Writes to a GSI that a transaction triggers add normal GSI write cost on top.

For a 1 KB Put as a normal write, you pay 1 write unit. In a transaction, you pay 2. Ten of them in one transaction cost 20 write units. Rates per unit are in the DynamoDB pricing post, as of November 2026.

On a small table the 2x is a rounding error. On a hot write path it is the second biggest reason to avoid transactions. The first is that they add conflicts.

Idempotency with ClientRequestToken

TransactWriteItems takes an optional ClientRequestToken. It makes the call idempotent. If you send the same token with the same parameters, DynamoDB returns success and does not apply the writes again.

The token is valid for 10 minutes. After the transaction finishes, a retry with the same token inside that window is safe. A retry after the window may apply the writes a second time.

If you reuse a token with different parameters inside the window, DynamoDB returns an IdempotentParameterMismatch error. If you send the same token while the first call is still running, you can get a TransactionInProgressException. Retry after a short wait.

Pick a token that comes from the business action, such as the order ID. Do not use a random value per attempt, because the point is that attempts match. Set your own token when the caller can retry across processes.

For idempotency that lasts longer than ten minutes, store a record in the table. See DynamoDB idempotency keys.

Conflicts and TransactionCanceledException

When a transaction fails, you get a TransactionCanceledException. It carries a CancellationReasons array with one entry per action, in the same order as your TransactItems. Each entry has a Code and a Message. An entry for an action that was not the problem has the code None.

The codes you will see:

CodeMeaningWhat to do
ConditionalCheckFailedA condition expression was falseBusiness outcome. Do not retry as is
TransactionConflictAnother transaction or write touches the same item right nowRetry with backoff
ThrottlingErrorThe request was throttledRetry with backoff
ProvisionedThroughputExceededThe table or an index ran out of capacityAdd capacity or retry with backoff
ValidationErrorThe request is malformed, for example the same item twiceFix the code
ItemCollectionSizeLimitExceededA write would grow an item collection past its limit (tables with an LSI)Redesign the key

The array tells you which action failed. Read it, do not just log the exception name.

try {
  await client.send(command)
} catch (err) {
  if ((err as Error).name === 'TransactionCanceledException') {
    const reasons = (err as { CancellationReasons?: { Code?: string }[] }).CancellationReasons ?? []
    if (reasons[1]?.Code === 'ConditionalCheckFailed') {
      throw new OutOfStockError() // action 1 was the stock update
    }
    if (reasons.some((r) => r.Code === 'TransactionConflict')) {
      return retryWithBackoff()
    }
  }
  throw err
}

Conflicts are the hidden cost. If many requests try to update one hot item in transactions, most are cancelled with TransactionConflict. A single counter that every order touches becomes a bottleneck. See avoiding hot partitions.

Single-table patterns

Uniqueness constraints

DynamoDB only enforces uniqueness on the primary key. To make an email unique, write a second item whose key is the email, in the same transaction as the user.

pk = "USER#u_01"          sk = "#METADATA"   email = "ada@acme.com"
pk = "EMAIL#ada@acme.com" sk = "#UNIQUE"     userId = "u_01"

Both Put actions use attribute_not_exists(pk). If the email already exists, the second Put fails with ConditionalCheckFailed, and the user is never created. Use the same idea for usernames and slugs.

When the user changes email, one transaction deletes the old EMAIL# item, puts the new one, and updates the user. The lookup item also gives you a free GetItem to find a user by email.

Counters with limits

A counter that must stay within a bound needs a condition. A seat count, a plan limit, a stock level. Put the counter update and the item creation in one transaction. The condition on the counter fails the whole thing when the limit is reached.

For counters that only need to be roughly right, skip the transaction. Update the count from a stream consumer and accept a small lag. It is cheaper and has no conflicts.

Parent and child writes

Create an order and its line items together, or an account and its first member.

Outbox

Write the business item and an OUTBOX# item in one transaction. A stream consumer publishes the event. The business write and the event cannot drift apart.

ElectroDB support

ElectroDB supports transactions through a Service. You group entities in a service, then call service.transaction.write or service.transaction.read. Each operation ends with .commit() instead of .go().

import { Entity, Service } from 'electrodb'

const user = new Entity({
  model: { entity: 'user', version: '1', service: 'app' },
  attributes: { userId: { type: 'string' }, email: { type: 'string' } },
  indexes: {
    byId: {
      pk: { field: 'pk', composite: ['userId'], casing: 'none', template: 'USER#${userId}' },
      sk: { field: 'sk', composite: [], casing: 'none', template: '#METADATA' },
    },
  },
}, { table, client })

const email = new Entity({
  model: { entity: 'email', version: '1', service: 'app' },
  attributes: { email: { type: 'string' }, userId: { type: 'string' } },
  indexes: {
    byEmail: {
      pk: { field: 'pk', composite: ['email'], casing: 'none', template: 'EMAIL#${email}' },
      sk: { field: 'sk', composite: [], casing: 'none', template: '#UNIQUE' },
    },
  },
}, { table, client })

const app = new Service({ user, email })

await app.transaction.write(({ user, email }) => [
  user.create({ userId: 'u_01', email: 'ada@acme.com' }).commit(),
  email.create({ email: 'ada@acme.com', userId: 'u_01' }).commit(),
]).go()

I ran this with ElectroDB 2.15.1 and .params(). Each create becomes a Put with attribute_not_exists on the key, so the uniqueness pattern works as written. If the email is taken, .go() rejects, and the user is not created. Check the ElectroDB docs for the current API and the error shape in your version. For setup, see the ElectroDB guide.

When not to use a transaction

  • A change to one item. Use a conditional write. It is free of the 2x.
  • A change where eventual consistency is fine. Use a stream.
  • A hot item that many requests update. Conflicts will cancel most of them.
  • More than 100 items. Batch the work and design for partial failure, or use a saga with state in the table. See workflow state machines.

If you find yourself reaching for transactions on every write path, the data model may fit a relational database better. That is a fair outcome. See when not to use single-table design.

I’m building singletable.dev so you can see which access patterns span more than one item before they become transactions in your code.

Limits and prices are as of November 2026 and change. See the DynamoDB transactions docs and the pricing page.

Tejovanth N

Tejovanth builds on DynamoDB in production: rasika.life, rekha.app, rrmstays. All single-table with ElectroDB.

LinkedIn codeculturecob.com

Related

Schema review

Want a second pair of eyes before you ship?

Async DynamoDB schema review. PK/SK design, GSI strategy, ElectroDB entity code. Fixed price, 5 business days.