Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 37 ยท Capacity, Consistency and Transactions

Conditional Writes and Optimistic Locking

Use DynamoDB condition expressions to insert only if absent, guard state changes, and implement optimistic locking with a version attribute and retry loop.

Two clients read an item, both change it, both write it back. The second write silently erases the first. This is the lost update problem, and DynamoDB solves it without locks: every write operation (PutItem, UpdateItem, DeleteItem) accepts a condition expression. The write happens only if the condition is true on the current item. If it is false, nothing changes and you receive a ConditionalCheckFailedException.

The check and the write are one atomic step on the server, so there is no gap for anyone to slip into. This is the foundation for unique values, state machines, inventory and counters, and for the transactions in the next lesson.

Condition expression syntax

A condition uses the same functions as filters:

  • comparisons: =, <>, <, <=, >, >=, BETWEEN, IN
  • attribute_exists(path) and attribute_not_exists(path)
  • begins_with(path, :v), contains(path, :v), size(path), attribute_type(path, :t)
  • combine with AND, OR, NOT and parentheses
Terminal
# Insert only if no item with this key exists (read-only CLI example)
aws dynamodb put-item --table-name Users \
  --item '{"PK":{"S":"EMAIL#[email protected]"},"SK":{"S":"LOCK"},"userId":{"S":"u1"}}' \
  --condition-expression "attribute_not_exists(PK)"

Because the condition is evaluated against the key's current item, attribute_not_exists(PK) means "this key is free". It is the standard way to enforce uniqueness, since DynamoDB only enforces uniqueness for the primary key.

You can ask for the old item on failure with ReturnValuesOnConditionCheckFailure=ALL_OLD, which saves a round trip.

Guarding a state change

State machines become safe: an order moves from PENDING to PAID only if it is still PENDING:

Python
# boto3 (read-only here)
table.update_item(
    Key={"PK": "ORDER#o21", "SK": "META"},
    UpdateExpression="SET #s = :paid, paidAt = :now",
    ConditionExpression="#s = :pending",
    ExpressionAttributeNames={"#s": "status"},
    ExpressionAttributeValues={":paid": "PAID", ":pending": "PENDING", ":now": "2026-03-09T10:00:00Z"},
)

If two payment webhooks race each other, the second one sees PAID instead of PENDING and fails cleanly instead of paying twice. The same idea protects stock: SET stock = stock - :n with ConditionExpression = "stock >= :n" never oversells.

Conditions protect writes

Insert if absent attribute_not_exists(PK)
State guard status = :pending
Stock guard stock >= :n
Version check version = :seen

Check and write are one atomic step.

1 / 2

Try it: a conditional store

This is a stand-in written in Python with a tiny condition function, to show the behavior. The real service evaluates DynamoDB expression strings.

Python Insert-if-absent and a stock guard

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.

Optimistic locking with a version number

For arbitrary updates, add a version attribute. A client reads the item and its version, computes the change, and writes with the condition version = :seen, setting version = :seen + 1. If someone wrote in between, the condition fails and the client re-reads and retries. No locks are held while the user thinks, which is why it is called optimistic.

Python
# boto3 sketch (read-only here)
table.put_item(
    Item={**doc, "version": seen + 1},
    ConditionExpression="version = :seen",
    ExpressionAttributeValues={":seen": seen},
)

Use attribute_not_exists(PK) OR version = :seen if the first write should also create the item. The boto3/AWS SDK for Java high-level mappers can manage a @DynamoDbVersionAttribute for you.

Python Optimistic locking with a retry loop

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 attempt lost the race and was rejected. The retry read the newer text, so both edits survive: hello world!, at version 3. Without the version check, the first client would have overwritten the other client's change.

Practical notes

  • A failed condition still consumes write capacity (at least 1 WCU).
  • Conditions apply to the item with that key. You cannot condition on a different item; use transactions for that.
  • Use ExpressionAttributeNames for reserved words such as status, name, value, data.
  • Catch the exception type (ConditionalCheckFailedException) separately from throttling errors. The first is a business answer; the second should be retried.
  • Idempotency: a client token stored with a condition (attribute_not_exists(requestId)) makes retries safe.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happens when a condition expression evaluates to false?

    The check and the write are one atomic operation. If the check fails, nothing is written.
  2. 2. Which condition makes PutItem fail if an item with the key already exists?

    attribute_not_exists(PK) is true only if no item exists for that key, which makes the put an insert-only operation.
  3. 3. How does optimistic locking detect a concurrent update?

    If another writer incremented the version, the condition fails and the client re-reads and retries.
  4. 4. How do you avoid overselling stock without reading first?

    The decrement and the guard are evaluated atomically on the server, so concurrent buyers cannot drive stock below zero.

Summary

  • Every write can carry a condition expression that is checked atomically with the write.
  • attribute_not_exists(PK) gives insert-if-absent and simple uniqueness.
  • State and stock guards turn races into clean ConditionalCheckFailedException errors.
  • Optimistic locking uses a version attribute and a retry loop; no locks are held.
  • Failed conditions still cost write capacity and cannot span several items; that is what transactions are for.

Next: Transactions