Back to blog
November 28, 2026•28 views

Building a Webhook-Driven Automation Backend in NestJS: A Production-Ready Tutorial

NestJSwebhooksAI automationBullMQNode.jsbackendidempotencyHMAChiring developers
Building a Webhook-Driven Automation Backend in NestJS: A Production-Ready Tutorial

Every automation project I have shipped in the last six years eventually hits the same wall. Not the AI part. Not the dashboard. The webhooks.

A payment gateway fires a payment.success event. Stripe sends invoice.paid. A courier API pings you when a parcel moves. bKash tells you a transaction settled. Your job is to receive that HTTP POST, trust it, process it exactly once, and trigger the next thing. Do that sloppily and you get double charges, duplicated emails, phantom orders, and a founder staring at a reconciliation spreadsheet at 2am.

This NestJS webhook automation tutorial walks through the full pipeline I use on client projects: a secure inbound endpoint, HMAC signature verification, idempotent processing, a BullMQ queue with retries and a dead-letter path, and outbound automation triggered by internal events. It is written for developers who want copy-pasteable patterns, and for founders who want to know what "production-ready" actually means before they hire someone.

Why webhooks break in production (and why founders should care)

A webhook is the least reliable "reliable" integration in software. The sender promises to POST to your URL. That promise comes with no guarantees about ordering, timing, or how many times it will fire.

Here is what actually goes wrong on real projects:

  • The sender retries. Stripe, GitHub, and most serious providers retry failed deliveries for hours or days. Your endpoint must survive the same event arriving three times. (See Stripe's retry behavior and GitHub's redelivery docs.)
  • Your endpoint is briefly down. A deploy, a restart, a cold container. The sender gets a 502 and queues a retry. Now you have a duplicate.
  • The payload arrives out of order. subscription.updated can land before subscription.created. If your handler assumes order, state goes wrong.
  • Someone finds your URL. An unauthenticated webhook endpoint is a free "create fake order" button for anyone with curl.
  • Processing takes too long. If you do the heavy work inside the request, the sender times out, assumes failure, and retries. Now you are processing the same thing twice, slowly.

The fix is an architecture, not a code snippet. Receive fast, verify hard, record the event, process asynchronously, retry with backoff, and keep a dead-letter pile you can inspect.

The architecture at a glance

Here is the flow I build on every automation backend:

[Provider] --POST--> [NestJS controller]
                          |
                     verify HMAC signature
                          |
                     store event (unique id = idempotency key)
                          |
                     enqueue BullMQ job --> return 200 immediately
                          |
                     [Worker] processes job
                          |
              success --> emit internal event --> outbound automation
              failure --> retry with backoff --> dead-letter after N attempts

Two rules drive everything. The controller does almost nothing, and the worker does everything. The controller's only job is to prove the request is genuine, persist a record, and hand off to the queue. That keeps response times well under a second, which is what providers expect (most allow a few seconds before they treat a delivery as failed).

Project setup

I assume a working NestJS project. If you are starting fresh:

nest new webhook-automation
cd webhook-automation
npm install @nestjs/bullmq bullmq ioredis @nestjs/event-emitter
npm install class-validator class-transformer

You will also want Redis running locally. Docker is the fastest path:

docker run -d --name redis -p 6379:6379 redis:7-alpine

Add the modules to your AppModule:

import { Module } from '@nestjs/common';
import { BullModule } from '@nestjs/bullmq';
import { EventEmitterModule } from '@nestjs/event-emitter';
import { WebhookModule } from './webhook/webhook.module';

@Module({
  imports: [
    EventEmitterModule.forRoot(),
    BullModule.forRoot({
      connection: {
        host: process.env.REDIS_HOST ?? 'localhost',
        port: Number(process.env.REDIS_PORT ?? 6379),
      },
    }),
    WebhookModule,
  ],
})
export class AppModule {}

Handling the raw body (the mistake that breaks signature verification)

