日本語

DynamoDB Atomic Counter with AWS Emulator (ADD and SET)

​​AWS Emulator​AWS CLI,DynamoDB

When you want to increase a numeric DynamoDB item attribute by 1, such as a page view or like count, don't read the item and write it back. Instead, write the update expression of UpdateItem as ADD views :one or SET views = views + :one. The addition happens on the table side, so the count is not lost even when many requests arrive at the same time. Below are the commands and output from testing with AWS Emulator, without an AWS account.

Note

The test environment was Ubuntu 24.04 (x86_64), AWS Emulator 1.0.624 (released November 26, 2026), and AWS CLI 2.42.4. I did not use an AWS account or credentials. I did not test how real DynamoDB behaves, its pricing or consumed write capacity, or how to call it from the AWS SDK. Where this article describes real DynamoDB, it is based on the official documentation. According to the AWS Emulator official documentation, AWS checks the emulator's behavior against the real service only in the US West (Oregon, us-west-2) Region (global services use us-east-1). The us-east-1 DynamoDB used in this article is not in that scope.

Start the emulator and create a table

AWS Emulator is an emulator that accepts AWS API calls locally. According to the official documentation, you do not need an AWS account, and requests are not sent to AWS. How to install it, and the environment variables that point the AWS CLI at the emulator, are covered in the separate articles "How to install AWS Emulator on Ubuntu and start using it" and "How to try DynamoDB with AWS Emulator without an account." In this article, I set the environment variables from the official documentation in the shell, started the emulator with aws-emulator -t off, and sent commands to it. -t off turns off the usage data (the telemetry) that the emulator sends to AWS by default.

If the connection works, the user name in the ARN returned by aws sts get-caller-identity is emulator. (The 12-digit account ID is replaced.) I create a table named Counters that has only a partition key pk (string).

text
$ aws sts get-caller-identity --query Arn --output text
arn:aws:iam::<12桁のアカウントID>:user/emulator

$ aws dynamodb create-table --table-name Counters --attribute-definitions AttributeName=pk,AttributeType=S --key-schema AttributeName=pk,KeyType=HASH --billing-mode PAY_PER_REQUEST --query TableDescription.TableStatus
"CREATING"

$ aws dynamodb wait table-exists --table-name Counters && aws dynamodb describe-table --table-name Counters --query Table.TableStatus
"ACTIVE"

In the commands below, the attribute name views is written as #v using --expression-attribute-names.

With SET, the first increment needs if_not_exists

The official update expression documentation shows how to add or subtract a numeric attribute with SET and + or -. However, writing SET #v = #v + :one for an attribute that does not exist yet was rejected with a ValidationException. The item was not created either (get-item returned nothing).

text
$ aws dynamodb update-item --table-name Counters --key '{"pk":{"S":"page#top"}}' --update-expression "SET #v = #v + :one" --expression-attribute-names '{"#v":"views"}' --expression-attribute-values '{":one":{"N":"1"}}' --return-values UPDATED_NEW

aws: [ERROR]: An error occurred (ValidationException) when calling the UpdateItem operation: The provided expression refers to an attribute that does not exist in the item

$ aws dynamodb get-item --table-name Counters --key '{"pk":{"S":"page#top"}}'

