Does DynamoDB have locking by default?

Kevin picture Kevin · Jan 11, 2018 · Viewed 15.1k times · Source

I'm looking over the dynamo documentation and it looks like they have optimistic. I'm wondering if this is used by default or not.

From the documentation, it looks like you need to code up the java application to use the @DynamoDBVersionAttribute annotation and get and set the versions. Without doing this, it looks like you can write to DynamoDB without any sort of locking.

Is that correct?

On a side note, I'm not too familiar with DBs without some sort of locking so what would happen if 2 people wrote to the same item at the same time in DynamoDB without any locking? Say the item we're writing to has 4 fields, would one write completely fail or is it possible that DynamoDB updates 2/4 fields with 1 write, and the other 2 fields with the other write?

Answer

F_SO_K picture F_SO_K · Jan 11, 2018

You are correct. DynamoDB does NOT have optimistic locking by default. There are various SDKs for DynamoDB and as far as I am aware the only one which provides optimistic locking functionality is the Java SDK.

Here's what the Java SDK optimistic locking actually supports:

  • Creates an attribute in your table called version
  • You must load an item from the database before updating it
  • When you try and save an item the SDK tests that the client item version number matches the one in the table, and if it does, the save is completed and the version number is incremented

This is pretty simple to implement yourself if you are using a different SDK. You would create the version attribute yourself. You would create a wrapper for the putItem method (and any other required save/update operations). You would use the Condition Expression to test that the version number in the database is one less than the version you saving.

To answer the second part of your question, both updates would succeed (assuming you had put no conditions on your update). The first one would make any updates specified, and the second one would come along and overwrite them.