Introduction
Self-hosted multi-tenant notification orchestration and guaranteed webhook delivery platform built on NestJS 12, PostgreSQL 18, and Redis 8.2 / BullMQ 6.
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 (
<10msp99): Authenticates thekmq_live_workspace API key (Authorization: BearerorX-API-Key), enforces sliding-window rate limits, locks theIdempotency-Key, validatespayloadagainst Ajv JSON Schemas (DISABLED,WARN, orSTRICT), writes the event and delivery records in a single PostgreSQL 18 transaction, enqueues BullMQ jobs, and immediately returns202 Accepted. The HTTP gateway never makes outbound network calls to external providers. - Isolated BullMQ Workers: Dedicated worker processes consume from the
deliveriesqueue (concurrency: 10) andmaintenancequeue, decrypt integration credentials in memory, render sandboxed Handlebars templates, invoke provider adapters under a strict10stimeout, and persist maskeddelivery_attemptsaudit rows.
# 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.jsDelivery Status Lifecycle (DeliveryStatus)
Every task in deliveries uses a UUID primary key and transitions strictly through the DeliveryStatus enum:
| Status | Meaning |
|---|---|
PENDING | Persisted and queued in BullMQ deliveries for immediate execution. |
SCHEDULED | Deferred via deliverAt (ISO-8601) with a BullMQ delayed job timer. |
RETRYING | Previous attempt failed with a transient error (429, 5xx, network timeout); waiting for nextRetryAt. |
DELIVERED | Provider responded with 2xx; deliveredAt recorded. |
FAILED | Terminal failure (fatal 4xx or maxAttempts exhausted); a dead-letter-delivery job is emitted to the deliveries-dlq queue for inspection and manual replay. |
CANCELED | Explicitly canceled via POST /v1/deliveries/:id/cancel before completion. |
PAUSED | Inbound 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 authenticatedAES-256-GCM(12-byterandom IV +16-byteGCM auth tag + ciphertext, stored in detached Base64 columnsencrypted_credentials/encrypted_signing_secret,iv,auth_tag) derived fromENCRYPTION_MASTER_KEY(exact 64 hex chars / 32 bytes). - Workspace outbound signing secret (
workspaces.webhook_signing_secret): Generated per workspace aswhsec_<64-hex>and rotatable viaPOST /v1/workspaces/:id/rotate-secret. - Workspace API keys (
kmq_live_<48-hex>): Returned in plaintext once upon creation; only the lowercase hexSHA-256digest (key_hash) is persisted inapi_keys(cached in Redis for300s). - Operator passwords & audit logs: Passwords use
Argon2id. Audit payloads and response bodies pass throughmaskSensitiveData, which recursively replacespassword,apiKey,credentials,token,secret,privateKey, andAuthorization(plus PII fieldsemailandphonein 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/jsonUser-Agent: KestrelMQ-Webhook/1.0X-KestrelMQ-Timestamp: Unix epoch timestamp in seconds.X-KestrelMQ-Signature:v1=<64-char-hex>computed asHMAC-SHA256("${timestamp}.${rawBody}", webhookSigningSecret).
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:
IngestionServiceacquires 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.- Repeating a completed call within 24 hours returns the original
202 Acceptedpayload withidempotentReplay: truewithout creating duplicateeventsor BullMQ jobs. - If a second identical request arrives while the first transaction is still in flight (
PROCESSING:<uuid>), KestrelMQ responds with409 Conflict(application/problem+json). IfSTRICTschema validation fails, the in-flight Redis lock is released immediately so the caller can fix the payload and retry.