#Increment Value in DynamoDB

6 messages · Page 1 of 1 (latest)

tacit ember
#

Is there a way to increment a value in DynamoDB through the GraphQL API?

For example: We have two different tables, Posts and Comments as shown below. Every time a new comment was added to the database, I want to increment the commentsCounter inside of the corresponding Post item.

The problem is that I can not just fetch the Posts item, read the value of commentsCounter, add a value of 1 and update the Posts Item again. When multiple comments are added at the same time, the value of commentsCounter would not update correctly.

type Posts @model {
  id: ID!
  title: String
  content: String
  comments [Comments] @hasMany(indexName: "byPosts", fields: ["id"])
  commentsCounter: Int
}

type Comments @model {
  id: ID!
  title: String
  content: String
  postId: ID!
  post: Posts @belongsTo(fields: ["postId"])
}

Looking forward to your help! 🙂

solar niche
#

We use DynamoDB trigger for this, so that when a new comment is created on Dynamo, a lambda is invoked, which will fetch the related Post and update the counter.

distant rose
#

You can do this via DynamoDB directly with an atomic counter (https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html#WorkingWithItems.AtomicCounters), and could use a GQL resolver to add the comment and update the counter. (edit: or put the atomic counter update behind a trigger as dral3x suggests). You can also consider subscriptions. This way, the cloud will poke your front-end when there's new relevant data. Using subscriptions, you would eliminate the commentsCounter field.

tacit ember
#

Thanks a lot for your answers!

@solar niche : The issue we see with this approach is: When multiple users create a comment at the same time the lambda function will be triggered several times. This means that the previous lambda function might not be finished with updating the commentsCounter which then leads the next lambda function to fetch a deprecated value for commentsCounter, right?

@distant rose : I will also have a look to your approach!

We need this behaviour at several places in our app. One is the comment counter which needs to increment by +1 every time, but we also have analytics data which needs to increment by Float Numbers.

wispy stream
#

If you cannot tolerate mistakes, you could use Conditional writes. They are described under the atomic counters on the page DaveDave linked

solar niche
#

Makes sense @tacit ember . Then I agree on the suggestions of @distant rose and @wispy stream