0

In my code I am creating partition keys for user forms and sending metadata of them to dynamodb. I use lambdas for this and using some auto-increment function to be sure that counter is increased 1 and this incremented partition key is not already in the table. Then finally submitting the new item to dynamodb. Question is while this incremental step is carried out simultaneously by multiple users at the same time, before put_item their sessions will still think that NEW INCREMENTED ID is not already taken and they will get all this new id.. (You might guess the rest easily, after this step when they try to submit themselves with this new id, bummm the same partition key id is overridden by machine who submit last and previous user data gets lost:/ ) It might be advised to use sort key to make data unique but I need UNIQUE PARTITION KEY for business purposes

mears
  • 359
  • 4
  • 13
  • 1
    A sort key would not change that because you just shift the "problem" to the uniqueness of the composite key. Anyway: in both cases the solution is to use a `PutItem` / `UpdateItem` with a `ConditionExpression` to ensure the item does not exist yet. – luk2302 Dec 30 '22 at 09:14
  • both answers show the functionality I was seeking for. thank you) – mears Dec 30 '22 at 09:22
  • Is there a reason you are using an auto-incrementing counter? What if your id was just a randomly generated UUID? The odds of collision are dramatically lower (but yes, if you need to know how many you have, a counter is more intuitive) – amrith Dec 30 '22 at 12:33
  • amrith: I agree UUID would be easier to handle but unfortunately business requirements asked incremental increase in id, such as 'ABC000001', 'ABC000002'. thanks though – mears Dec 30 '22 at 13:14

1 Answers1

2

You need to use a ConditionExpression and use the condition not_exists.

aws dynamodb put-item \
    --table-name ProductCatalog \
    --item file://item.json \
    --condition-expression "attribute_not_exists(Id)"

https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.ConditionExpressions.html#Expressions.ConditionExpressions.PreventingOverwrites

Leeroy Hannigan
  • 11,409
  • 3
  • 14
  • 31