Bootcamp Logo
Volver a los artículos
11 de noviembre, 2026
~6 min de lectura

Arquitectura de Webhooks Seguros en Producción: Firma Criptográfica HMAC, Idempotencia y Procesamiento Asíncrono con BullMQ

Aprende a diseñar receptores y emisores de webhooks resilientes en Node.js y Next.js: verificación de firmas HMAC SHA-256, claves de idempotencia en Redis y colas con BullMQ para cero pérdidas de eventos.

Arquitectura de Webhooks Seguros en Producción: Firma Criptográfica HMAC, Idempotencia y Procesamiento Asíncrono con BullMQ

En cualquier plataforma moderna de comercio digital, pasarelas de pago (Stripe, Polar, PayPal, Culqi) o sincronización SaaS, los webhooks son la columna vertebral de la comunicación entre sistemas. Sin embargo, procesar webhooks de forma síncrona en el endpoint HTTP es una de las principales causas de caídas por saturación, cobros duplicados y vulnerabilidades de inyección de eventos falsos.

Para garantizar alta concurrencia y tolerancia a fallos, una arquitectura de webhooks de grado de producción debe resolver tres pilares críticos:

  1. Autenticidad e Integridad (HMAC SHA-256): Garantizar matemáticamente que el payload proviene del emisor legítimo y no fue alterado en tránsito.
  2. Idempotencia Transaccional: Prevenir la duplicidad de acciones si el proveedor reintenta el mismo evento debido a un timeout temporal.
  3. Desacoplamiento Asíncrono (BullMQ + Redis): Responder inmediatamente
    Código / Script
    200 OK
    en menos de 50ms y delegar el procesamiento intensivo a trabajadores en segundo plano.

#1. Topología del Sistema: De Síncrono a Event-Driven

El error común es ejecutar la lógica de negocio (enviar correos, emitir facturas, activar matrículas) dentro del mismo ciclo de petición HTTP del webhook. Si la base de datos se demora o un servicio externo falla, la pasarela de pagos aborta por timeout y reenvía el evento.

La arquitectura recomendada desacopla la recepción del procesamiento:

Código / Script
[Proveedor Webhook (Stripe / Polar)]
              │  POST /api/webhooks (firma HMAC + raw body)
              ▼
[Receptor Webhook HTTP (Next.js / Express)]
   ├── 1. Validar cabecera de firma (crypto.timingSafeEqual)
   ├── 2. Extraer Event ID (clave de idempotencia)
   ├── 3. Encolar trabajo en Redis (BullMQ: job id = event_id)
   └── 4. Retornar HTTP 200 { received: true } (< 40ms)
              │
              ▼
    [Cola Redis: webhook-events]
              │
              ▼
[Worker BullMQ (Proceso en Segundo Plano)]
   ├── 1. Verificar lock de idempotencia en PostgreSQL/Redis
   ├── 2. Ejecutar transacción de negocio (pago confirmado)
   ├── 3. Manejo de reintentos con backoff exponencial
   └── 4. Dead Letter Queue (DLQ) en caso de fallos persistentes

#2. Verificación Criptográfica HMAC SHA-256 sin Ataques de Tiempo

Para validar que la petición no ha sido falsificada, el proveedor firma el cuerpo crudo (

Código / Script
raw body
) utilizando un secreto compartido. Es vital usar
Código / Script
crypto.timingSafeEqual
para evitar ataques de tiempo (timing attacks).

Código / Script
// src/lib/security/verify-webhook.ts
import crypto from 'node:crypto';

interface VerifyWebhookOptions {
  payload: string | Buffer;
  signatureHeader: string;
  secret: string;
  toleranceSeconds?: number;
}

export function verifyWebhookSignature({
  payload,
  signatureHeader,
  secret,
  toleranceSeconds = 300,
}: VerifyWebhookOptions): boolean {
  // Formato habitual: t=1731345600,v1=6a2b...c8d
  const elements = signatureHeader.split(',');
  let timestamp = 0;
  let receivedSignature = '';

  for (const element of elements) {
    const [key, value] = element.trim().split('=');
    if (key === 't') timestamp = parseInt(value, 10);
    if (key === 'v1') receivedSignature = value;
  }

  if (!timestamp || !receivedSignature) return false;

  // Prevenir ataques de repetición (Replay Attacks)
  const now = Math.floor(Date.now() / 1000);
  if (Math.abs(now - timestamp) > toleranceSeconds) {
    return false;
  }

  // Generar firma esperada
  const signedPayload = `${timestamp}.${payload.toString()}`;
  const expectedSignature = crypto
    .createHmac('sha256', secret)
    .update(signedPayload)
    .digest('hex');

  const receivedBuffer = Buffer.from(receivedSignature, 'hex');
  const expectedBuffer = Buffer.from(expectedSignature, 'hex');

  if (receivedBuffer.length !== expectedBuffer.length) {
    return false;
  }

  return crypto.timingSafeEqual(receivedBuffer, expectedBuffer);
}

#3. Manejo de Idempotencia en Redis y PostgreSQL

Las pasarelas de pago garantizan entrega "al menos una vez" (at-least-once delivery). Si un webhook se procesa dos veces, tu sistema no debe cobrar doble ni generar dos suscripciones.

Para garantizar idempotencia, vinculamos el

