Rules and integrations

SQL rules over published messages, with republish, HTTP webhook, MQTT bridge and Kafka actions; delivery semantics, connectors, the admin API, the dashboard and metrics.

The rule engine runs SQL statements over the messages clients publish and hands each result to actions: republish on this broker, call an HTTP(S) webhook, publish on another MQTT broker, or produce to Kafka. Rules are defined in orbitmq.toml ([[rule]]) or created at runtime through the admin API and the dashboard, without a restart.

orbitmq.toml
[[rule]]
id = "hot"
sql = '''SELECT payload.temp AS t, clientid FROM "sensors/+/temp" WHERE t > 30'''

[[rule.action]]
type = "republish"
topic = "alerts/${clientid}"
qos = 1

A client that publishes {"temp": 31.5} to sensors/dev-1/temp makes this rule publish {"t":31.5,"clientid":"dev-1"} to alerts/dev-1.

Available in source builds

The rule engine is part of milestone M4, which is in progress. It is in the broker's source today; no release has been published yet.

How rules run

  • A tap after routing. Every client PUBLISH and every will message is offered to the rule engine after authorization; a publish the ACL refuses is never seen by a rule. The message is routed to subscribers exactly as it would be without rules: rules only observe it.
  • Per-core evaluation. Each data-plane core keeps an index of the FROM filters of every enabled rule. A message that matches no filter costs one lookup and no allocation; with [rules] enabled = false the tap is not registered at all. A matching message is handed to that core's bounded queue (queue_capacity, default 10 000) and evaluated by a task on the rules runtime (workers threads), so messages from one core keep their order. A message is evaluated once per rule, even when several of the rule's filters match.
  • Overflow is counted and dropped. The core never waits. When its queue is full, the message is dropped for the rules it matched and counted in their dropped counter. Every action has its own bounded queue (action_queue_capacity, default 10 000); when it is full, the message is dropped for that action and counted. A slow webhook or an unreachable Kafka cluster therefore never slows publishers, never delays MQTT delivery and never delays the other actions of the rule.
  • No loops. Messages published by a republish action, and dead letters, are injected through the cores' control rings and are not tapped again. A rule cannot trigger itself or another rule, even when it republishes to a topic its own FROM matches.
  • Runtime changes. Creating, changing or deleting a rule builds a new rule set that every core picks up on its next message. Messages already queued finish with the rule they were matched with.

The SQL language

SELECT <column>[, <column>…] FROM "<topic filter>"[, "<topic filter>"…] [WHERE <condition>]
  • FROM takes one to 64 MQTT topic filters, each in double quotes; + and # wildcards work as in subscriptions, so "#" does not match $SYS/… topics but "$SYS/#" does. Shared-subscription filters ($share/…, $queue/…) are refused.
  • Columns are * or <expression> [AS alias]. Without an alias, a field or path column is named after its last segment (payload.temp → temp); any other expression is named after its SQL text (upper(topic)). WHERE can use the aliases of SELECT columns.
  • Output. A message for which WHERE is true produces one JSON object with the selected columns. That object is what the actions send.
  • Strings use single quotes ('text'). A double-quoted word in an expression is an identifier, and the error says so.
  • Keywords and function names are case-insensitive.

Fields

FieldValue
payloadThe payload as text (invalid UTF-8 is replaced).
payload.a.b, payload.a[1], payload['a b']A path into the payload decoded as JSON. Arrays are 1-based. The payload is decoded at most once per message. A payload that is not JSON, or a missing key, gives null.
topicTopic Name.
clientidClient identifier of the publisher.
usernameUser name of the publisher, null when it connected without one.
qosQoS as published (0, 1 or 2).
retainRETAIN flag as published.
peerhostIP address of the publisher.
timestampTime the message reached the rule engine, in milliseconds since the Unix epoch.
nodeThe node name: local unless [rules] node sets it.
user_propertiesMQTT 5.0 User Properties as an object (for a repeated name, the last value wins). Read one with user_properties.name.

SELECT * outputs every field above, with payload as text. A path also works on other values: user_properties.trace reads one property, and a path into a string column decodes that string as JSON first.

