Back to Blog
Development

Stripe Webhooks in n8n: Idempotency, Signatures and Replay

SoftivumLinkedIn
Engineering and delivery team
15 min
A developer at a laptop showing a workflow of connected blocks beside a card payment machine printing a receipt.
On this page

Stripe webhooks n8n idempotency: why events drop or repeat

A customer pays, the invoice never gets marked paid, and nothing in n8n is red. Or the opposite: one payment produces two welcome emails and two licence keys. Both outcomes come from the same gap. Stripe documents that an endpoint may receive the same event more than once and out of order, n8n answers the request on its own terms, and the receiver in between was built as if each event arrives exactly once, in order, while everything is healthy.

The design below neither loses nor repeats work. It verifies the signature on the raw body, writes the event ID to a table with a unique key, answers 200 only after that write, and processes from the table. Node-by-node tables, a failure-modes table and a go-live checklist follow. For India specifically, Stripe's support page says businesses from India cannot sign up for a new account on the website and need to request an invite, so a local aggregator is the usual gateway there (accepting UPI and card payments on a website in India), and the pattern below applies to any gateway that sends signed webhooks.

What Stripe promises, and what it does not

Everything in the table comes from Stripe's webhook documentation and its page on managing webhook endpoints. Read it as the contract your receiver is built against.

BehaviourWhat Stripe documentsWhat your receiver must do
DuplicatesEndpoints may receive the same event more than once. Sometimes two separate Event objects are generated for the same change.Log processed event IDs and skip repeats. For the two-object case, compare the ID of the object in data.object plus the event type.
OrderingDelivery order is not guaranteed. Timestamps are in whole seconds, so created cannot order events or prove you have seen one.Never act on arrival order. Fetch the current object from the API when state matters.
SuccessReturn a 2xx quickly, before any complex logic. A redirect (3xx) counts as a failure.Do only the minimum before answering. Never let the endpoint redirect.
Live retriesStripe retries for up to three days with exponential backoff.Assume every event can arrive again a day later.
Sandbox retriesThree retries over a few hours.Do not judge production resilience from sandbox behaviour.
Manual resendDashboard Resend works up to 15 days after the event, and the CLI command works up to 30 days. A manual resend does not cancel automatic retries.Treat a replay as another delivery. The dedupe table decides whether it runs.
Listing historyThe List Events API returns events from the last 30 days, and delivery_success=false narrows it to events that failed delivery to at least one endpoint.Run a reconciliation job against this list.
Raw bodyVerification needs the exact bytes Stripe sent. Any manipulation breaks it.Capture the raw body in n8n before anything parses it.

Two details deserve underlining. First, "delivered" in Stripe means your endpoint returned a 2xx. It says nothing about whether your business logic ran. Second, Stripe's own documentation recommends handling events with an asynchronous queue because a spike, such as the first of the month when subscriptions renew, can overwhelm a receiver that does the work inline.

Where n8n hides the drops

The n8n Webhook node has a Respond setting with three modes that matter here.

  • Immediately returns 200 with the message "Workflow got started". Stripe marks the event delivered the moment n8n accepts it. If a node fails afterwards, Stripe has nothing to retry.
  • When Last Node Finishes returns the output of the last node. Stripe waits for all of your work, so a slow downstream call turns into a timeout and a retry, and the retry runs the same work again.
  • Using the Respond to Webhook node lets you choose the exact point at which the response goes out. This is the mode the design below uses.

The Respond to Webhook node documents the behaviour that makes this safe. If the workflow errors before the first Respond to Webhook node runs, n8n returns an error message with a 500 status, which Stripe treats as a failed delivery and retries. A second Respond node after the first is ignored, so one response per execution is the rule.

That gives you the central idea. Place the Respond node after the one step that must not be lost, which is writing the event to durable storage. Before that step, any failure becomes a 500 and a Stripe retry. After it, the event is safe and can be processed at your own pace.

Two more n8n facts shape the build:

  1. Test and production URLs differ. The test URL is registered while you listen for a test event, and data appears in the editor. The production URL is registered when you publish, and runs appear in the Executions tab. A Stripe endpoint pointed at the test URL stops working when you stop listening.
  2. Concurrency limits queue executions. When concurrency control is enabled, production executions over the limit wait in a first-in, first-out queue. A receiver stuck behind a long processing run answers Stripe late. In queue mode the main instance or a dedicated webhook processor receives the request and workers run the execution, which keeps receiving separate from heavy processing.

