Atomic Counters - DynamoDB CRUD Operations
Syntax
ddb.update_item(
TableName='table_name',
Key={
'key': 'value'
},
UpdateExpression='SET counter = counter + :value',
ExpressionAttributeValues={
':value': {'N': '1'}
},
ReturnValues='UPDATED_NEW'
)
Example
Suppose we have a DynamoDB table named visitors
with the following schema:
{
"PK": "visitor_id",
"SK": "visit_timestamp",
"first_name",
"last_name",
"page_views"
}
We want to increment the number of page_views
for a specific visitor identified by their visitor_id
. We can use atomic counters in DynamoDB to achieve this with the following code:
import boto3
client = boto3.client('dynamodb')
response = client.update_item(
TableName='visitors',
Key={
'PK': {'S': 'user_123'},
'SK': {'S': '20220414213245'},
},
UpdateExpression="ADD page_views :value",
ExpressionAttributeValues={
':value': {'N': '1'}
},
ReturnValues="UPDATED_NEW"
)
print(response)
Output
The above code will increment the page_views
counter for the specified visitor by 1 and return the updated item as follows:
{
"Attributes": {
"PK": {
"S": "user_123"
},
"SK": {
"S": "20220414213245"
},
"first_name": {
"S": "John"
},
"last_name": {
"S": "Doe"
},
"page_views": {
"N": "5"
}
}
}
Explanation
In the example code above, we execute a update_item
operation to increment the page_views
counter for a specific visitor identified by their visitor_id
.
We specify the UpdateExpression
to use the ADD
operation to increment the page_views
attribute by the value of :value
which is specified in the ExpressionAttributeValues
as 1
.
Lastly, we specify ReturnValues
to return the updated item with the page_views
counter incremented by 1.
Use
Atomic counters in DynamoDB are useful when we want to increment/decrement a numeric attribute without risking the chance of concurrent writes causing conflicts.
For example, we can use atomic counters to keep track of views, likes, follows, and other such metrics.
Important Points
- Atomic counters in DynamoDB are designed to solve the problem of concurrent writes to a single numeric attribute.
- Atomic counters in DynamoDB use the
ADD
operation to increment/decrement a numeric attribute. - Atomic counters in DynamoDB provides strongly consistent reads, which means that reads will reflect the latest updates to the counter.
Summary
Atomic counters in DynamoDB provide an easy way to increment/decrement a numeric attribute without risking the chance of concurrent writes causing conflicts. They use the ADD
operation to increment/decrement a numeric attribute and provide strongly consistent reads, ensuring that reads reflect the latest updates to the counter.