Search code examples
pythonamazon-web-servicesamazon-dynamodbdatabase-concurrencydistributed-database

DynamoDb safe update


I am trying to update a counter in my simple database (one key, one numeric value). Atomic counters seem the natural solutions, but I need thread safe updates, i.e. I need to make sure that updates do not interfere with each other.

This answer seem to suggest that I need to double check that the data was not modified by another update before performing the actual write.

My question is, how do I reference the current value in the db in a ConditionExpression? Assuming table is dynamodb.Table object (Python API), this is the code I wrote for update_item:

table.update_item(
            Key={
                'key': my_key
            },
            UpdateExpression="set my_value = my_value + :inc",

            ConditionExpression="my_value = ?????" # should be value in the db now
            ExpressionAttributeValues={
                ':inc': my_increment,
            },
            ReturnValues="UPDATED_NEW"
        )

Solution

  • If you just want to use Atomic Counters then you don't need a condition. That answer you linked is just quoting the documentation (which you also linked) that states in some extremely important situations, such as incrementing a bank account balance, you will want to use a conditional expression if you aren't entirely sure that the first attempt to increment succeeded. For example if you tried to increment the value and lost network connection before you got a response from DynamoDB. In that case you wouldn't be sure if it was successful and would need to retry with a condition.

    You state that you just need thread safe updates, which Atomic Counters provide without the use of a conditional expression.