Step 1: verify the signature on the raw body

Stripe signs each event. The Stripe-Signature header carries a timestamp (t=) and one or more signatures (v1=). The signed string is the timestamp, a full stop, and the exact request body, run through HMAC with SHA-256 using the endpoint's signing secret. Stripe's libraries default to a five-minute tolerance between the timestamp and the current time, and the documentation warns against a tolerance of zero because that disables the recency check. When you roll a secret and keep the old one active for up to 24 hours, Stripe sends one signature per active secret, so a correct verifier accepts the event if any v1 signature matches and ignores every other scheme.

Why parsed JSON breaks it in n8n

The Webhook node hands you the body as parsed JSON in body. Stripe's documentation says frameworks that reorder keys, strip whitespace, convert to JSON or change encoding cause verification to fail. Rebuilding the string with JSON.stringify on the parsed object produces text that is semantically the same and byte-for-byte different, so the HMAC never matches. The error you see is the familiar "No signatures found matching the expected signature for payload".

The Webhook node has a Raw Body option. In n8n's source it places the unparsed bytes in a binary property named data, and body still holds the parsed object. Use the bytes for the signature check and nothing else.

Two ways to verify

Stripe Trigger nodeWebhook node with Raw Body and a Code node
SetupAdd a Signature Secret to the Stripe credential. n8n creates the endpoint in Stripe when you publish, and you copy the signing secret from that endpoint.Create the endpoint in Stripe yourself and store the signing secret as a credential or environment variable.
VerificationWhen a Signature Secret is set, the node checks Stripe-Signature and answers 401 for unsigned, forged or more than five minutes old requests, without running the workflow. Without a Signature Secret it does not verify at all.You write the check, so you control every rule: tolerance, multiple v1 values, constant-time comparison.
Response controlThe documentation lists no Respond setting, so treat it as acknowledge first.Full control through the Respond to Webhook node.
FitsInternal alerts and low-stakes flows.Anything that moves money, grants access or ships goods.

The Stripe Trigger path is a sound start, and n8n strongly recommends setting the Signature Secret. Because it acknowledges before your workflow runs, pair it with the reconciliation job described later.

The Code node, in words

The verification step reads the header stripe-signature and splits it into t and the list of v1 values. It reads the raw bytes with await this.helpers.getBinaryDataBuffer(0, 'data'), the helper n8n documents for this purpose, and builds the signed string from t, a full stop and those bytes. It computes HMAC SHA-256 with the signing secret, compares the result to each v1 using a constant-time comparison, and checks that t is within tolerance. It returns valid: true along with the event parsed from the same verified bytes, so nothing downstream trusts the unverified body. On failure it returns valid: false and does not throw.

The n8n Crypto node can produce an HMAC from binary data, but the signed string has the timestamp in front of the body, so the Code node is the straightforward route. On n8n Cloud the Code node allows the `crypto` module. On a self-hosted n8n instance, enable it with NODE_FUNCTION_ALLOW_BUILTIN=crypto, set on the task runners if your instance uses them.

Stripe's documentation also recommends allowlisting Stripe's published IP addresses alongside signature verification. The Webhook node has an IP allowlist option for this, and an in-front reverse proxy can do the same.

Step 2: the inbox table, where dedupe lives

Every defence against duplicates comes down to one question: have we already recorded this event ID? Answer it in a database with a unique constraint, because a constraint settles two simultaneous deliveries in one place. n8n's Remove Duplicates node can compare against earlier executions, but it keeps a bounded history (10,000 items by default), and a duplicate that arrives after the history has rolled over passes straight through. Workflow static data and execution history are not durable stores either.

A single Postgres table covers dedupe, retry state and the dead-letter list:

ColumnPurpose
event_idPrimary key. The evt_ ID from Stripe. This is the unique constraint.
type, object_id, livemodeRouting and filtering without parsing the payload.
payloadThe event as JSON, so a replay does not depend on Stripe being reachable.
statuspending, processing, done or dead. Default 'pending'.
attempts, last_errorRetry count (default 0) and the most recent failure message.
received_at, next_attempt_at, claimed_atOrdering, backoff and stuck-row detection. received_at and next_attempt_at default to now(), and claimed_at stays empty until a row is claimed.

The write uses an upsert so that one statement covers new events, duplicates and replays of dead events. In the Postgres node's Execute Query operation:

INSERT INTO stripe_events (event_id, type, object_id, livemode, payload) VALUES ($1, $2, $3, $4, $5) ON CONFLICT (event_id) DO UPDATE SET status = 'pending', attempts = 0, next_attempt_at = now() WHERE stripe_events.status = 'dead' RETURNING event_id

Pass the five values in the node's Query Parameters option, which n8n sanitises to prevent SQL injection. PostgreSQL documents that ON CONFLICT DO UPDATE guarantees an atomic insert-or-update outcome, even under high concurrency, and that a row left untouched because the WHERE condition fails is not returned. The result is three cases from one statement:

  • A new event inserts and returns its ID.
  • A duplicate of a pending, processing or done event does nothing and returns no row.
  • A resend of a dead event flips it back to pending, so a replay from the Stripe Dashboard revives it with no manual SQL.

The receiver, node by node

#NodeSettingWhy
1WebhookPOST, a path nobody guesses, Respond set to Using Respond to Webhook Node, Raw Body onCaptures the bytes and defers the response.
2CodeThe verification described aboveRejects forged and stale requests before any state changes.
3IFvalid is trueSplits good from bad.
4Respond to Webhook (false branch)Response code 400A request that fails verification gets a client error.
5PostgresThe upsert above, Always Output Data onRecords the event. A zero-row result still continues to the next node.
6Respond to WebhookResponse code 200, No DataStripe sees success only after the event is stored.
7Execute Sub-workflow (optional)Processor workflow, Wait For Sub-Workflow Completion off (documented option)Starts processing at once. The schedule in the next step is the safety net.

The Postgres node's Always Output Data setting returns an empty item when a query returns no rows, which keeps the duplicate case flowing to the 200 response. If the database is down, node 5 fails before any Respond node has run, n8n returns a 500, and Stripe retries on its own schedule. Set an error workflow on this workflow so that failure also pages someone.

Node 7 is a latency optimisation. Check on your n8n version, in the execution log, that nodes after the Respond node still run. If they do not, delete node 7 and let the schedule pick events up.

Respond after write, or acknowledge then process

Stripe's guidance is to return a 2xx before complex logic, and its example is a 200 before marking an invoice paid in your accounting system. There are three ways to honour that in n8n, and they fail differently.

Patternn8n setupWhat can go wrongUse it when
Acknowledge, then processRespond Immediately, work in the same executionA failure after the acknowledgement is invisible to Stripe, so the event is never retried and delivery_success=false never lists it.Alerts and notes where losing one is acceptable.
Respond after write (inbox)Respond to Webhook after a durable insertA slightly longer response, bounded by one database write. Processing has its own retry state.Payments, access, fulfilment, accounting.
Respond when work finishesRespond When Last Node FinishesSlow calls produce timeouts, retries and duplicate work under load.Trivial, fast, idempotent flows only.

Respond after write is a middle path that keeps Stripe's retry safety net for the one step that must not fail and gives the slow work its own retry loop. One more reason to keep the response fast: for hosted Checkout with a success_url, Stripe waits up to 10 seconds for your server to answer the checkout.session.completed webhook before redirecting the customer. A receiver that does the fulfilment inline makes the customer wait on it.

Step 3: the processor workflow

The processor reads from the table and does the real work. It starts from a Schedule Trigger, every minute for most flows, and from the sub-workflow trigger that node 7 calls.

  1. Release stuck rows. A Postgres query sets processing rows whose claimed_at is older than your slowest run back to pending. This covers an n8n restart in the middle of a run.
  2. Claim a batch. One statement moves a handful of pending rows to processing and returns them: UPDATE stripe_events SET status = 'processing', attempts = attempts + 1, claimed_at = now() WHERE event_id IN (SELECT event_id FROM stripe_events WHERE status = 'pending' AND next_attempt_at <= now() ORDER BY received_at LIMIT 10 FOR UPDATE SKIP LOCKED) RETURNING *. PostgreSQL documents SKIP LOCKED as suitable for queue-like tables with multiple consumers, so a scheduled run and an on-demand run never claim the same row.
  3. Fetch the current object. For each event, an HTTP Request node retrieves the object named by object_id from the Stripe API. See the next section for why.
  4. Route by type. A Switch node sends each event type to its branch.
  5. Guard the business key. Insert into a fulfilments table with a unique key such as the Checkout Session ID, and only continue when a row comes back.
  6. Do the side effects with derived idempotency keys on every Stripe call.
  7. Mark the outcome. On success set done. On error, compare attempts (the claim already counted this try) with your limit: set pending with a later next_attempt_at while attempts remain, or dead once they run out, and send an alert.

Set On Error on the action nodes to "Continue (using error output)", a documented node setting, so a failing call lands in the mark-failed branch with its error message instead of halting the run and leaving a row in processing.

Ordering: fetch the latest state, do not trust the payload

Stripe's example of why ordering cannot be assumed: creating a subscription can emit customer.subscription.created, invoice.created, invoice.paid and charge.created, and you can receive invoice.paid first. Stripe's advice is to retrieve the related objects through the API when that happens. The processor does this for every event. It reads the payload only to learn which object changed, then asks Stripe for that object as it stands now, and sets your system to match. An older event arriving late then re-applies a current truth and cannot overwrite a newer one.

Two layers of dedupe

The event ID table stops the same delivery from running twice. It does not stop two different events, or two different paths, from doing the same job. Stripe's fulfilment guide says the fulfilment function may be called multiple times, possibly concurrently, for the same Checkout Session, because both the webhook and the landing page trigger it. It must handle repeated calls with the same Session ID, check payment_status before fulfilling, and record that fulfilment happened. In the processor that is the fulfilments table with a unique key on the Session ID. For the two-Event-objects case, the key is the data.object ID plus the event type.

Outbound idempotency keys

When the workflow calls Stripe, for a refund, a customer, a transfer or an invoice, send an Idempotency-Key header from an HTTP Request node. Stripe's documentation on idempotent requests sets the rules that matter here:

  • For API v1, Stripe saves the status code and body of the first request made with a key, including 500 errors, and returns that saved response for retries with the same key.
  • Keys can be up to 255 characters, and Stripe suggests V4 UUIDs or similarly random strings.
  • Keys can be removed once they are at least 24 hours old, and reusing one after that creates a new request.
  • If incoming parameters differ from the original request, Stripe returns an error.
  • POST requests accept keys. GET and DELETE do not need them.
  • Stripe does not save a result when parameters fail validation or a request conflicts with one still executing, so those can be retried.

After a saved 500, a retry with the same key returns the same 500. Have the workflow GET the object first, and only retry with a suffixed key (for example evt_...:refund:2) if the object does not exist.

The practical consequence is that a random UUID generated inside the workflow is the wrong key. A retry runs the node again and generates a new UUID, so the key protects nothing. Derive the key from stable inputs instead.

CallKeyReason
Refund for an eventevt_...:refundA retried event reuses the key and gets the saved result.
Create a customer after checkoutcs_...:customerTwo events for one session share the key.
Create an invoice for a subscription changeevt_...:invoiceOne event cannot create two invoices.

Because Stripe may prune keys after 24 hours and a manual replay can arrive weeks later, the keys are the second line of defence behind the business-key table, which has no expiry.

Dead letters and replay

A dead row is an event that failed its allowed attempts. Keep it in the same table, with last_error filled in, and let people look at it. A short review routine works well: read the error, fix the cause (a missing customer, an expired credential, a changed field), then replay.

There are three ways to replay, each suited to a different situation:

  • Flip the status in SQL. Set the row back to pending and let the processor pick it up. Fast, and needs no Stripe access.
  • Resend from Stripe. Use Dashboard Resend within 15 days or stripe events resend <event_id> --webhook-endpoint=<endpoint_id> within 30 days. The upsert turns a dead row back into pending, and a done row ignores the resend. Stripe's documentation notes that a manual resend does not cancel automatic retries, so when your endpoint receives an event you have already handled it must still answer 200 to stop them.
  • Rebuild from the API. Past the resend window, list the relevant objects and rebuild state from them, since the processor already works from current object state.

Reconciliation catches what delivery cannot

