Software Development

Webhook Scaling & Performance: High-Volume Processing Architecture Guide

Learn to build webhook systems that handle millions of events per day. Master queue-based processing, worker pools, rate limiting, batching strategies, and horizontal scaling patterns for high-throughput webhook infrastructure.

By Inventive Software Engineering

When bursts, payload size, processing time, or a provider's response deadline make inline work unreliable, decouple receiving from processing: have the HTTP endpoint verify the provider signature over the raw payload, enqueue the authenticated event, and acknowledge promptly — then let workers handle database writes and downstream API calls asynchronously. Daily event count alone does not determine the need for a queue; measure peak arrival rate and end-to-end response time against the provider's timeout. A suitably sized queue can absorb bursts, workers can scale independently, and atomic idempotency handling helps prevent duplicate effects when providers retry. Batching, rate limiting, connection pooling, and autoscaling can be added where measurements justify them.

That is the summary an AI Overview will give you. Here is what it cannot show you: the concrete decision of which queue to pick at your volume, the exact request flow through a decoupled system, and a copy-paste readiness checklist you can run against your own stack before the next traffic spike. Those are below.

The Scaling Challenge

Webhook infrastructure fails in predictable stages as volume climbs. A single synchronous server may suffice at low volume, but burst traffic or slow downstream work can cause timeouts; queues and horizontal scaling become useful as measured load grows. The animated diagram below shows the three stages and what you gain (and lose) at each.

Webhook volume growth path across three architecture stages Stage 1 startup uses a single server with synchronous processing; Stage 2 growth adds a queue and worker; Stage 3 scale uses load-balanced receivers, a queue cluster, and a worker pool with autoscaling. Webhook Volume Growth Path Stage 1 · Startup Low volume Single Server Process Synchronously ✓ Simple ✗ No buffering ✗ Timeouts under burst Stage 2 · Growth Growing load Single Server Queue (buffer) Worker ✓ Decoupled · buffered · retries Stage 3 · Scale High load LB + Receivers Queue Cluster Worker Pool ✓ Horizontal · fault-tolerant ✓ Autoscaling on queue depth

The queue is the shock absorber: it decouples burst arrival rate from steady processing rate. Move left → right as sustained volume and burst peaks grow, not before.

Architecture Overview

The Fundamental Pattern: Receive Fast, Process Later

The receiver example assumes a provider-specific verifyProviderSignature helper that validates the raw body using the provider's configured secret. It throws InvalidWebhookSignatureError only for a missing or invalid signature; secret-store outages and other verification failures propagate as transient errors.

// High-performance webhook receiver
import express from 'express';
import { Queue } from 'bullmq';
import { Redis } from 'ioredis';

const redis = new Redis({
  host: process.env.REDIS_HOST,
  port: 6379,
  maxRetriesPerRequest: 3
});

const webhookQueue = new Queue('webhooks', {
  connection: redis,
  defaultJobOptions: {
    removeOnComplete: 1000,
    removeOnFail: 1000, // Bound terminal failures retained for review and DLQ reconciliation
    attempts: 5,
    backoff: {
      type: 'exponential',
      delay: 1000
    }
  }
});

const app = express();

class InvalidWebhookSignatureError extends Error {}

// Receive webhook - respond immediately
app.post('/webhooks/:provider',
  express.raw({ type: 'application/json', limit: '1mb' }),
  async (req, res) => {
    const startTime = Date.now();
    const provider = req.params.provider;

    try {
      // Implement provider-specific signature verification with the configured secret.
      // Reject missing or invalid signatures before any queue write.
      try {
        await verifyProviderSignature(provider, req.headers, req.body);
      } catch (error) {
        if (error instanceof InvalidWebhookSignatureError) {
          return res.sendStatus(401);
        }
        throw error;
      }
      const body = req.body.toString();

      // Add the authenticated event to the queue with minimal processing
      await webhookQueue.add(
        `${provider}-webhook`,
        {
          provider,
          headers: req.headers,
          body,
          receivedAt: Date.now()
        },
        {
          priority: getPriority(provider, body)
        }
      );

      // Respond fast (target: < 100ms)
      const duration = Date.now() - startTime;
      res.status(200).json({
        received: true,
        queueTime: duration
      });

    } catch (error) {
      console.error('Webhook receiver failed:', error);
      res.sendStatus(500);
    }
  }
);

function getPriority(provider: string, body: string): number {
  // Lower number = higher priority
  // Read Stripe's event type from the verified JSON payload.
  if (provider === 'stripe') {
    try {
      const eventType: unknown = JSON.parse(body).type;
      if (typeof eventType === 'string' &&
          (eventType.startsWith('payment_intent.') || eventType.startsWith('charge.'))) {
        return 1;
      }
    } catch {
      // Leave malformed payloads at default priority; handle them in the worker.
    }
  }
  return 5; // Default priority
}

app.listen(3000, () => {
  console.log('Webhook receiver running on port 3000');
});

Queue-Based Processing Architecture

The diagram below traces a single event end-to-end. The receiver verifies the raw-body signature and enqueues before acknowledging. Workers run asynchronously, but their processing time must fit the queue's lease or visibility timeout, or extend it while work continues. In the SQS example below, a message still being processed after the configured 60-second visibility timeout may be delivered again. The animated packet shows an event flowing through the whole pipeline.

Queue-based webhook architecture: providers to load-balanced receivers to queue to worker pool to datastores Providers send events to load-balanced receivers, which verify signatures and enqueue to a Redis or SQS queue before acknowledging; a worker pool then consumes the queue and writes to PostgreSQL, external APIs, and downstream fanout. Queue-Based Webhook Architecture

Providers Stripe GitHub Shopify

Receivers (LB) Receiver 1 Receiver N Verify · enqueue · 200 OK

