DEV Community

Abhishek Gupta for AWS

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

4 1 1

[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

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (0)

Heroku

This site is powered by Heroku

Heroku was created by developers, for developers. Get started today and find out why Heroku has been the platform of choice for brands like DEV for over a decade.

Sign Up

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay