gorgcow
gorgcow

Reputation: 123

Multiple requests updating same attribute in DynamoDB

I am currently using Dynamodb as database and NodeJS as backend. For every user, whenever I receive a request, I fetch that user's data from database, do some computation on the data at backend and at then end of request I update the data in the database.

The issue is that when a single user makes multiple requests at the same time, only some of updates are written on the database while the others are lost. Is there any way I can fix this issue.

For example, lets say I have a counter for each user and on every request I provide a value with which the counter will be incremented. So if I send 5 requests at the same time with value as 5, then the counter should increment by 25 but instead it only does with 10 or 15

I don't mind changing the database to mongodb if it can solve this issue

Upvotes: 1

Views: 3828

Answers (2)

Maurice
Maurice

Reputation: 13108

DynamoDB recommends you use Optimistic Locking for this:

https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBMapper.OptimisticLocking.html

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 this happens, you simply try again by retrieving the item and then trying to update it. Optimistic locking prevents you from accidentally overwriting changes that were made by others. It also prevents others from accidentally overwriting your changes.

The basic idea is:

  • Each record has a version number
  • When you read a record and edit it, you increment the version number
  • On the UpdateItem or PutItem call you add a condition that this should only succeed, if the version number still has the same value it did when you read the record.

If it's about incrementing a counter, you can do that using the ADD operator in an UpdateItem call, then DynamoDB will handle the concurrency issue.

https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_UpdateItem.html

Upvotes: 4

Maxim Tkachenko
Maxim Tkachenko

Reputation: 5798

Because of concurrent updates you lose some data. You should use $incr operator to properly increment an attribute.

Upvotes: 0

Related Questions