Run a scheduled workflow that calls the List Events API for the event types you handle, within the 30-day window, and checks that each ID exists in the inbox. Insert any that are missing as pending. This catches the acknowledge-first case, the Stripe Trigger path, and anything lost while your n8n instance was down for longer than the retry period. Stripe's documentation describes the manual recovery steps, using ending_before an event delivered before the outage, a types filter and delivery_success=false. For a reconciliation job, compare against all events rather than only failed deliveries, because an event you acknowledged and then lost was delivered as far as Stripe knows.

One rare case sits outside delivery altogether. Stripe documents (as a public preview feature) that it can occasionally fail to generate an event, and in that case it sends a v2.core.health.event_generation_failure.resolved event to tell you. The recovery it describes is to retrieve the affected resource from the API.

Test mode, live mode and endpoint secrets

Stripe's test mode documentation says objects in one mode are not accessible to the other, and the keys differ. Webhook secrets follow the same split. Stripe generates a unique signing secret for each endpoint, and if one endpoint serves both test and live keys, the secret is different for each. The secret printed by stripe listen is different again from a Dashboard endpoint's secret, and mixing them is the most common cause of signature failures.

EnvironmentEndpointSecretn8n side
Local developmentStripe CLI forwarding to the n8n test URLThe whsec_ value printed by stripe listenn8n listening for a test event
SandboxA Dashboard endpoint pointing at a published staging workflowThat endpoint's secretA separate n8n credential for sandbox keys
LiveA Dashboard endpoint pointing at the production URLThat endpoint's own secretA separate n8n credential for live keys

Each event carries a `livemode` flag. Store it in the inbox and have the processor refuse a row whose flag does not match the environment it runs in. That one check stops a sandbox event from triggering a real fulfilment if the wiring is ever crossed. Keep sandbox and live inboxes in separate tables or separate databases, so test event IDs never mix into production history.

A worked example: Checkout payment to fulfilment

Take a store using hosted Checkout that must create an account, send a confirmation and notify a team channel.

  1. Stripe sends checkout.session.completed. The receiver verifies it, inserts evt_123 with object_id set to the Session ID, and answers 200.
  2. Stripe retries the same delivery because the first response was slow. The insert conflicts, returns no row, and the receiver answers 200 again. Nothing else runs.
  3. The processor claims the row and fetches the Checkout Session from the API, which gives the current payment_status.
  4. If the payment method is delayed, the status is not final. The processor marks the row done without fulfilling, and the later checkout.session.async_payment_succeeded event, another inbox row, triggers fulfilment. Stripe's guide covers both event types and recommends reading payment_status before fulfilling.
  5. The processor inserts the Session ID into fulfilments. A row comes back, so it continues. If the customer's landing page had already fulfilled this session, nothing comes back and the side effects are skipped.
  6. It creates the account with an idempotency key derived from the Session ID, sends the confirmation, posts to the team channel and marks the row done. If sending the confirmation fails, the row retries with backoff and the account call returns its saved result.

The same shape serves any trigger. A failed-payment event that starts a dunning message is a candidate for the WhatsApp payment reminder flow, where the inbox keeps one failed payment from producing several nudges.

Failure modes at a glance

SymptomLikely causeFix
"No signatures found matching" on every eventThe body was parsed, or the secret belongs to another endpoint or modeUse Raw Body, read the binary data bytes, match the secret to the endpoint and mode.
Works while you listen, silent otherwiseStripe is pointed at the n8n test URLPublish the workflow and register the production URL.
Stripe shows Delivered, nothing happenedRespond Immediately, then a downstream failureRespond after the inbox write. Add reconciliation.
Duplicate emails or recordsNo dedupe, dedupe after the side effect, or two Event objects for one changeInsert the event ID first. Add a business-key table.
Old state overwrites newThe handler trusted the payload and events arrived out of orderFetch the current object and set state to match.
Failed deliveries with 3xxThe endpoint redirects, for example from http to https or by trailing slashRegister the final URL. Stripe counts redirects as failures.
Slow responses during burstsReceiving and heavy work share one instance, or concurrency limits queue the receiverKeep the receiver short. Use queue mode or webhook processors. Load-test.
Dead rows nobody readsNo alert on the dead statusAlert on the first dead row, and review the table on a schedule.
Replay creates a second charge or refundOutbound keys were random UUIDs, or the key had expiredDerive keys from event or session IDs. Keep the business-key table.
Verification fails during a secret rollThe verifier only checked one signatureAccept the event if any v1 matches.
Dedupe forgets old eventsStatic data or a bounded history node was the storeMove dedupe to a database unique key.