Operators and expressions

  • Comparison: =, !=, <>, <, <=, >, >=. A number compared with a numeric string compares as numbers (payload.temp > 30 holds for {"temp": "31"}); strings compare by value.

  • Logic: AND, OR, NOT, and parentheses.

  • Arithmetic: +, -, *, /, % and unary -. Integer arithmetic stays integer where the result is exact; 7 / 2 is 3.5. || and concat() concatenate as text.

  • Arithmetic does not convert numeric strings, as in EMQX's rule engine: + adds two numbers and concatenates when either operand is a string (the other one as text), and -, *, /, % on a string are evaluation errors. For {"temp": "31"}, payload.temp + 1 is '311' and payload.temp - 1 fails; convert first with float(payload.temp) + 1 or int(payload.temp) - 1.

    Expression{"n": 31, "s": "31"} gives
    payload.n + 132
    payload.s + 1, concat(payload.s, 1), payload.s || 1'311'
    1 + payload.s'131'
    'x' + 1.5'x1.5'
    payload.s - 1, payload.s * 2, -payload.sevaluation error
    int(payload.s) - 1, float(payload.s) + 130, 32.0
    payload.s > 30true (comparisons do convert)
    payload.s + nullnull
  • x IS NULL, x IS NOT NULL, x IS TRUE, x IS FALSE.

  • x IN (a, b, …), x NOT IN (…).

  • x BETWEEN low AND high, x NOT BETWEEN low AND high (bounds included).

  • CASE WHEN cond THEN a [WHEN …] [ELSE b] END and CASE x WHEN value THEN a … END.

  • Literals: integers, decimals, 'strings', true, false, null.

null propagates through operators and functions (SQL three-valued logic), and a WHERE condition passes only when it is true. Division by zero, arithmetic on a non-number, NOT or AND on a non-boolean, and a non-finite result are evaluation errors: the message is counted failed for that rule and no action runs.

Anything else is refused when the rule is created, including JOIN, GROUP BY, HAVING, ORDER BY, LIMIT, DISTINCT, WITH, subqueries, LIKE and window functions.

Functions

FunctionDescriptionExample → result
lower(s)Lower case.lower('AbC') → 'abc'
upper(s)Upper case.upper('abc') → 'ABC'
trim(s[, chars])Removes leading and trailing white space or, with chars, any of those characters. Also TRIM([BOTH] [chars] FROM s).trim(' a ') → 'a', trim('xxaxy', 'xy') → 'a'
ltrim(s[, chars])Removes leading white space, or any of chars. Also TRIM(LEADING [chars] FROM s).TRIM(LEADING '0' FROM '0042') → '42'
rtrim(s[, chars])Removes trailing white space, or any of chars. Also TRIM(TRAILING [chars] FROM s).rtrim('a ') → 'a'
concat(a, b, …)Joins 1 to 64 values as text; null if any is null.concat(clientid, '/', qos) → 'dev-1/1'
substr(s, start[, len])Substring, 1-based, in characters. Also substring(…) and SUBSTRING(s FROM start FOR len).substr('sensor', 2, 3) → 'ens'
length(s)Length in characters; for an array, its number of elements. Also strlen.length('héllo') → 5
replace(s, from, to)Replaces every occurrence.replace('a-b-c', '-', '/') → 'a/b/c'
split(s, sep)Splits into an array of strings.split('a,b,c', ',') → ["a","b","c"]
nth(n, array)The n-th element, 1-based; null when out of range.nth(2, split('a,b,c', ',')) → 'b'
regex_match(s, 'pattern')Whether s matches the pattern. The pattern must be a string literal; it is compiled once, without backtracking.regex_match(clientid, '^dev-[0-9]+$') → true
str(v)Text: strings unchanged, other values as JSON.str(42) → '42'
int(v)Integer: numbers are truncated, numeric strings parsed, booleans give 0 or 1.int('42.9') → 42
float(v)Floating-point number.float('2') → 2.0
bool(v)Boolean: 'true' and 'false' (any case), or a number other than 0.bool('TRUE') → true
abs(n)Absolute value.abs(-3) → 3
ceil(n)Rounds up. Also CEIL(n).ceil(1.2) → 2
floor(n)Rounds down. Also FLOOR(n).floor(1.8) → 1
round(n[, digits])Rounds half away from zero, to digits decimals (−15 to 15) when given.round(3.14159, 2) → 3.14
sqrt(n)Square root; an error for a negative number.sqrt(16) → 4.0
coalesce(a, b, …)The first value that is not null.coalesce(username, 'anonymous')
is_null(v)Whether v is null.is_null(payload.x)
is_not_null(v)Whether v is not null.is_not_null(payload.x)
json_encode(v)The value as JSON text.json_encode(payload.tags) → '["a","b"]'
json_decode(s)Parses JSON text; an error if it is not JSON.json_decode('{"a":1}') → {"a":1}
topic_level(n)The n-th level of the Topic Name, 1-based; null when absent.topic_level(2) on sensors/dev-1/temp → 'dev-1'
now_timestamp()The current time in milliseconds since the Unix epoch.now_timestamp() → 1792483200000

