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.
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.paidmatches onlyorder.paid. - Dot-prefix wildcard:
order.*matchesorder.created,order.paid,order.item.shipped, etc. (billing.invoice.*matches anybilling.invoice.<subpath>). - Global catch-all:
*matches every outbound event in the workspace.
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:
routingRule.targetOverride:- If prefixed with
payload.orrecipient.(e.g.payload.customer.emailorrecipient.webhookUrl), KestrelMQ extracts the nested property dynamically viagetByPath. - Otherwise, treats
targetOverrideas a static literal (e.g.https://erp.acme.internal/hooks/ordersor-100198273645).
- If prefixed with
- Explicit
event.recipientenvelope:EMAIL:recipient.emailTELEGRAM:recipient.telegramChatIdWEBHOOK:recipient.webhookUrlSLACK:recipient.slackWebhookUrlorrecipient.webhookUrl
- Automatic
event.payloadfallback paths:EMAIL:email→user.email→customer.email→recipient.emailTELEGRAM:telegramChatId→user.telegramChatId→customer.telegramChatId→chatIdWEBHOOK:webhookUrl→targetUrl→callbackUrlSLACK: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:
sanitizeContextValueclones variables ontoObject.create(null)objects while stripping__proto__,constructor, andprototype, and executes Handlebars withallowProtoPropertiesByDefault: falseandallowProtoMethodsByDefault: false.
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:
| Channel | BYOT Resolution (templateId: null) | Missing Field Behavior |
|---|---|---|
WEBHOOK | Uses payload.text if non-empty string, otherwise JSON.stringify(payload). | Always succeeds for valid JSON object payloads. |
EMAIL | Requires non-empty payload.subject and (payload.html or payload.text). | Throws fatal TemplateResolutionError (FAILED, no retries). |
TELEGRAM / SLACK | Requires 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"(scheduledForset) and enqueue BullMQ jobs withdelay: deliverAtMs - Date.now(). - Any uncompleted delivery in
PENDING,SCHEDULED,RETRYING, orPAUSEDstatus can be aborted viaPOST /v1/deliveries/:id/cancel(transitions status toCANCELEDand removes the waiting/delayed job from BullMQ). Attempting to cancel an alreadyDELIVERED,FAILED, orCANCELEDdelivery returns400 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 = 5total attempts on initial ingestion (1 initial execution + 4 retries):
| Attempt # | Delay Before Next Retry | DB 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.