0

We have a business rule that one account can only have 3 projects at any given time.

In order to keep it efficient, we track the number of projects in an "userData" field instead of doing a COUNT query

Consider the following example objects already in DynamoDB:

userData : { createdProjects : 2 }
project1 : { id : 1 }
project2 : { id : 2 }

In order to enforce this rule, we've done the following when creating a project (pseudo code)

in transaction:
  putItem(key = "project3", object = { id : 3 })
  updateItem(
    key = "userData", 
    expression = "createdProjects = createdProjects + 1"
    condition = "createdProjects < 3"
  )

Now, if the user tries to create a project at the same time with two computers let's say, will DynamoDB guarantee that he won't be able to create more than 3?

I know there are similar questions like this one, but I wanted to know if this also works in a transaction, because my condition is in another object.

Also, is my pseudo code the best approach? open to other ways

Mojimi
  • 2,561
  • 9
  • 52
  • 116

1 Answers1

2

You can use a transaction for this. Just include the PutItem request and UpdateItem request with the condition in a transaction and either both will complete or none of them.

Transactions are the way to provide this all or nothing behavior.

With the transaction write API, you can group multiple Put, Update, Delete, and ConditionCheck actions. You can then submit the actions as a single TransactWriteItems operation that either succeeds or fails as a unit. The same is true for multiple Get actions, which you can group and submit as a single TransactGetItems operation.

docs

Maurice
  • 11,482
  • 2
  • 25
  • 45