Atomic Counters in dynamodb helps to increment the values in dynamodb server instead of performing the calculation at the client application. For example, consider a field called "quantity" with any number, in order to increment or decrement this value, traditionally a get operation should be performed to retrieve the record and the actual value has to be computed by the application and an update statement stores the latest value, instead dynamodb offers a functionality, which increments or decrements the value of the "quantity" by the provided value.
But the update statement issued to dynamodb is not idempotent. Idempotent is a property which provides the same output irrespective of processing the update statement many times. In our case, since we are providing an update statement which just increments the value, processing the same statement multiple times may result in different output, hence the operation is not idempotent.
Why an update statement should be idempotent?
Even though the update statement is issued only once to the dynamodb, the dynamodb client (SDK library) automatically retries atleast 10 times (if the retry policy is not configured) incase of any network latency or timeouts, which causes an over or undercounting as per the dynamodb documentation.
To avoid this issue, AWS suggests a conditional update by adding condition expressions to the update statement, this leads to below issues,
1. The record should be retrieved and application code should perform the computation to find the end result.
2. Application code should retry the update expression with new conditional statements incase of failure.
ConditionalCheckFailedException due to DynamoDB retry
Hence, a conditional expression cannot be used to prevent the false increment of atomic counters.
How to make this Idempotent?
To make this idempotent, DynamoDB Transactions should be leveraged.
Including a client token with transactions will allow to retry a request if it fails without it being considered a new separate request. A client token lasts for 10 minutes and the same request can be retried multiple times within that period without it being considered a new request however after 10 minutes another retry would be consider a second request. Client Token will be included automatically for transactions incase of using official dynamodb SDK library.
Hence transactions can be used to precisely increment atomic counters which solves all the above issues.
Comments
Post a Comment