Dev.to Security πŸ” Cybersecurity πŸ‘ 0 πŸ“– 3 min read

Building and Consuming Webhooks Safely in Production

Most webhook failures aren't caused by malicious attacks. They are caused by unhandled retries, network timeouts, out-of-order deliveries, and trusting unverified data. A webhook endpoint is simply a publicly exposed HT

Most webhook failures aren't caused by malicious attacks. They are caused by unhandled retries, network timeouts, out-of-order deliveries, and trusting unverified data.

A webhook endpoint is simply a publicly exposed HTTP URL listening for incoming POST requests. Because the URL is public, anyone can send payloads to it. If your system accepts that data blindly, you invite security vulnerabilities, duplicate state changes, and pipeline blockages.

Here is a practical, step-by-step guide to building robust webhook handlers that fail gracefully and run reliably in production.

Step 1: Verify Signatures Before Processing

Never parse or trust an incoming webhook payload until you have verified its signature.

Webhook providers sign payloads using a shared secret key and an HMAC algorithm (commonly SHA-256). They send this signature in a request header (such as X-Hub-Signature-256 or Stripe-Signature).

Always use constant-time comparison to prevent timing attacks when checking signatures.

const crypto = require('crypto');

function verifyWebhookSignature(rawBody, signatureHeader, secret) {
  const expectedSignature = crypto
    .createHmac('sha256', secret)
    .update(rawBody, 'utf8')
    .digest('hex');

  const trustedBuffer = Buffer.from(expectedSignature, 'utf8');
  const untrustedBuffer = Buffer.from(signatureHeader, 'utf8');

  if (trustedBuffer.length !== untrustedBuffer.length) {
    return false;
  }

  // Prevents timing attacks
  return crypto.timingSafeEqual(trustedBuffer, untrustedBuffer);
}

Reject any request with an invalid signature immediately with a 401 Unauthorized status code before running any database or application logic.

Step 2: Separate Ingestion from Processing

Webhook providers expect a quick HTTP response (usually within 2 to 5 seconds). If your handler performs slow operationsβ€”such as calling external APIs, processing images, or running complex queriesβ€”the provider will time out and mark the delivery as failed.

This triggers automatic retries, flooding your server with duplicate requests.

To avoid this, decouple webhook ingestion from processing:

  1. Receive the webhook request.
  2. Verify the signature.
  3. Push the payload into a message queue (such as Redis, RabbitMQ, or AWS SQS).
  4. Immediately return a 200 OK status response to the provider.

Your background workers can then consume events from the queue at their own pace.

Step 3: Design for Idempotency

Providers guarantee at-least-once delivery, not exactly-once delivery. Network glitches, worker crashes, and provider retries mean your system will receive duplicate events.

If your handler processes an event twice, it could bill a customer twice or update inventory incorrectly. Your processing logic must be idempotent.

Track unique event identifiers in a fast store like Redis or your database before executing business logic.

async function processWebhookEvent(event, redisClient) {
  const eventKey = `processed_event:${event.id}`;

  // Atomically check if the event has been handled
  const isDuplicate = await redisClient.set(eventKey, 'locked', 'NX', 'EX', 86400);

  if (!isDuplicate) {
    console.log(`Duplicate event ignored: ${event.id}`);
    return;
  }

  try {
    // Execute business logic safely
    await handleBusinessLogic(event.type, event.data);
  } catch (error) {
    // Release key on failure so retries can attempt re-processing
    await redisClient.del(eventKey);
    throw error;
  }
}

Step 4: Handle Failures with a Dead Letter Queue (DLQ)

When background processing fails due to a bug, schema mismatch, or missing data, do not let the worker retry indefinitely or drop the event silently.

Route unprocessable messages to a Dead Letter Queue (DLQ) after a fixed number of failed attempts. A DLQ preserves the failed payload and stack trace, allowing you to debug the issue, deploy a fix, and replay the event without data loss.

Non-Negotiable Checklist for Webhook Security

To keep your integration reliable over time, adhere to these rules:

  • Enforce HTTPS: Never accept webhooks over plain HTTP.
  • Least Privilege: Give your background worker minimal required database permissions rather than full administrative access.
  • Plan for Out-of-Order Delivery: Events may arrive in a different order than they occurred (e.g., an order.updated event arriving before order.created). Compare timestamps on the payload to prevent stale overwrites.

Designing for failure from day one keeps your backend stable, predictable, and resilient under load.

Tanmay builds AI agents and automation for businesses and is open to freelance projects. Feel free to connect on LinkedIn.

πŸ“° Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.