Does DynamoDB have locking by default?
Asked Answered
M

2

14

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?

Majesty answered 11/1, 2018 at 2:24 Comment(0)
K
17

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.

Krieg answered 11/1, 2018 at 12:8 Comment(2)
Thanks! So each write must be atomic then I assume? As in, the first write can't partially be complete and then the second write starts.Majesty
Correct, there are no partial writes. puItem, updateItem and deleteItem are atomic.Krieg
T
5

Dynamodb doesn't support optimistic locking by default. As you mentioned, you need to use the annotation in the Java model class in order to use the optimistic locking.

If two threads write to the same item, the Dynamodb item will have the last write data (i.e. last thread which writes the data).

Townsend answered 11/1, 2018 at 10:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.