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

推荐订阅源

Engineering at Meta
Engineering at Meta
Hacker News: Ask HN
Hacker News: Ask HN
Know Your Adversary
Know Your Adversary
C
Cisco Blogs
T
The Exploit Database - CXSecurity.com
T
Threat Research - Cisco Blogs
Scott Helme
Scott Helme
T
Tor Project blog
T
Tenable Blog
P
Privacy & Cybersecurity Law Blog
C
Cybersecurity and Infrastructure Security Agency CISA
S
Securelist
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Hacker News - Newest:
Hacker News - Newest: "LLM"
S
Secure Thoughts
大猫的无限游戏
大猫的无限游戏
腾讯CDC
L
LangChain Blog
IT之家
IT之家
Recent Commits to openclaw:main
Recent Commits to openclaw:main
月光博客
月光博客
N
News and Events Feed by Topic
GbyAI
GbyAI
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
T
Tailwind CSS Blog
Jina AI
Jina AI
S
Security Affairs
T
The Blog of Author Tim Ferriss
博客园 - Franky
H
Hacker News: Front Page
Martin Fowler
Martin Fowler
D
DataBreaches.Net
酷 壳 – CoolShell
酷 壳 – CoolShell
Webroot Blog
Webroot Blog
L
Lohrmann on Cybersecurity
C
CXSECURITY Database RSS Feed - CXSecurity.com
U
Unit 42
S
Schneier on Security
B
Blog
Schneier on Security
Schneier on Security
Latest news
Latest news
TaoSecurity Blog
TaoSecurity Blog
Google DeepMind News
Google DeepMind News
The Register - Security
The Register - Security
Recorded Future
Recorded Future
O
OpenAI News
雷峰网
雷峰网
H
Heimdal Security Blog

The Practical Developer

The Libuv Thread Pool Trap: Why Node.js Async APIs Stall Under Load Postgres Covering Indexes with INCLUDE: Eliminate Heap Fetches on Read-Heavy Workloads Postgres DISTINCT ON: The Fastest Way to Get the Latest Row Per Group Postgres Transaction Isolation: The Anomalies Your App Actually Faces in Production Linux TCP Tuning for Node.js Microservices: The Kernel Settings That Stop Silent Connection Drops Under Load Postgres HOT Updates and Fillfactor: Why Not All Writes Are Created Equal Database Connection Pool Leaks: Finding the Promise That Never Returns Its Seat Linux OOM Killer in Production: Why Your Node.js Containers Die Without a Stack Trace Postgres Materialized Views: Refresh Strategies That Do Not Lock Your Dashboards API Dependency Health Checks: Why /health Is Not Enough Authorization with Zanzibar Tuples: How Google Manages Permissions and How To Build the Same Check in Node.js Postgres Advisory Locks: The 20-Character Primitive That Replaces Redis for Coordination Dead Letter Queues: The Message Queue Pattern That Saves You at 2 a.m. File Descriptor Exhaustion: The Kernel Limit That Silently Drops Node.js Connections Graceful Degradation: The Pattern That Turns Total Outages into Partial Success PostgreSQL Full-Text Search: Dropping Elasticsearch for 90% of Use Cases S3 Presigned Multipart Uploads: Stop Your API Server from Being a File Upload Bottleneck MessagePack vs JSON: The Binary Serialization Switch That Cut Our Internal RPC Overhead by 40% DNS Caching in Node.js: The Silent Cause of Production Latency Spikes Reliable Cron Jobs: The Pattern That Stops Double Runs, Missed Executions, And The 2 AM Page GraphQL Query Complexity: Stop the OOM Query Before It Reaches Your Resolver Node.js Event Loop Lag: The Hidden Metric Behind Random Latency Spikes API Request Validation with Zod: The Schema That Catches Bad Input Before It Corrupts Your Database Load Shedding in Node.js: How to Reject Traffic Before You Drown Request Hedging: Cut Tail Latency In Half Without Overprovisioning Git Bisect: The Automated Binary Search That Finds Breaking Commits in Minutes Node.js Garbage Collection Tuning: Stop Letting V8 Pause Your Event Loop Node.js Server Timeouts: The Settings That Stop Slow Clients from Holding Sockets Hostage Postgres BRIN Indexes: The Time-Series Secret That Shrinks Indexes by 99% Event Sourcing with PostgreSQL: The Pragmatic 80% Solution Node.js Cluster Mode: Scaling the Event Loop Across CPU Cores Postgres Partial Indexes: Stopping Soft Deletes from Ruining Your Query Performance Request Coalescing with the Singleflight Pattern: Stop Drowning Your Database on Every Cache Miss The Bulkhead Pattern: Why One Slow Endpoint Should Not Drown Your Whole Service Node.js AsyncLocalStorage: End-to-End Request Context Without the Propagation Hell Postgres Deadlocks: Logging the Victim, Reproducing the Race, and Fixing the Lock Order Your Node.js HTTP Client Is the Bottleneck: Connection Pool Tuning That Works Optimistic Locking in Postgres: Stop Losing Data to Race Conditions Postgres Read Replicas: Stop Serving Stale Data to Your Users Cursor Pagination: Why Offset Queries Explode at Scale and How to Fix Them Node.js Worker Threads: 60 Lines That Stop a CSV Upload from Timing Out Every Other Request Reliable Webhook Delivery: Architecture for Outbound HTTP You Can Trust Request Timeouts and Deadline Propagation: Stop the Chain of Slowness Advanced Security Practices in Node.js Graceful Shutdown in Node.js: The 40 Lines That Stop 502s During Deploys Finding Node.js Memory Leaks with Heap Snapshots Idempotency Keys in 30 Lines: Stop Your Webhook From Charging Customers Twice Backpressure In Node.js: The Fix For Slow-Motion Queue Meltdowns Retries Done Right: Jitter, Budgets, and the Stampede You Did Not See Coming The Cache Stampede: Why Your "Just Add Redis" Layer Crashes Postgres at 3 a.m. Postgres SKIP LOCKED: An 80-Line Job Queue You Can Run Without Redis Stop Doing Work Nobody Wants: AbortController in Node.js, Done Right The N+1 Query Problem: We Found 23 In One Codebase And Killed Every One I Tried 5 AI Coding Tools for a Month. Here Is What I Actually Use CI/CD From Zero to Production in 30 Minutes With GitHub Actions Node.js vs Bun vs Deno: Which Runtime Should You Pick in 2025? Kubernetes Resource Requests And Limits: The Numbers That Decide If Your Cluster Is Stable The Three Pillars of Observability Are A Myth: What Actually Matters In Production pnpm Vs npm Vs yarn Vs Bun For Monorepos: Which One Earns The Migration In 2024 JSONB Indexing In Postgres: GIN Vs Expression Indexes, And When Each Is The Right Choice A Code Review Checklist That Ends The Same Three Arguments Every Sprint gRPC Vs REST In 2024: When The Switch Pays For Itself React Suspense For Data Fetching: The Pattern That Replaces Half Your Loading State Code The Five-Stage Rollout: How To Ship A Risky Change Without Holding Your Breath GitHub Actions In A Monorepo: Caching, Path Filters, And Secret Boundaries That Actually Work The Blameless Postmortem That Actually Improves Things: A Template And Six Hard-Won Rules Recursive CTEs In Postgres: How To Query A Tree Without N Round Trips Node.js Streams: When They Actually Help, And When They Just Add Complexity Playwright Vs Cypress In 2024: The Honest Comparison Of Which One Earns The Test Time React Server Components: The Mental Model That Makes The "use client" Boundary Obvious Pod Disruption Budgets: The K8s Object That Keeps Your Service Up During Cluster Maintenance Postgres LISTEN/NOTIFY: The Pub/Sub You Already Have And Are Not Using Chaos Engineering Starter Kit: The Five Drills That Don't Need Netflix-Scale Spec-Driven API Development With OpenAPI: How To Stop Drifting From Your Docs Kubernetes Autoscaling Beyond CPU: The Custom-Metric HPA Pattern That Actually Works Postgres Partitioning For Time-Series: The Boring Setup That Saves Your Database Distributed Locks With Redis: An Honest Look At Redlock And When You Don't Need It HTTP/2 vs HTTP/3: What Actually Changes For Your App, And What Doesn't Image Optimization For The Web In 2023: srcset, AVIF, And The Lighthouse Score You Actually Want Kafka vs RabbitMQ: A Decision Tree That Doesn't Hate You UUID vs Bigint Primary Keys In Postgres: The Index Math That Decides For You Flame Graphs: How To Find The Slow Function In 30 Seconds Without Profiling Theatre Postgres Streaming Vs. Logical Replication: Which One Solves Your Actual Problem ESLint Rules That Earn Their Keep: The Twelve I Enable On Every Project Pre-Commit Hooks That Pay For Themselves: Husky, lint-staged, And The Five Rules That Stick Zero-Downtime Database Migrations: The Six-Step Pattern That Rules Them All Circuit Breakers In Node.js: 50 Lines That Stop A Failing Dependency From Taking Down Your Service Postgres VACUUM Is Not Magic: How Your Hot Table Bloats To 80GB And How To Fix It Kubernetes Liveness And Readiness Probes: The Difference That Causes Half Your Outages Rate Limiting In Production: A Token Bucket In 30 Lines Of Redis The Outbox Pattern: How To Stop Losing Events When Postgres And Kafka Disagree Load Testing With k6: The Three Scenarios That Find Real Bugs (Not Synthetic Numbers) Postgres Row-Level Security For Multi-Tenant Apps: The Pattern That Stops You From Leaking Data Rebase vs. Merge: The Team Policy That Ends The Argument Forever OpenTelemetry in Node.js: Distributed Tracing That Actually Helps During an Incident Feature Flags That Pay Rent: The 4 Flag Types And When To Delete Each ETag, Last-Modified, and the Caching Headers Most APIs Get Wrong Connection Pooling Without the Cargo Cult: pgbouncer in 100 Lines of Config JSONB Is Not a Schema: When To Reach For It in Postgres, And When To Stop Bash Strict Mode: The Three Lines That Stop Your Deploy Script From Lying To You
Webhook Signature Verification Is Not Enough: Stop Replay Attacks in Node.js
The Practica · 2026-05-11 · via The Practical Developer

Your payment provider sends a webhook when an invoice is paid. You verify the HMAC signature, update the subscription, send the welcome email, and move on.

Then the same signed request arrives again. Maybe the provider retried after a timeout. Maybe an attacker captured the request from a misconfigured proxy log. Maybe a developer replayed production traffic into staging and accidentally pointed it at production. The signature is still valid. Your handler runs again. The customer gets a second email, the fulfillment job runs twice, or worse, you credit an account twice.

That is the trap: signature verification answers one question only.

Did someone with the shared secret sign these exact bytes?

It does not answer:

  • Is this request recent?
  • Have we processed this event before?
  • Are two app instances racing to process the same event right now?
  • Did the body parser change the bytes before verification?

A production webhook endpoint needs all four answers. This post builds the boring version that survives retries, replay attacks, deploy races, and provider quirks.

The broken handler everybody ships first

Most webhook handlers start like this:

import express from 'express';
import crypto from 'node:crypto';

const app = express();
app.use(express.json());

app.post('/webhooks/billing', async (req, res) => {
  const signature = req.header('x-provider-signature');
  const expected = crypto
    .createHmac('sha256', process.env.WEBHOOK_SECRET!)
    .update(JSON.stringify(req.body))
    .digest('hex');

  if (signature !== expected) {
    return res.status(401).send('bad signature');
  }

  await activateSubscription(req.body.customerId);
  await sendWelcomeEmail(req.body.customerId);

  res.sendStatus(204);
});

This code has three real bugs.

First, it signs JSON.stringify(req.body), not the bytes the provider signed. JSON allows insignificant whitespace and object key ordering differences. Your framework parsed the payload, allocated a JavaScript object, then serialized a new string. That new string is not guaranteed to match the original body.

Second, signature !== expected leaks timing information. Is that the top priority on an internal admin webhook? Probably not. Is crypto.timingSafeEqual one line? Yes. Use it.

Third, it accepts the same valid request forever. If someone records the request today and sends it next month, the HMAC still matches.

Let’s fix the endpoint in layers.

Layer 1: verify the raw body, not parsed JSON

Most providers sign the raw request body. In Express, capture it with express.raw() for this route. Do not put express.json() in front of the webhook route.

import express from 'express';
import crypto from 'node:crypto';

const app = express();

app.post(
  '/webhooks/billing',
  express.raw({ type: 'application/json', limit: '1mb' }),
  async (req, res) => {
    const rawBody = req.body as Buffer;
    const signature = req.header('x-provider-signature');

    if (!signature || !verifySignature(rawBody, signature)) {
      return res.status(401).send('bad signature');
    }

    const event = JSON.parse(rawBody.toString('utf8'));
    await handleBillingEvent(event);

    res.sendStatus(204);
  },
);

function verifySignature(rawBody: Buffer, signatureHeader: string): boolean {
  const expected = crypto
    .createHmac('sha256', process.env.WEBHOOK_SECRET!)
    .update(rawBody)
    .digest('hex');

  const actual = Buffer.from(signatureHeader, 'hex');
  const expectedBuffer = Buffer.from(expected, 'hex');

  if (actual.length !== expectedBuffer.length) return false;
  return crypto.timingSafeEqual(actual, expectedBuffer);
}

If your provider uses a header like t=1715374800,v1=abc123, parse it explicitly. Do not compare the whole header string unless the documentation says that is the signed value.

Also notice the route-level body parser. This matters. A common production bug is this ordering:

app.use(express.json());
app.post('/webhooks/billing', express.raw({ type: 'application/json' }), handler);

By the time the request reaches express.raw(), it has already been consumed by express.json(). Your handler sees an object instead of a buffer. Put webhook routes before global JSON middleware, or mount them on a separate router.

Layer 2: reject old requests with a signed timestamp

Replay protection starts with freshness. The provider should include a timestamp in the signed material. Stripe-style headers are common:

x-provider-signature: t=1715374800,v1=9f2c...

The signature is computed over:

<timestamp>.<raw body>

That timestamp must be part of the HMAC input. If the timestamp is just an unsigned header, an attacker can replace it with the current time and replay the old body.

Here is a verifier with a five-minute tolerance window:

const MAX_SKEW_SECONDS = 5 * 60;

type ParsedSignature = {
  timestamp: number;
  signatures: string[];
};

function parseSignatureHeader(header: string): ParsedSignature | null {
  const parts = header.split(',');
  let timestamp: number | undefined;
  const signatures: string[] = [];

  for (const part of parts) {
    const [key, value] = part.split('=');
    if (key === 't') timestamp = Number(value);
    if (key === 'v1' && value) signatures.push(value);
  }

  if (!timestamp || signatures.length === 0) return null;
  return { timestamp, signatures };
}

function verifySignedRequest(rawBody: Buffer, header: string, now = Date.now()): boolean {
  const parsed = parseSignatureHeader(header);
  if (!parsed) return false;

  const ageSeconds = Math.abs(Math.floor(now / 1000) - parsed.timestamp);
  if (ageSeconds > MAX_SKEW_SECONDS) return false;

  const signedPayload = Buffer.concat([
    Buffer.from(`${parsed.timestamp}.`, 'utf8'),
    rawBody,
  ]);

  const expected = crypto
    .createHmac('sha256', process.env.WEBHOOK_SECRET!)
    .update(signedPayload)
    .digest('hex');

  return parsed.signatures.some((candidate) => safeHexEqual(candidate, expected));
}

function safeHexEqual(a: string, b: string): boolean {
  try {
    const aBuffer = Buffer.from(a, 'hex');
    const bBuffer = Buffer.from(b, 'hex');
    return aBuffer.length === bBuffer.length && crypto.timingSafeEqual(aBuffer, bBuffer);
  } catch {
    return false;
  }
}

Five minutes is a sane default. Too short and you reject legitimate retries when clocks drift or queues back up. Too long and you extend the replay window. Pick a value deliberately, monitor rejections, and keep NTP working on your servers.

This stops captured requests from being replayed next week. It does not stop a valid request from being replayed twice inside the five-minute window. Providers retry inside that window all the time. That is where idempotency comes in.

Layer 3: store event IDs, not vibes

A webhook event should have a stable unique ID from the provider: evt_123, invoice.paid:abc, a delivery ID, or a transaction ID. Use it. If the provider does not send one, derive a fingerprint from the provider name, event type, and raw body hash. A provider-issued ID is better because two legitimate events can have identical bodies.

Create a table for processed webhooks:

CREATE TABLE webhook_events (
  provider text NOT NULL,
  event_id text NOT NULL,
  event_type text NOT NULL,
  received_at timestamptz NOT NULL DEFAULT now(),
  processed_at timestamptz,
  status text NOT NULL CHECK (status IN ('processing', 'processed', 'failed')),
  error text,
  PRIMARY KEY (provider, event_id)
);

Then claim the event before doing side effects:

