Software Crafting

Bulletproof Webhook Ingestion: Architecting High-Throughput, Idempotent Processing Pipelines with Node.js, PostgreSQL, and AWS SQS

DDeepak RajputBackend Development12 min read04 Apr 2026Updated 2026-11-07
A dark circuit-covered cube where crossing bundles of blue and orange light fibres converge on a black background

TL;DR: Build a resilient webhook ingestion pipeline that decouples synchronous receiving from asynchronous processing using Node.js and AWS SQS. You will learn how to provision Standard SQS queues with a Dead-Letter Queue (DLQ) using the AWS SDK v3, and discover why preserving the raw byte stream in Express.js is critical for HMAC signature verification. By recording each event ID in PostgreSQL inside the same transaction as your business logic, retries and duplicate deliveries no longer repeat database side effects.

Key Takeaways

  • Decouple webhook ingestion from processing: verify the signature, enqueue the event in AWS SQS, and return 200 OK before any business logic runs.
  • Configure an SQS Dead-Letter Queue (DLQ) with a maxReceiveCount of 3 to automatically isolate "poison pill" messages that repeatedly fail.
  • Standard SQS queues have nearly unlimited throughput but no ordering or deduplication guarantees, so the database must handle idempotency. FIFO queues add ordering and a 5-minute deduplication window at lower, per-Region throughput quotas.
  • Avoid applying express.json() globally on webhook routes to preserve the raw byte stream required for HMAC signature verification.
  • Insert the provider's event ID with ON CONFLICT DO NOTHING in the same PostgreSQL transaction as the business logic, so a duplicate delivery commits nothing twice.
  • With current sqs-consumer versions, return the message from handleMessage to delete it. Returning undefined leaves it on the queue.

Picture this: you expose a POST /webhooks/stripe endpoint. In staging, it works. A customer makes a payment, your Node.js server verifies the cryptographic signature, updates the database, sends a welcome email, and responds with a 200 OK.

Then you deploy to production. At the start of the month, subscription renewals trigger thousands of webhooks in a few minutes. Your database connection pool is exhausted and the endpoint starts responding slowly. Stripe treats slow or failed responses as failed deliveries and retries them with exponential backoff for up to three days in live mode. Without idempotent processing, retried events repeat side effects: duplicate provisioning, repeated welcome emails, double-counted credits.

This is normal for third-party event ingestion. Providers deliver "at least once", which means they will sometimes send the same event more than once, and Stripe does not guarantee the order events arrive in. Stripe's own guidance is to return a 2xx quickly, before any complex logic, and to process events from an asynchronous queue.

So decouple ingestion from processing. In this guide, we will build an idempotent webhook pipeline that uses AWS SQS to absorb traffic spikes and PostgreSQL to record which events have been processed, in the same transaction as the work itself.

The Architecture of a Resilient Webhook Pipeline

A production-grade webhook receiver never executes business logic synchronously. Instead, it operates in two distinct phases:

  1. The Synchronous Ingestion Layer: Verifies the cryptographic signature, writes the event to a message queue (AWS SQS) and returns 200 OK. Its latency is roughly one SQS call.
  2. The Asynchronous Processing Worker: Pulls messages from the queue at a controlled concurrency limit, acquires an idempotency lock in PostgreSQL, executes the business logic, and acknowledges the message.

Before writing the Node.js application code, we must provision our queues. We require a primary Standard queue and a Dead-Letter Queue (DLQ). The DLQ acts as a safety net: if a webhook repeatedly fails to process (e.g., due to a persistent database error or a bug in your logic), SQS will automatically shunt it to the DLQ after a defined number of retries. This prevents "poison pill" messages from perpetually clogging the pipeline.

Here is how to provision this infrastructure programmatically using the AWS SDK v3:

// scripts/provision-queues.ts
import { SQSClient, CreateQueueCommand, GetQueueAttributesCommand } from '@aws-sdk/client-sqs';

const sqs = new SQSClient({ region: 'us-east-1' });

async function provisionWebhookQueues() {
  // 1. Create the Dead-Letter Queue
  const dlqResponse = await sqs.send(
    new CreateQueueCommand({
      QueueName: 'stripe-webhooks-dlq',
      Attributes: {
        MessageRetentionPeriod: '1209600', // Retain for 14 days
      },
    }),
  );

  // Look up the DLQ's ARN instead of hardcoding the account ID
  const { Attributes } = await sqs.send(
    new GetQueueAttributesCommand({
      QueueUrl: dlqResponse.QueueUrl,
      AttributeNames: ['QueueArn'],
    }),
  );
  const dlqArn = Attributes!.QueueArn;

  // 2. Create the Primary Queue with a Redrive Policy pointing to the DLQ
  const primaryResponse = await sqs.send(
    new CreateQueueCommand({
      QueueName: 'stripe-webhooks-primary',
      Attributes: {
        VisibilityTimeout: '60', // Worker has 60 seconds to process the message
        RedrivePolicy: JSON.stringify({
          deadLetterTargetArn: dlqArn,
          maxReceiveCount: 3, // Move to DLQ after 3 failed attempts
        }),
      },
    }),
  );

  console.log('Queues provisioned successfully', {
    primaryUrl: primaryResponse.QueueUrl,
    dlqUrl: dlqResponse.QueueUrl,
  });
}