Monitoring that tells you before a customer does

Alerts should come from the inbox, because the inbox knows more than either n8n or Stripe alone.

  • Dead rows. Alert on the first one. A dead event is a payment, access change or refund waiting for a person.
  • Age of the oldest pending row. If processing stalls, this number climbs while every workflow still looks healthy.
  • Rows stuck in processing. They indicate a crashed run or a node that never reported back.
  • Stripe's delivery view. The Event deliveries tab for the endpoint shows Delivered, Pending and Failed with the status code of each attempt. Check it after any change to the receiver.
  • The reconciliation result. Alert when it has to insert a missing event. That means delivery failed somewhere, and you want to know where.
  • n8n execution failures. Wire the receiver and the processor to the same error workflow so a failure in either reaches a person.

Go-live checklist

  1. Production endpoint uses the production webhook URL of a published workflow, over HTTPS, with no redirect.
  2. The endpoint subscribes only to the event types the workflow handles.
  3. Raw Body is on, and the verification step reads the binary bytes.
  4. Verification checks every v1 value, ignores other schemes, compares in constant time and enforces a tolerance greater than zero.
  5. The signing secret in n8n belongs to the live endpoint, and sandbox secrets live in separate credentials.
  6. The inbox table has a unique key on event_id, and the upsert is tested with the same event sent twice.
  7. The Respond to Webhook node comes after the insert, and a database outage was simulated to confirm a 500.
  8. The processor claims rows with FOR UPDATE SKIP LOCKED, releases stuck rows and caps attempts.
  9. Every handler fetches the current object instead of trusting the payload, and the livemode flag is checked.
  10. Business-key tables exist for every side effect that must happen once.
  11. Outbound Stripe calls send derived idempotency keys.
  12. Dead rows alert, a reconciliation job runs, and an error workflow is set on both workflows.
  13. A replay was rehearsed: a dead row revived by Dashboard Resend, and a done row ignored.
  14. Load was tested with a burst of events to check receiver response times under your concurrency settings.

Getting this built

A first workflow that loses or doubles an event is expensive to untangle later, so the receiver is worth building properly at the start. We build Stripe event receivers for n8n with the inbox, processor, reconciliation and alerting described above, on accounts you own, as part of our AI and systems integration work. If the receiver is one piece of a wider automation, our workflow automation service covers the whole flow, and Zapier, Make or n8n helps you decide whether n8n is the right home for it. Running costs and savings for automations of this kind are laid out in workflow automation services: cost and savings.

Sources

Share

Planning something like this?

Tell us what you are trying to fix and we will tell you how we would approach it.

Want Stripe events handled without drops or duplicates?

Tell us which Stripe events drive your workflows. We will design the receiver, the inbox table, the retry and replay path and the alerts, on accounts you own.

See our integration work

Questions about this topic

Stripe documents that an endpoint may receive the same event more than once, for example on a retry after a slow or failed response. Record every event ID in a table with a unique key and skip IDs you have already stored. Answer 200 on the repeat so Stripe stops retrying.

Usually the body was parsed before the check, or the signing secret belongs to a different endpoint or mode. Turn on Raw Body in the Webhook node, compute the HMAC over the timestamp, a full stop and the raw bytes, and use the secret of the exact endpoint receiving the event.

Respond after one durable write, the insert of the event into your own table, and before the slow work. A failure before the insert returns a 500 and Stripe retries. A failure after it is handled by your own retry state, so the event is never lost.

Fix the cause, then resend the event from the Stripe Dashboard within 15 days or with the CLI resend command within 30 days. If your table marks failed events as dead, the resend revives the row. Events older than that can be rebuilt from the current object in the API.

Derive it from stable inputs such as the event ID plus the action name, for example the event ID followed by a refund suffix. A random UUID created inside the workflow changes on every retry and protects nothing. Stripe may prune keys after 24 hours, so keep a business-key table too.
WhatsAppCall