Idempotency tokens help make sure that when you send the same request more than once, it only happens once in the database. This stops duplicate data or actions.
0
0
Idempotency tokens in DynamoDB
Introduction
When a user clicks a button multiple times but you want to save only one record.
When a network error causes you to resend a request and you want to avoid duplicate processing.
When processing payments to ensure the same payment is not charged twice.
When creating orders or bookings where duplicates would cause problems.
When retrying API calls that modify data to keep the operation safe and consistent.
Syntax
DynamoDB
Use a unique token (string) as an attribute in your item, for example: { "IdempotencyToken": "unique-string-value" } When writing to DynamoDB, use a condition expression to check if an item with this token already exists before inserting.
The token should be unique for each unique request.
Store the token as a key or attribute to check for duplicates.
Examples
This example inserts an order only if the token does not already exist, preventing duplicates.
DynamoDB
PutItem with idempotency token: { "TableName": "Orders", "Item": { "OrderId": {"S": "123"}, "IdempotencyToken": {"S": "abc-123-token"}, "Amount": {"N": "50"} }, "ConditionExpression": "attribute_not_exists(IdempotencyToken)" }
This checks if the token is already stored before processing a new request.
DynamoDB
Query to check if token exists: { "TableName": "Orders", "IndexName": "IdempotencyToken-index", "KeyConditionExpression": "IdempotencyToken = :token", "ExpressionAttributeValues": { ":token": {"S": "abc-123-token"} } }
Sample Program
This command tries to add a new order with a unique idempotency token. If the token already exists, DynamoDB will reject the request, preventing duplicates.
DynamoDB
aws dynamodb put-item \ --table-name Orders \ --item '{"OrderId": {"S": "123"}, "IdempotencyToken": {"S": "token-xyz"}, "Amount": {"N": "100"}}' \ --condition-expression "attribute_not_exists(IdempotencyToken)"
OutputSuccess
Important Notes
Always generate a new unique token for each new request.
Use condition expressions to enforce uniqueness in DynamoDB.
If a request fails due to token conflict, handle it gracefully in your app.
Summary
Idempotency tokens prevent duplicate actions in databases.
Use unique tokens and condition checks to enforce one-time operations.
This helps keep data clean and consistent, especially with retries.