Webhooks Explained: Signed Payloads and Retries

Backend2026-11-18TryQuickToolBox

You've built an API and now need to notify other services when events happen. You could have them poll your API, but that's inefficient and slow. Webhooks solve this by pushing events to subscribers in real-time. However, without proper security and reliability measures, webhooks can become a source of vulnerabilities and missed events.

In this guide, we'll cover how to implement webhooks with signed payloads to ensure authenticity and retry mechanisms to handle failures. We'll walk through the key concepts and provide practical code examples.

What Are Webhooks?

Webhooks are user-defined HTTP callbacks. When an event occurs in your system, you send an HTTP POST request to a URL provided by the subscriber. The request body typically contains data about the event, often in JSON format.

For example, a payment processor might send a webhook to a merchant's server when a payment succeeds. The merchant can then update their order status without constantly polling the payment API.

Webhooks are simple to implement but come with challenges: how do you ensure the request actually came from your service? How do you handle network failures or downtime on the subscriber's end?

Why Sign Webhook Payloads?

Without verification, anyone could send a fake webhook to a subscriber's endpoint, potentially triggering unauthorized actions. Signing payloads with a shared secret allows the receiver to verify that the request originated from your service and that the payload hasn't been tampered with.

The most common approach is to use HMAC (Hash-based Message Authentication Code) with SHA-256. You compute a signature over the request body using a secret key, and include it in a header. The receiver computes the same signature and compares it.

How HMAC Signing Works

Here's the process:

  1. Both parties share a secret key (never transmitted over the network).
  2. When sending a webhook, you create a string that includes the timestamp and the raw request body.
  3. You compute HMAC-SHA256 of that string using the secret key.
  4. You include the signature and timestamp in headers, e.g., X-Signature and X-Timestamp.
  5. The receiver reconstructs the string, computes the HMAC, and compares it to the received signature.

Including a timestamp prevents replay attacks: the receiver can reject requests with a timestamp too far in the past.

Implementing Signed Webhooks

Let's look at a simple example in Node.js using the built-in crypto module.

const crypto = require('crypto');

function signPayload(payload, secret, timestamp) {
  const hmac = crypto.createHmac('sha256', secret);
  hmac.update(`${timestamp}.${payload}`);
  return hmac.digest('hex');
}

// On the sender side:
const payload = JSON.stringify({ event: 'payment.success', amount: 100 });
const timestamp = Math.floor(Date.now() / 1000);
const signature = signPayload(payload, 'your-secret-key', timestamp);

// Send POST request with headers:
// X-Timestamp: timestamp
// X-Signature: signature
// Content-Type: application/json
// Body: payload

On the receiver side, you verify the signature:

function verifySignature(payload, secret, timestamp, receivedSignature) {
  const expectedSignature = signPayload(payload, secret, timestamp);
  // Use timing-safe comparison
  return crypto.timingSafeEqual(
    Buffer.from(expectedSignature, 'hex'),
    Buffer.from(receivedSignature, 'hex')
  );
}

// In your webhook endpoint:
app.post('/webhook', (req, res) => {
  const signature = req.headers['x-signature'];
  const timestamp = req.headers['x-timestamp'];
  const payload = JSON.stringify(req.body); // Use raw body if possible

  // Check timestamp to prevent replay attacks (e.g., within 5 minutes)
  if (Math.abs(Date.now() / 1000 - timestamp) > 300) {
    return res.status(400).send('Timestamp too old');
  }

  if (!verifySignature(payload, 'your-secret-key', timestamp, signature)) {
    return res.status(401).send('Invalid signature');
  }

  // Process the event
  res.status(200).send('OK');
});

Important: Always use the raw request body for signature verification. If you parse the JSON and then stringify it, the order of keys might change, causing the signature to fail. Many frameworks provide access to the raw body.

Handling Retries for Reliable Delivery

Webhooks can fail due to network issues, subscriber downtime, or errors in the subscriber's code. A robust webhook system should retry failed deliveries with exponential backoff.

Here's a typical retry strategy:

To implement retries, you need a queue system. You can use a database table to track pending webhooks and a background worker to process them. Alternatively, use a message queue like RabbitMQ or a cloud service like AWS SQS.

Example: Retry with Exponential Backoff

Here's a simplified example using a database table and a cron job:

// Table: webhook_deliveries
// id, url, payload, attempts, next_attempt_at, status

async function processWebhooks() {
  const now = new Date();
  const pending = await db.query(
    'SELECT * FROM webhook_deliveries WHERE status = $1 AND next_attempt_at