惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Hacker News: Ask HN
Hacker News: Ask HN
WordPress大学
WordPress大学
T
The Blog of Author Tim Ferriss
The GitHub Blog
The GitHub Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - 聂微东
A
About on SuperTechFans
Stack Overflow Blog
Stack Overflow Blog
雷峰网
雷峰网
Microsoft Azure Blog
Microsoft Azure Blog
腾讯CDC
爱范儿
爱范儿
酷 壳 – CoolShell
酷 壳 – CoolShell
博客园 - 【当耐特】
V
Visual Studio Blog
有赞技术团队
有赞技术团队
U
Unit 42
D
Docker
小众软件
小众软件
F
Full Disclosure
I
Intezer
Scott Helme
Scott Helme
P
Privacy International News Feed
P
Proofpoint News Feed
Engineering at Meta
Engineering at Meta
Google DeepMind News
Google DeepMind News
B
Blog
Martin Fowler
Martin Fowler
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Vercel News
Vercel News
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Spread Privacy
Spread Privacy
宝玉的分享
宝玉的分享
S
Security Affairs
www.infosecurity-magazine.com
www.infosecurity-magazine.com
月光博客
月光博客
C
Cisco Blogs
云风的 BLOG
云风的 BLOG
Schneier on Security
Schneier on Security
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
T
Threat Research - Cisco Blogs
量子位
Hacker News - Newest:
Hacker News - Newest: "LLM"
H
Heimdal Security Blog
N
Netflix TechBlog - Medium
H
Hacker News: Front Page
P
Proofpoint News Feed
G
GRAHAM CLULEY
V
Vulnerabilities – Threatpost
S
Schneier on Security

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Stripe Webhooks: Idempotency, Retries, and Queue Setup
Iurii Roguli · 2026-05-22 · via DEV Community

Stripe sent one webhook. Your database has three orders. What happened?

This is not a hypothetical. I've seen it in production — on vatnode.dev, on pikkuna.fi, on pi-pi.ee. The Stripe webhook hits your endpoint, your server takes 800ms to respond, Stripe times out and queues a retry. Meanwhile your server did complete the work. Now you have a duplicate. Then another one arrives 30 minutes later.

The naive implementation — parse the JSON, run your business logic, return 200 — fails in ways that only show up under real traffic. Here's what production actually looks like.

Why the Naive Implementation Breaks

Stripe's retry policy is more aggressive than most developers expect. If your endpoint returns anything other than a 2xx status code, or takes longer than 30 seconds to respond, Stripe retries. The schedule: immediately, then at 5 minutes, 30 minutes, 2 hours, 5 hours, 10 hours, and so on — up to 72 hours and roughly 15–18 total attempts.

That means if your server returned 500 at 9 AM on Monday due to a database hiccup, Stripe will still be trying to deliver the same event on Tuesday morning. If your server is back up, it will process the event — possibly creating a duplicate subscription, a duplicate order, or sending a duplicate email to your customer.

The naive handler looks like this:

// app/api/webhooks/stripe/route.ts — DON'T do this
export async function POST(request: Request) {
  const body = await request.json(); // Wrong: parsed body won't verify
  const event = body as Stripe.Event;

  if (event.type === "payment_intent.succeeded") {
    await createOrder(event.data.object); // No idempotency check
  }

  return new Response("ok", { status: 200 });
}

Enter fullscreen mode Exit fullscreen mode

Three problems here: no signature verification, no protection against replay attacks, and synchronous processing that blocks the response while your business logic runs. If createOrder takes 3 seconds and Stripe's timeout is strict, you'll get retries even when the order was created successfully.

