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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay