DynamoDBMapper Optimistic Locking - Do I have to call the load first?
I am trying to use Optimistic Locking for an application that I am creating. On the AWS website it mentions that "With optimistic locking, each item has an attribute that acts as a version number. If you retrieve an item from a table, the application records the version number of that item. You can update the item, but only if the version number on the server side has not changed. If there is a version mismatch, it means that someone else has modified the item before you did. The update attempt fails, because you have a stale version of the item." If I update an object without calling load first, does Optimistic Locking still work if a version mismatch were to happen? In other words, is call load mandatory for Optimistic Locking to work?
> In other words, is call load mandatory for Optimistic Locking to work?
It is not, but in general you'll have difficulty using optimistic locking if you don't load the item before trying to update it.
The reason is because of how it works: when you send a conditional update request for optimistic locking, the condition typically being on the value of a
version attribute on the item, that is also updated (generally incremented by 1) in the same update request.
Thus, in order for an update to work, you need to tell DynamoDB what the value of that
version attribute must be.
If you don't load the item before trying to send that conditional update request for optimistic locking, how would you know what the current version is? If you don't know what that version is, then you can't in general expect the conditional update request to work.
That said, there are some circumstances where it might make sense to not use optimistic locking for some requests.
For example, let's say that you need to change the value of a given attribute, and nothing in the state of the item would change your requirements. In this case, you don't need optimistic locking for this update: you can simply tell DynamoDB to perform the update (while also simultaneously incrementing your
version attribute!). Any other concurrent operations will either succeed if they are also not using optimistic locking (i.e., not using a conditional update), or they will fail if they are using it.