Intermediate7 min read

DynamoDB Condition Expressions: Make a Write Conditional

A condition expression is a predicate DynamoDB evaluates on the existing item before it commits your write. It is the closest thing DynamoDB has to a WHERE clause on a write, and the only safe way to enforce an invariant.

How do DynamoDB condition expressions work?

A condition expression is a predicate DynamoDB evaluates server-side against the current item before committing a write. If it's true, the write proceeds; if false, the write is rejected with ConditionalCheckFailedException and nothing changes. It folds the check and the mutation into one atomic operation, so concurrent callers can't race a stale read.

  • It guards writes only. PutItem, UpdateItem, DeleteItem and each TransactWriteItems action take one; reads use FilterExpression instead.
  • It replaces read-then-write. Coming from SQL, you'd read the row, check it in app code, then update. In DynamoDB that gap is a data-corruption bug waiting for a concurrent caller.
  • A rejected write still bills. It consumes write capacity for the size of the existing item it was checked against, or 1 unit when no item exists.

Where they apply

You attach a ConditionExpression to PutItem, UpdateItem, DeleteItem, and each action inside TransactWriteItems. It is not part of Query or Scan, which use FilterExpression, a different thing on the read path.

ConditionExpressionFilterExpression
PathWrites (Put/Update/Delete)Reads (Query/Scan)
Effect on failureRejects the whole writeDrops the item from results
SeesThe current item, pre-writeEach candidate item, post-read
CostFailed write still billsFiltered items are still billed for the read

Both run server-side. A false condition aborts the mutation; a false filter hides a row you already paid to read. (AWS: Condition Expressions)

Condition functions and operators

The condition language is small:

  • attribute_exists(path) / attribute_not_exists(path): does this exist on the item? The classic idiom for "create only if absent" / "update only if present".
  • Comparators =, <>, <, <=, >, >=, against a value or another attribute.
  • attribute_type, begins_with, contains, size: type and string/set checks.
  • BETWEEN … AND …, IN (…): range and membership.
  • AND, OR, NOT, parentheses: to combine the above.

(AWS: Comparison Operator and Function Reference)

There is no arithmetic. clearedCents - holdCents >= :amt is a syntax error, so a rule over two attributes needs its result stored as a third (see the worked example below).

attribute_not_exists on the is the canonical way to make PutItem behave like an insert that won't clobber an existing item. The item API has no separate insert op, so the condition is the insert semantics.

PartiQL's INSERT runs the same check for you and refuses an existing key. (AWS: PartiQL insert statements)

A worked example: guarding a ledger against overdraft

Take a banking ledger. Each account is one item:

PK = "ACCT#a7f3"
SK = "BALANCE"
clearedCents = 50000

A debit must never push the balance below zero, and you must never debit an account that doesn't exist. Two rules, both enforceable in the write itself.

The wrong way (the footgun)

GetItem ACCT#a7f3 / BALANCE     → clearedCents = 50000
if (50000 >= 30000) ...         ← app-side check
UpdateItem  SET clearedCents = 20000

Between the GetItem and the UpdateItem, a second debit can read the same 50000, pass its own check, and write too. Both succeed; the account goes negative. This is a read-modify-write race, and no amount of app-side validation fixes it, because the check and the write are separate operations.

The right way

Fold the check into the write. Debit 30000 cents with an update expression, conditional on the account existing and holding enough:

UpdateItem  ACCT#a7f3 / BALANCE
  SET clearedCents = clearedCents - :amt
  ConditionExpression:
    attribute_exists(PK) AND clearedCents >= :amt

with :amt = 30000, a value placeholder (see expression names and values).

If the balance is too low, or the item was never created, DynamoDB rejects the write with ConditionalCheckFailedException and the balance is untouched.

The condition compares the stored value, after any concurrent write has landed. A second debit of 30000 sees 20000 and is rejected; it never acts on the 50000 it might have read earlier.

If your rule spans two attributes, say cleared funds minus holds, keep the result in its own attribute (availableCents), change it in the same SET as its inputs, and condition on availableCents >= :amt.

The DynamoDB expression builder builds and copies the exact expression, names and values included. The one below is preset to the guarded debit above (attribute_exists(PK) plus clearedCents >= 30000) so you can read the generated ConditionExpression:

