Webhooks Explained: Signed Payloads and Retries

Backend2026-11-19TryQuickToolBox

Why Webhooks Fail and How to Fix Them

You've built an API that sends webhooks to notify other services about events. But then you notice some deliveries fail silently, or worse, malicious actors forge requests to your endpoint. Webhooks are powerful but come with two major challenges: security (ensuring the request truly comes from your service) and reliability (making sure events are delivered even when the receiver is temporarily down).

In this article, we'll tackle both: how to sign webhook payloads so receivers can verify authenticity, and how to implement retry logic with exponential backoff to handle transient failures.

What Are Webhooks?

Webhooks are user-defined HTTP callbacks triggered by specific events. When an event occurs (e.g., a new order, a payment success), your application sends an HTTP POST request to a pre-configured URL with details about the event. This allows real-time communication between services without polling.

Common use cases include payment notifications (Stripe), CI/CD triggers (GitHub), and messaging platforms (Slack).

The Security Problem: Forged Requests

Since webhook endpoints are publicly accessible, anyone can send a POST request to them. Without verification, your application might act on fake events—like marking an order as paid when it wasn't.

To prevent this, the sender should include a signature in the request headers. The receiver then recomputes the signature and compares it. If they match, the request is authentic.

How to Sign Webhook Payloads

The most common method is HMAC (Hash-based Message Authentication Code) with SHA-256. Here's the process:

  1. Sender and receiver share a secret key (configured out-of-band).
  2. Sender creates a signature by hashing the request body (and sometimes a timestamp) with the secret using HMAC-SHA256.
  3. Sender includes the signature in a header, e.g., X-Signature.
  4. Receiver recomputes the signature using the same secret and compares it to the header value.

Always use a constant-time comparison function to prevent timing attacks.

Example: Signing in Node.js

const crypto = require('crypto');

function signPayload(payload, secret) {
  return crypto
    .createHmac('sha256', secret)
    .update(JSON.stringify(payload))
    .digest('hex');
}

// On the sender side:
const payload = { event: 'order.created', data: { id: 123 } };
const signature = signPayload(payload, 'your-secret-key');
// Include signature in header: X-Signature: signature

Example: Verifying in Node.js

const crypto = require('crypto');

function verifySignature(payload, signature, secret) {
  const expected = signPayload(payload, secret);
  return crypto.timingSafeEqual(
    Buffer.from(signature),
    Buffer.from(expected)
  );
}

// In your webhook handler:
app.post('/webhook', (req, res) => {
  const signature = req.headers['x-signature'];
  if (!verifySignature(req.body, signature, 'your-secret-key')) {
    return res.status(401).send('Invalid signature');
  }
  // Process the event
  res.status(200).send('OK');
});

Note: Ensure you're using the raw request body for verification, not a parsed object, to avoid discrepancies.

Adding Timestamps to Prevent Replay Attacks

An attacker could capture a valid signed request and replay it later. To mitigate this, include a timestamp in the signed data and reject requests older than a few minutes.

const timestamp = Math.floor(Date.now() / 1000);
const signedData = `${timestamp}.${JSON.stringify(payload)}`;
const signature = crypto.createHmac('sha256', secret).update(signedData).digest('hex');
// Send timestamp in header: X-Timestamp: timestamp

On the receiver side, check that the timestamp is within an acceptable window (e.g., 5 minutes).

Reliability: Retrying Failed Deliveries

Webhook receivers can be temporarily unavailable due to network issues, deployments, or overload. A robust sender must retry failed deliveries.

What Counts as a Failure?

Retry Strategy: Exponential Backoff with Jitter

Retrying immediately can overwhelm a struggling receiver. Instead, use exponential backoff: wait longer between each retry. Add jitter (random variation) to avoid thundering herd problems.

Example schedule: 1st retry after 1 minute, 2nd after 5 minutes, 3rd after 30 minutes, 4th after 2 hours, etc. Limit retries (e.g., 5 attempts) and consider sending a failure notification.

Implementing Retries with a Queue

Use a message queue (like RabbitMQ, Redis, or a database-backed job queue) to schedule retries. Here's a simplified approach:

  1. When an event occurs, enqueue a delivery job.
  2. Worker picks up the job and attempts delivery.
  3. On failure, calculate next retry time and re-enqueue with a delay.
  4. Track attempt count; after max retries, mark as failed.
// Pseudocode for retry logic
async function deliverWebhook(url, payload, attempt = 1) {
  try {
    const response = await fetch(url, { method: 'POST', body: payload });
    if (!response.ok) throw new Error(`HTTP ${response.status}`);
  } catch (error) {
    if (attempt >= MAX_RETRIES) {
      await markAsFailed(payload.id);
      return;
    }
    const delay = Math.min(2 ** attempt * 1000, 3600000); // max 1 hour
    const jitter = Math.random() * 1000;
    await scheduleRetry(payload, attempt + 1, delay + jitter);
  }
}

Idempotency: Handling Duplicate Deliveries

Retries can cause duplicate deliveries. Receivers should be idempotent: processing the same event multiple times should have the same effect as once. Include a unique event ID in the payload, and have the receiver track processed IDs.

Comparison: Polling vs Webhooks

AspectPollingWebhooks
LatencyDepends on intervalNear real-time
Server loadHigh (frequent requests)Low (only on events)
ComplexitySimpleRequires retry and security logic
ReliabilityHigh (receiver controls)Depends on sender's retry policy

Best Practices Checklist

FAQ

What is a signed webhook payload?

A signed payload includes a cryptographic signature (usually HMAC) generated with a shared secret. The receiver can verify the signature to ensure the request is authentic and hasn't been tampered with.

How many times should I retry a failed webhook?

A common practice is 3–5 retries with exponential backoff. After that, mark the delivery as failed and notify the subscriber. The exact number depends on your SLA and the criticality of the event.

Can I use webhooks without HTTPS?

You should always use HTTPS for webhooks to prevent eavesdropping and man-in-the-middle attacks. Most webhook providers require HTTPS endpoints.

When debugging webhook payloads or analyzing server logs, having the right tools helps. For instance, you can use the JSON Formatter to pretty-print and validate JSON payloads, or the Nginx Log Analyzer to inspect incoming webhook requests in your access logs.