provisionWebhookQueues().catch(console.error);

A one-off script is fine for a first environment. For anything long-lived, declare the same queues in CloudFormation, CDK or Terraform so the redrive policy is reviewed and versioned like the rest of your infrastructure.

Production Note: This uses a Standard queue. Standard queues support a nearly unlimited request rate but may deliver a message more than once and out of order. FIFO queues preserve order within a message group and deduplicate within a 5-minute window, but have per-API throughput quotas (300 transactions per second per partition without high-throughput mode, much higher with it, varying by Region). Because the provider can also send duplicates hours apart, you need database-level idempotency either way, so a Standard queue is the simpler default.

Phase 1: Rapid Ingestion and Signature Verification

The rule for the ingestion route is to keep it short. If you want a team to review or build this kind of pipeline, our custom backend and API development services cover it.

The ingestion route has exactly two responsibilities: prove the request originated from the provider, and enqueue it. It should not perform database lookups, it should not validate business state, and it must not alter the raw request body prior to signature verification.

A common, critical failure in Express.js is applying express.json() globally. This middleware parses the incoming body into a JavaScript object, destroying the raw byte stream. Stripe, Shopify, and most other webhook providers require the exact raw bytes to successfully compute the HMAC hash.

// server/routes/webhooks.ts
import express from 'express';
import Stripe from 'stripe';
import { SQSClient, SendMessageCommand } from '@aws-sdk/client-sqs';

const router = express.Router();
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
const sqs = new SQSClient({ region: 'us-east-1' });
const QUEUE_URL = process.env.SQS_PRIMARY_QUEUE_URL!;

// CRITICAL: Use raw body parsing specifically for webhook routes
router.post('/stripe', express.raw({ type: 'application/json' }), async (req, res) => {
  const signature = req.headers['stripe-signature'];
  let event: Stripe.Event;

  try {
    // Verify signature synchronously using the raw buffer
    event = stripe.webhooks.constructEvent(
      req.body,
      signature as string,
      process.env.STRIPE_WEBHOOK_SECRET!,
    );
  } catch (err) {
    const message = err instanceof Error ? err.message : 'Unknown error';
    console.warn(`Webhook signature verification failed: ${message}`);
    return res.status(400).send('Invalid signature');
  }

  try {
    // Push validated event to SQS
    await sqs.send(
      new SendMessageCommand({
        QueueUrl: QUEUE_URL,
        // We pass the parsed event, as the signature is already verified
        MessageBody: JSON.stringify(event),
      }),
    );

    // Acknowledge receipt to Stripe
    res.status(200).json({ received: true });
  } catch (err) {
    console.error('Failed to enqueue webhook', err);
    // Return 500 so Stripe knows to retry if SQS is temporarily unreachable
    res.status(500).json({ error: 'Internal server error' });
  }
});

Because the route does one signature check and one SQS call, its throughput is bounded mainly by SQS latency and CPU, not by your database. Note that a Stripe event can exceed a few hundred kilobytes; SQS accepts messages up to 1 MiB, and for anything larger you store the payload in S3 and enqueue a reference.

Phase 2: Building Strict Idempotency in PostgreSQL

Now that events are buffered in SQS, our worker processes can consume them. Because SQS delivers "at least once", and providers can send the same webhook twice, our worker will encounter duplicate events.

Many teams use Redis for idempotency, setting a key with a TTL (for example SET stripe_evt_123 1 NX EX 86400). That is weaker than it looks for financial webhooks: keys can be evicted under memory pressure if the eviction policy allows it, a TTL eventually forgets the event, and the Redis write is not atomic with your database changes, so a crash between the two leaves them disagreeing.

Here we use PostgreSQL instead: a unique key on the event ID, written in the same transaction as the business logic.

First, we define our idempotency schema:

-- migration_create_webhook_events.sql
CREATE TABLE webhook_events (
    idempotency_key VARCHAR(255) PRIMARY KEY,
    provider VARCHAR(50) NOT NULL,
    event_type VARCHAR(100) NOT NULL,
    status VARCHAR(20) DEFAULT 'processing',
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    processed_at TIMESTAMP WITH TIME ZONE
);

CREATE INDEX idx_webhook_events_status ON webhook_events(status);

Next, in our Node.js worker, we implement an insertion strategy that leverages PostgreSQL's concurrency controls. We attempt to insert the idempotency key. If it already exists, another worker (or a previous execution) has already handled it, and we should silently skip processing.

