Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 38 ยท Webhooks

Idempotent Event Handling

Make webhook handlers safe to run twice. Store processed event ids, use database unique constraints, apply state changes atomically, and use idempotency keys for outgoing requests.

Stripe promises to deliver each event at least once, not exactly once. Network timeouts, your own deploys and Stripe's retries mean the same evt_... can arrive two, three or ten times. If your handler ships an order or credits a balance every time, a retry becomes a double shipment. The cure is idempotency: running the same operation again leaves the world in the same state as running it once.

This lesson shows three layers of defence: remember event ids, make the state change itself safe, and use idempotency keys on requests you send to Stripe. The examples use an in-memory store; in production the "store" is a database table with a unique constraint.

Layer 1: remember processed events

Keep a table of event ids you have handled. When an event arrives, try to insert its id first. If the insert fails because the id exists, you already did the work: reply 200 and stop.

Node.js Skipping duplicate events

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice the order: the id is recorded before the work. In a real system both steps belong in one database transaction, otherwise a crash between them leaves you either with lost work or with a duplicate.

Layer 2: a unique constraint is the real lock

An in-memory Set fails the moment you run two servers. Let the database arbitrate. A unique index on event_id means only one of two simultaneous requests can insert, and the loser gets an error you translate into "already handled".

SQL
CREATE TABLE webhook_events (
  event_id   TEXT PRIMARY KEY,
  type       TEXT NOT NULL,
  received_at TIMESTAMP NOT NULL,
  processed_at TIMESTAMP
);

A good pattern is a small state machine: insert the row as received, do the work, then set processed_at. If the row exists but processed_at is empty, a previous attempt crashed halfway, so you try again.

Node.js Receive, then process, with a crash

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Run it and look at the ledger: the credit appears twice. The status table alone is not enough, because the side effect happened before the row was marked done. That leads to layer 3.

Layer 3: make the effect itself idempotent

Prefer state changes that are naturally safe to repeat:

  • Set, don't increment. UPDATE orders SET status = 'paid' WHERE id = ? can run a hundred times. UPDATE balance SET amount = amount + 500 cannot.
  • Key the effect by the event or object. Insert a ledger row with a unique (payment_intent_id); a second insert is rejected.
  • Do the effect and the "processed" mark in one transaction, so they succeed or fail together.
flowchart TD
  A["Event arrives"] --> B{"Row exists and processed?"}
  B -- yes --> C["Reply 200, do nothing"]
  B -- no --> D["Begin transaction"]
  D --> E["Apply effect keyed by object id"]
  E --> F["Mark event processed"]
  F --> G["Commit, reply 200"]

One transaction covers the effect and the bookkeeping.

Node.js A ledger keyed by payment id

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Idempotency keys on outgoing requests

The same problem exists in the other direction. If your request to create a charge times out, did Stripe receive it? Retrying blindly might charge twice. Stripe lets you send an Idempotency-Key header: the first request with a given key is executed, and any retry with the same key returns the saved result instead of running again. Use a value that is stable for the logical operation, such as order-1042-payment, never a fresh random value per attempt.

JavaScript
// Read-only: needs the "stripe" npm package
const intent = await stripe.paymentIntents.create(
  { amount: 2000, currency: 'usd' },
  { idempotencyKey: 'order-1042-payment' },
);

Stripe stores idempotency keys for at least 24 hours. Reusing a key with different parameters returns an error, which helps you catch bugs.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What delivery guarantee do Stripe webhooks give?

    Retries mean an event can be delivered more than once, so handlers must tolerate duplicates.
  2. 2. Why is "UPDATE balance SET amount = amount + 500" risky in a webhook handler?

    Increments are not idempotent. Prefer setting a value or inserting a row with a unique key.
  3. 3. What makes an idempotency key useful for an outgoing request?

    A stable key lets Stripe recognise a retry and return the saved response.
  4. 4. Where should the effect and the "event processed" mark be written?

    One transaction makes them succeed or fail together, so a crash cannot leave them out of step.

Summary

  • Events arrive at least once, so duplicates are normal.
  • Record event ids with a unique constraint and reply 200 for repeats.
  • Make the effect itself safe: set values, key rows by object id, use transactions.
  • Send an Idempotency-Key for outgoing requests you may retry.

Next: Webhook Retries and Ordering