DynamoDB interview question · Most asked

How do conditional writes work, and how do you implement optimistic locking in DynamoDB?

Summary

A ConditionExpression makes a write succeed only if the condition holds on the current item (attribute_not_exists(PK), version = :expected, balance >= :amount); otherwise it fails with ConditionalCheckFailedException and nothing changes. Optimistic locking stores a version number and updates only when it matches.

Longer Answer

{
  "UpdateExpression": "SET #s = :shipped, version = version + :one",
  "ConditionExpression": "version = :expected AND #s = :paid",
  "ExpressionAttributeNames": {"#s": "status"},
  "ExpressionAttributeValues": {":shipped": "SHIPPED", ":paid": "PAID", ":expected": 7, ":one": 1}
}

Conditional writes are atomic per item and are the main tool for correctness under concurrency: preventing overwrites (attribute_not_exists on create), enforcing invariants, and state-machine transitions. A failed condition costs write capacity. ReturnValuesOnConditionCheckFailure returns the current item so you can explain the conflict.

Key Points

  • Write only if the condition holds.
  • attribute_not_exists for create-only.
  • Version attribute for optimistic locking.
  • Atomic per item.

More most-asked DynamoDB questions

← All DynamoDB questions