Most functions return null when the value they work on is null; coalesce, is_null, is_not_null and json_encode (which gives 'null') handle null themselves. A function result longer than 1 MiB is an evaluation error.

Limits and errors

Rules are parsed when they are loaded or sent to the API, never per message, and every input is bounded:

LimitValue
Rule text16 KiB
Operators in one rule256
Nesting of expressions (parentheses, function calls, NOT)32 levels
Depth of the planned expression tree (a long a + b + … chain is a deep tree)128
Topic filters in FROM64
Compiled regex_match pattern256 KiB
Rule id1 to 64 characters of A-Z a-z 0-9 - _; test is reserved
Description1024 bytes
Actions per rule16
Template4096 bytes

An invalid rule is refused with a message and, for the SQL, the line and column of the offending token. An error at the end of the input (a WHERE with nothing after it) points just past the last character. For example SELECT a FROM "t" gives:

{
  "error": "invalid_rule",
  "message": "unknown field `a` (use payload, payload.<key>, topic, clientid, username, qos, retain, peerhost, timestamp, node, user_properties or a column alias)",
  "field": "sql",
  "line": 1,
  "column": 8
}

Other examples: FROM t asks for double quotes (write the topic filter in double quotes: FROM "t"), an unknown function gives unknown function `nope` , a wrong number of arguments says how many the function takes, and ORDER BY gives ORDER BY is not supported in rules at the position of ORDER (the same holds for LIMIT, GROUP BY, HAVING, DISTINCT, WITH, UNION and a second statement). Errors in an action name its field, such as actions[0].topic or actions[1].connector. In orbitmq.toml, an invalid rule or connector stops the broker at start-up (exit status 2) with the rule id and the same message.

Actions

A rule runs each of its actions for every message that passes. Actions are [[rule.action]] tables in orbitmq.toml (an actions array in the API) and are independent of each other.

Templates

Topics, payloads, webhook bodies and Kafka keys, values and headers are templates: ${column} or ${column.path} is replaced by a column of the rule's output. Strings are inserted as they are, other values as JSON, and a missing or null value as nothing. Array elements in a path are 1-based (${tags.1}). An absent payload, body or value template sends the whole output object as JSON.

A topic template that produces an invalid Topic Name for a message (for example an empty level from a missing value, or a +) makes that message count as failed for the action. A topic without placeholders is checked when the rule is created.

republish

Publishes the output on this broker. The message is routed like any other publish, including retained-message handling, but it is not checked against the ACL and is not seen by rules.

KeyDefaultDescription
topicrequiredTopic template.
qos0QoS 0, 1 or 2.
retainfalsePublish as a retained message.
payloadthe output as JSONPayload template.
[[rule]]
id = "temperature-celsius"
sql = '''
SELECT topic_level(2) AS device, round((payload.temp_f - 32) * 5 / 9, 1) AS celsius
FROM "sensors/+/fahrenheit"
WHERE payload.temp_f IS NOT NULL
'''

[[rule.action]]
type = "republish"
topic = "sensors/${device}/celsius"
payload = "${celsius}"
retain = true

