Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 37 ยท Reading and Writing Items

Condition Expressions and Conditional Writes

Use condition expressions to make writes safe: attribute_not_exists, comparisons, begins_with, contains, size, optimistic locking with a version attribute, and error handling.

By default PutItem, UpdateItem and DeleteItem just do what you say. A PutItem replaces whatever is there, an UpdateItem creates the item if it is missing and a DeleteItem shrugs if there is nothing to delete. That is fast and simple, and it is wrong whenever two clients race or whenever "only if" matters. A condition expression makes a write succeed only if a test about the current stored item is true. The check and the write happen as one atomic step on the server.

Where conditions are used

  • PutItem, UpdateItem, DeleteItem: ConditionExpression.
  • Transaction items: each can carry its own condition, including "check only" items.
  • Query, Scan and GetItem use the same syntax for filter and projection expressions, covered in the next chapter lessons.

When the condition is false the call fails with ConditionalCheckFailedException and nothing is written. You are still charged a write unit for the attempt. In many designs this exception is not a bug but the normal "somebody else got there first" signal.

The syntax

A condition is built from comparisons, functions and logical operators, with #names and :values placeholders as in update expressions.

Form Example
Comparison Pages > :min, Status = :s, Version <> :v
Range Price BETWEEN :lo AND :hi
Membership Status IN (:a, :b, :c)
Existence attribute_exists(Email), attribute_not_exists(PK)
Type attribute_type(Age, :n) (type letters such as N)
Prefix begins_with(SK, :prefix)
Contains contains(Tags, :tag) (substring of a string, or member of a set or list)
Size size(Title) > :n, size(Tags) <= :max
Logic AND, OR, NOT, and parentheses

Reserved words such as Status and Size must be replaced with a #placeholder, as in #s = :open.

Pattern 1: create only if absent

To prevent PutItem from overwriting an existing item, require that the key attribute does not exist yet. This is the standard way to enforce uniqueness, for example one user per email address.

Terminal
aws dynamodb put-item --table-name Users \
  --item '{"PK": {"S": "EMAIL#[email protected]"}, "UserId": {"S": "u-1001"}}' \
  --condition-expression "attribute_not_exists(PK)"

If the item exists, DynamoDB returns ConditionalCheckFailedException.

Pattern 2: update only if it exists

Because UpdateItem creates missing items, guard it when that would be a bug:

TEXT
ConditionExpression: attribute_exists(PK)

Pattern 3: optimistic locking with a version number

Store a Version attribute. A writer reads the item and its version, makes changes, and writes back only if the version is still the one it read, bumping it by one. If someone else changed the item meanwhile, the condition fails and the writer re-reads and retries. No locks, no waiting.

TEXT
UpdateExpression:    SET Title = :t, Version = :next
ConditionExpression: Version = :seen

Pattern 4: state machines and guards

Conditions enforce rules that are otherwise race-prone:

  • an order may move to shipped only from paid: #s = :paid,
  • stock decrement only if enough remains: Stock >= :qty (with SET Stock = Stock - :qty),
  • a coupon can be redeemed once: attribute_not_exists(RedeemedAt),
  • a lease or lock: acquire only if attribute_not_exists(Owner) OR ExpiresAt < :now.

A condition evaluator

The stand-in below implements a small version of the condition language: comparisons, BETWEEN, IN, AND/OR/NOT, attribute_exists, attribute_not_exists, begins_with, contains and size. It is a teaching model that translates a condition to Python.

Python Stand-in: evaluate condition expressions

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 first write succeeds and the second is rejected because attribute_not_exists(PK) is false once the item is stored. The list of tests shows the operators on a sample item.

Optimistic locking in action

Here two writers edit the same article. The slower one holds a stale version and is rejected, then retries after re-reading.

Python Stand-in: version check with retry

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.

Bob's change is not lost and Alice's change is not overwritten. Both edits survive because Bob retried on top of the fresh item.

Handling the failure

In the SDKs ConditionalCheckFailedException is a distinct exception type you can catch. Treat it as an expected outcome:

Python
from botocore.exceptions import ClientError

try:
    table.put_item(
        Item={"PK": "EMAIL#[email protected]", "UserId": "u-2"},
        ConditionExpression="attribute_not_exists(PK)",
    )
except ClientError as err:
    if err.response["Error"]["Code"] == "ConditionalCheckFailedException":
        print("email already registered")
    else:
        raise

Set ReturnValuesOnConditionCheckFailure="ALL_OLD" to receive the existing item in the error, which saves a follow-up read.

Common mistakes

  • Writing the condition on the new item. The condition is checked against the stored item before the write, not against what you are about to write.
  • Forgetting placeholders for reserved words.
  • Assuming attribute_not_exists on a non-key attribute means "item missing". Use a key attribute for existence checks of the whole item.
  • Treating the failure as an error to log and ignore. Often you should re-read and retry, or tell the user.
  • Heavy contention on one item. Optimistic locking works well with occasional conflicts, but a single hot item with many writers needs a different design (counters per shard, queues).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Against what item is a ConditionExpression evaluated?

    DynamoDB checks the condition against the existing stored item, atomically with the write.
  2. 2. Which condition makes PutItem create an item only if it does not already exist?

    attribute_not_exists on a key attribute is true only when no item with that key is stored.
  3. 3. What does optimistic locking with a Version attribute do?

    The write is conditional on Version equalling the value you read. A concurrent change bumps it, so your stale write fails and you retry.
  4. 4. What error is raised when the condition is false?

    A false condition raises ConditionalCheckFailedException, and nothing is written.

Summary

  • A condition expression makes a write succeed only if a test on the stored item is true, atomically.
  • Operators include comparisons, BETWEEN, IN, attribute_exists, attribute_not_exists, begins_with, contains, size and AND/OR/NOT.
  • Use attribute_not_exists(PK) for create-only and a Version attribute for optimistic locking.
  • A failed condition raises ConditionalCheckFailedException; handle it as a normal outcome.
  • The same expression language powers filters and transactions.

Next: Batch Operations