async function claimWebhookEvent(event: BillingEvent): Promise<'claimed' | 'duplicate'> {
  const result = await db.query(
    `INSERT INTO webhook_events (provider, event_id, event_type, status)
     VALUES ($1, $2, $3, 'processing')
     ON CONFLICT (provider, event_id) DO NOTHING`,
    ['billing-provider', event.id, event.type],
  );

  return result.rowCount === 1 ? 'claimed' : 'duplicate';
}

Now the handler can acknowledge duplicates without repeating side effects:

async function handleBillingEvent(event: BillingEvent) {
  const claim = await claimWebhookEvent(event);
  if (claim === 'duplicate') return;

  try {
    await applyBillingEvent(event);

    await db.query(
      `UPDATE webhook_events
       SET status = 'processed', processed_at = now(), error = NULL
       WHERE provider = $1 AND event_id = $2`,
      ['billing-provider', event.id],
    );
  } catch (error) {
    await db.query(
      `UPDATE webhook_events
       SET status = 'failed', error = $3
       WHERE provider = $1 AND event_id = $2`,
      ['billing-provider', event.id, String(error)],
    );
    throw error;
  }
}

This is better, but there is a policy choice hidden in it: what should happen when the first attempt fails halfway through?

If the handler inserted processing, sent an email, then crashed before marking processed, the next retry will look like a duplicate and return. That might be exactly what you want for non-critical side effects. It is not okay for money movement.

For high-value workflows, make the business operation itself idempotent. The webhook event table prevents duplicate handler execution. The domain tables prevent duplicate outcomes.

CREATE TABLE subscription_activations (
  provider text NOT NULL,
  event_id text NOT NULL,
  customer_id text NOT NULL,
  activated_at timestamptz NOT NULL DEFAULT now(),
  PRIMARY KEY (provider, event_id)
);
async function activateSubscriptionOnce(event: BillingEvent) {
  await db.query('BEGIN');
  try {
    const activation = await db.query(
      `INSERT INTO subscription_activations (provider, event_id, customer_id)
       VALUES ($1, $2, $3)
       ON CONFLICT (provider, event_id) DO NOTHING`,
      ['billing-provider', event.id, event.customerId],
    );

    if (activation.rowCount === 1) {
      await db.query(
        `UPDATE subscriptions
         SET status = 'active', activated_at = now()
         WHERE customer_id = $1`,
        [event.customerId],
      );
    }

    await db.query('COMMIT');
  } catch (error) {
    await db.query('ROLLBACK');
    throw error;
  }
}

That unique constraint is not glamorous. It is the line between “we think this is idempotent” and “the database enforces it while three pods race during a deploy.”

Layer 4: handle concurrent delivery across instances

The Postgres INSERT ... ON CONFLICT DO NOTHING claim is already atomic, so for many systems you can stop there. One instance wins, the rest see duplicates.

A Redis lock is useful when you want to reject concurrent duplicates before they reach heavier processing, or when the event ID claim lives in a slower system. Keep it short-lived and treat it as an optimization, not the source of truth.

import { createClient } from 'redis';

const redis = createClient({ url: process.env.REDIS_URL });
await redis.connect();

async function withEventLock<T>(eventId: string, fn: () => Promise<T>): Promise<T | 'locked'> {
  const key = `webhook-lock:billing-provider:${eventId}`;
  const token = crypto.randomUUID();

  const acquired = await redis.set(key, token, {
    NX: true,
    PX: 2 * 60 * 1000,
  });

  if (acquired !== 'OK') return 'locked';

  try {
    return await fn();
  } finally {
    // Delete only our own lock. Never blindly DEL a lock another worker may own.
    await redis.eval(
      `if redis.call("get", KEYS[1]) == ARGV[1]
       then return redis.call("del", KEYS[1])
       else return 0 end`,
      { keys: [key], arguments: [token] },
    );
  }
}

Do not build correctness on a Redis lock alone. Redis can restart. TTLs can expire while work is still running. Network partitions are real. The final idempotency boundary belongs in the database that records the business outcome.

The complete Express route

Here is the endpoint with all the pieces wired together:

app.post(
  '/webhooks/billing',
  express.raw({ type: 'application/json', limit: '1mb' }),
  async (req, res) => {
    const rawBody = req.body as Buffer;
    const signature = req.header('x-provider-signature');

    if (!signature || !verifySignedRequest(rawBody, signature)) {
      return res.status(401).send('bad signature');
    }

    let event: BillingEvent;
    try {
      event = JSON.parse(rawBody.toString('utf8'));
    } catch {
      return res.status(400).send('invalid json');
    }

    if (!event.id || !event.type) {
      return res.status(400).send('missing event metadata');
    }

    const result = await withEventLock(event.id, async () => {
      const claim = await claimWebhookEvent(event);
      if (claim === 'duplicate') return 'duplicate';

      await applyBillingEvent(event);
      await markWebhookProcessed(event);
      return 'processed';
    });

    // A concurrent copy is already processing this event. Return 204 so the
    // provider does not turn a harmless duplicate into a retry storm.
    if (result === 'locked' || result === 'duplicate') {
      return res.sendStatus(204);
    }

    return res.sendStatus(204);
  },
);

One uncomfortable recommendation: return 204 for duplicates. Teams often want to return 409 Conflict because it feels semantically pure. Providers usually treat non-2xx responses as retryable failures. A duplicate that keeps getting retried is not more correct; it is just noisy. Once you know the event is authentic and already handled or currently being handled, acknowledge it.

For handler failures, return a 5xx so the provider retries. But make sure the retry path is safe because it will happen.

Test the replay path, not just the happy path

A webhook test that only sends one valid event is almost useless. Test the failure modes that caused the incident.

import request from 'supertest';

it('rejects an old but correctly signed event', async () => {
  const body = Buffer.from(JSON.stringify({ id: 'evt_old', type: 'invoice.paid' }));
  const timestamp = Math.floor(Date.now() / 1000) - 3600;
  const signature = signForTest(timestamp, body);

  await request(app)
    .post('/webhooks/billing')
    .set('content-type', 'application/json')
    .set('x-provider-signature', `t=${timestamp},v1=${signature}`)
    .send(body)
    .expect(401);
});

it('processes the same event once across concurrent deliveries', async () => {
  const body = Buffer.from(JSON.stringify({
    id: 'evt_concurrent',
    type: 'invoice.paid',
    customerId: 'cus_123',
  }));
  const timestamp = Math.floor(Date.now() / 1000);
  const signature = signForTest(timestamp, body);

  await Promise.all(
    Array.from({ length: 20 }, () =>
      request(app)
        .post('/webhooks/billing')
        .set('content-type', 'application/json')
        .set('x-provider-signature', `t=${timestamp},v1=${signature}`)
        .send(body)
        .expect(204),
    ),
  );

  const rows = await db.query(
    `SELECT count(*)::int AS count
     FROM subscription_activations
     WHERE provider = $1 AND event_id = $2`,
    ['billing-provider', 'evt_concurrent'],
  );

  expect(rows.rows[0].count).toBe(1);
});

If that second test flakes, your production handler is not idempotent. The fix is not another if statement in JavaScript. The fix is an atomic constraint where the state changes.

Operational details that save you later

Log these fields for every webhook: provider, event ID, event type, timestamp age, verification result, duplicate/processed status, and processing duration. Do not log the raw body unless you have reviewed the data classification. Webhooks often contain emails, addresses, invoice lines, and tokens you do not want in searchable logs.

Alert on these signals:

  • signature failures above a low baseline
  • timestamp-window rejections
  • a sudden spike in duplicates
  • events stuck in processing or failed
  • handler duration approaching the provider timeout

Keep the raw payload somewhere only if you need audit or replay tooling, and encrypt it if it contains sensitive data. Many teams can store just the event ID, type, status, and a hash of the payload.

Finally, rotate webhook secrets like any other credential. Supporting multiple active signatures makes rotation painless: accept signatures produced by the current and previous secret, deploy the new secret, update the provider, then remove the old secret after the retry window drains.

Practical takeaway

A safe webhook endpoint has four properties:

  1. It verifies the signature over the exact raw bytes received.
  2. It rejects signed requests outside a short timestamp window.
  3. It records provider event IDs with an atomic uniqueness constraint.
  4. It makes the business side effect idempotent, not just the HTTP handler.

The signature keeps strangers out. The timestamp limits replay. The event table handles provider retries. The unique business constraint protects you when concurrency, deploys, and partial failures stop being theoretical.

That is the difference between a demo webhook and a production one.

A note from Yojji

Webhook reliability sits at the boundary between backend design, security, and operations, exactly where small shortcuts turn into expensive incidents. Yojji helps teams build and harden custom web and cloud systems, including the idempotent APIs and deployment practices needed when third-party events drive real business workflows.