Queue Redis / SQS

Worker Pool Worker 1 Worker N async · process · retry

Sinks PostgreSQL External API Fanout

sync ← | → async

A load balancer spreads inbound events across stateless receivers; workers scale independently on queue depth. Workers need atomic idempotency for at-least-once delivery.

Message Queue Strategies

Which Queue Should You Use?

The queue choice affects throughput, durability, ordering, and operating effort. Use this table to match a queue to your workload and existing infrastructure.

QueueThroughput ceilingDurabilityOrderingBest forWatch out for
Redis + BullMQDepends on Redis setupIn-memory; needs AOF/RDB persistence; a replica adds availabilityPer-priority, not strict FIFOMost teams; you already run Redis; rich retry/priority/rate-limit built inData loss risk if Redis isn't persisted; memory-bound backlog
Amazon SQS (standard)Scales with demand; check current AWS quotasFully managed, at-least-onceNo strict orderingServerless / AWS shops wanting managed durabilityHandlers must be idempotent; check AWS's current message-size quota
Amazon SQS FIFOVaries by region and FIFO configuration; check current AWS quotasFully managed; duplicate sends suppressed only within the deduplication windowOrdered within each MessageGroupIdEvents needing per-group ordering, such as payment or inventory updatesDeduplication is bounded and does not make downstream side effects exactly once; design MessageGroupId and idempotent handlers
RabbitMQDepends on broker setupDurable queues + persistent messages + publisher confirmsQueue order can differ from processing order with competing consumers, priorities, or redelivery; ordered processing needs constraints such as a single active consumerComplex routing (topic/fanout), on-prem, per-message ack controlYou operate the broker; clustering is non-trivial
Apache KafkaDepends on cluster setupDisk-backed, replicated log, replayableStrict per partitionHigh throughput, event replay, multiple consumer groupsOffset management and retry design need care; consumers can commit offsets or seek to retry, and ShareConsumer supports explicit record acknowledgment
Which should I use?———Redis + BullMQ is a useful starting point if you operate Redis. Consider SQS for a managed queue, and Kafka when measured throughput or replay needs justify it.Compare failure recovery and operating needs before choosing.

The worker example uses application-specific hooks for parsing, processing, and error classification. Implement processEventIdempotently so a unique key scoped to the provider and event ID is claimed atomically with database changes in one transaction. A separate check followed by processing and marking can race across workers. For external API calls that cannot share that transaction, pass a stable idempotency key when supported and design for retries after partial failure. Terminal failures are retained temporarily in BullMQ's failed set and copied to a review queue. Monitor both sets and reconcile missed copies before retention removes the source jobs, since a worker can stop between failing a job and copying it. Treat the concurrency and limiter values in the example as values to tune from measured throughput, latency, and downstream limits.

// worker.ts - Webhook processing worker
import { Worker, Job, Queue, UnrecoverableError } from 'bullmq';
import { Redis } from 'ioredis';

const redis = new Redis({
  host: process.env.REDIS_HOST,
  port: 6379,
  maxRetriesPerRequest: null // Required for workers
});

interface WebhookJob {
  provider: string;
  headers: Record<string, string>;
  body: string;
  receivedAt: number;
}

const deadLetterQueue = new Queue('webhooks-dead-letter', {
  connection: redis,
  defaultJobOptions: { removeOnComplete: 1000, removeOnFail: 1000 }
});

// Create worker with concurrency
const worker = new Worker<WebhookJob>(
  'webhooks',
  async (job: Job<WebhookJob>) => {
    const { provider, headers, body, receivedAt } = job.data;
    const queueLatency = Date.now() - receivedAt;

    console.log(`Processing ${provider} webhook (queued ${queueLatency}ms)`);

    try {
      // Parse and validate the already authenticated event
      const event = await validateAndParse(provider, headers, body);

      // Application hook: atomically claim the provider/event ID and commit
      // database effects in one transaction; return 'duplicate' on a conflict.
      const outcome = await processEventIdempotently(provider, event);
      if (outcome === 'duplicate') {
        return { status: 'duplicate', eventId: event.id };
      }

      return {
        status: 'processed',
        eventId: event.id,
        processingTime: Date.now() - receivedAt
      };

    } catch (error) {
      // A permanent error belongs in the failed set without further attempts.
      if (!isRetriableError(error)) {
        throw new UnrecoverableError(String(error));
      }
      throw error instanceof Error ? error : new Error(String(error));
    }
  },
  {
    connection: redis,
    concurrency: parseInt(process.env.WORKER_CONCURRENCY || '10'),
    limiter: {
      max: 100,      // Max jobs per duration
      duration: 1000 // Duration in ms
    }
  }
);

// Monitor worker events
const pendingArchives = new Set<Promise<void>>();
worker.on('completed', (job, result) => {
  console.log(`Job ${job.id} completed:`, result);
});

worker.on('failed', (job, error) => {
  console.error(`Job ${job?.id} failed:`, error.message);
  if (!job) return;
  const archive = (async () => {
    // Retried attempts are not terminal failures.
    if (await job.getState() !== 'failed') return;
    await deadLetterQueue.add('review', {
      sourceQueue: 'webhooks',
      sourceJobId: job.id,
      webhook: job.data,
      reason: error.message
    }, { jobId: `webhooks-${job.id}` });
  })().catch(dlqError => {
    // Alert on this error; the source job remains in the failed set.
    console.error(`Could not archive failed job ${job.id}:`, dlqError);
  });
  pendingArchives.add(archive);
  void archive.finally(() => pendingArchives.delete(archive));
});

// Graceful shutdown
process.on('SIGTERM', async () => {
  console.log('Shutting down worker...');
  await worker.close();
  await Promise.allSettled([...pendingArchives]);
  await deadLetterQueue.close();
  process.exit(0);
});

