AWS DynamoDB Conditional Check Failed Fix
In this tutorial, you'll learn about AWS DynamoDB Conditional Check Failed Fix. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
Your DynamoDB write operation returns ConditionalCheckFailedException — the condition expression you provided did not evaluate to true, so the operation was rejected.
Step-by-Step Fix
1. Check the condition expression syntax
import boto3
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('orders')
# Wrong: condition with wrong attribute name
table.update_item(
Key={'order_id': 'ORD-001'},
UpdateExpression='SET status = :new_status',
ConditionExpression=':current_status = :expected',
ExpressionAttributeValues={
':new_status': 'shipped',
':current_status': 'pending',
':expected': 'pending'
}
)
# Right: reference the attribute in the condition correctly
table.update_item(
Key={'order_id': 'ORD-001'},
UpdateExpression='SET status = :new_status',
ConditionExpression='#s = :expected_status',
ExpressionAttributeNames={
'#s': 'status'
},
ExpressionAttributeValues={
':new_status': 'shipped',
':expected_status': 'pending'
}
)
2. Use attribute_exists to check optimistic locking
# Wrong: update without checking version
response = table.update_item(
Key={'id': 'doc-123'},
UpdateExpression='SET content = :content',
ExpressionAttributeValues={':content': 'new content'}
)
# Right: use version attribute for optimistic locking
response = table.update_item(
Key={'id': 'doc-123'},
UpdateExpression='SET content = :content, version = :new_version',
ConditionExpression='version = :expected_version',
ExpressionAttributeValues={
':content': 'new content',
':expected_version': 3,
':new_version': 4
},
ReturnValues='ALL_NEW'
)
print(response['Attributes'])
Expected output:
{
"id": "doc-123",
"content": "new content",
"version": 4
}
3. Handle conditional check failure in code
from boto3.dynamodb.conditions import Attr
from botocore.exceptions import ClientError
def update_with_retry(table, key, updates, expected_version, max_retries=3):
for attempt in range(max_retries):
try:
response = table.update_item(
Key=key,
UpdateExpression='SET content = :content, version = :new_version',
ConditionExpression=Attr('version').eq(expected_version),
ExpressionAttributeValues={
':content': updates['content'],
':expected_version': expected_version,
':new_version': expected_version + 1
},
ReturnValues='ALL_NEW'
)
return response['Attributes']
except ClientError as e:
if e.response['Error']['Code'] == 'ConditionalCheckFailedException':
# Re-read the current version and retry
current = table.get_item(Key=key)['Item']
expected_version = current['version']
print(f"Version conflict. Retrying with version {expected_version}")
else:
raise
raise Exception("Max retries exceeded for conditional update")
4. Use TransactWriteItems for atomic operations
# Update two items atomically with conditions
client = boto3.client('dynamodb')
try:
response = client.transact_write_items(
TransactItems=[
{
'Update': {
'TableName': 'accounts',
'Key': {'account_id': {'S': 'ACC-001'}},
'UpdateExpression': 'SET balance = balance - :amount',
'ConditionExpression': 'balance >= :amount',
'ExpressionAttributeValues': {
':amount': {'N': '100'},
':balance': {'N': 'balance'}
}
}
},
{
'Update': {
'TableName': 'accounts',
'Key': {'account_id': {'S': 'ACC-002'}},
'UpdateExpression': 'SET balance = balance + :amount',
'ExpressionAttributeValues': {
':amount': {'N': '100'}
}
}
}
]
)
print("Transaction succeeded")
except ClientError as e:
print(f"Transaction failed: {e}")
Prevention
- Always verify attribute names exist in the table before using them in conditions.
- Use
ExpressionAttributeNamesfor reserved words or special characters in attribute names. - Implement optimistic locking with a version attribute.
- Handle
ConditionalCheckFailedExceptionwith retry logic that re-reads the item. - Use transactions for multi-item atomic operations.
Common Mistakes with DynamoDB conditional
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists - Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
- Using
returnto exit a function early instead of wrapping a pure value in the monad
These mistakes appear frequently in real-world AWS code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro