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

推荐订阅源

罗磊的独立博客
Apple Machine Learning Research
Apple Machine Learning Research
The Cloudflare Blog
WordPress大学
WordPress大学
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
博客园 - 叶小钗
博客园 - 聂微东
阮一峰的网络日志
阮一峰的网络日志
腾讯CDC
博客园 - 三生石上(FineUI控件)
V
V2EX
有赞技术团队
有赞技术团队
V
Visual Studio Blog
小众软件
小众软件
Jina AI
Jina AI
酷 壳 – CoolShell
酷 壳 – CoolShell
博客园 - Franky
量子位
T
Tailwind CSS Blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
P
Palo Alto Networks Blog
Cisco Talos Blog
Cisco Talos Blog
I
Intezer
Project Zero
Project Zero
A
Arctic Wolf
P
Privacy International News Feed
V
Vulnerabilities – Threatpost
L
Lohrmann on Cybersecurity
S
Securelist
C
Cybersecurity and Infrastructure Security Agency CISA
C
CXSECURITY Database RSS Feed - CXSecurity.com
T
Tor Project blog
Hacker News - Newest:
Hacker News - Newest: "LLM"
S
Security @ Cisco Blogs
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Google DeepMind News
Google DeepMind News
N
News and Events Feed by Topic
TaoSecurity Blog
TaoSecurity Blog
L
LINUX DO - 热门话题
G
GRAHAM CLULEY
Help Net Security
Help Net Security
N
News | PayPal Newsroom
W
WeLiveSecurity
G
Google Developers Blog
Microsoft Security Blog
Microsoft Security Blog
Engineering at Meta
Engineering at Meta
MongoDB | Blog
MongoDB | Blog
C
Check Point Blog

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
Next.js Webhook Handling and Event-Driven Architecture
Mahdi BEN RHOUMA · 2026-06-15 · via DEV Community

Next.js Webhook Handling and Event-Driven Architecture

Building robust webhook handling in Next.js enables real-time responsiveness and event-driven architecture. This guide covers webhook security, retry mechanisms, event processing, and distributed system patterns for production applications.

TL;DR

Build production-ready event-driven systems using webhooks with Next.js and Supabase. You'll implement secure webhook endpoints, reliable event processing, retry mechanisms, and distributed system patterns for scalable applications.

Prerequisites

  • Next.js 14+ with API Routes experience
  • Supabase database and Edge Functions knowledge
  • Understanding of HTTP protocols and security
  • Basic knowledge of distributed systems concepts

Problem Statement

Modern applications need to react to events from multiple sources: payment processors, third-party APIs, user actions, and system events. Simple polling is inefficient and doesn't scale. Event-driven architecture with webhooks provides real-time responsiveness but introduces complexity around security, reliability, and error handling.

What Are Webhooks and How Do They Work?

Webhooks push data to your application when events occur, while polling requires your app to repeatedly check for changes. Webhooks are more efficient, provide real-time updates, and reduce server load, but require proper security and error handling.

How Do You Secure Webhook Endpoints in Next.js?

Verify webhook signatures using HMAC, validate the source IP if possible, use HTTPS only, implement rate limiting, and validate payload structure. Never trust webhook data without verification - treat it as potentially malicious input.

What Happens When Webhook Processing Fails?

Implement retry mechanisms with exponential backoff, use dead letter queues for failed events, monitor webhook health, and consider using message queues for reliability. Most webhook providers retry failed deliveries automatically, so your endpoint should handle duplicate events gracefully.

Step-by-Step Walkthrough

1. Webhook Infrastructure Setup

Create a robust webhook handling system:

-- Webhook events tracking table
CREATE TABLE webhook_events (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  event_id TEXT UNIQUE NOT NULL, -- External event ID for idempotency
  source TEXT NOT NULL, -- 'stripe', 'github', 'supabase', etc.
  event_type TEXT NOT NULL,
  payload JSONB NOT NULL,
  status TEXT NOT NULL DEFAULT 'pending', -- 'pending', 'processing', 'completed', 'failed'
  attempts INTEGER DEFAULT 0,
  last_attempt_at TIMESTAMPTZ,
  completed_at TIMESTAMPTZ,
  error_message TEXT,
  created_at TIMESTAMPTZ DEFAULT NOW()
);

-- Event processing jobs queue
CREATE TABLE event_jobs (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  webhook_event_id UUID REFERENCES webhook_events(id) ON DELETE CASCADE,
  job_type TEXT NOT NULL,
  payload JSONB NOT NULL,
  status TEXT NOT NULL DEFAULT 'queued', -- 'queued', 'processing', 'completed', 'failed'
  scheduled_for TIMESTAMPTZ DEFAULT NOW(),
  attempts INTEGER DEFAULT 0,
  max_attempts INTEGER DEFAULT 3,
  created_at TIMESTAMPTZ DEFAULT NOW(),
  updated_at TIMESTAMPTZ DEFAULT NOW()
);

-- Indexes for performance
CREATE INDEX idx_webhook_events_status ON webhook_events(status);
CREATE INDEX idx_webhook_events_source_type ON webhook_events(source, event_type);
CREATE INDEX idx_event_jobs_status_scheduled ON event_jobs(status, scheduled_for);

2. Secure Webhook Endpoint

Implement a secure, generic webhook handler:

// app/api/webhooks/[source]/route.ts
import { NextRequest, NextResponse } from 'next/server'
import { createClient } from '@/lib/supabase/server'
import { verifyWebhookSignature } from '@/lib/webhook-security'
import { queueEventJob } from '@/lib/event-queue'

interface WebhookConfig {
  secretKey: string
  signatureHeader: string
  verifySignature: (payload: string, signature: string, secret: string) => boolean
}

const WEBHOOK_CONFIGS: Record<string, WebhookConfig> = {
  stripe: {
    secretKey: process.env.STRIPE_WEBHOOK_SECRET!,
    signatureHeader: 'stripe-signature',
    verifySignature: verifyStripeSignature
  },
  github: {
    secretKey: process.env.GITHUB_WEBHOOK_SECRET!,
    signatureHeader: 'x-hub-signature-256',
    verifySignature: verifyGitHubSignature
  },
  supabase: {
    secretKey: process.env.SUPABASE_WEBHOOK_SECRET!,
    signatureHeader: 'x-supabase-signature',
    verifySignature: verifySupabaseSignature
  }
}

export async function POST(
  request: NextRequest,
  { params }: { params: { source: string } }
) {
  const source = params.source
  const config = WEBHOOK_CONFIGS[source]

  if (!config) {
    return NextResponse.json(
      { error: 'Unknown webhook source' },
      { status: 400 }
    )
  }

  try {
    // Get raw body for signature verification
    const body = await request.text()
    const signature = request.headers.get(config.signatureHeader)

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

    // Verify webhook signature
    if (!config.verifySignature(body, signature, config.secretKey)) {
      return NextResponse.json(
        { error: 'Invalid signature' },
        { status: 401 }
      )
    }

    const payload = JSON.parse(body)
    const eventId = extractEventId(source, payload)
    const eventType = extractEventType(source, payload)

    // Store webhook event with idempotency check
    const supabase = createClient()
    const { data: existingEvent } = await supabase
      .from('webhook_events')
      .select('id, status')
      .eq('event_id', eventId)
      .single()

    if (existingEvent) {
      // Event already processed or processing
      return NextResponse.json({ 
        message: 'Event already processed',
        status: existingEvent.status 
      })
    }

    // Store new webhook event
    const { data: webhookEvent, error } = await supabase
      .from('webhook_events')
      .insert({
        event_id: eventId,
        source,
        event_type: eventType,
        payload,
        status: 'pending'
      })
      .select()
      .single()

    if (error) throw error

    // Queue processing job
    await queueEventJob(webhookEvent.id, eventType, payload)

    return NextResponse.json({ 
      message: 'Webhook received',
      event_id: eventId 
    })

  } catch (error) {
    console.error('Webhook processing error:', error)
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    )
  }
}

// Helper functions for different webhook sources
function extractEventId(source: string, payload: any): string {
  switch (source) {
    case 'stripe':
      return payload.id
    case 'github':
      return payload.delivery || `${payload.repository?.id}-${Date.now()}`
    case 'supabase':
      return payload.record?.id || `${payload.table}-${Date.now()}`
    default:
      return `${source}-${Date.now()}`
  }
}

function extractEventType(source: string, payload: any): string {
  switch (source) {
    case 'stripe':
      return payload.type
    case 'github':
      return payload.action ? `${payload.action}` : 'unknown'
    case 'supabase':
      return `${payload.type}.${payload.table}`
    default:
      return 'unknown'
  }
}

3. Webhook Signature Verification

Implement secure signature verification for different providers:

// lib/webhook-security.ts
import crypto from 'crypto'

export function verifyStripeSignature(
  payload: string,
  signature: string,
  secret: string
): boolean {
  const elements = signature.split(',')
  const signatureElements = elements.reduce((acc, element) => {
    const [key, value] = element.split('=')
    acc[key] = value
    return acc
  }, {} as Record<string, string>)

  const timestamp = signatureElements.t
  const signatures = [signatureElements.v1]

  const expectedSignature = crypto
    .createHmac('sha256', secret)
    .update(`${timestamp}.${payload}`)
    .digest('hex')

  return signatures.some(sig => 
    crypto.timingSafeEqual(
      Buffer.from(sig, 'hex'),
      Buffer.from(expectedSignature, 'hex')
    )
  )
}

export function verifyGitHubSignature(
  payload: string,
  signature: string,
  secret: string
): boolean {
  const expectedSignature = crypto
    .createHmac('sha256', secret)
    .update(payload)
    .digest('hex')

  const actualSignature = signature.replace('sha256=', '')

  return crypto.timingSafeEqual(
    Buffer.from(actualSignature, 'hex'),
    Buffer.from(expectedSignature, 'hex')
  )
}

export function verifySupabaseSignature(
  payload: string,
  signature: string,
  secret: string
): boolean {
  const expectedSignature = crypto
    .createHmac('sha256', secret)
    .update(payload)
    .digest('base64')

  return crypto.timingSafeEqual(
    Buffer.from(signature),
    Buffer.from(expectedSignature)
  )
}

4. Event Processing Queue System

Build a reliable job queue for processing webhook events:

// lib/event-queue.ts
import { createClient } from '@/lib/supabase/server'

export async function queueEventJob(
  webhookEventId: string,
  jobType: string,
  payload: any,
  scheduledFor?: Date
) {
  const supabase = createClient()

  const { error } = await supabase
    .from('event_jobs')
    .insert({
      webhook_event_id: webhookEventId,
      job_type: jobType,
      payload,
      scheduled_for: scheduledFor?.toISOString() || new Date().toISOString()
    })

  if (error) throw error
}

export async function processEventJobs() {
  const supabase = createClient()

  // Get pending jobs
  const { data: jobs, error } = await supabase
    .from('event_jobs')
    .select('*')
    .eq('status', 'queued')
    .lte('scheduled_for', new Date().toISOString())
    .order('created_at', { ascending: true })
    .limit(10)

  if (error) throw error

  for (const job of jobs) {
    await processJob(job)
  }
}

async function processJob(job: any) {
  const supabase = createClient()

  try {
    // Mark job as processing
    await supabase
      .from('event_jobs')
      .update({ 
        status: 'processing',
        updated_at: new Date().toISOString()
      })
      .eq('id', job.id)

    // Process based on job type
    await processJobByType(job.job_type, job.payload)

    // Mark as completed
    await supabase
      .from('event_jobs')
      .update({ 
        status: 'completed',
        updated_at: new Date().toISOString()
      })
      .eq('id', job.id)

    // Mark webhook event as completed
    await supabase
      .from('webhook_events')
      .update({ 
        status: 'completed',
        completed_at: new Date().toISOString()
      })
      .eq('id', job.webhook_event_id)

  } catch (error) {
    console.error('Job processing failed:', error)

    const newAttempts = job.attempts + 1
    const shouldRetry = newAttempts < job.max_attempts

    if (shouldRetry) {
      // Schedule retry with exponential backoff
      const retryDelay = Math.pow(2, newAttempts) * 1000 // 2s, 4s, 8s...
      const scheduledFor = new Date(Date.now() + retryDelay)

      await supabase
        .from('event_jobs')
        .update({
          status: 'queued',
          attempts: newAttempts,
          scheduled_for: scheduledFor.toISOString(),
          updated_at: new Date().toISOString()
        })
        .eq('id', job.id)
    } else {
      // Mark as failed
      await supabase
        .from('event_jobs')
        .update({
          status: 'failed',
          attempts: newAttempts,
          updated_at: new Date().toISOString()
        })
        .eq('id', job.id)

      await supabase
        .from('webhook_events')
        .update({
          status: 'failed',
          error_message: error instanceof Error ? error.message : 'Unknown error'
        })
        .eq('id', job.webhook_event_id)
    }
  }
}

async function processJobByType(jobType: string, payload: any) {
  switch (jobType) {
    case 'payment.succeeded':
      await handlePaymentSucceeded(payload)
      break
    case 'user.created':
      await handleUserCreated(payload)
      break
    case 'subscription.updated':
      await handleSubscriptionUpdated(payload)
      break
    default:
      console.warn(`Unknown job type: ${jobType}`)
  }
}

5. Event Handlers Implementation

Create specific handlers for different event types:

// lib/event-handlers.ts
import { createClient } from '@/lib/supabase/server'
import { sendEmail } from '@/lib/email'
import { updateUserPlan } from '@/lib/billing'

export async function handlePaymentSucceeded(payload: any) {
  const supabase = createClient()

  const { customer, amount, currency, metadata } = payload.data.object

  // Update user's payment status
  const { error } = await supabase
    .from('payments')
    .insert({
      stripe_payment_id: payload.data.object.id,
      customer_id: customer,
      amount,
      currency,
      status: 'succeeded',
      metadata
    })

  if (error) throw error

  // Send confirmation email
  await sendEmail({
    to: metadata.user_email,
    template: 'payment-confirmation',
    data: { amount, currency }
  })

  // Update user plan if this was a subscription payment
  if (metadata.subscription_id) {
    await updateUserPlan(metadata.user_id, metadata.plan_id)
  }
}

export async function handleUserCreated(payload: any) {
  const supabase = createClient()
  const { user } = payload

  // Create user profile
  const { error } = await supabase
    .from('user_profiles')
    .insert({
      user_id: user.id,
      email: user.email,
      created_at: user.created_at
    })

  if (error) throw error

  // Send welcome email
  await sendEmail({
    to: user.email,
    template: 'welcome',
    data: { name: user.user_metadata?.name || 'there' }
  })

  // Create default workspace
  await supabase
    .from('workspaces')
    .insert({
      name: 'My Workspace',
      owner_id: user.id
    })
}

export async function handleSubscriptionUpdated(payload: any) {
  const supabase = createClient()
  const subscription = payload.data.object

  // Update subscription in database
  const { error } = await supabase
    .from('subscriptions')
    .upsert({
      stripe_subscription_id: subscription.id,
      customer_id: subscription.customer,
      status: subscription.status,
      current_period_start: new Date(subscription.current_period_start * 1000),
      current_period_end: new Date(subscription.current_period_end * 1000),
      plan_id: subscription.items.data[0]?.price?.id
    })

  if (error) throw error

  // Handle subscription status changes
  if (subscription.status === 'canceled') {
    await handleSubscriptionCanceled(subscription)
  } else if (subscription.status === 'past_due') {
    await handleSubscriptionPastDue(subscription)
  }
}

async function handleSubscriptionCanceled(subscription: any) {
  const supabase = createClient()

  // Downgrade user to free plan
  const { data: user } = await supabase
    .from('users')
    .select('id, email')
    .eq('stripe_customer_id', subscription.customer)
    .single()

  if (user) {
    await updateUserPlan(user.id, 'free')

    await sendEmail({
      to: user.email,
      template: 'subscription-canceled',
      data: { cancellation_date: new Date() }
    })
  }
}

6. Cron Job for Processing Events

Set up automated event processing:

// app/api/cron/process-events/route.ts
import { NextResponse } from 'next/server'
import { processEventJobs } from '@/lib/event-queue'

export async function GET(request: Request) {
  // Verify cron secret to prevent unauthorized access
  const authHeader = request.headers.get('authorization')
  if (authHeader !== `Bearer ${process.env.CRON_SECRET}`) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
  }

  try {
    await processEventJobs()
    return NextResponse.json({ message: 'Events processed successfully' })
  } catch (error) {
    console.error('Event processing failed:', error)
    return NextResponse.json(
      { error: 'Event processing failed' },
      { status: 500 }
    )
  }
}

7. Event Monitoring and Observability

Implement comprehensive monitoring:

// lib/webhook-monitoring.ts
import { createClient } from '@/lib/supabase/server'

export async function getWebhookMetrics(timeframe: 'hour' | 'day' | 'week' = 'day') {
  const supabase = createClient()

  const timeframeSql = {
    hour: "created_at >= NOW() - INTERVAL '1 hour'",
    day: "created_at >= NOW() - INTERVAL '1 day'",
    week: "created_at >= NOW() - INTERVAL '1 week'"
  }

  // Get event counts by status
  const { data: statusCounts } = await supabase
    .from('webhook_events')
    .select('status, count(*)')
    .gte('created_at', getTimeframeStart(timeframe))
    .group('status')

  // Get event counts by source
  const { data: sourceCounts } = await supabase
    .from('webhook_events')
    .select('source, count(*)')
    .gte('created_at', getTimeframeStart(timeframe))
    .group('source')

  // Get failed events with details
  const { data: failedEvents } = await supabase
    .from('webhook_events')
    .select('*')
    .eq('status', 'failed')
    .gte('created_at', getTimeframeStart(timeframe))
    .order('created_at', { ascending: false })
    .limit(10)

  // Get average processing time
  const { data: processingTimes } = await supabase
    .rpc('get_avg_processing_time', { timeframe })

  return {
    statusCounts,
    sourceCounts,
    failedEvents,
    avgProcessingTime: processingTimes?.[0]?.avg_time || 0
  }
}

