[20 Days of DynamoDB] Day 6 - Atomic counters with UpdateItem
Abhishek Gupta
Posted on January 15, 2024
Posted: 15/Jan/2024
Need to implement atomic counter using DynamoDB? If you have a use-case that can tolerate over-counting or under-counting (for example, visitor count), use the UpdateItem
API.
Here is an example that uses the SET operator in an update expression to increment num_logins
attribute:
resp, err := client.UpdateItem(context.Background(), &dynamodb.UpdateItemInput{
TableName: aws.String(tableName),
Key: map[string]types.AttributeValue{
"email": &types.AttributeValueMemberS{Value: email},
},
UpdateExpression: aws.String("SET num_logins = num_logins + :num"),
ExpressionAttributeValues: map[string]types.AttributeValue{
":num": &types.AttributeValueMemberN{
Value: num,
},
},
ReturnConsumedCapacity: types.ReturnConsumedCapacityTotal,
})
Note that every invocation of UpdateItem
will increment (or decrement) - hence it is not idempotent.
Recommended reading - Atomic Counters
💖 💪 🙅 🚩
Abhishek Gupta
Posted on January 15, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.