Código / Script
event_id
del proveedor a una clave atómica en Redis con
Código / Script
SET NX EX
:

Código / Script
// src/lib/queue/webhook-queue.ts
import { Queue } from 'bullmq';
import Redis from 'ioredis';

const redisConnection = new Redis(process.env.REDIS_URL || 'redis://localhost:6379', {
  maxRetriesPerRequest: null,
});

export const webhookQueue = new Queue('webhook-events', {
  connection: redisConnection,
  defaultJobOptions: {
    attempts: 5,
    backoff: {
      type: 'exponential',
      delay: 5000, // 5s, 10s, 20s, 40s...
    },
    removeOnComplete: { age: 3600 * 24 }, // Retener 24h para auditoría
    removeOnFail: { age: 3600 * 72 },     // Retener 72h para soporte
  },
});

export async function enqueueWebhookEvent(eventId: string, eventType: string, data: unknown) {
  // El jobId de BullMQ actúa como cerrojo de idempotencia:
  // Si entra el mismo eventId mientras está en cola, BullMQ descarta el duplicado
  return await webhookQueue.add(
    eventType,
    { eventId, eventType, data },
    { jobId: `webhook:${eventId}` }
  );
}

#4. Endpoint Receptor en Next.js 15 Route Handler

En Next.js App Router, debemos capturar el

Código / Script
raw body
tal cual llegó (sin parseo JSON previo) para que el hash coincida exactamente con la firma del emisor:

Código / Script
// src/app/api/webhooks/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { verifyWebhookSignature } from '@/lib/security/verify-webhook';
import { enqueueWebhookEvent } from '@/lib/queue/webhook-queue';

export async function POST(req: NextRequest) {
  try {
    const rawBody = await req.text();
    const signature = req.headers.get('x-webhook-signature');

    if (!signature) {
      return NextResponse.json({ error: 'Cabecera de firma requerida' }, { status: 401 });
    }

    const isValid = verifyWebhookSignature({
      payload: rawBody,
      signatureHeader: signature,
      secret: process.env.WEBHOOK_SIGNING_SECRET!,
    });

    if (!isValid) {
      return NextResponse.json({ error: 'Firma criptográfica inválida' }, { status: 403 });
    }

    const payload = JSON.parse(rawBody);
    const eventId = payload.id;
    const eventType = payload.type;

    // Desacoplar inmediatamente a la cola de trabajos
    await enqueueWebhookEvent(eventId, eventType, payload.data);

    // Responder 200 en tiempo récord (< 30ms)
    return NextResponse.json({ received: true, eventId }, { status: 200 });
  } catch (err: unknown) {
    const message = err instanceof Error ? err.message : 'Error interno';
    return NextResponse.json({ error: message }, { status: 500 });
  }
}

#5. El Worker de Fondo y Transacciones ACID

El worker consume eventos de Redis y ejecuta las operaciones dentro de una transacción aislada en PostgreSQL, registrando el evento procesado en una tabla

Código / Script
processed_events
:

Código / Script
// src/workers/webhook-worker.ts
import { Worker, Job } from 'bullmq';
import Redis from 'ioredis';
import { db } from '@/lib/db'; // Cliente PostgreSQL (Kysely / Prisma / Drizzle)

const connection = new Redis(process.env.REDIS_URL || 'redis://localhost:6379', {
  maxRetriesPerRequest: null,
});

export const webhookWorker = new Worker(
  'webhook-events',
  async (job: Job) => {
    const { eventId, eventType, data } = job.data;
    console.log(`[Worker] Procesando evento ${eventType} (${eventId})`);

    await db.transaction().execute(async (trx) => {
      // 1. Verificar si ya fue procesado a nivel de base de datos
      const alreadyProcessed = await trx
        .selectFrom('processed_webhook_events')
        .where('event_id', '=', eventId)
        .selectAll()
        .executeTakeFirst();

      if (alreadyProcessed) {
        console.log(`[Worker] Evento ${eventId} ya ejecutado previamente. Omitiendo.`);
        return;
      }

      // 2. Ejecutar lógica según tipo de evento
      switch (eventType) {
        case 'checkout.session.completed':
        case 'order.paid':
          await handlePaymentSuccess(trx, data);
          break;
        case 'subscription.cancelled':
          await handleSubscriptionCancelled(trx, data);
          break;
        default:
          console.log(`[Worker] Evento sin handler registrado: ${eventType}`);
      }

      // 3. Marcar como completado
      await trx
        .insertInto('processed_webhook_events')
        .values({
          event_id: eventId,
          event_type: eventType,
          processed_at: new Date(),
        })
        .execute();
    });
  },
  { connection, concurrency: 10 }
);

#Conclusión

El diseño de webhooks seguros no admite atajos. Adoptar verificación HMAC, claves de idempotencia y desacoplamiento asíncrono con BullMQ convierte una integración vulnerable en un pipeline tolerante a fallos capaz de absorber picos de miles de transacciones por segundo sin perder un solo evento.

En los programas avanzados de Bootcamp.lat, enseñamos a implementar estas arquitecturas con código listo para desplegar en clústeres de alta disponibilidad.

¿Te pareció útil este artículo?

Compártelo con tu red de desarrolladores y colegas.

Chatea con nosotros