Stripe delivers webhooks at least once. The same checkout.session.completed or customer.subscription.updated can hit your endpoint twice when a worker times out, you return HTTP 500, or the network blips mid-request. Idempotent Stripe webhook handling with event.id in your database is how you keep subscription rows correct and stop welcome emails, credit grants, and analytics from firing twice.
This guide goes deeper than the sketch in subscription sync with Prisma. You already verify signatures with request.text() and upsert on checkout.session.completed. Here we separate state upserts from side effects, lock processing with a StripeEvent table, and choose HTTP status codes so retries help instead of hurt.
Why upserts alone are not enough
Prisma upsert on stripeSubscriptionId makes database state converge when Stripe retries the same event. That is necessary but insufficient when your handler also:
Sends a “Thanks for subscribing” email
Grants onboarding credits or API quota
Creates a row in an
AuditLogor analytics pipelineCalls a fulfillment webhook to Zapier
Those actions are not naturally idempotent unless you key them by something Stripe stabilizes across retries: event.id (globally unique per delivery attempt cluster) or a durable resource id (session.id, invoice.id) combined with event type.
Operation Safe on retry without event.id? Notes Upsert Subscription by subscription.id Usually yes Same payload → same row Set User.stripeCustomerId once Risky Second delivery may noop or error resend.emails.send welcome No User gets two emails credits.create({ amount: 100 }) No Double credits Insert AuditLog per handler run No Duplicate audit noise
The fix: record event.id before irreversible work, or use a dedupe table per side effect (heavier). For most Next.js SaaS apps, one StripeEvent row per Stripe event id is enough.
Prerequisites
App Router route at
app/api/stripe/webhook/route.tswith signature verification (see the signature article in this series).Prisma with at least
User,Subscription, and room forStripeEvent.Handlers for events you care about (checkout completed pattern in checkout session + subscription).
Step 1: Add a StripeEvent model
Every processed Stripe event gets one row. The unique constraint is the enforcement layer.
model StripeEvent {
id String @id @default(cuid())
eventId String @unique
type String
createdAt DateTime @default(now())
}
Run npx prisma migrate dev --name add-stripe-event.
Why store type? Debugging and dashboards. When support asks “did we see invoice.paid for this customer?”, you search by eventId or filter by type and time.
Retention: Stripe event ids are stable forever. For high volume, archive rows older than 90 days to a cold store if the table grows. Do not delete until you are confident no manual replays need the audit trail.
Step 2: Claim the event before handling
Naive flow (from the sync guide):
findUnique({ eventId })→ if found, return 200.create({ eventId }).Run handlers.
Two concurrent requests with the same new event.id can both pass step 1, both create, and one throws unique violation. Treat that as success.
Recommended: create-first with unique constraint
import { Prisma } from "@prisma/client";
async function claimStripeEvent(event: Stripe.Event): Promise<boolean> {
try {
await db.stripeEvent.create({
data: { eventId: event.id, type: event.type },
});
return true;
} catch (error) {
if (
error instanceof Prisma.PrismaClientKnownRequestError &&
error.code === "P2002"
) {
return false;
}
throw error;
}
}
true: this request owns the event; run handlers.false: another worker already claimed it; return200immediately.
This pattern is an idempotent stripe webhook event.id database guard without a separate distributed lock.
Alternative: transaction + handler in one transaction
Prisma transactions work well when all side effects are DB-only. External APIs (email, Stripe API calls) do not roll back with the transaction. Prefer claim row first, then side effects, with outbox pattern if you need exactly-once email delivery later.
Step 3: Wire the webhook route
Keep raw body verification first. Only after constructEvent succeeds, claim and dispatch.
export const runtime = "nodejs";
export async function POST(request: Request) {
const body = await request.text();
const signature = (await headers()).get("stripe-signature");
if (!signature || !process.env.STRIPE_WEBHOOK_SECRET) {
return NextResponse.json({ error: "Missing signature" }, { status: 400 });
}
let event: Stripe.Event;
try {
event = stripe.webhooks.constructEvent(
body,
signature,
process.env.STRIPE_WEBHOOK_SECRET,
);
} catch (error) {
console.error("Stripe signature failed");
return NextResponse.json({ error: "Invalid signature" }, { status: 400 });
}
const shouldHandle = await claimStripeEvent(event);
if (!shouldHandle) {
return NextResponse.json({ received: true });
}
try {
await dispatchStripeEvent(event);
} catch (error) {
// Log for replay from Dashboard; see troubleshooting
console.error("Handler failed", event.type, event.id, error);
await db.stripeEvent.delete({ where: { eventId: event.id } }).catch(() => {});
return NextResponse.json({ error: "Handler error" }, { status: 500 });
}
return NextResponse.json({ received: true });
}
Deleting the claim on 500 is optional. If you keep the row, Stripe retries never re-run the handler until you delete the row or use a failedAt column and admin replay tool. Many teams keep the row and alert on failures; others delete so automatic retries can succeed after a deploy fix. Pick one policy and document it.
Step 4: Dispatch by event type
Keep dispatchStripeEvent boring: one switch, pure upserts inside, guarded side effects outside.
async function dispatchStripeEvent(event: Stripe.Event) {
switch (event.type) {
case "checkout.session.completed":
await onCheckoutCompleted(event);
break;
case "customer.subscription.updated":
case "customer.subscription.deleted":
await onSubscriptionChanged(event);
break;
case "invoice.paid":
await onInvoicePaid(event);
break;
default:
break;
}
}
Side effects inside onCheckoutCompleted should still use stable keys:
async function onCheckoutCompleted(event: Stripe.Event) {
const session = event.data.object as Stripe.Checkout.Session;
const userId = session.metadata?.userId;
if (!userId || !session.subscription) return;
const subscription = await stripe.subscriptions.retrieve(
session.subscription as string,
);
await upsertSubscription(userId, subscription);
// Idempotent welcome: key email by session.id, not only event.id
const alreadyEmailed = await db.checkoutEmailLog.findUnique({
where: { checkoutSessionId: session.id },
});
if (!alreadyEmailed) {
await sendWelcomeEmail(userId);
await db.checkoutEmailLog.create({
data: { checkoutSessionId: session.id, userId },
});
}
}
event.id dedupes whole handler runs. Per-resource tables dedupe individual side effects when multiple Stripe events could trigger the same email (e.g. invoice.paid and checkout.session.completed).
Step 5: HTTP status codes and Stripe retries
Response Stripe behavior 200 Success; stop retrying this delivery 400 on bad signature No retry; fix endpoint secret 500 on handler crash Retries with backoff
Return 400 only before you trust the payload. After verification, business failures are usually 500 or 200 plus internal alerting, not 400.
Never return 401 from Auth middleware on the webhook path (see middleware dashboard protection): Stripe is not logged in.
Step 6: Test duplicate delivery locally
After Stripe CLI listen:
stripe trigger checkout.session.completed
Trigger twice, or re-send the same event from the Dashboard Send test webhook while watching logs:
First request:
claimStripeEvent→true; handler runs.Second request:
false; handler skipped; still200.
Confirm Prisma: one StripeEvent row, one welcome email log row, one subscription upsert state.
Step 7: Plan gates stay webhook-driven
Plan gating should read Prisma Subscription.status, not “user returned from Checkout once.” Idempotency on webhooks keeps that read path consistent when retries arrive out of order (subscription.updated before checkout.session.completed). Upserts on Stripe ids absorb reordering; event.id stops duplicate emails during the messy middle.
Troubleshooting
Duplicate welcome emails still happen
You claimed event.id but email uses only event.id while two different event types both send welcome. Add checkoutSessionId or subscriptionId unique logs.
P2002 but handler never ran
Request A created the row then crashed before work finished. Request B sees duplicate and returns 200. Mitigation: status column on StripeEvent (processing, done, failed) or delete-on-failure policy.
Handler slow; Stripe retries while first still running
Two workers, same event.id: second hits P2002 and exits. Good. If you used find-then-create without try/catch, you could double-run. Prefer create-first.
Logging
Log event.type and event.id after verification, not raw card data or full customer objects.
Production checklist
Unique index on
StripeEvent.eventIdWebhook excluded from Auth middleware
runtime = "nodejs"on routeSide effects keyed by
event.idand/or Stripe resource ids200 on duplicate
event.idPlaybook for failed handlers (delete row vs manual replay)
Step 8: Extended event matrix
Event DB state safe on retry? Typical side effect needing dedupe checkout.session.completed Upsert subscription Welcome email, analytics customer.subscription.updated Upsert subscription Slack notify sales customer.subscription.deleted Upsert → canceled Offboarding survey invoice.paid Upsert period Receipt email, revenue event invoice.payment_failed Status past_due Dunning email sequence
Use event.id for “run handler once.” Use resource ids when different event types can trigger the same email.
Step 9: Observability without leaking secrets
Log structured fields:
console.info("stripe_webhook", {
eventId: event.id,
type: event.type,
claimed: shouldHandle,
});
Never log full payment methods or customer email from webhook JSON in production aggregators.
Stripe Dashboard → Developers → Webhooks shows delivery attempts. Correlate with your StripeEvent row by eventId.
Step 10: Outbox pattern (when email must be exactly-once)
If claim-then-send still races with partial failures, write an EmailOutbox row in the same transaction as StripeEvent claim, then a worker sends email and marks sentAt. That is beyond a single route but common at scale. Many startups start with event.id claim plus checkoutSessionId unique on welcome mail.
Step 11: Replays and Stripe support
Support may ask you to reprocess an event. Workflow:
Find
event.idin logs or Dashboard.Delete local
StripeEventrow if policy allows replay.Use Dashboard “Resend” or fetch event via Stripe API and call internal
dispatchStripeEventfrom a guarded admin command.
Do not expose a public replay endpoint.
Step 12: Multi-region and serverless caveats
Each serverless instance can still race findUnique without unique constraint. Always rely on database unique eventId, not in-memory locks. Cold starts do not change Stripe’s retry semantics.
Step 13: Testing idempotency in CI
Spin Prisma against SQLite or test DB, POST fixture twice with mocked constructEvent return value (same event.id). Assert handler mock called once. Vitest/Jest with fetch mock keeps regression from refactors.
Step 14: Ordering when events arrive out of sequence
Stripe does not guarantee that checkout.session.completed arrives before every customer.subscription.updated. Upserts keyed by subscription.id absorb reordering. Side effects that assume checkout always ran first (provisioning default project) should wait until userId exists in metadata or look up by stripeCustomerId.
Document per-handler prerequisites so on-call knows a missing row is timing, not data loss.
Step 15: When not to claim early
Some teams insert StripeEvent only after successful handler completion. That allows full automatic retries on failure but risks duplicate side effects if the handler succeeds and the insert fails. Claim-first is the default for email-heavy SaaS; complete-first suits pure DB transforms with transactional safety.
Pick explicitly in your runbook.
Step 16: Dashboard alerts for stuck webhooks
Monitor counts of:
New
StripeEventrows per hour vs Stripe Dashboard delivery countHandler 500 rate on
/api/stripe/webhookRows older than five minutes with a planned
processingstate if you add one
Misconfigured secrets show up as 400 spikes; handler bugs show as 500 with Stripe retries.
Step 17: Customer Portal and duplicate updates
Users toggling cancel in the Customer Portal may generate several subscription.updated events quickly. Idempotency on event.id dedupes each delivery; subscription upsert still runs once per unique event. UI should read DB state after webhooks, not optimistic client flags.
Stripe-ready idempotency in the kit
AI SaaS Starter Kit from Skryptix includes:
Signature-verified
/api/stripe/webhookPrisma subscription sync and
StripeEvent-style dedupe patternsCheckout, Customer Portal, Auth.js, and plan gates
Local Stripe CLI workflow docs
FAQ
What is Stripe webhook idempotency?
Processing the same Stripe event more than once does not duplicate side effects. Store Stripe’s event.id in your database with a unique constraint; skip handler logic when the id already exists.
Is event.id the same when Stripe retries?
Yes. Retries for a given event delivery use the same event.id. A new billing attempt generates a new event with a new id.
Should I return 200 or 409 for duplicate events?
Return 200 with { received: true }. Stripe treats non-2xx as failure and retries. Duplicates are expected, not errors.
Can I use Redis instead of Postgres for dedupe?
Yes for high throughput (SET key NX EX). A SQL unique index is simpler for most SaaS and matches Prisma. Same idea: claim event.id before handlers.
Does idempotency replace subscription upserts?
No. Keep upserting Subscription by stripeSubscriptionId. Idempotency protects emails, credits, and one-time inserts.
What if my handler needs to run again after a bug fix?
Delete the StripeEvent row for that event.id and replay from Stripe Dashboard, or build an admin “reprocess event id” tool that deletes the row and fetches the event from Stripe API.
How long should I store event.id rows?
At least 30–90 days for support debugging. Stripe’s id space does not collide; size is the only concern.
Does idempotency help with Stripe CLI test events?
Yes. Re-forwarding the same CLI event id during development should hit your dupl
