Web User
Web User

Reputation: 7736

Update sort key of DynamoDB Item while ensuring consistency

I want to update the Sort Key of the following DynamoDB item from FILE#789 to FILE#790. From DynamoDB docs as well as some StackOverflow answers, the right way to do this is to delete the existing item (DeleteItem) and recreate it (PutItem) with the updated primary key, performed with TransactWriteItems.

Item: {
  "PK": {
    "S": "USER#123"
  },
  "SK": {
    "S": "FILE#789"
  },
  "fileName": {
    "S": "Construction"
  }
}

DeleteItem is straightforward, since I know the composite Primary Key's values. But to re-create the item, I need the most current values of the item's attributes and then perform a PutItem. Reading the item separately, and then performing a DeleteItem and PutItem within a transaction does not guarantee that the most current values of the item's attributes are used to re-create the item. What is the recommended way to handle an update of an item's Primary Key in this scenario?

Upvotes: 0

Views: 1376

Answers (1)

Maurice
Maurice

Reputation: 13108

I'd use a variation of Optimistic Locking here. I've written a blog about the concept a while ago if you want to get into details, but here's the basic summary:

Each item gets a version counter that's incremented once you update it. When you want to update an item, you first read it and store the current version number. Then you perform your update and increment the version number. Now you need to write it back to the table and this is when you add a condition. The condition is that the current version of the item needs to be the same as it was when you read the item originally. If that's not the case the write should fail, because somebody else modified the item in the mean time.

Applied to your use case that means:

  1. Read the item and keep track of the version
  2. Update the item locally with the new key and version
  3. Prepare your transaction:
    1. The DeleteItem should be conditional with a check to make sure the version number is identical to 1)
    2. The PutItem can be without conditions
  4. You use TransactWrite to store the data

This way the transaction will fail if the original item has been updated while you were changing it. If it fails, you start at 1) again.

Upvotes: 1

Related Questions