Build your request
Generated code
new UpdateItemCommand({
  "TableName": "Ledger",
  "Key": {
    "PK": {
      "S": "ACCT#a7f3"
    },
    "SK": {
      "S": "BALANCE"
    }
  },
  "UpdateExpression": "SET #upd0 = #upd0 - :updValue0",
  "ConditionExpression": "attribute_exists(#cond0) AND #cond1 >= :condValue1",
  "ExpressionAttributeNames": {
    "#upd0": "clearedCents",
    "#cond0": "PK",
    "#cond1": "clearedCents"
  },
  "ExpressionAttributeValues": {
    ":updValue0": {
      "N": "30000"
    },
    ":condValue1": {
      "N": "30000"
    }
  }
})

dynamodb-expression-builder is the open-source (MIT) library behind this tool.

Making the debit safe to retry

The guarded debit is not idempotent. If the response is lost after the write lands, a retry sends it again, and with enough balance left it debits a second time without an error. The >= check can't tell a repeat from a new debit (the same trap as counters).

Give each debit an id and write a marker item for it in the same transaction:

TransactWriteItems
  Put     ACCT#a7f3 / TXN#t-123
    ConditionExpression: attribute_not_exists(PK)
  Update  ACCT#a7f3 / BALANCE
    SET clearedCents = clearedCents - :amt
    ConditionExpression: attribute_exists(PK) AND clearedCents >= :amt

A repeat of t-123 finds its marker and cancels the whole transaction, so the balance moves once. The price is double write units for the transaction and one small item per debit; give the markers a TTL attribute so they expire once your retry window has passed.

If you only need to cover retries of the same call, send the debit as a one-action TransactWriteItems with a ClientRequestToken and reuse the token: within 10 minutes, a repeat with the same token succeeds without applying twice. UpdateItem has no token parameter, so the token only protects a transaction. The marker also catches a retry your own code sends later.

Inspecting the guard in DynoTable

When a conditional write fails, you want to see the item's real state, not guess at it. Pull the account item up and read clearedCents directly.

The ledger account in DynoTable: the BALANCE item with its clearedCents value.
The ledger account in DynoTable: the BALANCE item with its clearedCents value.

Read the rejection, don't retry blindly

ConditionalCheckFailedException is not a transient error, so retrying the same write against the same state changes nothing. It means a business rule fired: insufficient funds, duplicate create, stale version. Surface it as a domain outcome.

Two things make failures debuggable:

  • ReturnValuesOnConditionCheckFailure: ALL_OLD. DynamoDB returns the current item alongside the failure, so you can show "balance was 20000, you asked for 30000" without a second read. (AWS: Working with Items)
  • Telling the two failure reasons apart. attribute_exists(PK) AND clearedCents >= :amt collapses "no account" and "no funds" into one exception. With ALL_OLD set, no returned item means the account doesn't exist; a returned item means the funds were short, unless a retry of your own debit already landed. In the marker transaction, CancellationReasons settles it: a failed marker Put means the debit already applied.

Optimistic locking is the same trick

Optimistic locking is a condition expression on a version attribute. Every write asserts the version you read and bumps it:

UpdateItem  ACCT#a7f3 / BALANCE
  SET clearedCents = :new, version = :next
  ConditionExpression: version = :seen

If another writer moved first, version = :seen is false, the write is rejected, and you re-read and retry. This is how DynamoDB does concurrency control without locks: assert what you saw, fail if it moved. (AWS: Optimistic Locking with Version Number)

DynoTable's staging area runs the same assert-what-you-saw check per attribute: an update commits only if the attributes still hold the values you started from, so a concurrent edit surfaces as a conflict to resolve.

Pitfalls and next steps

  • Names that collide with reserved words. status, name, ttl, and ~570 others are reserved. Unaliased, they fail with a ValidationException ("Attribute name is a reserved keyword; reserved keyword: status"). See expression names and values, or get the alias map from the reserved-words checker.
  • A condition can't reference another item. It only sees the item being written. Cross-item invariants need TransactWriteItems with a per-action ConditionExpression, or a ConditionCheck against a marker item, the pattern behind unique values across attributes.
  • Failed writes still cost write capacity. A rejection bills the size of the item that blocked it: 300 write units against a 300 KB item. Keep a hot guarded item small and move bulky payloads to a separate item or to S3 (item size limit).

For the writes these guards protect, see update expressions; for modeling the keys they run against, see single-table design. Write your own guards with the expression builder, which emits the ConditionExpression with both maps. When you edit real data, download DynoTable: its staged item edits commit with the assert-what-you-saw check above, so a concurrent edit surfaces as a conflict.

By Dmitriy · Updated