Skip to main content
TRUSTORYX.
Enterprise Architecture Guide

Enterprise API & Webhook Integration Planning Guide

Distributed, fault-tolerant API integrations build karne wale software architects ke liye comprehensive engineering guide. Cryptographic HMAC, Redis idempotency aur dead-letter queues.

Timing-Safe Cryptography Distributed Idempotency n8n & Node.js Patterns

1. HMAC SHA-256 Signatures

Unauthenticated webhooks par kabhi trust na karein. Timing attacks avoid karne ke liye timing-safe comparison se raw payloads verify karein.

2. Distributed Idempotency

Atomic Redis SETNX locks with 24h expiration duplicate payments aur database corruption ko effectively prevent karte hain.

3. Asynchronous Decoupling

Webhooks ko hamesha HTTP 202 Accepted se immediately acknowledge karein. Gateway timeouts prevent karne ke liye background queues use karein.

// Next.js 16 App Router: Idempotent Webhook Consumer with Timing-Safe HMAC
import { NextRequest, NextResponse } from 'next/server';
import crypto from 'crypto';

const WEBHOOK_SECRET = process.env.STRIPE_OR_PARTNER_SECRET!;

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

    if (!idempotencyKey) {
      return NextResponse.json({ error: 'Missing Idempotency-Key header' }, { status: 400 });
    }

    // 1. Timing-Safe HMAC Verification
    const expectedSig = crypto
      .createHmac('sha256', WEBHOOK_SECRET)
      .update(rawBody)
      .digest('hex');

    const isValid = crypto.timingSafeEqual(
      Buffer.from(signature, 'hex'),
      Buffer.from(expectedSig, 'hex')
    );

    if (!isValid) {
      return NextResponse.json({ error: 'Invalid HMAC Signature' }, { status: 401 });
    }

    // 2. Distributed Redis Idempotency Check (Atomic SETNX with 24h TTL)
    // const isNew = await redis.set(`idempotency:${idempotencyKey}`, 'processing', 'EX', 86400, 'NX');
    // if (!isNew) return NextResponse.json({ status: 'already_processed' }, { status: 200 });

    // 3. Immediately acknowledge HTTP 202 and push to background worker queue
    // await jobQueue.add('process_event', { payload: JSON.parse(rawBody) });

    return NextResponse.json({ received: true, status: 'queued' }, { status: 202 });
  } catch (error) {
    return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 });
  }
}
Need Enterprise Integration Engineering?

Connect Your CRM, ERP, and AI Systems Without Failures

Trustoryx architects resilient API pipelines, self-hosted n8n workflows, and custom SaaS connectors backed by strict SLA guarantees.