1

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"
        )
Community
  • 1
  • 1
meto
  • 3,425
  • 10
  • 37
  • 49

1 Answers1

2

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.

Mark B
  • 183,023
  • 24
  • 297
  • 295
  • Thanks, this simplifies my life a lot. Assuming I also want to make sure that the update succeeds, how can I do that? I could check again after the write, but at that point someone else might have changed the element – meto Feb 02 '16 at 00:47
  • As long as you get a successful response, then you know it succeeded. If it throws an error then you know there was an error. You would only be unsure about it if you lost network connectivity or your application crashed or something like that. – Mark B Feb 02 '16 at 02:27