the function to make idempotent
the options to configure the idempotency behavior
import { makeIdempotent, IdempotencyConfig } from '@aws-lambda-powertools/idempotency';
import { DynamoDBPersistenceLayer } from '@aws-lambda-powertools/idempotency/dynamodb';
const processRecord = (record: Record<string, unknown>): unknown => {
// your processing logic
return result;
};
const processIdempotently = makeIdempotent(processRecord, {
persistenceStore: new DynamoDBPersistenceLayer({ tableName: 'idempotency-table' }),
config: new IdempotencyConfig({
eventKeyJmesPath: 'transactionId', // hash only this field as idempotency key
}),
});
export const handler = async (event: { records: Record<string, unknown>[] }) => {
for (const record of event.records) {
// use the idempotent function
const result = await processIdempotently(record);
// ... do something with the result
}
};
Using a different function argument (useful for multi-parameter functions)
import { makeIdempotent } from '@aws-lambda-powertools/idempotency';
import { DynamoDBPersistenceLayer } from '@aws-lambda-powertools/idempotency/dynamodb';
const processRecord = (record: Record<string, unknown>, userId: string): unknown => {
// your processing logic
return result;
};
const processIdempotently = makeIdempotent(processRecord, {
persistenceStore: new DynamoDBPersistenceLayer({ tableName: 'idempotency-table' }),
dataIndexArgument: 1, // hash the userId (second argument) instead of first (record)
});
export const handler = async (event: { records: Record<string,unknown>[]; userId: string }) => {
for (const record of event.records) {
const userId = event.userId;
// use the idempotent function
const result = await processIdempotently(record, userId);
// ... do something with the result
}
};
Function wrapper to make any function idempotent.
The
makeIdempotentfunction is a higher-order function that takes another function and returns a new version of that function with idempotency behavior. This means that if the function is called multiple times with the same input, it will return the same result without re-executing the original function logic.By default, the entire first argument is hashed to create the idempotency key. You can customize this behavior:
eventKeyJmesPathto hash only a subset of the payloadItempotentFunctionOptions.dataIndexArgumentto hash a different function argumentUsing a subset of the payload