The IdempotencyConfig class provides extensive configuration options for customizing idempotency behavior, including JMESPath expressions, caching, expiry, hash functions, and payload validation.
Configures the behavior of the idempotency utility with options for key extraction, caching, expiry, and validation.
/**
* Configuration class for the idempotency feature.
* Controls how idempotency keys are extracted, how long records persist,
* whether to use local caching, and payload validation behavior.
*
* @param config - Configuration options
*/
class IdempotencyConfig {
constructor(config: IdempotencyConfigOptions);
/** JMESPath expression to extract the idempotency key from the event (default: '') */
public eventKeyJmesPath: string;
/** Number of seconds idempotency keys are valid (default: 3600 = 1 hour) */
public expiresAfterSeconds: number;
/** Hash function used to generate idempotency keys (default: 'md5') */
public hashFunction: string;
/** Options for parsing JMESPath expressions with custom functions */
public jmesPathOptions: JMESPathParsingOptions;
/** AWS Lambda context object for timeout tracking */
public lambdaContext?: Context;
/** Maximum number of items to store in local cache (default: 1000) */
public maxLocalCacheSize: number;
/** JMESPath expression to extract payload for validation */
public payloadValidationJmesPath?: string;
/** Throw error if idempotency key not found (default: false) */
public throwOnNoIdempotencyKey: boolean;
/** Hook that runs when an idempotent request is made */
public responseHook?: ResponseHook;
/** Use local cache to store idempotency keys (default: false) */
public useLocalCache: boolean;
/**
* Determines if the idempotency feature is enabled.
* Can be disabled via POWERTOOLS_IDEMPOTENCY_DISABLED environment variable.
*
* @returns True if idempotency is enabled
*/
public isEnabled(): boolean;
/**
* Register AWS Lambda context for timeout tracking.
* Automatically called for Lambda handlers.
*
* @param context - AWS Lambda context object
*/
public registerLambdaContext(context: Context): void;
}
interface IdempotencyConfigOptions {
/** JMESPath expression to extract the idempotency key from event */
eventKeyJmesPath?: string;
/** JMESPath expression to extract payload for validation */
payloadValidationJmesPath?: string;
/** Custom JMESPath functions */
jmesPathOptions?: Functions;
/** Throw error if no idempotency key found (default: false) */
throwOnNoIdempotencyKey?: boolean;
/** Seconds before record expires (default: 3600) */
expiresAfterSeconds?: number;
/** Enable local caching (default: false) */
useLocalCache?: boolean;
/** Max local cache size (default: 1000) */
maxLocalCacheSize?: number;
/** Hash function name (default: 'md5') */
hashFunction?: string;
/** AWS Lambda context object */
lambdaContext?: Context;
/** Hook for idempotent responses */
responseHook?: ResponseHook;
}
type ResponseHook = (response: JSONValue, record: IdempotencyRecord) => JSONValue;Usage Examples:
Basic Configuration
import { IdempotencyConfig } from '@aws-lambda-powertools/idempotency';
import { DynamoDBPersistenceLayer } from '@aws-lambda-powertools/idempotency/dynamodb';
import { makeIdempotent } from '@aws-lambda-powertools/idempotency';
const persistenceStore = new DynamoDBPersistenceLayer({
tableName: 'idempotencyTable',
});
// Use default configuration
const config = new IdempotencyConfig({});
const myHandler = async (event: any, context: any) => {
// Your logic
};
export const handler = makeIdempotent(myHandler, { persistenceStore, config });JMESPath for Idempotency Key
import { IdempotencyConfig } from '@aws-lambda-powertools/idempotency';
import { DynamoDBPersistenceLayer } from '@aws-lambda-powertools/idempotency/dynamodb';
import { makeIdempotent } from '@aws-lambda-powertools/idempotency';
const persistenceStore = new DynamoDBPersistenceLayer({
tableName: 'idempotencyTable',
});
// Extract only specific fields for the idempotency key
const config = new IdempotencyConfig({
eventKeyJmesPath: 'requestContext.identity.user',
});
const myHandler = async (event: any, context: any) => {
// Only the 'user' field is used for idempotency
};
export const handler = makeIdempotent(myHandler, { persistenceStore, config });JMESPath with Built-in Functions
import { IdempotencyConfig } from '@aws-lambda-powertools/idempotency';
import { DynamoDBPersistenceLayer } from '@aws-lambda-powertools/idempotency/dynamodb';
import { makeIdempotent } from '@aws-lambda-powertools/idempotency';
const persistenceStore = new DynamoDBPersistenceLayer({
tableName: 'idempotencyTable',
});
// Use powertools_json() to decode JSON body and extract fields
const config = new IdempotencyConfig({
eventKeyJmesPath: 'powertools_json(body).["userId", "orderId"]',
});
const myHandler = async (event: any, context: any) => {
// Only userId and orderId from the JSON body are used
};
export const handler = makeIdempotent(myHandler, { persistenceStore, config });Payload Validation
import { IdempotencyConfig } from '@aws-lambda-powertools/idempotency';
import { DynamoDBPersistenceLayer } from '@aws-lambda-powertools/idempotency/dynamodb';
import { makeIdempotent } from '@aws-lambda-powertools/idempotency';
const persistenceStore = new DynamoDBPersistenceLayer({
tableName: 'idempotencyTable',
});
// Validate that the full payload hasn't changed
const config = new IdempotencyConfig({
eventKeyJmesPath: 'orderId', // Use orderId as key
payloadValidationJmesPath: 'orderData', // Validate orderData hasn't changed
});
const myHandler = async (event: any, context: any) => {
// Throws IdempotencyValidationError if orderData differs
};
export const handler = makeIdempotent(myHandler, { persistenceStore, config });Local Caching
import { IdempotencyConfig } from '@aws-lambda-powertools/idempotency';
import { DynamoDBPersistenceLayer } from '@aws-lambda-powertools/idempotency/dynamodb';
import { makeIdempotent } from '@aws-lambda-powertools/idempotency';
const persistenceStore = new DynamoDBPersistenceLayer({
tableName: 'idempotencyTable',
});
// Enable local caching to reduce database calls
const config = new IdempotencyConfig({
useLocalCache: true,
maxLocalCacheSize: 500, // Cache up to 500 records
});
const myHandler = async (event: any, context: any) => {
// Subsequent requests check local cache first
};
export const handler = makeIdempotent(myHandler, { persistenceStore, config });Custom Expiry Time
import { IdempotencyConfig } from '@aws-lambda-powertools/idempotency';
import { DynamoDBPersistenceLayer } from '@aws-lambda-powertools/idempotency/dynamodb';
import { makeIdempotent } from '@aws-lambda-powertools/idempotency';
const persistenceStore = new DynamoDBPersistenceLayer({
tableName: 'idempotencyTable',
});
// Records expire after 5 minutes
const config = new IdempotencyConfig({
expiresAfterSeconds: 300,
});
const myHandler = async (event: any, context: any) => {
// Your logic
};
export const handler = makeIdempotent(myHandler, { persistenceStore, config });Custom Hash Function
import { IdempotencyConfig } from '@aws-lambda-powertools/idempotency';
import { DynamoDBPersistenceLayer } from '@aws-lambda-powertools/idempotency/dynamodb';
import { makeIdempotent } from '@aws-lambda-powertools/idempotency';
const persistenceStore = new DynamoDBPersistenceLayer({
tableName: 'idempotencyTable',
});
// Use SHA-256 instead of MD5
const config = new IdempotencyConfig({
hashFunction: 'sha256',
});
const myHandler = async (event: any, context: any) => {
// Your logic
};
export const handler = makeIdempotent(myHandler, { persistenceStore, config });Throw on Missing Key
import { IdempotencyConfig } from '@aws-lambda-powertools/idempotency';
import { DynamoDBPersistenceLayer } from '@aws-lambda-powertools/idempotency/dynamodb';
import { makeIdempotent } from '@aws-lambda-powertools/idempotency';
const persistenceStore = new DynamoDBPersistenceLayer({
tableName: 'idempotencyTable',
});
// Throw error if idempotency key cannot be extracted
const config = new IdempotencyConfig({
eventKeyJmesPath: 'headers."idempotency-key"',
throwOnNoIdempotencyKey: true, // Fail fast if key missing
});
const myHandler = async (event: any, context: any) => {
// Throws IdempotencyKeyError if header is missing
};
export const handler = makeIdempotent(myHandler, { persistenceStore, config });Response Hook
import { IdempotencyConfig } from '@aws-lambda-powertools/idempotency';
import { DynamoDBPersistenceLayer } from '@aws-lambda-powertools/idempotency/dynamodb';
import { makeIdempotent } from '@aws-lambda-powertools/idempotency';
import type { JSONValue } from '@aws-lambda-powertools/commons/types';
import type { IdempotencyRecord } from '@aws-lambda-powertools/idempotency/persistence';
const persistenceStore = new DynamoDBPersistenceLayer({
tableName: 'idempotencyTable',
});
// Add custom logic when returning idempotent responses
const config = new IdempotencyConfig({
responseHook: (response: JSONValue, record: IdempotencyRecord) => {
// Modify response to indicate it was cached
return {
...response,
fromCache: true,
cachedAt: record.expiryTimestamp,
};
},
});
const myHandler = async (event: any, context: any) => {
return { statusCode: 200, body: 'Success' };
};
export const handler = makeIdempotent(myHandler, { persistenceStore, config });Complete Configuration
import { IdempotencyConfig } from '@aws-lambda-powertools/idempotency';
import { DynamoDBPersistenceLayer } from '@aws-lambda-powertools/idempotency/dynamodb';
import { makeIdempotent } from '@aws-lambda-powertools/idempotency';
const persistenceStore = new DynamoDBPersistenceLayer({
tableName: 'idempotencyTable',
});
const config = new IdempotencyConfig({
eventKeyJmesPath: 'powertools_json(body).transactionId',
payloadValidationJmesPath: 'powertools_json(body).amount',
throwOnNoIdempotencyKey: true,
expiresAfterSeconds: 1800, // 30 minutes
useLocalCache: true,
maxLocalCacheSize: 100,
hashFunction: 'sha256',
responseHook: (response, record) => ({
...response,
idempotent: true,
}),
});
const myHandler = async (event: any, context: any) => {
// Your logic
};
export const handler = makeIdempotent(myHandler, { persistenceStore, config });Extracts a subset of the event payload to use as the idempotency key. Useful when the event contains timestamps or request IDs that change between retries.
Example: 'requestContext.requestId', 'body.userId', 'Records[0].messageId'
Validates that specific parts of the payload haven't changed. Throws IdempotencyValidationError if the payload differs from the stored record.
Example: 'body', 'orderDetails'
Controls behavior when the idempotency key cannot be extracted:
false (default): Logs a warning and continues without idempotencytrue: Throws IdempotencyKeyErrorTime in seconds before idempotency records expire and can be reused.
3600 (1 hour)Enables in-memory caching of idempotency records within the Lambda execution environment.
falseMaximum number of records to keep in the local cache.
1000Hash algorithm to generate idempotency keys from payload data.
'md5'crypto.createHash()'sha256', 'sha512', 'sha1'Function called when returning a cached idempotent response. Allows modifying the response before returning it.
AWS Lambda context object, automatically registered for Lambda handlers to track timeouts.
Set the environment variable POWERTOOLS_IDEMPOTENCY_DISABLED=true to completely disable idempotency. The function will execute normally without any idempotency checks.
POWERTOOLS_IDEMPOTENCY_DISABLED=trueCheck if idempotency is enabled:
const config = new IdempotencyConfig({});
if (config.isEnabled()) {
// Idempotency is active
}