Queue Configuration for Different Scenarios

These queue options retain a bounded number of failed jobs for review. Give each queue a terminal-failure handler and reconciliation process like the webhooks worker above before relying on a dead-letter workflow; retention alone does not copy jobs to a review queue. Export records needed for longer audits before BullMQ removes them.

// queue-config.ts
import { Queue, QueueOptions } from 'bullmq';

// High-priority queue for payment events
const paymentQueue = new Queue('payments', {
  defaultJobOptions: {
    attempts: 10,
    backoff: {
      type: 'exponential',
      delay: 2000
    },
    removeOnComplete: 1000,
    removeOnFail: 1000
  }
});

// Standard queue for general events
const standardQueue = new Queue('standard', {
  defaultJobOptions: {
    attempts: 5,
    backoff: {
      type: 'exponential',
      delay: 1000
    },
    removeOnComplete: 1000,
    removeOnFail: 1000
  }
});

// Low-priority queue for analytics/logging
const analyticsQueue = new Queue('analytics', {
  defaultJobOptions: {
    attempts: 3,
    backoff: {
      type: 'fixed',
      delay: 5000
    },
    removeOnComplete: 100,
    removeOnFail: 1000
  }
});

// Route webhooks to appropriate queue
export function routeToQueue(provider: string, eventType: string): Queue {
  if (provider === 'stripe' && eventType.includes('payment')) {
    return paymentQueue;
  }
  if (eventType.includes('analytics') || eventType.includes('log')) {
    return analyticsQueue;
  }
  return standardQueue;
}

Amazon SQS for Higher Durability

This example sends to a standard SQS queue. If you configure SQS_QUEUE_URL for a FIFO queue, supply the required message group and deduplication settings for that queue. The worker extends visibility while processing; if an extension fails or the worker stops, the message can be delivered again, so processing must be idempotent. Configure a redrive policy on the source queue, for example {"deadLetterTargetArn":"<DLQ ARN>","maxReceiveCount":"5"}, to move messages to a DLQ after repeated receives; the worker does not create that policy.

// sqs-processor.ts
import {
  SQSClient,
  ReceiveMessageCommand,
  DeleteMessageCommand,
  ChangeMessageVisibilityCommand,
  SendMessageCommand
} from '@aws-sdk/client-sqs';

const sqs = new SQSClient({ region: 'us-east-1' });
const QUEUE_URL = process.env.SQS_QUEUE_URL!;

interface WebhookMessage {
  provider: string;
  eventId: string;
  body: string;
  headers: Record<string, string>;
  attempts: number;
}

async function pollMessages(): Promise<void> {
  while (true) {
    try {
      const response = await sqs.send(new ReceiveMessageCommand({
        QueueUrl: QUEUE_URL,
        MaxNumberOfMessages: 10,
        WaitTimeSeconds: 20, // Long polling
        VisibilityTimeout: 60,
        MessageAttributeNames: ['All']
      }));

      if (response.Messages) {
        await Promise.all(
          response.Messages.map(async (message) => {
            let visibilityTimer: NodeJS.Timeout | undefined;
            try {
              const webhook: WebhookMessage = JSON.parse(message.Body!);
              visibilityTimer = setInterval(() => {
                void sqs.send(new ChangeMessageVisibilityCommand({
                  QueueUrl: QUEUE_URL,
                  ReceiptHandle: message.ReceiptHandle!,
                  VisibilityTimeout: 60
                })).catch(error => console.error('Visibility extension failed:', error));
              }, 30000);
              await processWebhook(webhook);
              clearInterval(visibilityTimer);
              visibilityTimer = undefined;

              // Delete on success
              await sqs.send(new DeleteMessageCommand({
                QueueUrl: QUEUE_URL,
                ReceiptHandle: message.ReceiptHandle!
              }));

            } catch (error) {
              console.error('Processing failed:', error);
              // Message returns to queue after visibility timeout
              // A configured redrive policy moves it to the DLQ after maxReceiveCount
            } finally {
              if (visibilityTimer) clearInterval(visibilityTimer);
            }
          })
        );
      }
    } catch (error) {
      console.error('Polling error:', error);
      await sleep(5000);
    }
  }
}

// Send webhook to the standard queue configured by SQS_QUEUE_URL.
// FIFO queues require a separate configuration with group and deduplication IDs.
export async function queueWebhook(webhook: WebhookMessage): Promise<void> {
  await sqs.send(new SendMessageCommand({
    QueueUrl: QUEUE_URL,
    MessageBody: JSON.stringify(webhook)
  }));
}

Worker Pool Management

Advertisement

Dynamic Worker Scaling

The worker counts, concurrency, queue-depth thresholds, and scale increments below are illustrative starting values. Tune them with representative load tests, queue wait time, CPU and memory use, downstream latency, and the database connection budget; CPU core count alone does not determine useful I/O concurrency.

// worker-pool.ts
import { Worker, Queue } from 'bullmq';
import os from 'os';

interface WorkerPoolConfig {
  minWorkers: number;
  maxWorkers: number;
  scaleUpThreshold: number;  // Queue depth to trigger scale up
  scaleDownThreshold: number;
  scaleInterval: number; // ms
}

class WorkerPool {
  private workers: Worker[] = [];
  private queue: Queue;
  private config: WorkerPoolConfig;
  private scaleTimer?: NodeJS.Timeout;

  constructor(queue: Queue, config: Partial<WorkerPoolConfig> = {}) {
    this.queue = queue;
    this.config = {
      minWorkers: config.minWorkers || 2,
      maxWorkers: config.maxWorkers || os.cpus().length * 2,
      scaleUpThreshold: config.scaleUpThreshold || 1000,
      scaleDownThreshold: config.scaleDownThreshold || 100,
      scaleInterval: config.scaleInterval || 10000
    };
  }