Delivery is at most once from the rule's point of view: when the cores' control queues stay full, the batch is retried briefly and then counted failed.

webhook

Sends one HTTP request per message.

KeyDefaultDescription
urlrequiredhttps://…. Plain http:// is accepted only for loopback hosts (localhost, 127.0.0.1, [::1]) unless allow_http = true.
method"POST""POST" or "PUT".
headersnoneHeader names and values. Values are secrets: inline, { env = "NAME" } or { file = "/path" }.
bodythe output as JSONBody template. Content-Type is application/json unless headers sets one.
timeout_ms5000Time allowed per request, 100 to 60 000.
max_retries3Retries after a retriable failure, 0 to 100.
dead_letter_topicnoneWhere a message goes when it is given up; see Dead letters.
allow_httpfalseAccept http:// to any host.
tlsbundled and system rootsTLS options for https://.
[[rule]]
id = "door-events"
sql = '''SELECT clientid, payload.state AS state, timestamp FROM "doors/+/state"'''

[[rule.action]]
type = "webhook"
url = "https://events.example.com/ingest"
headers = { Authorization = { env = "EVENTS_TOKEN" }, X-Source = "orbitmq" }
timeout_ms = 3000
max_retries = 5
dead_letter_topic = "deadletter/door-events"

A 2xx answer is a success. Connection errors, timeouts, 429 and 5xx are retried; any other status fails at once. Up to 32 requests are in flight per action, so the order of requests is not guaranteed. Redirects are not followed, and at most 64 KiB of a response body is read.

Webhooks reach anything the broker can reach

A webhook can call any address the broker host can connect to, including internal services. Creating rules is an administrator capability: only admin-API token holders can do it. Restrict the token accordingly.

mqtt (bridge)

Publishes the output on another MQTT broker through a named MQTT connector.

KeyDefaultDescription
connectorrequiredName of a [[connector]] with kind = "mqtt".
topicrequiredTopic template on the remote broker.
qos00 or 1.
retainfalseRETAIN flag.
payloadthe output as JSONPayload template.
max_retries3Retries after a retriable failure, 0 to 100.
dead_letter_topicnoneSee Dead letters.
[[connector]]
name = "cloud"
kind = "mqtt"
address = "mqtt.example.com:8883"
tls = {}
client_id = "edge-1"
username = "edge"
password = { file = "/run/secrets/cloud" }

[[rule]]
id = "forward-alarms"
sql = '''SELECT * FROM "alarms/#"'''

[[rule.action]]
type = "mqtt"
connector = "cloud"
topic = "sites/edge-1/${topic}"
qos = 1

With QoS 1, a message stays in flight until the remote broker acknowledges it and is resent after a reconnect, so delivery is at least once while the broker runs. A PUBACK with an error reason code fails the message at once. A timeout (request_timeout_ms) or a lost connection is retried.

kafka

Produces one record per message to Kafka through a named Kafka connector.

KeyDefaultDescription
connectorrequiredName of a [[connector]] with kind = "kafka".
topicrequiredKafka topic template.
keynoneKey template. Without a key, records are spread round-robin over the partitions.
valuethe output as JSONValue template.
headersnoneRecord headers: names and value templates.
batch_max500Most records per produce batch, 1 to 10 000.
linger_ms5How long a batch waits for more records, 0 to 10 000.
max_retries10Retries of a batch after a retriable failure, 0 to 100.
dead_letter_topicnoneSee Dead letters.
[[connector]]
name = "events"
kind = "kafka"
bootstrap = ["kafka-1:9093", "kafka-2:9093"]
tls = { ca_file = "/etc/orbitmq/kafka-ca.pem" }
sasl = { mechanism = "scram-sha-512", username = "orbitmq", password = { env = "KAFKA_PASSWORD" } }

[[rule]]
id = "telemetry-to-kafka"
sql = '''
SELECT clientid, topic_level(2) AS site, payload.temp AS temp, payload.humidity AS humidity, timestamp
FROM "telemetry/+/climate"
WHERE payload.temp IS NOT NULL
'''

