Docs / Core Concepts

Routing Rules & Templates

Match events with dot-prefix wildcards, resolve recipient targets dynamically, render isolated Handlebars templates or BYOT payloads, schedule delayed deliveries, and handle retries and DLQ.

Updated 2026-11-28~6 min readDelivery Engine

Routing rules decouple event producers from downstream notification channels. Producers emit a domain event such as order.paid, and KestrelMQ fans it out into independent Delivery records for every active rule whose eventName pattern matches.

Creating Routing Rules (POST /v1/rules)

Manage routing rules with an operator Access JWT (OWNER or ADMIN) and the X-Workspace-Id header (or workspaceId in the JSON body):

  • Exact match: order.paid matches only order.paid.
  • Dot-prefix wildcard: order.* matches order.created, order.paid, order.item.shipped, etc. (billing.invoice.* matches any billing.invoice.<subpath>).
  • Global catch-all: * matches every outbound event in the workspace.
create-routing-rule.sh
curl -s -X POST http://localhost:3000/v1/rules \
  -H "Authorization: Bearer ${ACCESS_TOKEN}" \
  -H "X-Workspace-Id: ${WORKSPACE_ID}" \
  -H "Content-Type: application/json" \
  -d '{
    "eventName": "order.*",
    "integrationId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
    "templateId": "8f14e45f-ceea-467a-9a38-7b2c1d9e04f1",
    "targetOverride": "payload.customer.email",
    "isActive": true
  }'

Programmatic JsonLogic support

Internally, RulesService.evaluateRules also supports evaluating JsonLogic predicates against { event, payload, recipient } while REST CreateRuleDto / UpdateRuleDto expose eventName, integrationId, templateId, targetOverride, and isActive.

Recipient & Target Resolution Priority

For each matched rule, RulesService.resolveRecipientTarget resolves the destination address, chat ID, or webhook URL in strict priority order:

  1. routingRule.targetOverride:
    • If prefixed with payload. or recipient. (e.g. payload.customer.email or recipient.webhookUrl), KestrelMQ extracts the nested property dynamically via getByPath.
    • Otherwise, treats targetOverride as a static literal (e.g. https://erp.acme.internal/hooks/orders or -100198273645).
  2. Explicit event.recipient envelope:
    • EMAIL: recipient.email
    • TELEGRAM: recipient.telegramChatId
    • WEBHOOK: recipient.webhookUrl
    • SLACK: recipient.slackWebhookUrl or recipient.webhookUrl
  3. Automatic event.payload fallback paths:
    • EMAIL: email → user.email → customer.email → recipient.email
    • TELEGRAM: telegramChatId → user.telegramChatId → customer.telegramChatId → chatId
    • WEBHOOK: webhookUrl → targetUrl → callbackUrl
    • SLACK: slackWebhookUrl → webhookUrl

If no target resolves on WEBHOOK or TELEGRAM, the adapter falls back to credentials.url or credentials.defaultChatId on the integration.

Sandboxed Handlebars & BYOT Fallback

Templates (POST /v1/templates with { name, subjectTemplate?, bodyTemplate }) are validated at write time (Handlebars.parse + precompile), cached in an LRU map (500 entries), and rendered inside an isolated context:

  • Prototype isolation: sanitizeContextValue clones variables onto Object.create(null) objects while stripping __proto__, constructor, and prototype, and executes Handlebars with allowProtoPropertiesByDefault: false and allowProtoMethodsByDefault: false.
order-paid-telegram.hbs
Order Paid · {{orderId}}
Customer: {{customer.email}}
Total: ${{amount}} {{currency}}

Bring Your Own Template (BYOT) Mode (templateId: null)

When templateId is null or omitted on a routing rule, TemplatesService.resolveContent reads pre-rendered content directly from event.payload:

ChannelBYOT Resolution (templateId: null)Missing Field Behavior
WEBHOOKUses payload.text if non-empty string, otherwise JSON.stringify(payload).Always succeeds for valid JSON object payloads.
EMAILRequires non-empty payload.subject and (payload.html or payload.text).Throws fatal TemplateResolutionError (FAILED, no retries).
TELEGRAM / SLACKRequires non-empty payload.text.Throws fatal TemplateResolutionError (FAILED, no retries).

Delayed Delivery (deliverAt) & Cancellation

Pass an ISO-8601 deliverAt timestamp when ingesting an event (POST /v1/events, CSV deliver_at, SDK, or MCP send_event) to defer execution:

  • Future timestamps create deliveries with status: "SCHEDULED" (scheduledFor set) and enqueue BullMQ jobs with delay: deliverAtMs - Date.now().
  • Any uncompleted delivery in PENDING, SCHEDULED, RETRYING, or PAUSED status can be aborted via POST /v1/deliveries/:id/cancel (transitions status to CANCELED and removes the waiting/delayed job from BullMQ). Attempting to cancel an already DELIVERED, FAILED, or CANCELED delivery returns 400 Bad Request.

Exponential Backoff, FAILED & deliveries-dlq

Provider adapters enforce a 10s HTTP timeout (DEFAULT_PROVIDER_TIMEOUT_MS = 10_000). Transient failures (408, 429, 5xx, network/timeout errors) retry automatically with ±10% symmetric jitter (DEFAULT_BACKOFF_JITTER_RATIO = 0.1, scalable via BACKOFF_SCALE_FACTOR):

  • DEFAULT_DELIVERY_MAX_ATTEMPTS = 5 total attempts on initial ingestion (1 initial execution + 4 retries):
Attempt #Delay Before Next RetryDB DeliveryStatus on Failure
Attempt #1 (initial)10s (±10%)RETRYING (nextRetryAt populated)
Attempt #2 (retry 1)1m (±10%)RETRYING
Attempt #3 (retry 2)5m (±10%)RETRYING
Attempt #4 (retry 3)30m (±10%)RETRYING
Attempt #5 (retry 4)Exhausted (5th tier 2h used when attempts > 5 on replay)FAILED + job added to deliveries-dlq

Fatal 4xx & configuration errors fail immediately

Non-retryable client responses (400, 401, 403, 404, 422), TemplateResolutionError, and ProviderConfigurationError throw BullMQ UnrecoverableError, immediately setting status = "FAILED" and emitting a dead-letter-delivery record to deliveries-dlq without burning retry slots.

Replaying Failed Deliveries (POST /v1/deliveries/:id/replay)

Calling POST /v1/deliveries/:id/replay (or kestrel.deliveries.replay(id) / MCP replay_delivery) resets status to PENDING (nextRetryAt: null) and enqueues a new BullMQ job with attempts = attemptCount + maxAttempts, granting a fresh 5-attempt budget along 10s -> 1m -> 5m -> 30m -> 2h.