Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DynamoDB key uniqueness across primary and global secondary index

I'm working on creating a DynamoDB table to hold comments associated to a single object.

Comments are posted to an object at a specific time, I am using the time posted as the range so comments are sortable in time descending order. I have a global secondary index of the userId of the user who posted the comment, this should allow me to get all comments posted by a given user.

My question is, will this key be unique? I'm worried that since it is technically possible for two users to post a comment to the same objectId at the same time, the comment hash and range key will be identical.

My hope is that since it should be impossible for the same user to post two comments on the same object at the same time the global secondary index will make the key unique.

 Comment table:

   Hash Key                   Range Key                      Global Secondary Index Hash
 ---------------------------------------------------------------------------------------
|   objectId   |              datePosted                 |           userId             |
| (not unique) |      (not unique if multiple users      | (unique across objectId and  |
|              |  post for the same object @ same time)  |         datePosted)          |
 ---------------------------------------------------------------------------------------
like image 596
francis Avatar asked Aug 17 '14 14:08

francis


1 Answers

DynamoDB indexes have nothing to do with uniqueness. Global and local indexes are allowed to have duplicate hash key & range key pairs. Only the hash key and range key of the table itself are unique.

In your example, it would be possible for two different users to comment on an object at the same exact moment and produce a duplicate objectId, datePosted key. There are a couple ways to deal with this. You could use a PutItem request with a condition that the primary key is null as mentioned in the API reference. That would cause the second comment save to fail and you could report an error to the user or simply try again with an updated time-stamp. Without the condition, the second comment will overwrite the first. Alternatively, you could make the range key of the table a composite value of datePosted concatenated with userId. That way, the range keys will always be unique, but will still be sorted in date time order. This is a common practice with DynamoDB.

like image 156
Jeff Walker Code Ranger Avatar answered Nov 20 '22 15:11

Jeff Walker Code Ranger