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
- What are DynamoDB Streams, and how are they used?
- Query or Scan: what is the difference, and why avoid Scan?
- What is DynamoDB, and what workloads is it a good fit for?
- What is a hot partition, and how do you avoid one?
- How do you approach data modelling in DynamoDB, and how is it different from relational design?
- Explain partition keys, sort keys and the two kinds of primary key.
- Global secondary index or local secondary index: what is the difference?
- DynamoDB or a relational database such as Aurora PostgreSQL: how do you decide?