I want to use optimistic locking for my Amazon DynamoDB table instead of DynamoDBMapper.
Short description
To implement optimistic locking without a DynamoDBMapper, write custom code in your AWS SDK with condition and update expressions. The custom code checks whether the version numbers in your table match.
Resolution
Complete the following steps:
-
Create a DynamoDB table with a version number attribute.
Note: You must associate a version number with each item that you want to update.
-
Add the SET clause to your update expression to update the item. If you don't have an update expression, then create one.
Example update expression syntax:
UpdateExpression='SET #attr = :val',
ExpressionAttributeNames={
'#attr': 'attribute_to_update'
},
ExpressionAttributeValues={
':val': new_value
},
ConditionExpression='condition_expression'
Note: Replace attribute_to_update with your attributes and new_value with the new value that you want to update to.
-
Update the condition expression to test the version number between the request and the value in the DynamoDB table. If you don't have a condition expression, then create one.
Example condition expression syntax:
ExpressionAttributeNames = {
"#attr": "attribute_name"
}
ExpressionAttributeValues = {
":val": "new_value"
}
Note: Replace attribute_name with your expression attribute name and new_value with the new value that you want to update to.
If the version numbers match, then the update is successful. If the version numbers don't match, then you receive the "ConditionalCheckFailedExpection" error and can't overwrite changes that other clients make.
To manage the "ConditionalCheckFailedExpection" error, use the following error handling logic in your AWS SDK:
print("Update successful")
except ClientError as e:
if e.response['Error']['Code'] == 'ConditionalCheckFailedException':
print("Item was modified by another process. Please retry.")
else: raise e
To test your custom expressions, include a wrong version number in your request.
Related information
Putting an Item (Java)
Putting an Item (.NET)
DynamoDB condition expression CLI example
Why do I get a "ConditionalCheckFailedException" error in DynamoDB?