[[rule.action]]
type = "kafka"
connector = "events"
topic = "telemetry.${site}"
key = "${clientid}"
headers = { source = "orbitmq", site = "${site}" }
  • Partitioning. A keyed record goes to the partition that the Java client's default partitioner picks (murmur2 of the key), so OrbitMQ and other producers place the same key on the same partition, and records with the same key keep their order.
  • Acknowledgement. Records are produced with acks = all. The record timestamp is the time the message reached the rule engine.
  • Topics. OrbitMQ does not create topics; create them first. An unknown topic is treated as a retriable error.

Delivery semantics

republishwebhookmqttkafka
GuaranteeAt most onceAt least once while the broker runsQoS 0: at most once. QoS 1: at least once while the broker runsAt least once while the broker runs
RetriesBriefly, when the control queues are fullmax_retries (3)max_retries (3)max_retries (10), per batch
OrderNot guaranteedNot kept (32 in flight)Not kept (32 in flight)Kept per partition
Dead-letter topicNoYesYesYes
  • Retries with backoff. A retriable failure is retried after 100 ms, then 200 ms, 400 ms and so on, up to 5 s between attempts. A permanent failure (for example an HTTP 400) is not retried.
  • Circuit breaker. After 5 consecutive failures of an action, its attempts pause for 5 seconds; then one attempt probes the target, and a success closes the breaker. An open breaker delays attempts but does not use them up: a message is given up only after its own max_retries.
  • Shedding order. Nothing blocks. Messages are shed, and counted, where they wait: a full core queue (dropped on the rule), a full action queue (dropped on the action), then exhausted retries (failed or dead_lettered on the action).
  • Queues are in memory. Messages waiting in the rule engine's queues are lost when the broker stops or crashes. "At least once" covers every message accepted into an action's queue while the broker runs.
  • Kafka specifics. There is no idempotent producer yet, so a retry after a lost acknowledgement can write a record twice (consistent with at least once). Records are not compressed.

Dead letters

When an action sets dead_letter_topic, a message that exhausts its retries or fails permanently is published on this broker to that topic instead of being dropped: QoS 1, not retained, with the payload as it was sent (the Kafka value, the webhook body, the MQTT payload) and three MQTT 5.0 User Properties:

PropertyValue
ruleRule id.
actionThe action's position in the rule, from 0.
errorWhy it failed, for example HTTP 503 or timeout. Never contains a secret.

Subscribe to the dead-letter topic to inspect, alert on or replay failures. Without dead_letter_topic, the message is counted failed and dropped.

Connectors

MQTT bridge and Kafka actions use named connectors: [[connector]] tables in orbitmq.toml. A connector is shared by every action that names it, and its credentials stay in the configuration file: they are never sent through the API. Connectors can be changed only in the file (restart to apply). Names are 1 to 64 characters of A-Z a-z 0-9 - _ and must be unique; a rule that names a missing connector, or one of the other kind, is refused.

MQTT connectors

KeyDefaultDescription
namerequiredName used by actions.
kindrequired"mqtt".
addressrequiredhost:port of the remote broker.
tlsnone (plain TCP)TLS options; tls = {} uses the default roots.
client_idorbitmq-bridge-<name>Client identifier.
usernamenoneUser name.
passwordnoneSecret.
protocol"5""5" or "3.1.1".
keep_alive_secs60Keep Alive.
max_inflight32Most unacknowledged QoS 1 messages; lowered to the remote broker's Receive Maximum.
request_timeout_ms10000Time allowed for one publish, waiting included.

The connection is opened at start-up and reconnected with backoff (0.5 s, doubling up to 30 s).

Kafka connectors

KeyDefaultDescription
namerequiredName used by actions.
kindrequired"kafka".
bootstraprequiredBootstrap brokers, ["host:port", …].
client_id"orbitmq"Kafka client id.
tlsnone (plaintext)TLS options.
saslnone{ mechanism, username, password }; mechanism is "plain", "scram-sha-256" or "scram-sha-512", password a secret.
allow_plaintextfalseAllow SASL PLAIN without TLS.
request_timeout_ms10000Time allowed for one produce request, the client's own retries included.