This is the number one reason webhook signature checks fail for developers. HMAC verification runs against the exact bytes the provider sent. If a JSON body parser has already parsed and re-serialized the payload, whitespace and key order can change, and the signature no longer matches.

In NestJS, the platform adapter parses JSON before your code runs. You need the raw buffer. The cleanest approach is to capture it with a body-parser verify hook:

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import * as bodyParser from 'body-parser';

async function bootstrap() {
  const app = await NestFactory.create(AppModule, { bodyParser: false });

  app.use(
    bodyParser.json({
      verify: (req: any, _res, buf) => {
        // stash the raw bytes for signature verification
        req.rawBody = buf;
      },
    }),
  );

  await app.listen(3000);
}
bootstrap();

Now every request has req.rawBody available. For Stripe specifically, you verify against req.rawBody, never JSON.stringify(req.body). On AWS Lambda deployments I have seen teams use @nestjs/platform-express with a custom middleware for the same reason, because the default parser strips the buffer. If you are deploying this on Lambda behind API Gateway, my guide to building a cost-effective serverless API with Next.js and AWS Lambda covers the same raw-body pitfalls on the serverless side.

A scoped alternative

If you do not want to disable the global parser, apply bodyParser.raw() only on the webhook route before the JSON parser runs. That is cleaner in larger apps where most routes do not need raw bodies:

app.use('/webhooks/stripe', bodyParser.raw({ type: 'application/json' }));

The tradeoff is you now have to parse the JSON yourself inside that handler. For a single high-traffic provider I usually take this approach.

Verifying the signature with HMAC

Stripe, GitHub, Shopify, and most serious providers sign their payloads. The pattern is consistent: they compute an HMAC of the raw body using a shared secret, put it in a header, and you recompute and compare in constant time. (Stripe's scheme is documented in their signature verification guide; GitHub uses a single X-Hub-Signature-256 header, see GitHub's docs.)

Here is a Stripe-style verifier. Note the crypto.timingSafeEqual call, which prevents timing attacks:

import { createHmac, timingSafeEqual } from 'crypto';

export function verifySignature(
  rawBody: Buffer,
  header: string,
  secret: string,
  toleranceSeconds = 300,
): boolean {
  const parts = header.split(',').reduce<Record<string, string>>((acc, part) => {
    const [k, v] = part.split('=');
    acc[k] = v;
    return acc;
  }, {});

  const timestamp = Number(parts['t']);
  const provided = parts['v1'];
  if (!timestamp || !provided) return false;

  // replay protection: reject events older than tolerance
  const now = Math.floor(Date.now() / 1000);
  if (Math.abs(now - timestamp) > toleranceSeconds) return false;

  const expected = createHmac('sha256', secret)
    .update(`${timestamp}.${rawBody.toString('utf8')}`)
    .digest('hex');

  const a = Buffer.from(expected);
  const b = Buffer.from(provided);
  if (a.length !== b.length) return false;
  return timingSafeEqual(a, b);
}