  async start(): Promise<void> {
    // Start minimum workers
    for (let i = 0; i < this.config.minWorkers; i++) {
      await this.addWorker();
    }

    // Start auto-scaling
    this.scaleTimer = setInterval(
      () => this.autoScale(),
      this.config.scaleInterval
    );

    console.log(`Worker pool started with ${this.workers.length} workers`);
  }

  private async addWorker(): Promise<void> {
    const worker = new Worker(
      this.queue.name,
      async (job) => {
        return await processWebhookJob(job);
      },
      {
        concurrency: 10,
        connection: this.queue.opts.connection
      }
    );

    worker.on('failed', (job, error) => {
      console.error(`Worker failed job ${job?.id}:`, error);
    });

    this.workers.push(worker);
    console.log(`Added worker, total: ${this.workers.length}`);
  }

  private async removeWorker(): Promise<void> {
    if (this.workers.length <= this.config.minWorkers) return;

    const worker = this.workers.pop();
    if (worker) {
      await worker.close();
      console.log(`Removed worker, total: ${this.workers.length}`);
    }
  }

  private async autoScale(): Promise<void> {
    const queueStatus = await this.queue.getJobCounts();
    const queueDepth = queueStatus.waiting + queueStatus.active;

    console.log(`Queue depth: ${queueDepth}, Workers: ${this.workers.length}`);

    if (queueDepth > this.config.scaleUpThreshold) {
      if (this.workers.length < this.config.maxWorkers) {
        // Scale up
        const toAdd = Math.min(
          Math.ceil(queueDepth / 500), // Illustrative increment; tune from measured processing rate
          this.config.maxWorkers - this.workers.length
        );
        for (let i = 0; i < toAdd; i++) {
          await this.addWorker();
        }
      }
    } else if (queueDepth < this.config.scaleDownThreshold) {
      // Scale down (remove one at a time)
      await this.removeWorker();
    }
  }

  async stop(): Promise<void> {
    if (this.scaleTimer) {
      clearInterval(this.scaleTimer);
    }

    await Promise.all(this.workers.map(w => w.close()));
    this.workers = [];
    console.log('Worker pool stopped');
  }
}

Kubernetes Horizontal Pod Autoscaler

The replica limits, resource requests, concurrency, queue-depth target, and scaling policies below are example values to validate and tune against your workload and downstream limits.

# kubernetes/webhook-workers.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: webhook-workers
spec:
  replicas: 3
  selector:
    matchLabels:
      app: webhook-worker
  template:
    metadata:
      labels:
        app: webhook-worker
    spec:
      containers:
        - name: worker
          image: myapp/webhook-worker:latest
          resources:
            requests:
              cpu: "500m"
              memory: "512Mi"
            limits:
              cpu: "2000m"
              memory: "2Gi"
          env:
            - name: WORKER_CONCURRENCY
              value: "20"
            - name: REDIS_HOST
              value: redis-master.default.svc.cluster.local
---
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: webhook-workers-hpa
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: webhook-workers
  minReplicas: 3
  maxReplicas: 50
  metrics:
    # Scale based on queue depth (custom metric)
    - type: External
      external:
        metric:
          name: redis_queue_depth
          selector:
            matchLabels:
              queue: webhooks
        target:
          type: AverageValue
          averageValue: "500"
    # Also consider CPU
    - type: Resource
      resource:
        name: cpu
        target:
          type: Utilization
          averageUtilization: 70
  behavior:
    scaleUp:
      stabilizationWindowSeconds: 60
      policies:
        - type: Pods
          value: 5
          periodSeconds: 60
    scaleDown:
      stabilizationWindowSeconds: 300
      policies:
        - type: Percent
          value: 10
          periodSeconds: 60

Batching Strategies

Database Write Batching

Each queued job below remains pending until its batch insert succeeds. If the insert fails, the affected job promises reject so the queue can retry them. The example's batch size and wait time are starting values to tune against write throughput and event latency. Run enough concurrent jobs to fill batches, and drain in-flight jobs during shutdown; an interrupted insert may be retried, so the database write should be idempotent.

// batch-processor.ts
import { Job } from 'bullmq';

interface BatchConfig {
  maxSize: number;
  maxWaitMs: number;
}

class BatchProcessor<T> {
  private batch: Array<{
    item: T;
    resolve: () => void;
    reject: (error: unknown) => void;
  }> = [];
  private timer: NodeJS.Timeout | null = null;
  private config: BatchConfig;
  private processor: (items: T[]) => Promise<void>;

  constructor(
    processor: (items: T[]) => Promise<void>,
    config: Partial<BatchConfig> = {}
  ) {
    this.processor = processor;
    this.config = {
      maxSize: config.maxSize || 100,
      maxWaitMs: config.maxWaitMs || 1000
    };
  }

  add(item: T): Promise<void> {
    return new Promise((resolve, reject) => {
      this.batch.push({ item, resolve, reject });

      if (this.batch.length >= this.config.maxSize) {
        void this.flush();
      } else if (!this.timer) {
        this.timer = setTimeout(() => { void this.flush(); }, this.config.maxWaitMs);
      }
    });
  }

  async flush(): Promise<void> {
    if (this.timer) {
      clearTimeout(this.timer);
      this.timer = null;
    }

    if (this.batch.length === 0) return;

    const pending = this.batch;
    this.batch = [];

    try {
      await this.processor(pending.map(entry => entry.item));
      pending.forEach(entry => entry.resolve());
      console.log(`Processed batch of ${pending.length} items`);
    } catch (error) {
      console.error('Batch processing failed:', error);
      // Reject the jobs so the queue can retry them.
      pending.forEach(entry => entry.reject(error));
    }
  }
}

// Usage: Batch database inserts
const eventBatcher = new BatchProcessor<WebhookEvent>(
  async (events) => {
    // Single bulk insert instead of N inserts
    await db.query(`
      INSERT INTO webhook_events (event_id, event_type, payload, received_at)
      SELECT * FROM UNNEST($1::text[], $2::text[], $3::jsonb[], $4::timestamptz[])
    `, [
      events.map(e => e.id),
      events.map(e => e.type),
      events.map(e => JSON.stringify(e.data)),
      events.map(e => e.receivedAt)
    ]);
  },
  { maxSize: 100, maxWaitMs: 500 }
);

// In worker
async function processWebhookJob(job: Job): Promise<void> {
  const event = parseWebhookEvent(job.data);
  // Do not complete the job until the bulk insert succeeds.
  await eventBatcher.add(event);
}

API Call Batching

Use this example only for an API with a documented /batch endpoint that accepts this request body and returns per-request IDs, data, and errors. Adapt the route and response handling to the downstream API's actual contract; tune the example's batch size and wait time against its request limits and your latency target.

// api-batcher.ts
interface BatchableRequest {
  id: string;
  endpoint: string;
  payload: any;
  resolve: (result: any) => void;
  reject: (error: Error) => void;
}

class APIBatcher {
  private pending = new Map<string, BatchableRequest[]>();
  private timers = new Map<string, NodeJS.Timeout>();
  private config: { maxBatch: number; maxWait: number };

  constructor(config = { maxBatch: 50, maxWait: 200 }) {
    this.config = config;
  }

  async request(endpoint: string, payload: any): Promise<any> {
    return new Promise((resolve, reject) => {
      const request: BatchableRequest = {
        id: crypto.randomUUID(),
        endpoint,
        payload,
        resolve,
        reject
      };

      if (!this.pending.has(endpoint)) {
        this.pending.set(endpoint, []);
      }

      this.pending.get(endpoint)!.push(request);

      if (this.pending.get(endpoint)!.length >= this.config.maxBatch) {
        this.flush(endpoint);
      } else if (!this.timers.has(endpoint)) {
        this.timers.set(
          endpoint,
          setTimeout(() => this.flush(endpoint), this.config.maxWait)
        );
      }
    });
  }

  private async flush(endpoint: string): Promise<void> {
    const timer = this.timers.get(endpoint);
    if (timer) {
      clearTimeout(timer);
      this.timers.delete(endpoint);
    }

    const requests = this.pending.get(endpoint) || [];
    this.pending.delete(endpoint);

    if (requests.length === 0) return;

    try {
      // Make single batch API call
      const response = await fetch(`${endpoint}/batch`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          requests: requests.map(r => ({
            id: r.id,
            payload: r.payload
          }))
        })
      });
      if (!response.ok) {
        throw new Error(`Batch request failed with HTTP ${response.status}`);
      }

      const results = await response.json();
      if (!Array.isArray(results)) {
        throw new Error('Batch response must be an array');
      }

      // Resolve individual promises
      for (const request of requests) {
        const result = results.find((r: any) => r.id === request.id);
        if (!result) {
          request.reject(new Error(`Missing batch result for ${request.id}`));
        } else if (result.error) {
          request.reject(new Error(result.error));
        } else if (!Object.prototype.hasOwnProperty.call(result, 'data')) {
          request.reject(new Error(`Missing batch data for ${request.id}`));
        } else {
          request.resolve(result.data);
        }
      }
    } catch (error) {
      // Reject all on batch failure
      for (const request of requests) {
        request.reject(error as Error);
      }
    }
  }
}

Rate Limiting

Token Bucket Rate Limiter

// rate-limiter.ts
import { Redis } from 'ioredis';

class TokenBucketLimiter {
  private redis: Redis;

  constructor(redis: Redis) {
    this.redis = redis;
  }

  async acquire(
    key: string,
    maxTokens: number,
    refillRate: number, // tokens per second
    tokensNeeded: number = 1
  ): Promise<{ allowed: boolean; retryAfter?: number }> {
    const now = Date.now();
    const bucketKey = `ratelimit:${key}`;

    // Lua script for atomic token bucket
    const script = `
      local key = KEYS[1]
      local max_tokens = tonumber(ARGV[1])
      local refill_rate = tonumber(ARGV[2])
      local tokens_needed = tonumber(ARGV[3])
      local now = tonumber(ARGV[4])

      local bucket = redis.call('HMGET', key, 'tokens', 'last_refill')
      local tokens = tonumber(bucket[1]) or max_tokens
      local last_refill = tonumber(bucket[2]) or now

      -- Refill tokens based on time elapsed
      local elapsed = math.max(0, (now - last_refill) / 1000)
      tokens = math.min(max_tokens, tokens + (elapsed * refill_rate))

      if tokens >= tokens_needed then
        -- Consume tokens
        tokens = tokens - tokens_needed
        redis.call('HMSET', key, 'tokens', tokens, 'last_refill', now)
        redis.call('EXPIRE', key, math.ceil(max_tokens / refill_rate) + 1)
        return {1, 0}
      else
        -- Calculate wait time
        local wait = (tokens_needed - tokens) / refill_rate * 1000
        redis.call('HMSET', key, 'tokens', tokens, 'last_refill', now)
        redis.call('EXPIRE', key, math.ceil(max_tokens / refill_rate) + 1)
        return {0, math.ceil(wait)}
      end
    `;

    const result = await this.redis.eval(
      script,
      1,
      bucketKey,
      maxTokens,
      refillRate,
      tokensNeeded,
      now
    ) as [number, number];

    return {
      allowed: result[0] === 1,
      retryAfter: result[1] || undefined
    };
  }
}

// Usage inside a BullMQ processor. Choose limits for the specific downstream
// API and account from current provider docs or observed quota responses.
import { DelayedError, Job } from 'bullmq';
const redis = new Redis({ host: process.env.REDIS_HOST, maxRetriesPerRequest: null });
const limiter = new TokenBucketLimiter(redis);

async function processWithRateLimit(
  job: Job,
  token: string | undefined,
  scopeKey: string,
  limit: { max: number; rate: number },
  process: () => Promise<void>
): Promise<void> {
  if (!Number.isFinite(limit.max) || limit.max < 1 ||
      !Number.isFinite(limit.rate) || limit.rate <= 0) {
    throw new Error('Rate limit requires a positive capacity and refill rate');
  }
  const { allowed, retryAfter } = await limiter.acquire(
    scopeKey,
    limit.max,
    limit.rate
  );

  if (!allowed) {
    // Requeue the same job for later without holding a worker slot.
    await job.moveToDelayed(Date.now() + retryAfter!, token);
    throw new DelayedError();
  }

  await process();
}

// In the Worker processor, pass BullMQ's lock token to the helper:
// async (job, token) => processWithRateLimit(
//   job, token, job.data.scopeKey, configuredLimit,
//   () => callDownstreamIdempotently(job.data)
// )

Sliding Window Rate Limiter

// sliding-window.ts
class SlidingWindowLimiter {
  private redis: Redis;

  constructor(redis: Redis) {
    this.redis = redis;
  }

  async isAllowed(
    key: string,
    limit: number,
    windowMs: number
  ): Promise<{ allowed: boolean; remaining: number; resetAt: number }> {
    const now = Date.now();
    const windowKey = `sliding:${key}`;

    const script = `
      local key = KEYS[1]
      local limit = tonumber(ARGV[1])
      local window = tonumber(ARGV[2])
      local now = tonumber(ARGV[3])
      local window_start = now - window

      -- Remove old entries
      redis.call('ZREMRANGEBYSCORE', key, 0, window_start)

      -- Count current requests
      local count = redis.call('ZCARD', key)

      if count < limit then
        -- Add new request
        redis.call('ZADD', key, now, now .. '-' .. math.random())
        redis.call('EXPIRE', key, math.ceil(window / 1000))
        return {1, limit - count - 1, now + window}
      else
        -- Get oldest entry to calculate reset time
        local oldest = redis.call('ZRANGE', key, 0, 0, 'WITHSCORES')
        local reset_at = oldest[2] and (tonumber(oldest[2]) + window) or (now + window)
        return {0, 0, reset_at}
      end
    `;

    const result = await this.redis.eval(
      script,
      1,
      windowKey,
      limit,
      windowMs,
      now
    ) as [number, number, number];

    return {
      allowed: result[0] === 1,
      remaining: result[1],
      resetAt: result[2]
    };
  }
}

Performance Optimization

Connection Pooling

Set DB_POOL_MAX from the database's connection budget: maximum worker processes or pods × connections per pool, plus connections used by other clients, must fit within the database limit. Recheck the budget when increasing replica counts.

// db-pool.ts
import { Pool, PoolConfig } from 'pg';

const maxPoolConnections = Number(process.env.DB_POOL_MAX);
if (!Number.isInteger(maxPoolConnections) || maxPoolConnections < 1) {
  throw new Error('DB_POOL_MAX must be a positive integer sized for all worker replicas');
}

// Pool limit is per worker process, not a cluster-wide limit
const poolConfig: PoolConfig = {
  host: process.env.DB_HOST,
  database: process.env.DB_NAME,
  user: process.env.DB_USER,
  password: process.env.DB_PASSWORD,
  max: maxPoolConnections,    // Max connections per worker process
  min: 0,                     // Avoid reserving idle connections in every replica
  idleTimeoutMillis: 30000,   // Close idle connections
  connectionTimeoutMillis: 5000,
  statement_timeout: 10000,   // Query timeout
};

const pool = new Pool(poolConfig);

// Monitor pool health
pool.on('error', (err) => {
  console.error('Pool error:', err);
});

pool.on('connect', () => {
  console.log('New connection established');
});

// Use connection for transaction batching
export async function batchInsert<T>(
  table: string,
  columns: string[],
  rows: T[][]
): Promise<void> {
  if (!columns.length || !rows.length) return;
  if (rows.some(row => row.length !== columns.length)) {
    throw new Error('Each row must match the column list');
  }
  // Identifiers cannot be SQL parameters. Accept only unqualified names from
  // a trusted allowlist, then quote them as PostgreSQL identifiers.
  const allowedTables: Record<string, readonly string[]> = {
    webhook_events: ['event_id', 'event_type', 'payload', 'received_at']
  };
  if (!Object.prototype.hasOwnProperty.call(allowedTables, table) ||
      columns.some(column => !allowedTables[table].includes(column)) ||
      new Set(columns).size !== columns.length) {
    throw new Error('Table or column is not allowed');
  }
  const quoteIdent = (name: string) => `"${name.replace(/"/g, '""')}"`;
  const identifiers = columns.map(quoteIdent).join(', ');
  const client = await pool.connect();

  try {
    await client.query('BEGIN');

    // Parameterize values; the allowlist above restricts SQL identifiers.
    const placeholders = rows.map((_, i) =>
      `(${columns.map((_, j) => `$${i * columns.length + j + 1}`).join(', ')})`
    ).join(', ');

    await client.query(
      `INSERT INTO ${quoteIdent(table)} (${identifiers}) VALUES ${placeholders}`,
      rows.flat()
    );

    await client.query('COMMIT');
  } catch (error) {
    await client.query('ROLLBACK');
    throw error;
  } finally {
    client.release();
  }
}

Caching Frequently Accessed Data

// cache.ts
class WebhookCache {
  private redis: Redis;
  private localCache = new Map<string, { value: any; expires: number }>();

  constructor(redis: Redis) {
    this.redis = redis;
  }

  // Two-tier caching: local memory + Redis
  async get<T>(key: string): Promise<T | null> {
    // Check local cache first
    const local = this.localCache.get(key);
    if (local && local.expires > Date.now()) {
      return local.value;
    }

    // Check Redis
    const cached = await this.redis.get(key);
    if (cached) {
      const value = JSON.parse(cached);
      // Store in local cache for 10 seconds
      this.localCache.set(key, {
        value,
        expires: Date.now() + 10000
      });
      return value;
    }

    return null;
  }

  async set<T>(key: string, value: T, ttlSeconds: number): Promise<void> {
    await this.redis.setex(key, ttlSeconds, JSON.stringify(value));
    this.localCache.set(key, {
      value,
      expires: Date.now() + Math.min(ttlSeconds * 1000, 10000)
    });
  }

  // Cache webhook secrets to avoid DB lookups
  async getWebhookSecret(provider: string): Promise<string | null> {
    const key = `webhook_secret:${provider}`;
    let secret = await this.get<string>(key);

    if (!secret) {
      // Load from database
      const result = await db.query(
        'SELECT secret FROM webhook_configs WHERE provider = $1',
        [provider]
      );
      if (result.rows[0]) {
        secret = result.rows[0].secret;
        await this.set(key, secret, 3600); // Cache for 1 hour
      }
    }

    return secret;
  }

}

Monitoring and Observability

Prometheus Metrics

// metrics.ts
import { Counter, Histogram, Gauge, Registry } from 'prom-client';

const register = new Registry();

export const metrics = {
  webhooksReceived: new Counter({
    name: 'webhooks_received_total',
    help: 'Total webhooks received',
    labelNames: ['provider', 'event_type'],
    registers: [register]
  }),

  webhooksProcessed: new Counter({
    name: 'webhooks_processed_total',
    help: 'Total webhooks processed',
    labelNames: ['provider', 'event_type', 'status'],
    registers: [register]
  }),

  processingDuration: new Histogram({
    name: 'webhook_processing_duration_seconds',
    help: 'Webhook processing duration',
    labelNames: ['provider', 'event_type'],
    buckets: [0.01, 0.05, 0.1, 0.5, 1, 2, 5, 10],
    registers: [register]
  }),

  queueDepth: new Gauge({
    name: 'webhook_queue_depth',
    help: 'Current webhook queue depth',
    labelNames: ['queue', 'status'],
    registers: [register]
  }),

  queueLatency: new Histogram({
    name: 'webhook_queue_latency_seconds',
    help: 'Time spent in queue before processing',
    labelNames: ['provider'],
    buckets: [0.1, 0.5, 1, 5, 10, 30, 60],
    registers: [register]
  }),

  activeWorkers: new Gauge({
    name: 'webhook_active_workers',
    help: 'Number of active worker instances',
    registers: [register]
  }),

  batchSize: new Histogram({
    name: 'webhook_batch_size',
    help: 'Size of processing batches',
    buckets: [1, 10, 25, 50, 100, 200, 500],
    registers: [register]
  })
};

// Update queue metrics periodically
async function updateQueueMetrics(): Promise<void> {
  const counts = await webhookQueue.getJobCounts();

  metrics.queueDepth.set({ queue: 'webhooks', status: 'waiting' }, counts.waiting);
  metrics.queueDepth.set({ queue: 'webhooks', status: 'active' }, counts.active);
  metrics.queueDepth.set({ queue: 'webhooks', status: 'delayed' }, counts.delayed);
  metrics.queueDepth.set({ queue: 'webhooks', status: 'failed' }, counts.failed);
}

setInterval(updateQueueMetrics, 5000);

// Metrics endpoint
app.get('/metrics', async (req, res) => {
  res.set('Content-Type', register.contentType);
  res.send(await register.metrics());
});

Grafana Dashboard Configuration

{
  "dashboard": {
    "title": "Webhook Processing",
    "panels": [
      {
        "title": "Webhooks Received/sec",
        "type": "graph",
        "targets": [
          {
            "expr": "rate(webhooks_received_total[1m])",
            "legendFormat": "{{provider}}"
          }
        ]
      },
      {
        "title": "Queue Depth",
        "type": "graph",
        "targets": [
          {
            "expr": "webhook_queue_depth",
            "legendFormat": "{{status}}"
          }
        ],
        "alert": {
          "name": "High Queue Depth",
          "conditions": [
            {
              "evaluator": { "type": "gt", "params": [10000] },
              "query": { "params": ["A", "5m", "now"] }
            }
          ]
        }
      },
      {
        "title": "Processing Latency (p99)",
        "type": "graph",
        "targets": [
          {
            "expr": "histogram_quantile(0.99, sum by (le, provider) (rate(webhook_processing_duration_seconds_bucket[5m])))",
            "legendFormat": "{{provider}}"
          }
        ]
      },
      {
        "title": "Error Rate",
        "type": "graph",
        "targets": [
          {
            "expr": "rate(webhooks_processed_total{status=\"error\"}[5m]) / rate(webhooks_processed_total[5m])",
            "legendFormat": "{{provider}}"
          }
        ]
      }
    ]
  }
}

High-Volume Readiness Checklist

Run this against your own stack before a traffic spike. Prioritize gaps using your burst profile, provider deadlines, downstream dependencies, and recovery requirements; the items below are not ranked by incident likelihood.

