If your Lambda receives payment or booking webhooks, wrap the processing in Powertools’ makeIdempotent and change two defaults: the key (use the event ID, not the whole event) and the expiry (longer than the sender’s retry window). It takes one DynamoDB table and about 20 lines.
The problem it solves
A webhook is an HTTP call another system makes to you when something happens: a payment goes through, a subscription renews, a new appointment is booked. If your endpoint is slow, fails or returns an error, the sender tries again. Stripe’s documentation is explicit: in live mode it retries delivery “for up to three days” with exponential back-off, and it warns that your endpoint “might occasionally receive the same event more than once”.
For most functions that doesn’t matter. For one that activates a subscription, sends a receipt or takes a slot out of the calendar, it does: the same event processed twice is a duplicate email at best and a double booking at worst.
The fix has a name: idempotency. An operation is idempotent if running it once or ten times leaves the system in the same state. Stripe suggests logging the IDs of events you’ve already processed and skipping repeats. You can write that yourself or use a library that already gets it right.
What the Powertools idempotency utility is
Powertools for AWS Lambda (TypeScript) is a set of official AWS utilities for Lambda. The idempotency one, in the @aws-lambda-powertools/idempotency package (version 2.36.0 on npm as of today), works like this:
- It hashes the part of the event you choose and uses it as the key.
- Before running your code, it stores an “in progress” record with that key in DynamoDB.
- If your code succeeds, it stores the result. When a retry arrives with the same key, it returns that result without running anything again.
- If your code throws, it deletes the record so the next retry can actually run.
- If a duplicate arrives while the first call is still running, it throws
IdempotencyAlreadyInProgressError. Your endpoint returns an error and the sender retries later.
Records expire after one hour by default (expiresAfterSeconds: 3600).
How to use it
1. Install the packages.
npm i @aws-lambda-powertools/idempotency @aws-sdk/client-dynamodb @aws-sdk/lib-dynamodb
2. Create the table. The utility expects a string partition key named id and stores the expiry in an expiration attribute. Turn on DynamoDB TTL for that attribute so old records clean themselves up. With CDK:
const table = new dynamodb.TableV2(this, 'Idempotency', {
partitionKey: { name: 'id', type: dynamodb.AttributeType.STRING },
timeToLiveAttribute: 'expiration',
});
The function needs dynamodb:GetItem, PutItem, UpdateItem and DeleteItem on that table.
3. Make the processing idempotent, not the whole handler. This is the first trap. If you wrap the API Gateway handler as is, Powertools hashes the full event, headers included. Stripe generates a new signature and timestamp for every retry, so each retry would get a different key and the protection would do nothing. Verify the signature first, then make the function that processes the verified event idempotent, keyed on its id:
import { makeIdempotent, IdempotencyConfig } from '@aws-lambda-powertools/idempotency';
import { DynamoDBPersistenceLayer } from '@aws-lambda-powertools/idempotency/dynamodb';
import type { APIGatewayProxyEvent, Context } from 'aws-lambda';
import Stripe from 'stripe';
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
const persistenceStore = new DynamoDBPersistenceLayer({ tableName: process.env.IDEMPOTENCY_TABLE! });
const config = new IdempotencyConfig({
eventKeyJmesPath: 'id', // the Stripe event ID
expiresAfterSeconds: 4 * 24 * 60 * 60, // 4 days, longer than the 3-day retry window
});
const processEvent = makeIdempotent(
async (stripeEvent: Stripe.Event) => {
if (stripeEvent.type === 'invoice.paid') {
// activate the subscription, send the receipt…
}
return { processed: stripeEvent.id };
},
{ persistenceStore, config }
);
export const handler = async (event: APIGatewayProxyEvent, context: Context) => {
config.registerLambdaContext(context); // in case the Lambda runs out of time
const stripeEvent = stripe.webhooks.constructEvent(
event.body!,
event.headers['Stripe-Signature']!, // lowercase on HTTP APIs
process.env.STRIPE_WEBHOOK_SECRET!
);
await processEvent(stripeEvent);
return { statusCode: 200, body: '' };
};
You need registerLambdaContext because the wrapped function isn’t the handler: it tells Powertools how much time the Lambda has left, so a timeout doesn’t leave an “in progress” record stuck. If the signature is invalid, return a 400 instead of letting a 500 bubble up; no number of retries will fix a bad signature.
4. Raise the expiry. The second trap is the one-hour default. If Stripe retries after five hours, the record is gone and the event gets processed again. Set expiresAfterSeconds to each sender’s retry window, with some margin.
5. For bookings from your own app, validate the content. If your frontend sends an Idempotency-Key header when someone taps “Book”, you can use it as the key and add payloadValidationJmesPath with the fields that matter:
const config = new IdempotencyConfig({
eventKeyJmesPath: 'headers."idempotency-key"',
payloadValidationJmesPath: 'powertools_json(body).[service, time]',
});
If the same key arrives with a different time, Powertools throws IdempotencyValidationError instead of quietly returning the earlier booking. That’s the gap between a harmless double tap and an app bug that mixes up two bookings.
My take
I’d add this to any webhook that moves money or calendar slots before launch, not after the first double charge. The cost is close to zero: an on-demand table with TTL and one extra write per event. The cost of skipping it lands on the customer, as a repeated receipt or a duplicate appointment, and then on you, as support time.
What I like most about Powertools is that it covers the odd cases nobody writes by hand: the duplicate that arrives while the first call is still running, the timeout halfway through, and the error that has to allow a retry. What I don’t like is that the defaults suit a demo, not a real webhook. Hashing the whole event and expiring after an hour works in the example and breaks with Stripe.
Two limits worth knowing. Idempotency protects your function, not what sits behind it: if your code calls another API that charges money, that call needs its own idempotency key too. And it doesn’t replace responding fast: Stripe asks you to return a 2xx before any heavy logic, so if your processing is slow, the next step is to push the event to an SQS queue and process it from there with the same utility.
Sources
- Powertools for AWS Lambda (TypeScript): Idempotency
- IdempotencyConfig reference (Powertools TypeScript)
- AWS Compute Blog: Implementing idempotent AWS Lambda functions with Powertools for AWS Lambda (TypeScript)
- Stripe: Receive Stripe events in your webhook endpoint
- @aws-lambda-powertools/idempotency on npm
If you want to see how I build SaaS on AWS serverless without a team, follow me on LinkedIn.