// worker/idempotency.ts
import { PoolClient } from 'pg';

export async function checkIdempotencyAndAcquireLock(
  client: PoolClient,
  idempotencyKey: string,
  provider: string,
  eventType: string,
): Promise<boolean> {
  // Attempt to insert the record. ON CONFLICT DO NOTHING handles duplicates.
  const result = await client.query(
    `
    INSERT INTO webhook_events (idempotency_key, provider, event_type, status)
    VALUES ($1, $2, $3, 'processing')
    ON CONFLICT (idempotency_key) DO NOTHING
    RETURNING idempotency_key;
  `,
    [idempotencyKey, provider, eventType],
  );

  // If rowCount is 1, we successfully inserted and "own" the lock for this event.
  // If rowCount is 0, the event is already processing or completed.
  return result.rowCount === 1;
}

export async function markIdempotencyComplete(client: PoolClient, idempotencyKey: string) {
  await client.query(
    `
    UPDATE webhook_events 
    SET status = 'completed', processed_at = NOW()
    WHERE idempotency_key = $1;
  `,
    [idempotencyKey],
  );
}

Production Note: In the worker below, the insert and the business logic share one transaction. If the worker crashes mid-execution, PostgreSQL rolls the transaction back and the processing row disappears with it, so no cleanup job is needed. You only need a sweeper for stale processing rows if you commit the idempotency row in a separate transaction before doing the work, for example because the work calls external APIs that cannot run inside a database transaction.

Phase 3: The Async Worker and Dead-Letter Queues (DLQs)

With our database locks ready, we can wire up the SQS consumer. While you can write a raw polling loop using @aws-sdk/client-sqs, the widely used sqs-consumer library handles long polling, deletion and error events for you.

Visibility Timeout is a critical mechanism here. When a worker pulls a message from SQS, the message isn't instantly deleted. It becomes "invisible" to other workers for the duration of the visibility timeout. If the worker successfully processes the message, it actively deletes it. If the worker crashes or hangs, the timeout expires, and the message reappears on the queue for another worker to try.

// worker/consumer.ts
import { Consumer } from 'sqs-consumer';
import { SQSClient } from '@aws-sdk/client-sqs';
import { pool } from './db'; // Configured pg.Pool instance
import { checkIdempotencyAndAcquireLock, markIdempotencyComplete } from './idempotency';
import { processStripeEvent } from './businessLogic';

const sqsClient = new SQSClient({ region: 'us-east-1' });

const webhookConsumer = Consumer.create({
  queueUrl: process.env.SQS_PRIMARY_QUEUE_URL!,
  sqs: sqsClient,
  handleMessage: async (message) => {
    if (!message.Body) throw new Error(`Empty message ${message.MessageId}`);

    const event = JSON.parse(message.Body);
    const idempotencyKey = `stripe_${event.id}`;

    // Check out a client from the pg pool to manage our transaction
    const client = await pool.connect();

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

      const isNewEvent = await checkIdempotencyAndAcquireLock(
        client,
        idempotencyKey,
        'stripe',
        event.type,
      );

      if (!isNewEvent) {
        console.log(`[SKIPPED] Duplicate event detected: ${idempotencyKey}`);
        await client.query('ROLLBACK');
        return message; // Returning the message acknowledges (deletes) it
      }

      // Execute actual business logic (e.g., update user subscription)
      await processStripeEvent(client, event);

      // Mark event as fully processed
      await markIdempotencyComplete(client, idempotencyKey);

      await client.query('COMMIT');
      console.log(`[SUCCESS] Processed event: ${idempotencyKey}`);
      return message;
    } catch (error) {
      await client.query('ROLLBACK');
      console.error(`[ERROR] Failed to process ${idempotencyKey}:`, error);

      // Throwing an error prevents SQS message deletion.
      // After the visibility timeout, SQS will make it available again.
      // After maxReceiveCount is hit, it automatically moves to the DLQ.
      throw error;
    } finally {
      client.release();
    }
  },
});

webhookConsumer.on('error', (err) => console.error(err.message));
webhookConsumer.on('processing_error', (err) => console.error(err.message));

webhookConsumer.start();
console.log('Webhook SQS consumer started');

In current sqs-consumer releases, a message is deleted only when handleMessage returns it (or when you set alwaysAcknowledge: true). A handler that resolves with undefined leaves the message on the queue, so it is redelivered after the visibility timeout and eventually moved to the DLQ.

Because the idempotency insert and the business logic run inside a single PostgreSQL transaction (BEGIN / COMMIT), they succeed or fail together. If updating the user's subscription table fails, the idempotency row is rolled back too, and the event is retried on the next SQS delivery. This atomicity only covers database writes. Side effects outside PostgreSQL, such as sending an email or calling another API, are not rolled back, so make them idempotent themselves (for example with the provider's idempotency keys) or move them to an outbox table that a separate job processes after commit.