Receive layer (verify and enqueue)

  • Endpoint verifies the provider signature before enqueueing, then acknowledges promptly; no database writes or downstream calls run inline.
  • Inline work is: read raw body, verify provider signature, enqueue, respond.
  • Enqueue failures return 5xx so the provider can retry; do not acknowledge an event that was not queued.
  • Receivers are stateless and sit behind a load balancer so you can add instances horizontally.

Queue layer (the shock absorber)

  • Queue durability is configured and tested for the recovery target. Redis AOF/RDB and replication reduce loss risk but can still lose acknowledged writes.
  • Priority or separate queues exist for critical events (payments) vs. best-effort (analytics).
  • Terminal failures, including permanent errors and exhausted retries, reach a review queue or retained failed set; alert on failures and reconcile any missed dead-letter copies.
  • Retry policy uses exponential backoff with a cap and a max attempt count.

Worker layer (async processing)

  • Handlers that apply database effects use an atomic, provider-scoped event ID claim with those effects, and external side effects handle retries safely (at-least-once delivery can produce duplicates).
  • Workers parse and validate the authenticated event before processing.
  • Workers autoscale on queue depth (KEDA/HPA custom metric), not just CPU.
  • Worker count and concurrency are tuned from measured throughput, queue wait time, CPU and memory use, downstream latency, and database connection limits.
  • Graceful shutdown drains in-flight jobs on SIGTERM before exit.

Downstream protection

  • Where bulk writes help under representative load, batch database writes (bulk INSERT / COPY / UNNEST) with a size and wait time that meet latency requirements.
  • Connection pooling is in place (PgBouncer or a bounded client pool), with the total connection budget checked across worker replicas and other clients.
  • Rate limits are scoped to the relevant downstream API and account or store (token bucket / sliding window) to protect downstream calls from overload.

Observability

  • You track queue depth, processing latency (p50/p95/p99), and error rate — not just request counts.
  • Alerts cover sustained queue-depth growth, processing latency, worker failures, and errors; investigate downstream outages as well as worker capacity when backlog grows.
  • Distributed tracing spans receive → enqueue → process so you can locate bottlenecks.

Summary

Building scalable webhook infrastructure requires:

  1. Decouple receiving from processing - Respond immediately, queue for async processing
  2. Choose the right queue - Redis/BullMQ for many cases, SQS for managed durability, Kafka when replay or sustained throughput needs justify it
  3. Scale workers independently - Auto-scale based on queue depth and latency
  4. Batch for efficiency - Where supported and useful under load, batch database writes and API calls to reduce overhead
  5. Implement rate limiting - Protect downstream services from overload
  6. Monitor everything - Track queue depth, latency percentiles, and error rates

The key insight is that webhook scaling is primarily about managing queues and workers effectively. The receiving layer should be as thin as possible—validate minimally and queue quickly—while the processing layer handles the heavy lifting with proper batching, rate limiting, and error handling.

Frequently Asked Questions

How many webhooks can a single server handle?

A single server's capacity depends on payload size, signature checks, queue latency, hardware, and burst shape. Measure the receiver and worker bottlenecks under representative load. For sustained or bursty traffic, decouple reception from processing using a durable queue.

Should I process webhooks synchronously or asynchronously?

Usually asynchronously for work that can outlast the provider's response deadline. Verify the provider signature on the raw body, enqueue the authenticated event, then respond promptly with 200 and process the remaining work via a job queue. This reduces timeout risk and allows independent scaling of receivers and processors.

What message queue should I use for webhooks?

Redis with BullMQ is excellent for most use cases (simple, fast). For higher durability requirements, use RabbitMQ or Amazon SQS. For sustained high throughput or replay needs, consider Apache Kafka after measuring your workload. Match the queue to your reliability and throughput needs.

How do I handle webhook bursts without dropping events?

Use a message queue as a buffer between receiving and processing. Size the queue for bursts and scale workers using queue depth and processing latency. Redis AOF/RDB and replication reduce loss risk but do not guarantee zero loss of acknowledged writes; choose and test a durability configuration that fits your recovery requirements. See the Redis persistence documentation.

What's the optimal number of webhook workers?

There is no general worker-to-core ratio. Start with a small deployment and measure throughput, queue wait time, CPU and memory use, and downstream latency and limits under representative load. Tune worker count and per-worker concurrency together, keeping total database connections within budget; set autoscaling thresholds from the backlog and processing latency you can tolerate.

How do I implement rate limiting for webhook processing?

Use a token bucket or sliding window algorithm. Scope counters to the downstream API and account or store where its limits apply. Set rates from current provider documentation or quota responses, then delay or queue calls when that scope reaches its limit.

Should I batch webhook processing?

Consider batching when the database supports bulk writes or the downstream API supports batch requests. A 10-100-event batch is only a measurement starting point: tune its size and wait time against latency, payload, and downstream limits. Bulk operations can reduce statements and network round trips, and supported API batches can reduce request count; database connection count depends on pool size, concurrency, and replica count.

How do I scale webhook processing horizontally?

Deploy multiple worker instances that pull from the same queue. Use an atomic, provider-scoped event ID claim with the related database changes so concurrent deliveries cannot both commit. Keep handlers idempotent and auto-scale workers using Kubernetes HPA based on queue depth metrics.

What database patterns work best for high-volume webhooks?

Use connection pooling (PgBouncer, ProxySQL). Batch inserts with COPY or bulk INSERT. Consider time-series databases for event logs. Partition large tables by date. Use read replicas for queries. Implement proper indexing on lookup columns.

How do I monitor webhook processing performance?

Track: events received/sec, queue depth, processing latency (p50, p95, p99), error rate, and worker utilization. Alert on queue depth growth, latency spikes, and error rate increases. Use distributed tracing to identify bottlenecks in processing pipelines.

webhooksscalingperformancearchitecturequeuesredis