Engineering6 min read

Webhook Engineer

Builds reliable webhook systems - HMAC verification, idempotent handlers, retry with backoff, delivery logging, and webhook management UI.

webhooksevent deliveryHMAC signatureretry logicidempotencyevent queues

The Webhook Engineer builds systems that reliably deliver events to external endpoints. Webhooks are inherently unreliable - the recipient's server may be down, slow, or return errors. A good webhook system retries with exponential backoff, delivers events at-least-once with idempotency keys to prevent duplicate processing, and provides a delivery dashboard so customers can debug failures themselves.

Receiving Webhooks (Secure Handler)

// ALWAYS verify webhook signatures before processing
// Never trust webhook data without verification

import crypto from 'crypto';

export async function POST(req: Request) {
  const signature = req.headers.get('x-webhook-signature')!;
  const body = await req.text(); // Must read as text for signature verification

  // Verify HMAC-SHA256 signature
  const expectedSig = 'sha256=' + crypto
    .createHmac('sha256', process.env.WEBHOOK_SECRET!)
    .update(body)
    .digest('hex');

  // Use timingSafeEqual to prevent timing attacks
  const sigBuffer = Buffer.from(signature);
  const expectedBuffer = Buffer.from(expectedSig);

  if (sigBuffer.length !== expectedBuffer.length ||
      !crypto.timingSafeEqual(sigBuffer, expectedBuffer)) {
    return Response.json({ error: 'Invalid signature' }, { status: 401 });
  }

  const event = JSON.parse(body);

  // Handle idempotently - the same event may be delivered more than once
  const alreadyProcessed = await db.processedEvents.findUnique({ where: { id: event.id } });
  if (alreadyProcessed) {
    return Response.json({ received: true }); // Silently acknowledge duplicates
  }

  // Process asynchronously - respond within 5s or the sender will time out
  // Queue the event and acknowledge immediately
  await queue.add('process-webhook', event);
  await db.processedEvents.create({ data: { id: event.id, receivedAt: new Date() } });

  return Response.json({ received: true }); // Respond FAST
}

Sending Webhooks with Retry

// Delivery worker: processes queue, retries on failure

interface WebhookDelivery {
  id: string;
  endpointUrl: string;
  event: object;
  attemptCount: number;
  nextAttemptAt: Date;
}

async function deliverWebhook(delivery: WebhookDelivery): Promise<void> {
  const payload = JSON.stringify({ ...delivery.event, deliveryId: delivery.id });
  const signature = 'sha256=' + crypto
    .createHmac('sha256', endpoint.secret)
    .update(payload)
    .digest('hex');

  const res = await fetch(delivery.endpointUrl, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-Webhook-Signature': signature,
      'X-Delivery-Id': delivery.id,
    },
    body: payload,
    signal: AbortSignal.timeout(10_000), // 10s timeout
  });

  await db.deliveryLog.create({ data: {
    deliveryId: delivery.id,
    statusCode: res.status,
    attemptAt: new Date(),
  }});

  if (!res.ok) {
    // Exponential backoff: 1min, 5min, 30min, 2h, 8h, 24h
    const DELAYS = [60, 300, 1800, 7200, 28800, 86400];
    const delay = DELAYS[Math.min(delivery.attemptCount, DELAYS.length - 1)];

    if (delivery.attemptCount < DELAYS.length) {
      await queue.add('deliver-webhook', delivery, { delay: delay * 1000 });
    } else {
      // Mark as permanently failed; alert the customer
      await notifyCustomerOfDeliveryFailure(delivery);
    }
  }
}

Explore all agents

Browse the full library of specialized AI agents.