If you wrap the expression as if_not_exists(#v, :zero), the value is replaced with :zero (0) when the attribute is missing, and the current value is used otherwise, before the addition. The first call created the item with 1, and the second call made it 2. Once the attribute exists, you can add to it without if_not_exists. Adding --return-values UPDATED_NEW returns the value after the addition.

text
$ aws dynamodb update-item --table-name Counters --key '{"pk":{"S":"page#top"}}' --update-expression "SET #v = if_not_exists(#v, :zero) + :one" --expression-attribute-names '{"#v":"views"}' --expression-attribute-values '{":zero":{"N":"0"},":one":{"N":"1"}}' --return-values UPDATED_NEW
{
    "Attributes": {
        "views": {
            "N": "1"
        }
    }
}

$ aws dynamodb update-item --table-name Counters --key '{"pk":{"S":"page#top"}}' --update-expression "SET #v = if_not_exists(#v, :zero) + :one" --expression-attribute-names '{"#v":"views"}' --expression-attribute-values '{":zero":{"N":"0"},":one":{"N":"1"}}' --return-values UPDATED_NEW
{
    "Attributes": {
        "views": {
            "N": "2"
        }
    }
}

$ aws dynamodb update-item --table-name Counters --key '{"pk":{"S":"page#top"}}' --update-expression "SET #v = #v + :one" --expression-attribute-names '{"#v":"views"}' --expression-attribute-values '{":one":{"N":"1"}}' --return-values UPDATED_NEW
{
    "Attributes": {
        "views": {
            "N": "3"
        }
    }
}

With ADD, you can add even when the attribute does not exist

The ADD update action works only on number and set attributes. According to the official documentation, if the attribute does not exist yet, an attribute with the value you pass is created. In the emulator too, sending ADD #v :n (5) to a key with no item created the item, and views became 5. Sending it again made it 10.

text
$ aws dynamodb update-item --table-name Counters --key '{"pk":{"S":"page#about"}}' --update-expression "ADD #v :n" --expression-attribute-names '{"#v":"views"}' --expression-attribute-values '{":n":{"N":"5"}}' --return-values ALL_NEW
{
    "Attributes": {
        "views": {
            "N": "5"
        },
        "pk": {
            "S": "page#about"
        }
    }
}

$ aws dynamodb update-item --table-name Counters --key '{"pk":{"S":"page#about"}}' --update-expression "ADD #v :n" --expression-attribute-names '{"#v":"views"}' --expression-attribute-values '{":n":{"N":"5"}}' --return-values UPDATED_NEW
{
    "Attributes": {
        "views": {
            "N": "10"
        }
    }
}

To decrease, either pass a negative number to ADD, or write SET #v = #v - :n. Neither one stops the value from going below 0. Subtracting 3 from 10 gave 7, and then subtracting 10 gave -3.

text
$ aws dynamodb update-item --table-name Counters --key '{"pk":{"S":"page#about"}}' --update-expression "ADD #v :n" --expression-attribute-names '{"#v":"views"}' --expression-attribute-values '{":n":{"N":"-3"}}' --return-values UPDATED_NEW
{
    "Attributes": {
        "views": {
            "N": "7"
        }
    }
}

$ aws dynamodb update-item --table-name Counters --key '{"pk":{"S":"page#about"}}' --update-expression "SET #v = #v - :n" --expression-attribute-names '{"#v":"views"}' --expression-attribute-values '{":n":{"N":"10"}}' --return-values UPDATED_NEW
{
    "Attributes": {
        "views": {
            "N": "-3"
        }
    }
}

For a number that must not go below 0, such as inventory, add a condition expression when you decrease it. I cover that in the separate article "How to try DynamoDB conditional writes with AWS Emulator."

The official documentation for ADD says that SET is generally recommended over ADD to make operations idempotent. However, an update that adds to a number still adds again every time it is sent, even when written with SET. In the SET examples above, the value also went up each time it was sent, becoming 1, 2, and then 3.

Get the value before or after the addition

With --return-values UPDATED_OLD, you get the value before the addition. With UPDATED_NEW, you get the value after it. This matches the official documentation on return values. Adding 1 to -3 with UPDATED_OLD returned -3. Adding another 1 and using --query and --output text to get only the number gave -1.

text
$ aws dynamodb update-item --table-name Counters --key '{"pk":{"S":"page#about"}}' --update-expression "ADD #v :n" --expression-attribute-names '{"#v":"views"}' --expression-attribute-values '{":n":{"N":"1"}}' --return-values UPDATED_OLD
{
    "Attributes": {
        "views": {
            "N": "-3"
        }
    }
}

$ aws dynamodb update-item --table-name Counters --key '{"pk":{"S":"page#about"}}' --update-expression "ADD #v :n" --expression-attribute-names '{"#v":"views"}' --expression-attribute-values '{":n":{"N":"1"}}' --return-values UPDATED_NEW --query Attributes.views.N --output text
-1

Even when 50 processes add at the same time, the count is not lost

I sent 50 background update-item calls, each adding 1, at the same time. There were no errors, and the final read value was 50.

text
$ for i in $(seq 1 50); do aws dynamodb update-item --table-name Counters --key '{"pk":{"S":"race#add"}}' --update-expression "ADD #v :one" --expression-attribute-names '{"#v":"views"}' --expression-attribute-values '{":one":{"N":"1"}}' >/dev/null 2>>err-add.txt & done; wait; echo "エラーの行数: $(wc -l < err-add.txt)"
エラーの行数: 0

$ aws dynamodb get-item --table-name Counters --key '{"pk":{"S":"race#add"}}' --consistent-read --query Item.views.N --output text
50

For comparison, I ran 50 processes at the same time that each read the current value with get-item, added 1, and wrote it back with put-item. These also produced no errors, but the final value was 1. This is because the last process to write back had also read 0, before the other processes wrote back, and it overwrote all the earlier writes with 1.

text
$ aws dynamodb put-item --table-name Counters --item '{"pk":{"S":"race#rmw"},"views":{"N":"0"}}'

$ for i in $(seq 1 50); do ( n=$(aws dynamodb get-item --table-name Counters --key '{"pk":{"S":"race#rmw"}}' --consistent-read --query Item.views.N --output text); aws dynamodb put-item --table-name Counters --item "{\"pk\":{\"S\":\"race#rmw\"},\"views\":{\"N\":\"$((n+1))\"}}" ) >/dev/null 2>>err-rmw.txt & done; wait; echo "エラーの行数: $(wc -l < err-rmw.txt)"
エラーの行数: 0

$ aws dynamodb get-item --table-name Counters --key '{"pk":{"S":"race#rmw"}}' --consistent-read --query Item.views.N --output text
1
Comparison of two processes adding to a count at the same time. Top: both read views = 0 and write views = 1, so the result is 1. Bottom: both send ADD views 1, and the table adds them one after another, 0, 1, 2, so the result is 2. (Diagram reduced to two processes.)
Read-then-write loses one increment; ADD does not lose any (diagram reduced to two processes)

The official documentation on atomic counters says that adding to a number with UpdateItem increments it without interfering with other writes, and that writes are applied in the order they arrive.

Change several numbers in one request

In one update expression, you can list several ADD actions separated by commas. You can also combine them with SET. The example below adds to the like count and the view count, and writes the update time.

text
$ aws dynamodb update-item --table-name Counters --key '{"pk":{"S":"post#42"}}' --update-expression "ADD likes :one, #v :one SET updatedAt = :t" --expression-attribute-names '{"#v":"views"}' --expression-attribute-values '{":one":{"N":"1"},":t":{"S":"2026-11-26T00:00:00Z"}}' --return-values ALL_NEW
{
    "Attributes": {
        "pk": {
            "S": "post#42"
        },
        "likes": {
            "N": "1"
        },
        "updatedAt": {
            "S": "2026-11-26T00:00:00Z"
        },
        "views": {
            "N": "1"
        }
    }
}

To keep per-day counts in a map (daily), you first need to create the map itself. Sending ADD daily.#d :one when daily does not exist was rejected with a ValidationException. The official documentation also says that nested attributes cannot be updated if the parent map does not exist. After creating an empty map with SET daily = if_not_exists(daily, :empty), I could add the per-date counts. Adding also works with the SET and if_not_exists form.

text
$ aws dynamodb update-item --table-name Counters --key '{"pk":{"S":"post#42"}}' --update-expression "ADD daily.#d :one" --expression-attribute-names '{"#d":"2026-11-26"}' --expression-attribute-values '{":one":{"N":"1"}}'

aws: [ERROR]: An error occurred (ValidationException) when calling the UpdateItem operation: The document path provided in the update expression is invalid for update

$ aws dynamodb update-item --table-name Counters --key '{"pk":{"S":"post#42"}}' --update-expression "SET daily = if_not_exists(daily, :empty)" --expression-attribute-values '{":empty":{"M":{}}}'

$ aws dynamodb update-item --table-name Counters --key '{"pk":{"S":"post#42"}}' --update-expression "ADD daily.#d :one" --expression-attribute-names '{"#d":"2026-11-26"}' --expression-attribute-values '{":one":{"N":"1"}}' --return-values UPDATED_NEW
{
    "Attributes": {
        "daily": {
            "M": {
                "2026-11-26": {
                    "N": "1"
                }
            }
        }
    }
}

$ aws dynamodb update-item --table-name Counters --key '{"pk":{"S":"post#42"}}' --update-expression "SET daily.#d = if_not_exists(daily.#d, :zero) + :one" --expression-attribute-names '{"#d":"2026-11-27"}' --expression-attribute-values '{":zero":{"N":"0"},":one":{"N":"1"}}' --return-values UPDATED_NEW
{
    "Attributes": {
        "daily": {
            "M": {
                "2026-11-27": {
                    "N": "1"
                }
            }
        }
    }
}

When requests are rejected: reserved keyword names, string attributes, and overflow

If an attribute name is a DynamoDB reserved keyword, you cannot write it directly in an update expression. When I used total as the attribute that holds the total, the ValidationException said it was a reserved keyword. Replacing it with #t using --expression-attribute-names made the request succeed. The official naming rules also say that reserved keyword names must be replaced in expressions.

text
$ aws dynamodb update-item --table-name Counters --key '{"pk":{"S":"decimal"}}' --update-expression "ADD total :n" --expression-attribute-values '{":n":{"N":"0.1"}}'

aws: [ERROR]: An error occurred (ValidationException) when calling the UpdateItem operation: 1 validation error detected: Invalid UpdateExpression: Attribute name is a reserved keyword; reserved keyword: total

$ aws dynamodb update-item --table-name Counters --key '{"pk":{"S":"decimal"}}' --update-expression "ADD #t :n" --expression-attribute-names '{"#t":"total"}' --expression-attribute-values '{":n":{"N":"0.1"}}' --return-values UPDATED_NEW --query Attributes.total.N --output text
0.1

As the output above shows, decimals can be added too. Adding 0.2 to 0.1 gave exactly 0.3. I did not see the rounding error that the same addition produces with floating-point numbers in Python.

text
$ aws dynamodb update-item --table-name Counters --key '{"pk":{"S":"decimal"}}' --update-expression "ADD #t :n" --expression-attribute-names '{"#t":"total"}' --expression-attribute-values '{":n":{"N":"0.2"}}' --return-values UPDATED_NEW --query Attributes.total.N --output text
0.3

$ python3 -c "print(0.1 + 0.2)"
0.30000000000000004

According to the official documentation, DynamoDB stores numbers with up to 38 digits of precision, and going beyond that raises an exception. Adding 1 to a 38-digit number made of nines gave a number with 1 followed by 38 zeros (one significant digit with 39 digits total), and that succeeded. Adding the 38-digit nines again was rejected with a Number overflow ValidationException, and the value did not change. The message says the magnitude is out of range, but the value falls within the positive range in the official documentation (up to 9.9999999999999999999999999999999999999E+125). What was exceeded is the 38-digit precision.

text
$ aws dynamodb update-item --table-name Counters --key '{"pk":{"S":"big"}}' --update-expression "ADD #t :n" --expression-attribute-names '{"#t":"total"}' --expression-attribute-values '{":n":{"N":"99999999999999999999999999999999999999"}}' --return-values UPDATED_NEW --query Attributes.total.N --output text
99999999999999999999999999999999999999

$ aws dynamodb update-item --table-name Counters --key '{"pk":{"S":"big"}}' --update-expression "ADD #t :n" --expression-attribute-names '{"#t":"total"}' --expression-attribute-values '{":n":{"N":"1"}}'

$ aws dynamodb get-item --table-name Counters --key '{"pk":{"S":"big"}}' --query Item.total.N --output text
100000000000000000000000000000000000000

$ aws dynamodb update-item --table-name Counters --key '{"pk":{"S":"big"}}' --update-expression "ADD #t :n" --expression-attribute-names '{"#t":"total"}' --expression-attribute-values '{":n":{"N":"99999999999999999999999999999999999999"}}'

aws: [ERROR]: An error occurred (ValidationException) when calling the UpdateItem operation: Number overflow. Attempting to store a number with magnitude larger than supported range

$ aws dynamodb get-item --table-name Counters --key '{"pk":{"S":"big"}}' --query Item.total.N --output text
100000000000000000000000000000000000000

If an attribute that holds a number was stored as a string (S), you cannot add to it with either ADD or SET. Both were rejected with a ValidationException about the data type, and the value stayed "10".

text
$ aws dynamodb put-item --table-name Counters --item '{"pk":{"S":"string"},"views":{"S":"10"}}'

$ aws dynamodb update-item --table-name Counters --key '{"pk":{"S":"string"}}' --update-expression "ADD #v :one" --expression-attribute-names '{"#v":"views"}' --expression-attribute-values '{":one":{"N":"1"}}'

aws: [ERROR]: An error occurred (ValidationException) when calling the UpdateItem operation: An operand in the update expression has an incorrect data type

$ aws dynamodb update-item --table-name Counters --key '{"pk":{"S":"string"}}' --update-expression "SET #v = #v + :one" --expression-attribute-names '{"#v":"views"}' --expression-attribute-values '{":one":{"N":"1"}}'

aws: [ERROR]: An error occurred (ValidationException) when calling the UpdateItem operation: An operand in the update expression has an incorrect data type

$ aws dynamodb get-item --table-name Counters --key '{"pk":{"S":"string"}}' --query Item.views
{
    "S": "10"
}

If you resend, it counts twice

When I sent the same update-item twice in a row, both calls were applied in the emulator, and the count became 2.

text
$ for i in 1 2; do aws dynamodb update-item --table-name Counters --key '{"pk":{"S":"retry"}}' --update-expression "ADD #v :one" --expression-attribute-names '{"#v":"views"}' --expression-attribute-values '{":one":{"N":"1"}}' --return-values UPDATED_NEW --query Attributes.views.N --output text; done
1
2
Warning

The official documentation on atomic counters says that this kind of update is not idempotent. If you resend a request you think failed, the count may end up too high when adding a positive number, and too low when adding a negative number. It is suitable for counts where a small error is acceptable, such as page views. It is not suitable for counts where errors are not acceptable, such as a bank balance. For those, the documentation says a conditional update is safer.

The official explanation of idempotency for conditional writes gives an example: if you check the attribute being updated with a condition, such as "add 3 only when the current value is 20," then resending the same request applies the change only once.

Delete the table when you are done.

text
$ aws dynamodb delete-table --table-name Counters --query TableDescription.TableName
"Counters"

​Posted by 86