Handling Extreme Race Conditions: PostgreSQL Advisory Locks

What happens if the same event is delivered twice and two workers pick up both copies at the same moment?

The unique key already handles correctness. When the second worker's INSERT ... ON CONFLICT DO NOTHING hits a key that the first worker inserted but has not yet committed, PostgreSQL makes the second insert wait. If the first transaction commits, the second insert does nothing and returns no row; if it rolls back, the second insert proceeds. Either way, the work is committed once.

The cost is that the second worker holds a database connection while it waits for the first worker's business logic to finish. If that logic is slow, duplicates can tie up your pool. PostgreSQL advisory locks let the second worker fail fast instead. Unlike row-level locks (SELECT ... FOR UPDATE), which require a row to already exist, advisory locks lock an application-defined integer. We can hash the idempotency key into two 32-bit integers and try the lock before the INSERT.

// worker/advanced-idempotency.ts
import crypto from 'crypto';
import { PoolClient } from 'pg';

/**
 * Converts a string idempotency key into two 32-bit integers
 * for PostgreSQL's two-argument advisory lock function.
 */
function generateLockIds(key: string): [number, number] {
  const hash = crypto.createHash('sha256').update(key).digest();
  // Read the first 8 bytes as two 32-bit signed integers
  return [hash.readInt32LE(0), hash.readInt32LE(4)];
}

export async function acquireAdvisoryLock(client: PoolClient, key: string): Promise<boolean> {
  const [lockId1, lockId2] = generateLockIds(key);

  // pg_try_advisory_xact_lock acquires a lock tied to the current transaction.
  // It returns true if locked, false if another transaction holds the lock.
  // The lock is automatically released on COMMIT or ROLLBACK.
  const result = await client.query(`SELECT pg_try_advisory_xact_lock($1, $2) as acquired`, [
    lockId1,
    lockId2,
  ]);

  return result.rows[0].acquired;
}

By injecting this at the very start of your SQS handleMessage loop:

// Inside handleMessage
await client.query('BEGIN');

const lockAcquired = await acquireAdvisoryLock(client, idempotencyKey);
if (!lockAcquired) {
  console.warn(`[LOCKED] Event ${idempotencyKey} is currently processing elsewhere. Delaying.`);
  await client.query('ROLLBACK');
  throw new Error('Concurrency lock active, retrying later'); // Let SQS retry
}

// Proceed with checkIdempotencyAndAcquireLock...

The second worker now gives up immediately and lets SQS redeliver the message after the visibility timeout, by which point the first worker has usually committed and the duplicate is skipped. Advisory locks are scoped to one PostgreSQL database, so this works across any number of worker containers that share it. A hash collision between two different keys only makes one of them wait for a retry; it never causes a duplicate.

Summary

A webhook pipeline that holds up under spikes assumes that providers will retry, duplicate and reorder events, and that your own workers will crash. With this architecture:

  1. SQS buffers traffic: The ingestion route does a signature check and one queue write, so it responds quickly even when the database is under load.
  2. PostgreSQL records processed events: A unique key written in the same transaction as the business logic means a duplicate delivery commits nothing twice. Advisory locks keep duplicates from tying up connections.
  3. DLQs isolate failures: Messages that keep failing are moved aside after maxReceiveCount attempts instead of blocking the queue, and an alarm on DLQ depth tells you to act.

Sources

Frequently Asked Questions

Why should a webhook endpoint respond before processing the event?

Providers expect a 2xx response within a few seconds and retry if they do not get one. Verify the signature, store the raw event, queue it, and return immediately; slow processing inside the request causes timeouts, retries, and duplicate deliveries.

How do you make webhook processing idempotent?

Store each event with a unique constraint on the provider event ID before doing any work. An INSERT ... ON CONFLICT DO NOTHING tells you whether the event is new, so a retried delivery is acknowledged without running its side effects again.

Why put SQS between the endpoint and the worker?

The queue absorbs traffic spikes, lets you scale workers independently, and retries failed jobs automatically. Messages that keep failing go to a dead-letter queue for investigation instead of being lost.

When do you need PostgreSQL advisory locks?

Not for correctness against duplicates, which the unique key already provides. Use them to make a duplicate fail fast instead of holding a connection, or, keyed on an object ID such as an order, to make different events for the same object run one after another without locking unrelated rows.

About the author

Deepak Rajput

Founder and CEO of SoftwareCrafting

Deepak Rajput is the Founder and CEO of SoftwareCrafting in Delhi and writes about web, mobile, backend, cloud, security, and engineering leadership.

Writes about Next.js, Node.js, React Native, PostgreSQL, AWS, Kubernetes.

View author profile

Last updated: 2026-11-07