Conditional Writes and Optimistic Locking
Two requests can update the same item at the same time.
Introduction
Two requests can update the same item at the same time. Without protection, the last write silently wins and the first update is lost. Condition expressions make a write succeed only if the item is in the state you expect; optimistic locking applies that idea with a version number.
Purpose of this lesson
You will prevent duplicate creates, enforce state transitions, implement version-based optimistic locking, and handle ConditionalCheckFailedException correctly.
Understanding the topic
Building blocks:
attribute_not_exists(PK)— create only if the item does not already exist.#status = :expected— allow a transition only from a given state (PLACED → SHIPPED).version = :vwithSET version = version + :one— optimistic locking.- A failed condition throws
ConditionalCheckFailedException; a failed conditional write still consumes write capacity. ReturnValuesOnConditionCheckFailure: "ALL_OLD"returns the current item in the error, saving a follow-up read.- Atomic counters (
ADD views :one) need no read, but are not idempotent — a retried request increments twice.
Informative example
Ship an order only if it is still PLACED and unchanged:
import { UpdateCommand } from "@aws-sdk/lib-dynamodb";import { ConditionalCheckFailedException } from "@aws-sdk/client-dynamodb";import { ddb, TABLE } from "./ddb";export async function shipOrder(orderId: string, expectedVersion: number) {try {const res = await ddb.send(new UpdateCommand({TableName: TABLE,Key: { PK: `ORDER#${orderId}`, SK: "HEADER" },UpdateExpression: "SET #s = :shipped, version = version + :one",ConditionExpression: "#s = :placed AND version = :v",ExpressionAttributeNames: { "#s": "status" },ExpressionAttributeValues: { ":shipped": "SHIPPED", ":placed": "PLACED", ":v": expectedVersion, ":one": 1 },ReturnValues: "ALL_NEW",ReturnValuesOnConditionCheckFailure: "ALL_OLD",}));return { ok: true as const, order: res.Attributes };} catch (err) {if (err instanceof ConditionalCheckFailedException) {// err.Item holds the current item (low-level attribute values).return { ok: false as const, reason: "conflict", current: err.Item };}throw err;}}
On a conflict, re-read the item, re-apply the business rule, and retry with the new version — or report the conflict to the user. Never retry blindly with the same expected version.
Best practices
- Guard every create with
attribute_not_existson the partition key. - Model state machines with conditions on the current state.
- Use a version attribute for read-modify-write flows edited by people or by several services.
- Treat
ConditionalCheckFailedExceptionas an expected business outcome, not a 500 error.
Common mistakes
- Read-then-write without a condition (lost updates).
- Retrying atomic counter increments on timeouts, which double-counts.
- Using conditions on attributes that are not in the item —
attribute_not_existson a non-key attribute means something different from 'item does not exist'.
Advanced interview questions
Interview Prep
Practice concise answers, then expand each card for the explanation.
1IntermediateQuestionHow does optimistic locking work in DynamoDB?+
Answer
2BeginnerQuestionDo failed conditional writes cost capacity?+
Answer
Hands-on exercise
Hands-on: run two concurrent shipOrder("o1", 1) calls with Promise.all. Confirm exactly one succeeds and the other returns reason: "conflict" with the current version 2.
Summary
Condition expressions make writes safe under concurrency: guard creates, enforce state transitions, and use version numbers for optimistic locking.