# Handle duplicate snapshot and thin events

Save one shared key so snapshot and thin handlers don't process the same event twice.

During a [snapshot-to-thin migration](https://docs.stripe.com/webhooks/migrate-snapshot-to-thin-events.md#cut-over-with-idempotency), Stripe can deliver the same logical event as both a snapshot event and a thin event. To prevent duplicate processing, both handlers use the same idempotency key:

**Snapshot handler:** Use `event.id`.

**Thin handler:** Use `snapshot_event` from the retrieved complete event, or `event.id` if there’s no corresponding snapshot event.

The first handler to save the key processes the event. The second handler finds the key and returns `200` without processing it again. If processing fails after the key is saved, delete the key before you return an error so Stripe’s retry can try again.

If you already store processed events, save this key in that store. This table uses SQLite. `tryInsertIdempotencyKey` saves the key, and `releaseIdempotencyKey` deletes it. Replace these two functions if you use your own database.

```sql
CREATE TABLE event_idempotency (
  idempotency_key TEXT PRIMARY KEY,
  event_type TEXT NOT NULL,
  processed_at INTEGER NOT NULL
);
```

Next, implement the idempotency helper:

```javascript
// Try to insert idempotency key. Returns true if successfully inserted, false if duplicate.
function tryInsertIdempotencyKey(idempotencyKey, eventType) {
  // ON CONFLICT DO NOTHING skips the insert when the key already exists, so the
  // result doesn't depend on driver-specific error codes. Use your database's
  // equivalent (for example, INSERT IGNORE in MySQL).
  const result = db
    .prepare(
      `
      INSERT INTO event_idempotency (idempotency_key, event_type, processed_at)
      VALUES (?, ?, ?)
      ON CONFLICT (idempotency_key) DO NOTHING
    `,
    )
    .run(idempotencyKey, eventType, Date.now());
  return result.changes === 1; // false means duplicate - event already processed
}
```

If processing fails after you insert the key, delete it before returning an error. Otherwise, your handler skips the event when Stripe retries the delivery.

```javascript
// Delete an idempotency key so that Stripe's retry processes the event again.
function releaseIdempotencyKey(idempotencyKey) {
  db.prepare('DELETE FROM event_idempotency WHERE idempotency_key = ?').run(
    idempotencyKey,
  );
}
```

These handlers [verify webhook signatures](https://docs.stripe.com/webhooks.md#verify-events). Allow traffic only from Stripe’s [IP addresses](https://docs.stripe.com/ips.md).

Update both handlers to use this pattern. First, update the *snapshot handler*:

```javascript
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);

app.post(
  '/webhook/snapshot',
  express.raw({type: 'application/json'}),
  (req, res) => {
    const sig = req.headers['stripe-signature'];
    const snapshotWebhookSecret = process.env.SNAPSHOT_WEBHOOK_SECRET;
    let insertedKey = null;

    try {
      const event = stripe.webhooks.constructEvent(
        req.body,
        sig,
        snapshotWebhookSecret,
      );

      // For snapshot events, idempotency key is just the event ID
      const idempotencyKey = event.id;

      // Try to insert idempotency key. If fails (duplicate), skip processing.
      if (!tryInsertIdempotencyKey(idempotencyKey, event.type)) {
        console.log(`Already processed: ${idempotencyKey}`);
        return res.sendStatus(200);
      }
      insertedKey = idempotencyKey;

      // Process the event
      if (event.type === 'customer.created') {
        createCustomerInDatabase(event.data.object);
      }

      res.sendStatus(200);
    } catch (err) {
      // Release the key so that Stripe's retry processes the event again
      if (insertedKey) releaseIdempotencyKey(insertedKey);
      console.log(`Webhook Error: ${err.message}`);
      res.status(400).send(`Webhook Error: ${err.message}`);
    }
  },
);
```

Next, update the thin handler:

```javascript
const client = require('stripe')(process.env.STRIPE_SECRET_KEY, {
  apiVersion: '2026-09-30.endive',
});

app.post(
  '/webhook/thin',
  express.raw({type: 'application/json'}),
  async (req, res) => {
    const sig = req.headers['stripe-signature'];
    const thinWebhookSecret = process.env.THIN_WEBHOOK_SECRET;
    let insertedKey = null;

    try {
      const thinNotification = client.parseEventNotification(
        req.body,
        sig,
        thinWebhookSecret,
      );
      const event = await thinNotification.fetchEvent();

      // For the thin version of snapshot events, use snapshot_event if present, otherwise event ID
      const idempotencyKey = event.snapshot_event || event.id;

      // Try to insert idempotency key. If fails (duplicate), skip processing.
      if (!tryInsertIdempotencyKey(idempotencyKey, event.type)) {
        console.log(`Already processed: ${idempotencyKey}`);
        return res.sendStatus(200);
      }
      insertedKey = idempotencyKey;

      // Process the event
      if (event.type === 'v1.customer.created') {
        const customer = await thinNotification.fetchRelatedObject();
        createCustomerInDatabase(customer);
      }

      res.sendStatus(200);
    } catch (err) {
      // Release the key so that Stripe's retry processes the event again
      if (insertedKey) releaseIdempotencyKey(insertedKey);
      console.log(`Webhook Error: ${err.message}`);
      res.status(400).send(`Webhook Error: ${err.message}`);
    }
  },
);
```
