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

[20-days-of-dynamodb]-day-6-–-atomic-counters-with-updateitem

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

Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post
seven-sites-for-free-low-code-app-templates

Seven Sites for Free Low-Code App Templates

Next Post
std::optional?-proceed-with-caution!

std::optional? Proceed with caution!

Related Posts