Docs / Getting Started

Introduction

Self-hosted multi-tenant notification orchestration and guaranteed webhook delivery platform built on NestJS 12, PostgreSQL 18, and Redis 8.2 / BullMQ 6.

Updated 2026-11-28~4 min readCore Architecture

KestrelMQ is a self-hosted operational control plane for guaranteed outbound webhook, email, and Telegram delivery, signed inbound webhook buffering, and native MCP agent tooling. Your backend emits one structured event and KestrelMQ handles schema validation, fan-out routing, cryptographic signing, exponential retries, and dead-letter recovery.

Split API Gateway & BullMQ Workers

KestrelMQ enforces a strict process boundary between ingestion (node dist/main.js) and execution (node dist/worker.js):

  • Stateless API Gateway (<10ms p99): Authenticates the kmq_live_ workspace API key (Authorization: Bearer or X-API-Key), enforces sliding-window rate limits, locks the Idempotency-Key, validates payload against Ajv JSON Schemas (DISABLED, WARN, or STRICT), writes the event and delivery records in a single PostgreSQL 18 transaction, enqueues BullMQ jobs, and immediately returns 202 Accepted. The HTTP gateway never makes outbound network calls to external providers.
  • Isolated BullMQ Workers: Dedicated worker processes consume from the deliveries queue (concurrency: 10) and maintenance queue, decrypt integration credentials in memory, render sandboxed Handlebars templates, invoke provider adapters under a strict 10s timeout, and persist masked delivery_attempts audit rows.
architecture-processes.sh
# Stateless HTTP API & MCP Server (<10ms ingestion, zero outbound I/O)
node dist/main.js

# Isolated BullMQ delivery & retention workers (horizontally scalable)
node dist/worker.js

Delivery Status Lifecycle (DeliveryStatus)

Every task in deliveries uses a UUID primary key and transitions strictly through the DeliveryStatus enum:

StatusMeaning
PENDINGPersisted and queued in BullMQ deliveries for immediate execution.
SCHEDULEDDeferred via deliverAt (ISO-8601) with a BullMQ delayed job timer.
RETRYINGPrevious attempt failed with a transient error (429, 5xx, network timeout); waiting for nextRetryAt.
DELIVEREDProvider responded with 2xx; deliveredAt recorded.
FAILEDTerminal failure (fatal 4xx or maxAttempts exhausted); a dead-letter-delivery job is emitted to the deliveries-dlq queue for inspection and manual replay.
CANCELEDExplicitly canceled via POST /v1/deliveries/:id/cancel before completion.
PAUSEDInbound webhook buffered while its InboundSource has isPaused = true.

AES-256-GCM Credential Vault & Secret Storage

Sensitive material is protected across four distinct cryptographic primitives:

  • External credentials (integrations & inbound_sources): Encrypted at rest with authenticated AES-256-GCM (12-byte random IV + 16-byte GCM auth tag + ciphertext, stored in detached Base64 columns encrypted_credentials/encrypted_signing_secret, iv, auth_tag) derived from ENCRYPTION_MASTER_KEY (exact 64 hex chars / 32 bytes).
  • Workspace outbound signing secret (workspaces.webhook_signing_secret): Generated per workspace as whsec_<64-hex> and rotatable via POST /v1/workspaces/:id/rotate-secret.
  • Workspace API keys (kmq_live_<48-hex>): Returned in plaintext once upon creation; only the lowercase hex SHA-256 digest (key_hash) is persisted in api_keys (cached in Redis for 300s).
  • Operator passwords & audit logs: Passwords use Argon2id. Audit payloads and response bodies pass through maskSensitiveData, which recursively replaces password, apiKey, credentials, token, secret, privateKey, and Authorization (plus PII fields email and phone in response bodies and error logs) with "[REDACTED]".

Keep ENCRYPTION_MASTER_KEY immutable

Provider credentials in integrations and upstream secrets in inbound_sources are sealed with ENCRYPTION_MASTER_KEY. Changing this key makes previously stored ciphertexts undecryptable (ProviderConfigurationError).

Outbound HMAC-SHA256 Signatures (v1=)

When dispatching an outbound HTTP webhook (CUSTOM_WEBHOOK), WebhookAdapter sends:

  • Content-Type: application/json
  • User-Agent: KestrelMQ-Webhook/1.0
  • X-KestrelMQ-Timestamp: Unix epoch timestamp in seconds.
  • X-KestrelMQ-Signature: v1=<64-char-hex> computed as HMAC-SHA256("${timestamp}.${rawBody}", webhookSigningSecret).
verify-webhook.ts
import { createHmac, timingSafeEqual } from "node:crypto";

export function verifyKestrelSignature(
  rawBody: string | Buffer,
  signatureHeader: string,
  timestampHeader: string,
  signingSecret: string,
  toleranceSec = 300
): boolean {
  if (!signingSecret || !signatureHeader.startsWith("v1=")) return false;

  const ts = Number(timestampHeader);
  if (!Number.isInteger(ts)) return false;

  const nowSec = Math.floor(Date.now() / 1000);
  if (Math.abs(nowSec - ts) > toleranceSec) return false;

  const providedHex = signatureHeader.slice(3);
  if (!/^[0-9a-fA-F]{64}$/.test(providedHex)) return false;

  const expectedDigest = createHmac("sha256", signingSecret)
    .update(`${ts}.`, "utf8")
    .update(typeof rawBody === "string" ? Buffer.from(rawBody, "utf8") : rawBody)
    .digest();

  return timingSafeEqual(Buffer.from(providedHex, "hex"), expectedDigest);
}

Idempotent Ingestion

Supplying an Idempotency-Key header or idempotencyKey body field (1–255 non-whitespace characters; if both are provided, they must match or KestrelMQ returns 400 Bad Request) guarantees at-most-once event persistence per workspace:

  1. IngestionService acquires a 24-hour Redis lock (idempotency:{workspaceId}:{key}, SET NX EX 86400) backed by PostgreSQL's partial unique index (workspace_id, idempotency_key) WHERE idempotency_key IS NOT NULL.
  2. Repeating a completed call within 24 hours returns the original 202 Accepted payload with idempotentReplay: true without creating duplicate events or BullMQ jobs.
  3. If a second identical request arrives while the first transaction is still in flight (PROCESSING:<uuid>), KestrelMQ responds with 409 Conflict (application/problem+json). If STRICT schema validation fails, the in-flight Redis lock is released immediately so the caller can fix the payload and retry.