DynamoDB rookie here, interested to learning about NoSQL databases.
I have a scenario where I have a table which has a partition key of userId, a sort-key of time and a numeric handle. The handle is a sequential counter that increments by 1.
Here is an example of the table:
userId, time, handle
0 , 123 , 1
0 , 456 , 2
1 , 123 , 1
1 , 234 , 2
0 , 789 , 3
1 , 345 , 3
for a given userId, handles cannot have duplicates
What I want to be able to do is add a new record for userId 0, for time 891 and have a handle 1 greater than the last written record for userId 0 - which would be the penultimate row in the database, that is, 3 + 1 = 4.
The naive way is to query the database for userId of 0, sorting by the last time stamp (if that is even possible) to get the handle (3). That is the first request. You would then create a put_item request on the database which adds 1 to the handle (3 + 1 = 4) and creates a new record.
Clearly there is a race condition here, where inbetween the read query and creating the put_item request, another lambda/API/endpoint could have committed a new record to the database with the same handle (4), e.g. (1, 888, 4). When I commit my the original record (0, 891, 4), the handle is 4 when it should now be 5.
Is it possible to perform this read and write operation in a single transaction (maybe I have the wrong mindset).
Let me know if my question is not clear.