The timestamp check matters. Without it, an attacker who captures a valid request can replay it forever. Five minutes is a reasonable tolerance window (Stripe's default is also five minutes). Some providers (bKash, SSLCommerz) sign differently and you will adapt the header parsing, but the shape is the same.

What about secret rotation?

Rotate secrets on a schedule, and support two active secrets during the overlap window. Verify against the new secret first, fall back to the old one, and drop the old one after a week. I keep secrets in environment variables or a secrets manager, never in code, and I log "signature mismatch" as a warning metric, not an error. A sudden spike in signature failures usually means a rotation went wrong, not an attack. If you are hardening the rest of the stack too, my practical WordPress security checklist for 2026 follows the same "assume the endpoint is public" mindset.

Idempotent webhook processing

Idempotency is the difference between a hobby project and something you can invoice a client for. The rule: the same event, delivered twice, produces the same result once.

There are two layers to this. First, record every inbound event with a unique key before processing. Second, make the processing itself safe to run twice.

Layer 1: The event record

I use a Postgres table with a unique constraint on provider + event_id:

CREATE TABLE webhook_events (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  provider TEXT NOT NULL,
  event_id TEXT NOT NULL,
  payload JSONB NOT NULL,
  status TEXT NOT NULL DEFAULT 'received',
  attempts INT NOT NULL DEFAULT 0,
  last_error TEXT,
  created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
  UNIQUE (provider, event_id)
);

The unique constraint is doing the heavy lifting. When a duplicate arrives, the insert throws a unique violation, and you return 200 without processing. The provider is happy, you did not double-charge anyone.

Layer 2: Idempotent handlers

Even with the event record, your handler can be interrupted mid-flight (worker crashes after the DB write but before the email send). Design handlers so re-running them is safe. A few patterns:

  • Use INSERT ... ON CONFLICT DO NOTHING for state transitions.
  • Send emails and messages through a separate queue job keyed by the same event id.
  • For balance updates, use atomic SQL like UPDATE accounts SET balance = balance + $1 WHERE id = $2, not read-modify-write.

The controller

Here is what the whole inbound endpoint looks like:

import { Controller, Post, Req, Headers, HttpCode, Logger } from '@nestjs/common';
import { InjectQueue } from '@nestjs/bullmq';
import { Queue } from 'bullmq';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { WebhookEvent } from './entities/webhook-event.entity';
import { verifySignature } from './verify-signature';

@Controller('webhooks')
export class WebhookController {
  private readonly logger = new Logger(WebhookController.name);

  constructor(
    @InjectQueue('webhook-processing') private readonly queue: Queue,
    @InjectRepository(WebhookEvent) private readonly events: Repository<WebhookEvent>,
  ) {}

  @Post('stripe')
  @HttpCode(200)
  async handleStripe(
    @Req() req: any,
    @Headers('stripe-signature') signature: string,
  ) {
    if (!verifySignature(req.rawBody, signature, process.env.STRIPE_SECRET)) {
      this.logger.warn('Invalid Stripe signature');
      return { received: false };
    }

    const event = JSON.parse(req.rawBody.toString('utf8'));

    try {
      await this.events.insert({
        provider: 'stripe',
        eventId: event.id,
        payload: event,
        status: 'received',
      });
    } catch (err) {
      if (isUniqueViolation(err)) {
        this.logger.log(`Duplicate event ${event.id}, ignoring`);
        return { received: true, duplicate: true };
      }
      throw err;
    }

    await this.queue.add('process', { eventId: event.id }, { jobId: event.id });
    return { received: true };
  }
}

Note the jobId option. BullMQ deduplicates jobs with the same id, which gives you a second layer of idempotency for free. If the same event somehow gets past the DB check, the queue will reject the duplicate job. (See BullMQ's jobId docs.)

BullMQ: retries, backoff, and dead-letter

The worker is where the real automation lives. Here is a job processor with exponential backoff and a dead-letter path:

import { Processor, WorkerHost } from '@nestjs/bullmq';
import { Job } from 'bullmq';
import { Logger } from '@nestjs/common';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { WebhookEvent } from './entities/webhook-event.entity';

@Processor('webhook-processing', {
  concurrency: 10,
  limiter: { max: 100, duration: 1000 },
})
export class WebhookProcessor extends WorkerHost {
  private readonly logger = new Logger(WebhookProcessor.name);

  constructor(
    @InjectRepository(WebhookEvent) private readonly events: Repository<WebhookEvent>,
    private readonly emitter: EventEmitter2,
  ) {
    super();
  }

  async process(job: Job<{ eventId: string }>): Promise<void> {
    const record = await this.events.findOneBy({ eventId: job.data.eventId });
    if (!record || record.status === 'processed') return;

    try {
      // actual business logic
      await this.route(record);

      await this.events.update(record.id, { status: 'processed', attempts: job.attemptsMade + 1 });
      this.emitter.emit('webhook.processed', { eventId: record.eventId, provider: record.provider });
    } catch (err) {
      const message = (err as Error).message;
      await this.events.update(record.id, {
        status: job.attemptsMade + 1 >= 5 ? 'dead_letter' : 'failed',
        attempts: job.attemptsMade + 1,
        last_error: message,
      });
      this.logger.error(`Job ${job.id} failed: ${message}`);
      throw err; // let BullMQ handle retry
    }
  }

  private async route(record: WebhookEvent) {
    switch (record.payload.type) {
      case 'invoice.paid':
        // update subscription, send receipt, notify Slack
        break;
      case 'payment_intent.succeeded':
        // fulfil order
        break;
      default:
        this.logger.log(`Unhandled event type ${record.payload.type}`);
    }
  }
}

Register the queue with retry defaults in the module:

BullModule.registerQueue({
  name: 'webhook-processing',
  defaultJobOptions: {
    attempts: 5,
    backoff: { type: 'exponential', delay: 2000 },
    removeOnComplete: { age: 86400, count: 5000 },
    removeOnFail: false, // keep failures for inspection
  },
}),

That configuration gives you five attempts with exponential backoff (roughly 2s, 4s, 8s, 16s, 32s between attempts). After that, the job sits in the failed pile. The removeOnFail: false is deliberate: you want to inspect those, either through a dashboard like Bull Board or by querying Postgres where I mark the status dead_letter.

When to use what

A quick decision table I keep in my head on new projects:

Mechanism Best for Latency Reliability Notes
Webhook (inbound) Real-time events from providers Seconds High with retries Requires public URL and signature verification
Polling APIs without webhooks Minutes High (idempotent by design) Wastes requests, misses real-time
Cron / scheduled job Reconciliation, reports Hours High Great as a safety net behind webhooks
BullMQ queue Internal async processing Milliseconds Very high Adds Redis dependency
Event emitter In-process decoupling Microseconds Low (no persistence) Use only for fire-and-forget

My rule: webhooks for real-time, cron for reconciliation, and a queue in between. Run a nightly cron that re-fetches state from the provider and repairs anything the webhooks missed. That single safety net has saved more client relationships than any other pattern I know.

Outbound automation: triggering the next thing

This is where the "automation" part of the NestJS webhook automation tutorial actually pays off. Once an event is processed, you often want to notify three other systems: send a Slack message, update a CRM, fire a webhook to a client's own endpoint.

I use @nestjs/event-emitter to decouple the worker from the follow-up actions:

@Injectable()
export class SlackNotifier {
  @OnEvent('webhook.processed')
  async handle(event: { eventId: string; provider: string }) {
    // enqueue a separate outbound job, do not await HTTP here
  }
}

The outbound side deserves its own queue with its own retries. Sending to a third-party webhook is exactly as unreliable as receiving from one. Keep the same discipline: sign your outbound payloads with HMAC, include a timestamp, and expose a retry endpoint on your side so clients can ask you to redeliver. If you are wiring these events into an AI agent that takes multi-step actions, the tracing patterns in AI agent observability: logging and debugging multi-step agents in production are worth reading before you ship.

Local testing and observability

For local development, expose your endpoint with a tunnel:

ngrok http 3000
# or, if you have a stable domain
cloudflared tunnel --url http://localhost:3000

Point the provider's webhook config at the tunnel URL. For testing without touching a real provider, I write a small script that signs a payload and POSTs it, so I can assert on signature failures and duplicates:

curl -X POST http://localhost:3000/webhooks/stripe \
  -H "stripe-signature: t=$(date +%s),v1=$(openssl dgst -sha256 -hmac "$SECRET" -binary payload.json | xxd -p)" \
  --data-binary @payload.json

For observability, log every inbound request with provider, event id, signature result, and processing duration. Emit metrics for queue depth, retry count, and dead-letter count. Alert on queue depth growing over a threshold for more than ten minutes. That alert catches most production incidents before a customer does. If you are running this on Next.js for the frontend and NestJS for the backend, Next.js performance monitoring with OpenTelemetry shows how to join the two traces end to end.

A short note for founders evaluating an automation developer

If you are a founder in Dhaka, Sydney, Toronto, or Auckland reading this to decide who to hire, here is the test I would give any candidate. Ask them to walk you through what happens when the same webhook arrives twice. If they say "we just process it," keep looking. If they mention idempotency keys, signatures, and a retry queue, you have someone who has shipped real automation.

The difference between a demo and a production system is rarely the AI model or the framework. It is whether the plumbing survives retries, restarts, and bad actors. A developer who understands this saves you money on reconciliation, support, and the very expensive class of bugs that only appear at 3am on Black Friday. If you are still building the hiring brief, my guides to hiring a full-stack developer in 2026 and hiring a web developer in Australia both include the screening questions I use to filter for exactly this kind of production experience.

FAQ

Do I need Redis to do webhook automation in NestJS?

Not strictly, but you will want it. Without a queue, you either process inline (slow, risks provider timeouts and duplicates) or build your own retry mechanism, which is worse. Redis plus BullMQ is the standard, well-documented path, and it is cheap to run on any cloud.

How do I verify a webhook signature if my framework already parsed the body?

Capture the raw body before parsing. In NestJS, use a body-parser verify hook or apply bodyParser.raw() to the webhook route specifically. Never sign JSON.stringify(req.body), because key order and whitespace can change and the HMAC will not match.

What is an idempotency key in webhook processing?

It is a unique identifier for an event (usually the provider's event id) that you store alongside the processed result. When a duplicate arrives, you detect it via a unique constraint or a lookup and skip reprocessing. This is what prevents double charges and duplicate emails.

How many retry attempts should a webhook job have?

Five attempts with exponential backoff covers most transient failures (deploys, third-party blips). Beyond that, the failure is usually structural and needs a human. Route those to a dead-letter status, alert on the count, and provide a manual replay tool. Silent infinite retries hide real bugs.

Wrapping up

Webhook automation is unglamorous work. It is signature verification, unique constraints, and retry budgets. But it is the foundation every serious automation project sits on, and getting it right is what separates a developer who can build a demo from one who can run your business on it.

If you are building an automation backend in NestJS and want a second set of eyes on the architecture, or you need someone to ship it end to end, I take on a small number of projects each quarter. You can reach me through the contact page and tell me what you are trying to automate. I will tell you honestly whether it needs a queue, a cron, or just a well-placed webhook.

Frequently asked questions

Do I need Redis to do webhook automation in NestJS?

Not strictly, but you will want it. Without a queue, you either process inline (slow, risks provider timeouts and duplicates) or build your own retry mechanism, which is worse. Redis plus BullMQ is the standard, well-documented path, and it is cheap to run on any cloud.

How do I verify a webhook signature if my framework already parsed the body?

Capture the raw body before parsing. In NestJS, use a body-parser verify hook or apply bodyParser.raw() to the webhook route specifically. Never sign JSON.stringify(req.body), because key order and whitespace can change and the HMAC will not match.

What is an idempotency key in webhook processing?

It is a unique identifier for an event (usually the provider's event id) that you store alongside the processed result. When a duplicate arrives, you detect it via a unique constraint or a lookup and skip reprocessing. This is what prevents double charges and duplicate emails.

How many retry attempts should a webhook job have?

Five attempts with exponential backoff covers most transient failures (deploys, third-party blips). Beyond that, the failure is usually structural and needs a human. Route those to a dead-letter status, alert on the count, and provide a manual replay tool. Silent infinite retries hide real bugs.

Share this post

Native Web Share is available on mobile, so that share sheet includes Instagram and any other app you have installed.

Let's Connect

Get In Touch

Let's build something premium together.

Contact info

Follow me
Chat on WhatsApp