function getTimeframeStart(timeframe: string): string {
  const now = new Date()
  switch (timeframe) {
    case 'hour':
      return new Date(now.getTime() - 60 * 60 * 1000).toISOString()
    case 'day':
      return new Date(now.getTime() - 24 * 60 * 60 * 1000).toISOString()
    case 'week':
      return new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000).toISOString()
    default:
      return new Date(now.getTime() - 24 * 60 * 60 * 1000).toISOString()
  }
}

// Database function for calculating processing times
/*
CREATE OR REPLACE FUNCTION get_avg_processing_time(timeframe TEXT)
RETURNS TABLE(avg_time INTERVAL) AS $$
BEGIN
  RETURN QUERY
  SELECT AVG(completed_at - created_at) as avg_time
  FROM webhook_events
  WHERE status = 'completed'
    AND created_at >= CASE
      WHEN timeframe = 'hour' THEN NOW() - INTERVAL '1 hour'
      WHEN timeframe = 'day' THEN NOW() - INTERVAL '1 day'
      WHEN timeframe = 'week' THEN NOW() - INTERVAL '1 week'
      ELSE NOW() - INTERVAL '1 day'
    END;
END;
$$ LANGUAGE plpgsql;
*/

8. Event Replay and Recovery

Implement event replay for failed or missed events:

// lib/event-replay.ts
import { createClient } from '@/lib/supabase/server'
import { queueEventJob } from '@/lib/event-queue'

export async function replayFailedEvents(
  source?: string,
  eventType?: string,
  fromDate?: Date
) {
  const supabase = createClient()

  let query = supabase
    .from('webhook_events')
    .select('*')
    .eq('status', 'failed')

  if (source) query = query.eq('source', source)
  if (eventType) query = query.eq('event_type', eventType)
  if (fromDate) query = query.gte('created_at', fromDate.toISOString())

  const { data: failedEvents, error } = await query
    .order('created_at', { ascending: true })

  if (error) throw error

  for (const event of failedEvents) {
    // Reset event status
    await supabase
      .from('webhook_events')
      .update({ status: 'pending' })
      .eq('id', event.id)

    // Queue new processing job
    await queueEventJob(event.id, event.event_type, event.payload)
  }

  return { replayedCount: failedEvents.length }
}

export async function replayEventById(eventId: string) {
  const supabase = createClient()

  const { data: event, error } = await supabase
    .from('webhook_events')
    .select('*')
    .eq('id', eventId)
    .single()

  if (error) throw error

  // Reset status and queue for processing
  await supabase
    .from('webhook_events')
    .update({ status: 'pending' })
    .eq('id', eventId)

  await queueEventJob(event.id, event.event_type, event.payload)

  return { message: 'Event queued for replay' }
}

Common Pitfalls

1. Not Implementing Idempotency

Problem: Processing the same webhook multiple times causes data inconsistency.
Solution: Always use unique event IDs and check for existing events before processing.

2. Synchronous Processing

Problem: Long-running webhook processing causes timeouts and retries.
Solution: Acknowledge webhooks immediately and process asynchronously with job queues.

3. Insufficient Error Handling

Problem: Failed webhooks are lost without proper retry mechanisms.
Solution: Implement exponential backoff, dead letter queues, and monitoring for failed events.

Production Considerations

Security Hardening

  • Always verify webhook signatures using timing-safe comparison
  • Implement rate limiting per source to prevent abuse
  • Use HTTPS only and validate SSL certificates
  • Log all webhook attempts for security auditing

Reliability and Scaling

  • Use database transactions for atomic event processing
  • Implement circuit breakers for external service calls
  • Consider using message queues (Redis, RabbitMQ) for high-volume scenarios
  • Set up monitoring and alerting for webhook failures

Performance Optimization

  • Index webhook events table on frequently queried columns
  • Implement connection pooling for database operations
  • Use batch processing for high-volume events
  • Consider event streaming for real-time requirements

Further Reading

  1. Event Sourcing Patterns - Building audit trails and event stores
  2. Multi-Tenant Architecture - Handling tenant-scoped events and webhooks
  3. Message Queue Integration - Redis, RabbitMQ, and cloud solutions
  4. Error Handling and Observability - Metrics, logging, and alerting
  5. Webhook Security Standards - Industry best practices and compliance

Originally published at https://www.iloveblogs.blog