Stripe Idempotency Keys, Webhooks and Duplicate Customers

Stripe duplicate customers appear when your server calls the create endpoint twice for one user: a double click, a retry after a timeout, or Checkout without a customer ID. Fix it in three layers: save one customer ID per user and reuse it, lock creation, and send a Stripe idempotency key so retries return the first result.
Key takeaways
- A Stripe idempotency key makes a retried
POSTreturn the saved first response instead of creating a second object. Stripe keeps keys for at least 24 hours and can remove them after that, so the key is a retry guard, not your duplicate check. - The durable guard is your own database: one
stripe_customer_idper user, a unique constraint on it, and a row lock while the customer is being created. - Webhook signature verification needs the raw request body. Parsing JSON first is the most common reason
constructEventfails. - Stripe does not guarantee event order and can deliver the same event more than once. Record processed event IDs and fetch the current object from Stripe instead of trusting the order.
- Each fix below comes with a test you can run in test mode, so you can prove it works before a customer finds the gap.
Checked November 13, 2026 against Stripe's documentation on idempotent requests, error handling and webhooks, and the official stripe-node library (v23.1.0). Code samples use Node.js; the same calls exist in every official Stripe SDK.
Why does Stripe create duplicate customers?
The Create customer API has no field that makes an email unique, so every successful call returns a new cus_ ID. Duplicates appear whenever your code reaches that call twice for the same person. The usual paths are:
- Create on every checkout. The app creates a customer each time the user clicks Subscribe, instead of looking up the one it already made.
- Two requests at the same moment. A double click, a refresh, or two tabs both pass the "does this user have a customer yet?" check before either one saves the result.
- Retries without a key. The request reaches Stripe, the response is lost to a timeout, and your code or a queue retries it as a brand new request.
- Checkout without a customer. A Checkout Session in
subscriptionmode always needs a Customer, so if you do not passcustomer, Checkout creates one for that session.
This is a common finding in apps built with AI tools, because generated code tends to create the customer inline in the checkout handler. In one of our sample audit reports, two first-time requests created two payment customers for the same account. Billing history, refunds and cancellations then point at different records.
How do I stop duplicate customers in Stripe?
Create the customer in exactly one server function, store its ID against your user, and make that function safe to call twice. The sketch below uses PostgreSQL and the pg client; the pattern carries over to any database with row locks.
// Schema, once:
// ALTER TABLE users ADD COLUMN stripe_customer_id text UNIQUE;
// ALTER TABLE users ADD COLUMN stripe_create_key uuid NOT NULL DEFAULT gen_random_uuid();
import Stripe from 'stripe';
import pg from 'pg';
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
const pool = new pg.Pool();
export async function getOrCreateStripeCustomer(userId) {
const db = await pool.connect();
try {
await db.query('BEGIN');
// Lock this user's row. A second request for the same user waits here.
const { rows } = await db.query(
'SELECT email, stripe_customer_id, stripe_create_key FROM users WHERE id = $1 FOR UPDATE',
[userId]
);
const user = rows[0];
if (!user) throw new Error('Unknown user');
if (user.stripe_customer_id) {
await db.query('COMMIT');
return user.stripe_customer_id; // reuse, never create again
}
const customer = await stripe.customers.create(
{ email: user.email, metadata: { app_user_id: String(userId) } },
{ idempotencyKey: user.stripe_create_key } // random per user, stored, reused on retry
);
await db.query('UPDATE users SET stripe_customer_id = $1 WHERE id = $2', [customer.id, userId]);
await db.query('COMMIT');
return customer.id;
} catch (err) {
await db.query('ROLLBACK');
throw err;
} finally {
db.release();
}
}
What each part does:
- The saved ID is the real guard. Once
stripe_customer_idis set, the function returns it and never calls Stripe again. TheUNIQUEconstraint stops two users from pointing at one customer by mistake. - The row lock serializes creation.
SELECT ... FOR UPDATEmakes a second concurrent request wait until the first commits, and then it finds the saved ID. The trade-off is that the transaction stays open during one Stripe call, which is acceptable for a one-time action like this. - The idempotency key covers retries. Stripe's docs say retries with the same key return the saved response, including
500errors. The key here is a random UUID stored per user (PostgreSQL'sgen_random_uuid()makes a version 4 UUID), because Stripe recommends V4 UUIDs and asks you not to use email addresses or other personal identifiers as keys. - Metadata links the two systems. Stripe's error handling guide recommends putting a local identifier in metadata so an object that arrives through a webhook can be matched to your records.
Then pass the saved ID to every Checkout Session, so Checkout attaches the subscription to the existing customer instead of making a new one:
const customerId = await getOrCreateStripeCustomer(currentUser.id);
const session = await stripe.checkout.sessions.create({
mode: 'subscription',
customer: customerId, // without this, subscription Checkout creates a new customer
line_items: [{ price: process.env.STRIPE_PRICE_ID, quantity: 1 }],
success_url: 'https://example.com/billing/success',
cancel_url: 'https://example.com/billing',
});
What a Stripe idempotency key does and does not do
stripe-node also retries some failed requests on its own and adds idempotency keys where appropriate (network retries are on by default since v13). That protects a single SDK call. If your app retries across separate calls or process restarts, Stripe's guide says to generate and persist a key for the operation and send it with every attempt, which is what the stored per-user key does.
How do I clean up the duplicates I already have?
- List customers by email with
stripe.customers.list({ email }). The filter is an exact, case-sensitive match. Avoid the Search API for this kind of check right after a write: Stripe says search data is not immediately available and is normally searchable in under a minute. - For each person, keep the customer your database already points at and review the others in the Dashboard: which one holds the active subscription, the saved payment method and the invoices.
- Do not delete a duplicate that has history without checking it first. Deleting a customer cannot be undone and immediately cancels any active subscriptions on it.
How do I verify Stripe webhook signatures?
Pass the raw request body, the Stripe-Signature header and your endpoint secret to stripe.webhooks.constructEvent(), and reject the request if it throws. Stripe's documentation is explicit: it requires the raw body of the request, and any change to that body, including parsing and re-serializing JSON, makes verification fail. Without verification, anyone who finds the URL can post a fake checkout.session.completed and unlock a paid plan.
In Express, the webhook route needs express.raw() and must be registered before a global express.json(). This follows Stripe's official Express example:
import express from 'express';
import Stripe from 'stripe';
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
const endpointSecret = process.env.STRIPE_WEBHOOK_SECRET; // whsec_..., one per endpoint and mode
const app = express();
// Register the webhook route BEFORE any global express.json(),
// and give it the raw body as a Buffer.
app.post('/webhooks/stripe', express.raw({ type: 'application/json' }), async (req, res) => {
let event;
try {
event = stripe.webhooks.constructEvent(req.body, req.headers['stripe-signature'], endpointSecret);
} catch (err) {
return res.status(400).send(`Webhook Error: ${err.message}`);
}
try {
await handleEvent(event); // keep this fast, or enqueue the work
} catch (err) {
return res.status(500).end(); // non-2xx: Stripe retries the delivery
}
res.json({ received: true });
});
app.use(express.json()); // the rest of the app
In the Next.js App Router, read the body with await req.text(), as Stripe's Next.js example does:
// app/api/webhooks/stripe/route.ts (Next.js App Router)
import Stripe from 'stripe';
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY as string);
export async function POST(req: Request) {
const body = await req.text(); // raw text, never req.json()
const signature = req.headers.get('stripe-signature') ?? '';
let event: Stripe.Event;
try {
event = stripe.webhooks.constructEvent(body, signature, process.env.STRIPE_WEBHOOK_SECRET as string);
} catch {
return new Response('Invalid signature', { status: 400 });
}
await handleEvent(event);
return Response.json({ received: true });
}
Stripe webhook signature verification failed: what to check
Sources for the table: Stripe's webhook guide covers the per-endpoint secret, the default tolerance of 5 minutes (stripe-node sets DEFAULT_TOLERANCE: 300 seconds), the warning that a tolerance of 0 "disables the recency check entirely", and the NTP advice. When you rotate a secret, the Dashboard lets you keep the old one valid for up to 7 days while you deploy the new one.
What if Stripe webhooks arrive out of order or more than once?
Plan for both. Stripe's docs say it doesn't guarantee the delivery of events in the order that they're generated, and that endpoints "might occasionally receive the same event more than once". Creating a subscription can produce customer.subscription.created, invoice.created, invoice.paid and charge.created in any order. In live mode, Stripe retries a failed delivery for up to three days, so an old event can land after a newer one.
The classic bug: a customer.subscription.updated from before an upgrade arrives after the upgrade, and the app writes the old plan back. In one of our sample audit reports, an older payment event overwrote a newer plan state. Two rules prevent it:
- Record event IDs you have processed and skip repeats. Stripe recommends exactly this. Do not use the event's
createdfield to decide order or whether you have seen it: Stripe notes that distinct events can share a timestamp. In rare cases Stripe generates two separate Event objects for one change; to catch those, compare the ID indata.objecttogether withevent.type. - Fetch the current object instead of trusting the payload order. When any subscription event arrives, retrieve the subscription from the API and save its current state. Stripe's docs suggest the same approach for retrieving missing objects.
// CREATE TABLE stripe_events (id text PRIMARY KEY, type text NOT NULL, processed_at timestamptz DEFAULT now());
async function handleEvent(event) {
const seen = await pool.query('SELECT 1 FROM stripe_events WHERE id = $1', [event.id]);
if (seen.rowCount > 0) return; // duplicate delivery: do nothing
if (event.type.startsWith('customer.subscription.')) {
// Do not trust the order of events. Ask Stripe for the current state and save that.
const sub = await stripe.subscriptions.retrieve(event.data.object.id);
await pool.query(
'UPDATE users SET plan_status = $1, stripe_subscription_id = $2 WHERE stripe_customer_id = $3',
[sub.status, sub.id, sub.customer]
);
}
// One-off side effects (emails, credits) belong here, after the duplicate check.
await pool.query(
'INSERT INTO stripe_events (id, type) VALUES ($1, $2) ON CONFLICT (id) DO NOTHING',
[event.id, event.type]
);
}
Syncing the current state is safe to repeat, so a duplicate that slips past the check does no harm. One-off actions such as a welcome email or granting credits must sit after the duplicate check. Keep the handler fast: Stripe asks endpoints to return a 2xx quickly, before complex logic that might time out. If the work is slow, store the event and process it from a queue.
A note on event formats
Stripe now also offers thin events for new integrations. The examples here use the classic snapshot Event objects that constructEvent returns, which is what most existing apps receive. The ordering and duplicate rules apply to both.
How do I test Stripe idempotency and webhooks before launch?
Run these in test mode. Each one maps to a failure described above.
# Forward test-mode events to your local server and print the signing secret
stripe listen --forward-to localhost:3000/api/webhooks/stripe
# In a second terminal, fire a test event
stripe trigger payment_intent.succeeded
# A forged request must be rejected with 400
curl -i -X POST localhost:3000/api/webhooks/stripe \
-H 'Content-Type: application/json' \
-H 'Stripe-Signature: t=1,v1=forged' \
-d '{"id":"evt_fake","type":"customer.subscription.deleted"}'
- Concurrency: as a brand new test user, send two checkout requests at the same moment (two tabs, or two parallel
curlcalls). Count customers with that email in the Dashboard. The answer must be one. - Retry: call your create function twice with the same stored key and confirm the second call returns the same
cus_ID. - Forged webhook: the
curlabove must get a400, and nothing in your database may change. - Duplicate delivery: resend an event you already processed, from the Dashboard event page or with
stripe events resend <event_id> --webhook-endpoint=<endpoint_id>(the CLI can resend for up to 30 days after creation). Nothing may change. - Out of order: upgrade a test subscription, then resend the older
customer.subscription.updatedevent. The plan in your database must still match Stripe.
These checks also appear in our production readiness checklist for vibe-coded apps, next to the other payment and auth items worth testing before launch. If you want to review the code yourself first, our guide on how to audit a vibe-coded app walks through where to look.
What good looks like
What good looks like
- Each user record holds at most one
stripe_customer_id, with a unique constraint. - Customer creation lives in one server function that locks the user row and reuses a stored idempotency key.
- Every Checkout Session receives
customerfor a logged-in user. - The webhook route reads the raw body, verifies every event with
constructEvent, and returns400on failure. - Processed event IDs are stored, and a resent event changes nothing.
- Subscription state is fetched from Stripe on each event, so the plan in your database matches the Dashboard after any delivery order.
If your app was generated quickly, payments are rarely the only place where this pattern shows up. Our overview of security risks in vibe-coded apps covers the other areas we check most often.
Get the rest of your app checked
Duplicate customers and unverified webhooks are two findings. An app that has them usually has a few more in auth, data access and secrets.
Valletta Software runs a fixed-price vibe code audit, from $199, for apps built with AI tools. We read the source code, we do not touch your production systems or customer data, and you get a written report with what to fix first.
FAQ
What is a Stripe idempotency key?
It is a unique string you send in the Idempotency-Key header with a POST request. If the same request is retried with the same key, Stripe returns the saved first response instead of performing the operation again. Stripe recommends random V4 UUIDs, up to 255 characters, and no emails or personal data.
How long does a Stripe idempotency key last?
For API v1, Stripe keeps keys for at least 24 hours and can remove them after that. A request that reuses a key after it has been removed runs as a new request. That is why a saved customer ID in your own database, not the key, is the long-term guard against duplicates.
Does Stripe prevent duplicate customers with the same email?
No. The Create customer API has no option to make an email unique, so each successful call creates a new customer. Prevent duplicates in your own code: store one Stripe customer ID per user, lock creation so concurrent requests cannot both run it, and pass that ID to every Checkout Session.
Why does Stripe webhook signature verification fail?
Usually because the body was parsed before verification. Stripe needs the exact raw bytes it signed, so use express.raw() on the webhook route or await req.text() in Next.js. Other causes are using the wrong endpoint secret, mixing test and live secrets, or a server clock outside the 5 minute tolerance.
Can Stripe webhooks arrive out of order?
Yes. Stripe states that it does not guarantee delivery in the order events were generated, and the same event can arrive more than once. Store processed event IDs to skip repeats, and when a subscription event arrives, retrieve the current subscription from the API and save that state instead of applying events blindly.
Should I use an idempotency key on every Stripe request?
Use one on every API v1 POST, such as creating customers, payments or refunds. Stripe says sending a key with GET or DELETE has no effect, because those requests are already idempotent. If you retry across process restarts, persist the key with the operation and reuse it for every attempt.