name="How to handle Stripe webhooks reliably in production"
totalTime="PT3H"
tools={[
"Next.js 16",
"TypeScript",
"Stripe SDK",
"BullMQ",
"ioredis",
"Drizzle ORM",
"PostgreSQL",
]}
steps={[
{
name: "Verify the signature using raw bytes",
text: "Use request.arrayBuffer() — not request.json() — to get the raw body before passing it to stripe.webhooks.constructEvent. Parsing the body first changes the bytes and makes signature verification always fail.",
},
{
name: "Implement dual-layer idempotency",
text: "Store processed Stripe event IDs in PostgreSQL as the source of truth. Add a Redis pre-check layer for sub-millisecond lookups on hot paths. Return 200 immediately when a duplicate is detected.",
},
{
name: "Enqueue the event with BullMQ",
text: "Return 200 from the HTTP handler within 50ms by enqueuing to BullMQ using event.id as the jobId for deduplication. Never run business logic synchronously inside the webhook handler.",
},
{
name: "Process events in a separate worker",
text: "Run a BullMQ worker with concurrency 5 that handles payment_intent.succeeded, customer.subscription.deleted, and invoice.payment_failed. Double-check idempotency inside the worker to cover edge cases like mid-job restarts.",
},
{
name: "Wrap critical handlers in transactions",
text: "Use a database transaction for payment_intent.succeeded so that partial writes never leave inconsistent state. Send confirmation emails outside the transaction — a failed email shouldn't roll back the order.",
},
{
name: "Test with Stripe CLI locally",
text: "Use stripe listen --forward-to localhost:3000/api/webhooks/stripe and stripe trigger payment_intent.succeeded to replay events. Verify idempotency by re-sending the same event ID and confirming the duplicate response.",
},
]}
/>

Idempotency — The Foundation

slug="api-integrations"
text="Need a production-grade Stripe webhook pipeline — idempotency, BullMQ, signature verification, retry handling — wired into your SaaS or e-commerce stack? This is what I build."
/>

Before any queue, before any worker, you need idempotency: the guarantee that processing the same event twice produces the same result as processing it once.

Stripe makes this straightforward — every event has a unique id field (e.g., evt_1OqXyz...). Store this ID when you process the event. On subsequent attempts, check the store first and short-circuit.

I use PostgreSQL for durable idempotency keys and Redis for a fast pre-check layer. Here's the Drizzle ORM schema:

// packages/db/schema/webhook-events.ts
import { pgTable, text, timestamp, jsonb } from "drizzle-orm/pg-core";

export const webhookEvents = pgTable("webhook_events", {
  id: text("id").primaryKey(), // Stripe event ID — evt_1OqXyz...
  type: text("type").notNull(), // payment_intent.succeeded, etc.
  processedAt: timestamp("processed_at").notNull().defaultNow(),
  payload: jsonb("payload").notNull(),
});

Enter fullscreen mode Exit fullscreen mode

And the idempotency check — run this before any business logic:

// lib/webhook-idempotency.ts
import { db } from "@/packages/db";
import { webhookEvents } from "@/packages/db/schema/webhook-events";
import { eq } from "drizzle-orm";
import { redis } from "@/lib/redis"; // ioredis instance

export async function isAlreadyProcessed(eventId: string): Promise<boolean> {
  // Fast path: Redis check first (sub-millisecond)
  const cached = await redis.get(`webhook:processed:${eventId}`);
  if (cached) return true;

  // Slow path: database check (handles Redis eviction or restarts)
  const existing = await db
    .select({ id: webhookEvents.id })
    .from(webhookEvents)
    .where(eq(webhookEvents.id, eventId))
    .limit(1);

  if (existing.length > 0) {
    // Restore to Redis cache so future checks are fast
    await redis.set(`webhook:processed:${eventId}`, "1", "EX", 86400 * 7);
    return true;
  }

  return false;
}

export async function markAsProcessed(
  eventId: string,
  type: string,
  payload: unknown
): Promise<void> {
  // Write to DB first — this is the source of truth
  await db.insert(webhookEvents).values({
    id: eventId,
    type,
    payload,
  });

  // Then cache in Redis for fast future lookups
  await redis.set(`webhook:processed:${eventId}`, "1", "EX", 86400 * 7);
}

Enter fullscreen mode Exit fullscreen mode

Signature Verification in Next.js App Router

Here's the subtle thing that breaks almost every Next.js webhook tutorial: request.json() returns a parsed object. Stripe's signature verification requires the raw bytes of the original request body. Once parsed, the signature check will always fail.

In the Pages Router, you'd disable bodyParser. In the App Router, you use request.arrayBuffer():

// app/api/webhooks/stripe/route.ts
import Stripe from "stripe";
import { NextResponse } from "next/server";
import { isAlreadyProcessed } from "@/lib/webhook-idempotency";
import { webhookQueue } from "@/lib/webhook-queue";

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
  apiVersion: "2025-01-27.acacia",
});

const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET!;