The producer connects on first use and reconnects by itself. Partition lists are cached for 60 seconds. The client is written in Rust; no C library is linked.

TLS

Webhooks, MQTT connectors and Kafka connectors take the same tls table as the authentication sources. TLS uses rustls; certificate verification cannot be turned off.

KeyDefaultDescription
roots"both"Trusted roots on top of ca_file: "bundled" (the Mozilla list compiled into the broker), "system" (the operating system's store), "both", or "none" (only ca_file).
ca_filenoneExtra trusted CA certificates (PEM), for example a private CA.
client_cert, client_keynoneClient certificate chain and key (PEM) for mutual TLS.
server_namethe hostName to verify when it differs from the host connected to.

SASL PLAIN without TLS is refused at start-up, because it would send the password in clear text; add tls, or set allow_plaintext = true on a network you trust. SCRAM mechanisms never send the password.

Secrets

Passwords and webhook header values accept three forms, as elsewhere in orbitmq.toml:

password = "inline value"
password = { env = "KAFKA_PASSWORD" }      # read from the environment at start-up
password = { file = "/run/secrets/kafka" } # read from a file; one trailing line break is removed

Secrets never appear in logs or error messages. GET /api/v1/config shows inline values as <redacted> and keeps env and file references. The rules API returns inline webhook header values as ******; sending ****** back in a PUT keeps the stored value. Values created through the API are stored in the rules state file, which is written with mode 0600.

Configuration

orbitmq.toml
[rules]
enabled = true                # false: no tap, no cost; [[rule]] tables are ignored and the API answers 503
queue_capacity = 10000        # per core, messages waiting for evaluation
action_queue_capacity = 10000 # per action
workers = 2                   # threads of the rules runtime (1 to 64)
# state_file = "/var/lib/orbitmq/orbitmq.rules-state.toml"
KeyDefaultEnvDescription
enabledtrueORBITMQ_RULES_ENABLEDRun the rule engine.
queue_capacity10000ORBITMQ_RULES_QUEUE_CAPACITYCapacity of each core's queue to the evaluation tasks.
action_queue_capacity10000ORBITMQ_RULES_ACTION_QUEUE_CAPACITYCapacity of each action's queue.
workers2ORBITMQ_RULES_WORKERSThreads of the rules runtime (evaluation and delivery), clamped to 1 to 64.
state_fileorbitmq.rules-state.toml next to the configuration fileORBITMQ_RULES_STATE_FILEWhere rules created through the API are kept.
node"local"noneValue of the node field in rules.

A rule in orbitmq.toml has the keys id, description, sql, enabled (default true) and its [[rule.action]] tables. The same keys are listed in the configuration reference, whose orbitmq.example.toml ends with a commented [rules], [[rule]] and [[connector]] example.

The rules state file

Rules from orbitmq.toml have source = "config" and are read-only through the API (409 read_only): change them in the file and restart. Rules created through the API have source = "api" and are kept in the rules state file:

  • By default orbitmq.rules-state.toml in the directory of the configuration file, beside orbitmq.auth-state.toml. Set [rules] state_file or ORBITMQ_RULES_STATE_FILE to move it.
  • It holds version = 1 and [[rule]] tables in the orbitmq.toml shape (actions are written as [[rule.actions]]; orbitmq.toml accepts both [[rule.action]] and [[rule.actions]]). It is written atomically (temporary file, fsync, rename) with mode 0600, because webhook headers may hold credentials.
  • It adds to the rules of orbitmq.toml. A stored rule with the id of a configuration rule is ignored with a warning.
  • An invalid state file stops the start-up. When it cannot be written, the API answers 500 persist_failed and nothing changes.
  • Without a configuration file and without state_file, API changes live in memory only and the API reports "persisted": false.

Admin API

All endpoints need the admin bearer token. With [rules] enabled = false they answer 503 unavailable. The full schemas are in the Admin API reference.

MethodPathPurpose
GET/api/v1/rulesEvery rule, sorted by id, with source, from and counters; plus persisted.
POST/api/v1/rulesCreate a rule (201).
GET/api/v1/rules/{id}One rule.
PUT/api/v1/rules/{id}Replace an API rule. Its counters are kept; its actions restart with fresh queues.
DELETE/api/v1/rules/{id}Delete an API rule (204). Messages already queued for its actions are still delivered.
GET/api/v1/rules/{id}/metricsCounters of the rule and of each action.
POST/api/v1/rules/testEvaluate SQL against a sample message. Nothing is stored and no action runs.
GET/api/v1/connectorsConnectors with their status, counters and last error (no credentials).

Create a rule:

curl -s -X POST -H "Authorization: Bearer $ORBITMQ_TOKEN" -H 'Content-Type: application/json' \
  http://127.0.0.1:18083/api/v1/rules -d '{
    "id": "hot",
    "description": "Temperatures above 30",
    "sql": "SELECT payload.temp AS t, clientid FROM \"sensors/+/temp\" WHERE t > 30",
    "actions": [
      { "type": "republish", "topic": "alerts/${clientid}", "qos": 1 }
    ]
  }'

