How to create atomic counter in AWS DynamoDB with AWS CLI

A step by step procedure to create and update atomic counter in AWS DynamoDB table.

Creating counter in DDB!

First of all, we will see what is atomic counter and why do we need it. We will also check why DybamoDB is chosen in this use case.

What is atomic counter?

Often it would help if you tracked some numerical like website visits, which are incremental in nature. Such counters need to be stored in a centralized place, and the update should be atomic. Atomic means one request executes without interfering with another request. i.e. concurrent updates do not clash with each other and so no data lost in the process. Since everyone is leveraging temporary infrastructure like EC2 getting replaced by Auto Scaling groups or containers, storing such counter locally is not a good idea. So to get central storage, DDB is the best choice since it’s an ultra-fast, single-digit milliseconds latency, NoSQL database. Perfect for the atomic operation of scaling infra/traffic.

Now let’s get into the process of creating this counter and updating it.

Creating DynamoDB table for the counter

  1. Login to DDB console
  2. Click on Create table
  3. Enter Table Name
  4. Enter Primary Key (Partition Key)
  5. We don’t need a sort key here since our table will carry only one counter value. Keep the rest of the settings default and click Create
Create DynamoDB table

You can use below Cloudformation resource block to create a DDB table:

Type: AWS::DynamoDB::Table
    Properties:
      TableName: kerneltalks-counter
      AttributeDefinitions: 
        - AttributeName: ID
          AttributeType: S
      KeySchema: 
        - AttributeName: ID
          KeyType: HASH

Make sure you change the TableName to your choice. You can also explorer other properties supported by DDB in CloudFormation.

Preparing DynamoDB table for counter updates

Now, you will be presented with newly created table details.

Goto Items tab and click Create item

Create DynamoDB Item

Add attributes in item as mentioned below :

Click on Save. Now your DDB table is ready for updating the counter

DDB table creation can be done via AWS CLI as well using the below command:

$ aws dynamodb put-item --table-name kerneltalks-counter --item '{"ID": { "S": "Counter" }, "TotalCount": { "N": "0" }}'

Updating counter in DDB table

Now you can use below AWS CLI command below to update the counter! Every time you run the command, it will update the counter by 1. You can code it in your application at the appropriate place to run this command/API call to update the counter.

$ aws dynamodb update-item --table-name kerneltalks-counter --key '{"ID": { "S": "Counter" }}' --update-expression "SET TotalCount = TotalCount + :incr" --expression-attribute-values '{":incr":{"N":"1"}}' --return-values UPDATED_NEW
{
    "Attributes": {
        "TotalCount": {
            "N": "1"
        }
    }
}

The command should return with the updated attribute in JSON format. You can format it to text for easy usability in code.

$ aws dynamodb update-item --table-name kerneltalks-counter --key '{"ID": { "S": "Counter" }}' --update-expression "SET TotalCount = TotalCount + :incr" --expression-attribute-values '{":incr":{"N":"1"}}' --return-values UPDATED_NEW --output text
TOTALCOUNT      2

The same can be verified in the console.

Counter in DDB.

That’s all! Now you have a counter in DDB which can be updated from different sources using API calls.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.