export async function POST(request: Request) {
  // arrayBuffer() gives us raw bytes — required for signature verification
  const rawBody = await request.arrayBuffer();
  const signature = request.headers.get("stripe-signature");

  if (!signature) {
    return NextResponse.json({ error: "Missing signature" }, { status: 400 });
  }

  let event: Stripe.Event;

  try {
    // Convert ArrayBuffer to Buffer for the Stripe SDK
    event = stripe.webhooks.constructEvent(Buffer.from(rawBody), signature, webhookSecret);
  } catch (err) {
    console.error("Webhook signature verification failed:", err);
    return NextResponse.json({ error: "Invalid signature" }, { status: 400 });
  }

  // Check idempotency before doing anything else
  const alreadyProcessed = await isAlreadyProcessed(event.id);
  if (alreadyProcessed) {
    // Return 200 so Stripe stops retrying — this is intentional
    return NextResponse.json({ received: true, duplicate: true });
  }

  // Enqueue the event — don't process synchronously
  await webhookQueue.add(
    event.type,
    { event },
    {
      jobId: event.id, // BullMQ deduplicates by jobId within the active window
      attempts: 5,
      backoff: { type: "exponential", delay: 5000 },
    }
  );

  // Return immediately — Stripe considers this success
  return NextResponse.json({ received: true });
}

Enter fullscreen mode Exit fullscreen mode

Two things to notice. First, the idempotency check runs before enqueuing — so if Stripe retries and the job is still in the queue (not yet processed), you return 200 and BullMQ's jobId deduplication handles the rest. Second, the endpoint returns immediately after enqueuing. This response time is typically under 50ms, well within Stripe's timeout window.

BullMQ Queue Architecture

Processing webhooks synchronously in the HTTP handler means your response time is tied to every downstream API call — CRM updates, email sends, database writes. One slow dependency and you're getting retries.

The right architecture: webhook endpoint enqueues, a separate worker processes.

// lib/webhook-queue.ts
import { Queue } from "bullmq";
import { redis } from "@/lib/redis";

export const webhookQueue = new Queue("stripe-webhooks", {
  connection: redis,
  defaultJobOptions: {
    attempts: 5,
    backoff: {
      type: "exponential",
      delay: 5000, // 5s, 10s, 20s, 40s, 80s
    },
    removeOnComplete: { count: 1000 }, // Keep last 1000 for debugging
    removeOnFail: false, // Keep failed jobs in DLQ for inspection
  },
});

Enter fullscreen mode Exit fullscreen mode

// workers/stripe-webhook.worker.ts
import { Worker, Job } from "bullmq";
import Stripe from "stripe";
import { redis } from "@/lib/redis";
import { isAlreadyProcessed, markAsProcessed } from "@/lib/webhook-idempotency";
import { handlePaymentSucceeded } from "./handlers/payment-succeeded";
import { handleSubscriptionDeleted } from "./handlers/subscription-deleted";
import { handleInvoicePaymentFailed } from "./handlers/invoice-payment-failed";

const worker = new Worker(
  "stripe-webhooks",
  async (job: Job<{ event: Stripe.Event }>) => {
    const { event } = job.data;

    // Double-check idempotency inside the worker — edge case: worker restart mid-job
    const alreadyProcessed = await isAlreadyProcessed(event.id);
    if (alreadyProcessed) {
      return { skipped: true, reason: "duplicate" };
    }

    switch (event.type) {
      case "payment_intent.succeeded":
        await handlePaymentSucceeded(event.data.object as Stripe.PaymentIntent);
        break;

      case "customer.subscription.deleted":
        await handleSubscriptionDeleted(event.data.object as Stripe.Subscription);
        break;

      case "invoice.payment_failed":
        await handleInvoicePaymentFailed(event.data.object as Stripe.Invoice);
        break;

      default:
        console.log(`Unhandled webhook type: ${event.type}`);
        return { skipped: true, reason: "unhandled_type" };
    }

    // Mark processed only after the handler succeeds
    // If the handler throws, BullMQ retries the job — we don't mark it done
    await markAsProcessed(event.id, event.type, event.data.object);

    return { processed: true };
  },
  {
    connection: redis,
    concurrency: 5,
  }
);

worker.on("failed", (job, err) => {
  // After all retries exhausted, alert your team
  console.error(`Webhook job ${job?.id} failed permanently:`, err);
});

Enter fullscreen mode Exit fullscreen mode

