DEV Community

Abhishek Gupta for AWS

Posted on • Edited on • Originally published at community.aws

[20 Days of DynamoDB] Day 6 - Atomic counters with UpdateItem

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,
    })
Enter fullscreen mode Exit fullscreen mode

Note that every invocation of UpdateItem will increment (or decrement) - hence it is not idempotent.

Recommended reading - Atomic Counters

Top comments (0)