Test SQL before saving it:

curl -s -X POST -H "Authorization: Bearer $ORBITMQ_TOKEN" -H 'Content-Type: application/json' \
  http://127.0.0.1:18083/api/v1/rules/test -d '{
    "sql": "SELECT payload.temp AS t, upper(clientid) AS who FROM \"sensors/+/temp\" WHERE t > 30",
    "context": { "topic": "sensors/a/temp", "payload": "{\"temp\": 31.5}", "clientid": "dev-1" }
  }'
{ "matched": true, "passed": true, "output": { "t": 31.5, "who": "DEV-1" } }

context takes topic, payload (text), clientid, username, qos, retain and peerhost; timestamp is the current time. matched says whether the topic matches a FROM filter; the SQL is evaluated either way.

StatuserrorMeaning
400invalid_ruleThe rule or request is invalid; field names it, and line and column locate SQL errors. Also returned by /rules/test when evaluation fails (field: "context").
404not_foundNo such rule.
409conflictPOST: a rule with this id exists.
409read_onlyThe rule is defined in orbitmq.toml.
500persist_failedThe rules state file could not be written; nothing changed.
503unavailableThe rule engine is disabled.

Dashboard

The dashboard's Rules page lists every rule with its source, FROM filters, actions and matched, passed, failed and dropped counters. Rules created through the API can be edited, enabled, disabled and deleted there; configuration rules are shown read-only. It warns when changes are not persisted. A rule's page shows its SQL, per-action counters (succeeded, failed, dropped, retried, dead-lettered, queued) and a test panel that runs the SQL against a sample topic and payload. New rules are written in an SQL editor with action forms for the four action types. The Connectors section shows each connector's kind, target, status, delivered, failed and queued counts and last error.

Metrics

MetricTypeLabelsDescription
orbitmq_rule_messages_totalcounterrule, resultMessages seen by each rule. matched: evaluated (FROM matched and the message was queued); passed: WHERE true; filtered: WHERE not true; failed: evaluation error; dropped: the core's rules queue was full.
orbitmq_rule_action_messages_totalcounterrule, action, type, resultMessages handled by each action. success, failed (given up without a dead-letter topic, or an invalid rendered topic), dropped (action queue full), retried (retry attempts; for Kafka, records in the retried batch), dead_lettered.
orbitmq_rule_action_queuedgaugerule, action, typeMessages waiting in each action's queue.
orbitmq_connector_upgaugeconnector, kind1 while the connector is connected, 0 otherwise. A Kafka connector reports 0 until its first use.

action is the action's position in the rule, from 0; type is republish, webhook, mqtt or kafka. The counters start at zero when the broker starts or the rule is created. See also Observability.

PromQL
# Messages shed by the rule engine, per rule
sum by (rule) (rate(orbitmq_rule_messages_total{result="dropped"}[5m]))
  + sum by (rule) (rate(orbitmq_rule_action_messages_total{result="dropped"}[5m]))

# Failed or dead-lettered deliveries per action
sum by (rule, action, type) (rate(orbitmq_rule_action_messages_total{result=~"failed|dead_lettered"}[5m]))

# Connectors that are down
orbitmq_connector_up == 0

On this page