The dead letter queue behavior is built into BullMQ — failed jobs (after all retries) stay in the failed state. I keep a Telegram alert on the failed event so I know immediately when something needs manual intervention.

Handling the Key Events

payment_intent.succeeded — the most critical handler. Wrap it in a database transaction so partial writes don't leave inconsistent state:

// workers/handlers/payment-succeeded.ts
import Stripe from "stripe";
import { db } from "@/packages/db";
import { orders, users } from "@/packages/db/schema";
import { eq } from "drizzle-orm";

export async function handlePaymentSucceeded(paymentIntent: Stripe.PaymentIntent): Promise<void> {
  const customerId = paymentIntent.customer as string;
  const metadata = paymentIntent.metadata;

  await db.transaction(async (tx) => {
    await tx.insert(orders).values({
      stripePaymentIntentId: paymentIntent.id,
      customerId,
      amount: paymentIntent.amount,
      currency: paymentIntent.currency,
      status: "paid",
    });

    if (metadata.plan) {
      await tx
        .update(users)
        .set({ plan: metadata.plan, planActivatedAt: new Date() })
        .where(eq(users.stripeCustomerId, customerId));
    }
  });

  // Send confirmation email outside the transaction — failure here
  // doesn't roll back the order; it just retries the email separately
  await sendOrderConfirmation({ paymentIntentId: paymentIntent.id });
}

Enter fullscreen mode Exit fullscreen mode

customer.subscription.deleted — downgrade the user, don't delete their data. Keep at least 30 days of data post-cancellation. Stripe fires this for both immediate cancellations and end-of-period ones — check cancel_at_period_end to differentiate.

invoice.payment_failed — send a dunning email, don't immediately revoke access. Stripe's Smart Retries will attempt the charge again. Give the customer a grace period to update their payment method.

Testing with Stripe CLI

# Forward all events to your local Next.js dev server
stripe listen \
  --forward-to localhost:3000/api/webhooks/stripe

# Trigger specific events
stripe trigger payment_intent.succeeded
stripe trigger customer.subscription.deleted
stripe trigger invoice.payment_failed

Enter fullscreen mode Exit fullscreen mode

For testing idempotency: copy the event ID from the CLI output and call your endpoint twice with the same payload — the second call should return { received: true, duplicate: true } within milliseconds.

Gotchas That Cost Me Real Time

request.json() silently breaks signature verification. The raw body and the serialized JSON aren't byte-for-byte identical. Always use request.arrayBuffer(). This is the most common issue I see in Next.js webhook implementations.

BullMQ jobId deduplication only covers active jobs. If a job is completed or failed, BullMQ will accept a new job with the same ID. That's why the database idempotency check is still necessary — it covers retries arriving weeks after the original was processed.

STRIPE_WEBHOOK_SECRET differs between environments. The CLI secret (whsec_... with CLI prefix) is different from the dashboard secret. Use separate environment variables for each environment.

Never trust event.data.object amounts without checking currency. EUR amounts are in cents (100 = €1.00). JPY has no minor unit (100 = ¥100). Always pair the amount with the currency field when storing.

What This Looks Like in Production

On vatnode.dev, webhooks hit the endpoint and return within 40–60ms. The BullMQ worker processes the actual subscription logic asynchronously, with 5 concurrent workers handling bursts. Zero duplicate subscriptions created since launch.

On pikkuna.fi, the same architecture drives the full order pipeline — Stripe fires the webhook, the worker triggers Zoho CRM, PostNord shipment creation, Netvisor invoice, and Mailgun confirmation email in sequence. The webhook endpoint returns 200 within 50ms; the full chain completes in under 2 minutes.


If you're building a SaaS or e-commerce platform with Stripe, you'll hit exactly these problems — usually at the worst moment, like during a product launch or after a server restart.

I've built reliable Stripe integrations across several production systems, from subscription SaaS (vatnode.dev) to high-volume international e-commerce (pikkuna.fi). Once the webhook pipeline is solid, the order automation layer on top becomes straightforward — see how the full e-commerce order pipeline works.

If you need a senior developer who can own the payment infrastructure end-to-end — get in touch. I'm available for API integration and e-commerce development projects and long-term engagements.


Related projects: Pikkuna E-commerce Platform — full order pipeline with Stripe, Zoho CRM, and PostNord integration. Vatnode VAT validation SaaS — subscription billing where this webhook architecture is in production.