Idempotency
The idempotency utility provides a simple solution to convert your Lambda functions into idempotent operations which are safe to retry.
Terminology¶
The property of idempotency means that an operation does not cause additional side effects if it is called more than once with the same input parameters.
Idempotent operations will return the same result when they are called multiple times with the same parameters. This makes idempotent operations safe to retry. Read more about idempotency.
Idempotency key is a hash representation of either the entire event or a specific configured subset of the event, and invocation results are JSON serialized and stored in your persistence storage layer.
Key features¶
- Prevent Lambda handler function from executing more than once on the same event payload during a time window
- Ensure Lambda handler returns the same result when called with the same payload
- Select a subset of the event as the idempotency key using JMESPath expressions
- Set a time window in which records with the same payload should be considered duplicates
Getting started¶
Installation¶
Depending on your version of Java (either Java 1.8 or 11+), the configuration slightly changes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
Required resources¶
Before getting started, you need to create a persistent storage layer where the idempotency utility can store its state - your Lambda functions will need read and write access to it.
As of now, Amazon DynamoDB is the only supported persistent storage layer, so you'll need to create a table first.
Default table configuration
If you're not changing the default configuration for the DynamoDB persistence layer, this is the expected default configuration:
Configuration | Value | Notes |
---|---|---|
Partition key | id |
|
TTL attribute name | expiration |
This can only be configured after your table is created if you're using AWS Console |
Tip: You can share a single state table for all functions
You can reuse the same DynamoDB table to store idempotency state. We add your function name in addition to the idempotency key as a hash key.
AWS Serverless Application Model (SAM) example | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
|
Warning: Large responses with DynamoDB persistence layer
When using this utility with DynamoDB, your function's responses must be smaller than 400KB. Larger items cannot be written to DynamoDB and will cause exceptions.
Info: DynamoDB
Each function invocation will generally make 2 requests to DynamoDB. If the result returned by your Lambda is less than 1kb, you can expect 2 WCUs per invocation. For retried invocations, you will see 1WCU and 1RCU. Review the DynamoDB pricing documentation to estimate the cost.
Idempotent annotation¶
You can quickly start by initializing the DynamoDBPersistenceStore
and using it with the @Idempotent
annotation on your Lambda handler.
Important
Initialization and configuration of the DynamoDBPersistenceStore
must be performed outside the handler, preferably in the constructor.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
|
1 2 3 4 |
|
Idempotent annotation on another method¶
You can use the @Idempotent
annotation for any synchronous Java function, not only the handleRequest
one.
When using @Idempotent
annotation on another method, you must tell which parameter in the method signature has the data we should use:
- If the method only has one parameter, it will be used by default.
- If there are 2 or more parameters, you must set the
@IdempotencyKey
on the parameter to use.
The parameter must be serializable in JSON. We use Jackson internally to (de)serialize objects
This example also demonstrates how you can integrate with Batch utility, so you can process each record in an idempotent manner.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
|
Choosing a payload subset for idempotency¶
Tip: Dealing with always changing payloads
When dealing with an elaborate payload (API Gateway request for example), where parts of the payload always change, you should configure the EventKeyJMESPath
.
Use IdempotencyConfig
to instruct the Idempotent annotation to only use a portion of your payload to verify whether a request is idempotent, and therefore it should not be retried.
Payment scenario
In this example, we have a Lambda handler that creates a payment for a user subscribing to a product. We want to ensure that we don't accidentally charge our customer by subscribing them more than once.
Imagine the function executes successfully, but the client never receives the response due to a connection issue. It is safe to retry in this instance, as the idempotent decorator will return a previously saved response.
Warning: Idempotency for JSON payloads
The payload extracted by the EventKeyJMESPath
is treated as a string by default, so will be sensitive to differences in whitespace even when the JSON payload itself is identical.
To alter this behaviour, you can use the JMESPath built-in function powertools_json()
to treat the payload as a JSON object rather than a string.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
|
Idempotency request flow¶
This sequence diagram shows an example flow of what happens in the payment scenario:
sequenceDiagram
participant Client
participant Lambda
participant Persistence Layer
alt initial request
Client->>Lambda: Invoke (event)
Lambda->>Persistence Layer: Get or set (id=event.search(payload))
activate Persistence Layer
Note right of Persistence Layer: Locked to prevent concurrent<br/>invocations with <br/> the same payload.
Lambda-->>Lambda: Call handler (event)
Lambda->>Persistence Layer: Update record with result
deactivate Persistence Layer
Persistence Layer-->>Persistence Layer: Update record with result
Lambda-->>Client: Response sent to client
else retried request
Client->>Lambda: Invoke (event)
Lambda->>Persistence Layer: Get or set (id=event.search(payload))
Persistence Layer-->>Lambda: Already exists in persistence layer. Return result
Lambda-->>Client: Response sent to client
end
Idempotent sequence
The client was successful in receiving the result after the retry. Since the Lambda handler was only executed once, our customer hasn't been charged twice.
Note
Bear in mind that the entire Lambda handler is treated as a single idempotent operation. If your Lambda handler can cause multiple side effects, consider splitting it into separate functions.
Lambda timeouts¶
This is automatically done when you annotate your Lambda handler with @Idempotent annotation.
To prevent against extended failed retries when a Lambda function times out, Powertools for AWS Lambda (Java) calculates and includes the remaining invocation available time as part of the idempotency record.
Example
If a second invocation happens after this timestamp, and the record is marked as INPROGRESS
, we will execute the invocation again as if it was in the EXPIRED
state.
This means that if an invocation expired during execution, it will be quickly executed again on the next retry.
Important
If you are using the @Idempotent annotation on another method to guard isolated parts of your code, you must use registerLambdaContext
method available in the Idempotency
object to benefit from this protection.
Here is an example on how you register the Lambda context in your handler:
Registering the Lambda context | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
|
Lambda timeout sequence diagram¶
This sequence diagram shows an example flow of what happens if a Lambda function times out:
sequenceDiagram
participant Client
participant Lambda
participant Persistence Layer
alt initial request
Client->>Lambda: Invoke (event)
Lambda->>Persistence Layer: Get or set (id=event.search(payload))
activate Persistence Layer
Note right of Persistence Layer: Locked to prevent concurrent<br/>invocations with <br/> the same payload.
Note over Lambda: Time out
Lambda--xLambda: Call handler (event)
Lambda-->>Client: Return error response
deactivate Persistence Layer
else concurrent request before timeout
Client->>Lambda: Invoke (event)
Lambda->>Persistence Layer: Get or set (id=event.search(payload))
Persistence Layer-->>Lambda: Request already INPROGRESS
Lambda--xClient: Return IdempotencyAlreadyInProgressError
else retry after Lambda timeout
Client->>Lambda: Invoke (event)
Lambda->>Persistence Layer: Get or set (id=event.search(payload))
activate Persistence Layer
Note right of Persistence Layer: Locked to prevent concurrent<br/>invocations with <br/> the same payload.
Lambda-->>Lambda: Call handler (event)
Lambda->>Persistence Layer: Update record with result
deactivate Persistence Layer
Persistence Layer-->>Persistence Layer: Update record with result
Lambda-->>Client: Response sent to client
end
Idempotent sequence for Lambda timeouts
Handling exceptions¶
If you are using the @Idempotent
annotation on your Lambda handler or any other method, any unhandled exceptions that are thrown during the code execution will cause the record in the persistence layer to be deleted.
This means that new invocations will execute your code again despite having the same payload. If you don't want the record to be deleted, you need to catch exceptions within the idempotent function and return a successful response.
sequenceDiagram
participant Client
participant Lambda
participant Persistence Layer
Client->>Lambda: Invoke (event)
Lambda->>Persistence Layer: Get or set (id=event.search(payload))
activate Persistence Layer
Note right of Persistence Layer: Locked during this time. Prevents multiple<br/>Lambda invocations with the same<br/>payload running concurrently.
Lambda--xLambda: Call handler (event).<br/>Raises exception
Lambda->>Persistence Layer: Delete record (id=event.search(payload))
deactivate Persistence Layer
Lambda-->>Client: Return error response
Idempotent sequence exception
If an Exception is raised outside the scope of a decorated method and after your method has been called, the persistent record will not be affected. In this case, idempotency will be maintained for your decorated function. Example:
Exception not affecting idempotency record sample | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
Warning
We will throw an IdempotencyPersistenceLayerException
if any of the calls to the persistence layer fail unexpectedly.
As this happens outside the scope of your decorated function, you are not able to catch it.
Persistence stores¶
DynamoDBPersistenceStore¶
This persistence store is built-in, and you can either use an existing DynamoDB table or create a new one dedicated for idempotency state (recommended).
Use the builder to customize the table structure:
Customizing DynamoDBPersistenceStore to suit your table structure | |
---|---|
1 2 3 4 5 6 7 8 |
|
When using DynamoDB as a persistence layer, you can alter the attribute names by passing these parameters when initializing the persistence layer:
Parameter | Required | Default | Description |
---|---|---|---|
TableName | Y | Table name to store state | |
KeyAttr | id |
Partition key of the table. Hashed representation of the payload (unless SortKeyAttr is specified) | |
ExpiryAttr | expiration |
Unix timestamp of when record expires | |
StatusAttr | status |
Stores status of the Lambda execution during and after invocation | |
DataAttr | data |
Stores results of successfully idempotent methods | |
ValidationAttr | validation |
Hashed representation of the parts of the event used for validation | |
SortKeyAttr | Sort key of the table (if table is configured with a sort key). | ||
StaticPkValue | idempotency#{LAMBDA_FUNCTION_NAME} |
Static value to use as the partition key. Only used when SortKeyAttr is set. |
Advanced¶
Customizing the default behavior¶
Idempotency behavior can be further configured with IdempotencyConfig
using a builder:
Customizing IdempotencyConfig | |
---|---|
1 2 3 4 5 6 7 8 9 |
|
These are the available options for further configuration:
Parameter | Default | Description |
---|---|---|
EventKeyJMESPath | "" |
JMESPath expression to extract the idempotency key from the event record. See available built-in functions |
PayloadValidationJMESPath | "" |
JMESPath expression to validate whether certain parameters have changed in the event |
ThrowOnNoIdempotencyKey | False |
Throw exception if no idempotency key was found in the request |
ExpirationInSeconds | 3600 | The number of seconds to wait before a record is expired |
UseLocalCache | false |
Whether to locally cache idempotency results (LRU cache) |
LocalCacheMaxItems | 256 | Max number of items to store in local cache |
HashFunction | MD5 |
Algorithm to use for calculating hashes, as supported by java.security.MessageDigest (eg. SHA-1, SHA-256, ...) |
These features are detailed below.
Handling concurrent executions with the same payload¶
This utility will throw an IdempotencyAlreadyInProgressException
if we receive multiple invocations with the same payload while the first invocation hasn't completed yet.
Info
If you receive IdempotencyAlreadyInProgressException
, you can safely retry the operation.
This is a locking mechanism for correctness. Since we don't know the result from the first invocation yet, we can't safely allow another concurrent execution.
Using in-memory cache¶
By default, in-memory local caching is disabled, to avoid using memory in an unpredictable way.
Warning
Be sure to configure the Lambda memory according to the number of records and the potential size of each record.
You can enable it as seen before with:
Enable local cache | |
---|---|
1 2 3 |
|
LocalCacheMaxItems
parameter.
Note: This in-memory cache is local to each Lambda execution environment
This means it will be effective in cases where your function's concurrency is low in comparison to the number of "retry" invocations with the same payload, because cache might be empty.
Expiring idempotency records¶
Note
By default, we expire idempotency records after an hour (3600 seconds).
In most cases, it is not desirable to store the idempotency records forever. Rather, you want to guarantee that the same payload won't be executed within a period of time.
You can change this window with the ExpirationInSeconds
parameter:
Customizing expiration time | |
---|---|
1 2 3 |
|
Records older than 5 minutes will be marked as expired, and the Lambda handler will be executed normally even if it is invoked with a matching payload.
Note: DynamoDB time-to-live field
This utility uses expiration
as the TTL field in DynamoDB, as demonstrated in the SAM example earlier.
Payload validation¶
Question: What if your function is invoked with the same payload except some outer parameters have changed?
Example: A payment transaction for a given productID was requested twice for the same customer, however the amount to be paid has changed in the second transaction.
By default, we will return the same result as it returned before, however in this instance it may be misleading; we provide a fail fast payload validation to address this edge case.
With PayloadValidationJMESPath
, you can provide an additional JMESPath expression to specify which part of the event body should be validated against previous idempotent invocations
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
|
1 2 3 4 5 6 7 8 9 |
|
1 2 3 4 5 6 7 8 9 |
|
In this example, the userDetail
and productId
keys are used as the payload to generate the idempotency key, as per EventKeyJMESPath
parameter.
Note
If we try to send the same request but with a different amount, we will raise IdempotencyValidationException
.
Without payload validation, we would have returned the same result as we did for the initial request. Since we're also returning an amount in the response, this could be quite confusing for the client.
By using withPayloadValidationJMESPath("amount")
, we prevent this potentially confusing behavior and instead throw an Exception.
Making idempotency key required¶
If you want to enforce that an idempotency key is required, you can set ThrowOnNoIdempotencyKey
to true
.
This means that we will throw IdempotencyKeyException
if the evaluation of EventKeyJMESPath
is null
.
When set to false
(the default), if the idempotency key is null, then the data is not persisted in the store.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
1 2 3 4 5 6 7 |
|
Notice that orderId
is now accidentally within user
key
1 2 3 4 5 6 7 |
|
Customizing DynamoDB configuration¶
When creating the DynamoDBPersistenceStore
, you can set a custom DynamoDbClient
if you need to customize the configuration:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
Default configuration is the following:
1 2 3 4 5 |
|
Using a DynamoDB table with a composite primary key¶
When using a composite primary key table (hash+range key), use SortKeyAttr
parameter when initializing your persistence store.
With this setting, we will save the idempotency key in the sort key instead of the primary key. By default, the primary key will now be set to idempotency#{LAMBDA_FUNCTION_NAME}
.
You can optionally set a static value for the partition key using the StaticPkValue
parameter.
Reusing a DynamoDB table that uses a composite primary key | |
---|---|
1 2 3 4 5 6 |
|
Data would then be stored in DynamoDB like this:
id | sort_key | expiration | status | data |
---|---|---|---|---|
idempotency#MyLambdaFunction | 1e956ef7da78d0cb890be999aecc0c9e | 1636549553 | COMPLETED | {"id": 12391, "message": "success"} |
idempotency#MyLambdaFunction | 2b2cdb5f86361e97b4383087c1ffdf27 | 1636549571 | COMPLETED | {"id": 527212, "message": "success"} |
idempotency#MyLambdaFunction | f091d2527ad1c78f05d54cc3f363be80 | 1636549585 | IN_PROGRESS |
Bring your own persistent store¶
This utility provides an abstract base class, so that you can implement your choice of persistent storage layer.
You can extend the BasePersistenceStore
class and implement the abstract methods getRecord
, putRecord
,
updateRecord
and deleteRecord
. You can have a look at DynamoDBPersistenceStore
as an implementation reference.
Danger
Pay attention to the documentation for each method - you may need to perform additional checks inside these methods to ensure the idempotency guarantees remain intact.
For example, the putRecord
method needs to throw an exception if a non-expired record already exists in the data store with a matching key.
Compatibility with other utilities¶
Validation utility¶
The idempotency utility can be used with the @Validation
annotation from the validation module. Ensure that idempotency is the innermost annotation.
Using Idempotency with JSONSchema Validation utility | |
---|---|
1 2 3 4 5 |
|
Tip: JMESPath Powertools for AWS Lambda (Java) functions are also available
Built-in functions like powertools_json
, powertools_base64
, powertools_base64_gzip
are also available to use in this utility. See JMESPath Powertools for AWS Lambda (Java) functions
Testing your code¶
The idempotency utility provides several routes to test your code.
Disabling the idempotency utility¶
When testing your code, you may wish to disable the idempotency logic altogether and focus on testing your business logic. To do this, you can set the environment variable POWERTOOLS_IDEMPOTENCY_DISABLED
to true.
If you prefer setting this for specific tests, and are using JUnit 5, you can use junit-pioneer library:
1 2 3 4 5 6 |
|
You can also disable the idempotency for all tests using maven-surefire-plugin
and adding the environment variable:
1 2 3 4 5 6 7 8 9 |
|
Testing with DynamoDB Local¶
Unit tests¶
To unit test your function with DynamoDB Local, you can refer to this guide to setup with Maven.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
SAM Local¶
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
|
1 2 3 4 5 |
|
Extra resources¶
If you're interested in a deep dive on how Amazon uses idempotency when building our APIs, check out this article.