MQTT broker
skaidb nodes speak MQTT natively: Home Assistant, zigbee2mqtt, Tasmota, ESPHome, Shelly and any standard MQTT client connect directly to the database — no separate Mosquitto in the stack. Both MQTT 3.1.1 and 5.0 are served (plus read-compat MQTT 3.1), over TCP, TLS, and WebSocket.
What makes it different from a file-backed broker: broker state lives in
replicated skaidb tables (the reserved _mqtt database). Retained
messages, persistent sessions, subscriptions and offline queues survive a
node restart — and on a cluster they survive node loss: a client can
disconnect from one node and resume its session, with its queued messages,
on any other node. Broker state is also SQL-inspectable:
SELECT topic, stored_at FROM _mqtt.retained WHERE topic LIKE 'homeassistant/%';
SELECT client_id, disconnected_at FROM _mqtt.sessions;
Enabling
[mqtt]
enabled = true
port = 1883 # plain / opportunistic TLS per [encryption].client_tls
tls_port = 8883 # always-TLS; bound only when client_tls != "off"
allow_anonymous = false # see Authentication below
acl_default = "open" # "closed": a role uses only the topics it is granted (Topic ACLs)
enabled and the ports need a restart; every limit, allow_anonymous and
acl_default are runtime-mutable via config set. The full knob list with
defaults is in config/skaidb.toml. CLI/env overrides: --mqtt-enabled /
SKAIDB_MQTT_ENABLED, --mqtt-port, --mqtt-tls-port,
--mqtt-allow-anonymous, --mqtt-acl-default / SKAIDB_MQTT_ACL_DEFAULT.
Transports
- TCP on
mqtt.port(1883). Withclient_tls = "opportunistic"the same port also accepts TLS; with"required", plaintext is refused. - TLS on
mqtt.tls_port(8883), always-TLS. The MQTT listeners present the[encryption]certificate unlessmqtt.tls_cert_file/mqtt.tls_key_filename their own pair (a public device endpoint on its own hostname while the SQL ports keep the internal one); either pair rotates live when its files change. The MQTT acceptor offers ALPNmqtt; clients that send no ALPN still connect. - WebSocket (
ws://andwss://): auto-detected on the same listeners — an HTTP GET upgrade (RFC 6455, subprotocolmqtt) instead of an MQTT CONNECT. No extra port or configuration. Client frames must be masked, and a control frame (ping, pong, close) may carry at most 125 bytes; either violation closes the connection with code 1002.
Authentication & authorization
CONNECT username/password authenticates against the same user catalog as
every other endpoint (CREATE USER … PASSWORD …). Failures answer CONNACK
0x05/0x04 (3.1.1) or 0x86 (5.0).
Two ways in that never put a password on the wire, tried before the username/password fields:
- 5.0 enhanced authentication (AUTH packets). A CONNECT carrying an
Authentication Methodruns the exchange of §4.12 — AUTH 0x18 both ways, the CONNACK closes it with the method and the server's final message in its properties. Methods offered: SCRAM-SHA-256, RFC 5802 message syntax, so any SCRAM client library produces the right bytes: CONNECTAuthentication Data=n,,n=<user>,r=<nonce>(=2C/=3Descaping in the user); the server AUTHsr=<nonce+ext>,s=<base64 salt>,i=<iterations>; the client AUTHsc=biws,r=<nonce+ext>,p=<base64 proof>; the CONNACK's data isv=<base64 server signature>— verify it, the server proved itself too. The SCRAM user is the identity (the CONNECT username/password fields are ignored). A failed proof is 0x86; stepping out of the exchange (any packet but AUTH 0x18) is 0x82.GSSAPI(Kerberos), on akerberosbuild withauth.gssapi_enabled: CONNECT data = the initial token, AUTH packets shuttle the rest, the CONNACK carries the final mutual-auth token; the principal maps to an external user (CREATE USER "<principal>" GSSAPI) exactly as on the binary port. Not authorized is 0x87.- anything else, or a method this build/config does not offer: 0x8C
(Bad authentication method).
Re-authentication (§4.12.1): on a connection that authenticated this
way, the client may send AUTH 0x19 with the SAME method to prove its
credentials again; the exchange continues over AUTH 0x18 and ends with
AUTH 0x00 (SCRAM's carries the server's
v=signature). Other packets keep flowing meanwhile. The new proof must be for the same role the connection holds (its topic ACLs were resolved at CONNECT); a failed proof or a different role ends the connection with DISCONNECT 0x87, a different method or a re-auth on a password/certificate connection with 0x82. - TLS client-certificate identity (
auth.x509_enabled = true,auth.x509_ca_file = <CA PEM>). Every client-TLS port then requests a client certificate (a client without one still connects and authenticates otherwise). On the MQTT listener — and on the binary protocol (mechanism EXTERNAL, see PROTOCOL.md §2.4) and on REST (a request with noAuthorizationheader) — a certificate chaining to that CA is the credential: its subject Common Name is the username (the Mosquittouse_identity_as_usernameconvention) — no password; the user must exist (CREATE USER "device-7" …, any kind). A CONNECT username that disagrees with the CN is refused (0x05/0x87); a CN naming no user is 0x04/0x86. Certificate rotation is live like the server's own (the acceptor rebuilds when the PEM files change).
mqtt.allow_anonymous is an extra gate on top of [auth]: even when
server auth is disabled, the MQTT listener refuses credential-less
CONNECTs unless it is true — the IoT listener is usually the most
exposed surface on the box. It is read at every CONNECT, so a config set
applies to the next one. Per-IP CONNECT rate limiting
(mqtt.connect_rate_limit, default 20/s with 2× burst) blunts reconnect
storms.
Bridging to another broker
[[mqtt.bridge]] mirrors topics between this broker and another one — the
migration or federation tool Mosquitto users know as a bridge connection:
[[mqtt.bridge]]
name = "cloud"
remote = "broker.example.com:8883"
remote_tls = true
remote_tls_ca = "/etc/skaidb/cloud-ca.pem" # empty = the public roots
remote_user = "site42"
remote_password = "…"
local_user = "bridge" # a catalog user holding the topic grants
local_password = "…"
out = ["tele/#", "state/#"] # local → remote as <remote_prefix><topic>
remote_prefix = "site42/"
in = ["site42/cmd/#"] # remote → local as <local_prefix><topic>
local_prefix = ""
qos = 1
keep_alive_secs = 30
A bridge is a thread holding two ordinary MQTT 3.1.1 clients: a loopback
link into this broker (so it is subject to local_user's topic grants,
admission limits and QoS like any device) and a link to the remote. A
message a bridge brings in is a client publish here — forwarded to
cluster peers, captured by sinks, queued for offline sessions. Rules:
out and in must not overlap after remapping (MQTT carries no origin,
so that is the only loop prevention, exactly as in Mosquitto); retain
does not cross a bridge (a 3.1.1 subscriber never sees a publisher's
retain flag on a live delivery); either link failing drops both, and the
bridge reconnects with a capped backoff (1 s to 30 s) and resubscribes —
messages during the outage are not replayed. Counters:
skaidb_mqtt_bridge_messages_total{bridge,direction} and
skaidb_mqtt_bridge_reconnects_total{bridge}. With client_tls =
"required" the loopback link uses the TLS port and trusts the node's own
certificate. local_user's topic grants decide the loopback link as they
decide any client (see Topic ACLs). Under acl_default = "closed" it
needs SUBSCRIBE covering its out filters and PUBLISH covering
local_prefix + its in filters. Under either value, a local_user
holding SUBSCRIBE grants reaches an out filter into a $ tree
($SYS/#) only through a grant that names the tree (GRANT SUBSCRIBE ON
TOPIC '$SYS/#') or SUBSCRIBE ON * — a # grant does not. The loopback
is 3.1.1, so a refused publish is acknowledged and dropped (counted as
reason="acl"). A refused out subscription stops the whole bridge, in
both directions: it is logged (bridge '<name>': local subscribe:
subscription refused: [<SUBACK codes, in the order of out>]) and the
bridge reconnects with its backoff, so it comes up at the first attempt
after the grant. The loopback link's client id,
skaidb-bridge-<name>-local, is held to client-id grants like any
client's (see Client ids): when a grant reserves it ('skaidb-*', say),
or local_user's role holds client-id patterns that do not admit it, the
loopback CONNECT is refused and logged as bridge '<name>': local link:
CONNECT refused (code 0x2): the broker refused the client id
'skaidb-bridge-<name>-local' for local_user '<user>' — GRANT CONNECT ON
CLIENT 'skaidb-bridge-<name>-local' TO <user>, and the bridge retries
with its backoff, coming up at the first attempt after that grant.
Publishing from SQL
PUBLISH '<topic>' PAYLOAD <expr> [QOS 0|1|2] [RETAIN] sends one message
through this node's broker — subscribers here get it, peers forward it
like any client publish, RETAIN stores it for late subscribers. A
string payload publishes its bytes, a document or array its JSON:
PUBLISH 'tele/kitchen' PAYLOAD {"t": 21.5, "unit": 'C'} QOS 1;
PUBLISH 'state/door' PAYLOAD 'open' RETAIN;
The topic is a literal (concrete name: no wildcards, not $), so the
check is static: the role needs PUBLISH on it under the same topic
grants a client connection gets (GRANT PUBLISH ON TOPIC 'tele/#' TO
role; a role with no topic grants is decided by mqtt.acl_default, as a
connected client is — any topic under open, none under closed). A procedure
body may PUBLISH, which is how a trigger turns a row change into an
MQTT message (change data capture without a separate stream tail):
CREATE PROCEDURE announce(id TEXT, total INT)
BEGIN
PUBLISH 'orders/new' PAYLOAD {"id": id, "total": total};
END;
CREATE TRIGGER order_out ON orders WHEN (total > 0) CALL announce(NEW.id, NEW.total);
The trigger runs as its definer, whose PUBLISH on the topic is checked
before every run under these same grants and the same setting — a definer
that no longer exists (its user or role was dropped) is refused, whatever
the setting — and a refused run is recorded in SHOW TRIGGERS; a CALL by
hand is gated on the body's topics.
Delivery only — topic→table capture rules ([[mqtt.sink]]) run on
client publishes, under the publishing client's role, not on SQL ones.
Needs the broker ([mqtt] enabled = true); otherwise the statement says so.
A statement answers once its messages are routed — handed to the matching
sessions on this node, and written to the queue of every persistent
session a QoS 1/2 message goes to — which is what an MQTT client's PUBACK
promises. Peers are sent the usual forward for their own live sessions;
the statement does not wait for it (a forward the peer link cannot take is
dropped and counted, skaidb_mqtt_cluster_forward_dropped_total).
Routing a message can need the engine (a queue row is a write of its
own), so a statement holds its messages until it has released its locks
and routes them then, on its own connection, in the order it published
them: all of a CALL's messages go out when the CALL ends, after its
rows are written. Concurrent sessions route their own messages side by
side.
- A message whose queue row cannot be written fails the statement —
resource limit: PUBLISH '<topic>': …, SQLSTATE53000over the PostgreSQL port. Live subscribers may have it: running the statement again can deliver it to them twice (at-least-once, as for an MQTT client's refused PUBACK). Routing stops there; the error says how many of the statement's messages were routed. Outside a transaction what the statement wrote stays: aCALL's rows are written before its messages go out. - A statement killed (
KILL QUERY), whose client goes away, or paststorage.statement_timeout_secs(counted from its start) while it routes stops there and says how many of its messages were routed; the rest are not published. - A statement that fails after it published keeps, outside a transaction, what it did: its messages are routed (one that is not makes its error end by saying how many were).
- The messages a statement holds count against its byte budget
(
storage.scan_byte_budget), each its topic and payload plus what holding it takes (about 200 bytes, so many tiny messages count for the memory they occupy): a statement holding more is refused withresource limit: PUBLISH: … byte budget …, SQLSTATE54000. With no budget (storage.scan_byte_budget = 0) the built-in one, 256 MiB, applies. The budget is each statement's own: statements running side by side can each hold up to a full budget. - Inside a transaction a message goes out when its statement ends, not at
COMMIT, and aROLLBACKdoes not take it back; a statement that fails there publishes nothing, and one whose message cannot be queued fails and is undone. A statement refused on a row another transaction holds and run again publishes once. A transaction run again fromBEGIN— what a driver's transaction helper does after a conflict — publishes its messages again. - A trigger's (or a job's) body routes each message once the body statement that published it is done; a message that cannot be queued fails the run, and the trigger runs the event again (a live subscriber may get it twice).
- A clean stop waits, within its MQTT phase, for the messages statements are still routing; a crash loses them.
Topic ACLs
Topic ACLs are grants, of two kinds — topics a role may publish to and topics it may subscribe to:
GRANT PUBLISH ON TOPIC 'tele/#' TO sensors;
GRANT SUBSCRIBE ON TOPIC 'cmnd/+/set' TO sensors;
REVOKE PUBLISH ON TOPIC 'tele/#' FROM sensors;
- A role holding any grant of a kind is confined to its grants of that kind.
- A role holding no grant of a kind is decided by
mqtt.acl_default: "open"(the default): every topic of that kind — what a default Mosquitto gives Home Assistant;"closed": none — the role may do only what it is granted.
The kinds are decided separately: under "open", a role granted only
SUBSCRIBE ON TOPIC 'cmnd/#' publishes anywhere.
- Never restricted, under both values: the superuser, a role holding
ADMIN on *, and a role holding the kind's own privilege on *
(GRANT PUBLISH ON * TO r, GRANT SUBSCRIBE ON * TO r), directly or
through a role it holds — over MQTT and from SQL alike. With
authentication off every client is the superuser, so the setting changes
nothing.
"closed" is recommended for any listener reachable beyond trusted
devices. The setting is live: SET CONFIG mqtt.acl_default = 'closed'
applies at the next check of every connection, delivery, offline queue
decision, will, PUBLISH from SQL and job or trigger run. Nothing is
disconnected and no subscription is removed: one made under "open"
delivers nothing under "closed" until the role is granted its topics. It
decides topic grants only, not client ids (see Client ids).
Before setting "closed":
- Grant every device role its topics, its will's included: a CONNECT carrying a will the role may not publish is refused (3.1.1 0x05, 5.0 0x87), and a 3.1.1 publish it may not make is acknowledged and dropped.
- Grant a bridge's
local_userits topics (see Bridging above). - Grant trigger and job definers the topics their bodies publish to: a
refused run is a failed run in
SHOW TRIGGERS/SHOW JOBS, and a trigger skips the event after three attempts. - A role that should stay open on ordinary topics can be granted
PUBLISH ON TOPIC '#'andSUBSCRIBE ON TOPIC '#'. - Set the same value on every member. Each member decides what it handles
— the connections it holds and the deliveries to them, the queue rows it
writes, the wills it fires, its statements and the jobs it runs — so
members that disagree answer a client by the node it reaches. A member
that does not know the key (an older release, during a roll or after a
downgrade) ignores it with a start-up warning and behaves as
"open". - Check the value in force. A misspelt key (
acl_defualt) is only warned about at start, like any unknown key, and changes nothing; a value other thanopenorclosedrefuses the start (andSET CONFIGrefuses it). The start-up linemqtt: a role with no topic grants of a kind may use every topic|no topic of it (mqtt.acl_default = …)and the gaugeskaidb_mqtt_acl_closed(1 under"closed", per member) show it.
A filter holding ;, a single quote or U+001E cannot be granted (a
stored grant cannot carry it; see
QUERY_SYNTAX.md).
Grant filters use MQTT wildcard semantics. A publish is allowed when any
granted filter matches the topic; a subscribe is allowed when any
granted filter covers the requested filter (a grant of home/# covers a
subscription to home/+/temp). Denied publishes answer 0x87 Not
authorized on 5.0 (3.1.1 has no error channel: the packet is acknowledged
per QoS and silently not routed, counted in
skaidb_mqtt_messages_dropped_total{reason="acl"}); denied subscriptions
get a per-filter SUBACK failure. A will whose topic the role may not
publish is refused at CONNECT. The $ trees are reached only by a grant
that names them: a grant whose first level is # or + neither matches
nor covers $SYS/… or $stream/…, so a SUBSCRIBE there under such a
grant is refused — grant SUBSCRIBE ON TOPIC '$SYS/#' (or
'$stream/<db>/<name>'), or SUBSCRIBE ON *.
Grant changes apply at once, to live connections and stored sessions alike:
- The next publish and subscribe of a connection are checked against the grants as they are then.
- A message is delivered only while the role may receive its topic — some
granted subscribe filter of the role matches it, or, holding none, the
setting allows it — checked for every message, whatever subscription it
arrives through. A subscription made before a
REVOKEstays, and receives only what the grants still cover; aGRANTback restores it with no resubscribe. A message the grants refuse is not queued for a persistent session either, and one queued before aREVOKEis not delivered at the resume. - A shared group never picks a member whose grants refuse the topic.
- A will is checked when it goes out, delayed or not.
- A connection whose user is dropped ends (5.0 reason 0x87) at its next
publish, subscribe, ping or delivery, and its stored session —
subscriptions and queue — is discarded when it ends; so is the stored
session of a user dropped while offline (within about a second), and its
delayed will does not go out. Before a node discards such an offline
session it reads the session's
_mqtt.sessionsrow, atmqtt.state_consistency(up to 100 sessions to a statement): a row of another user, or of a login its own record does not know — a CONNECT through another node whose notice it missed — keeps the session on every node, and the node's record follows the row, unless the row's user is gone too (the same dropped user's later login, or another dropped user's session), which is discarded at once; a row it cannot read (a lost quorum) discards nothing, and the node looks again a second later, then at doubling intervals up to a minute while the row stays unreadable. A user dropped and created again under its name is another user (see Users and roles): the same holds for the dropped user's connections, sessions and wills, whenever the broker looks — the name existing again changes nothing — and none of them passes to the new user (see Sessions & QoS). The sessions discarded because their user is no one's now are counted inskaidb_mqtt_sessions_superseded_total{cause}:connect(the CONNECT of the user made again under the client id),sweep(offline),end(at its connection's end). A configured user's role need not be in the catalog, and is never considered dropped (holding no grants, it is decided by the setting). What another node took over or discarded meanwhile is not the ending connection's to discard: whatever is stored under the client id then — another user's newer session included — stays, and a session without persistence, which stores nothing, ends by dropping only its own subscriptions on its node.
A REVOKE of a role's last grant of a kind leaves it with none: every
topic of that kind under "open", none under "closed".
Client ids
Client ids are granted to roles, as topics are:
GRANT CONNECT ON CLIENT 'sensor-*' TO sensors; -- the ids the pattern admits
GRANT CONNECT ON CLIENT '%u/*' TO fleet; -- ids that begin with the role's own name and '/'
GRANT CONNECT ON * TO ops; -- every id
REVOKE CONNECT ON CLIENT 'sensor-*' FROM sensors;
A pattern is literal text, compared case-sensitively, with at most one
* (any run of characters) and an optional leading %u, which stands for
the name of the role the login acts as — a catalog user's own name. So
'%u/*' granted to a role gives each of its members its own ids. User
names can be prefixes of one another (ann, ann-b): end the %u part
with a separator user names do not hold, as '%u/*' does. Grants inherit
through GRANT ROLE. The pattern rules and what a GRANT refuses are in
QUERY_SYNTAX.md.
The ids a role may use:
- a role holding
CONNECTorADMINon*(directly or through a role): every id; - a role holding client-id patterns: the ids they admit, and no other
(
'*'alone admits any id no grant reserves); - a role holding none: any id that no grant reserves. A pattern
reserves every id it admits — a
%upattern, for each role holding it, the ids it admits with that role's name — whether or not anyone uses it, so a grant keeps its ids from the roles that hold no client-id grant.'*'andON *reserve nothing.
mqtt.acl_default does not decide client ids: under "closed" too, a
role holding no client-id grant uses any id nothing reserves.
The id is decided first at CONNECT, before the will and before any session under it is looked at: an id the role may not use is refused (5.0 0x85 Client Identifier not valid, 3.1.1 0x02 identifier rejected), and grants that cannot be read refuse the CONNECT as server unavailable (0x88 / 0x03). Never held to client-id grants: an id the server assigns (an empty client id), which is that connection's own for its life; the superuser; and, with authentication off, every client (each is the superuser).
Grant changes apply at once. A connection whose role may no longer use its
id — a REVOKE, or a grant that now reserves the id for another role —
ends at its next publish, subscribe, ping or delivery (5.0 DISCONNECT
0x87), and its will goes out as at any abnormal end. Its stored session is
kept — row, subscriptions, queue — and what is routed to it
meanwhile is queued as for an offline session, because grant changes are
not atomic (a REVOKE then a GRANT; REVOKE ROLE old then GRANT ROLE
new). Its owner resumes it once allowed the id again; until then it
expires as usual, the operator can release it (see Sessions & QoS), or a
grantee displaces it. A REVOKE of a role's last client-id grant leaves
it with none: any id nothing reserves, the revoked one included unless
another grant still admits it.
Displacement. A session whose owner may no longer use its id — a
dropped user's included, whatever the id — is discarded (subscriptions,
queue and delayed will, on every node) when a user a grant gives the id
connects under it: one of that user's patterns other than '*' admits
the id, or it holds CONNECT or ADMIN on * (the superuser counts
too). A connection live under the id is ended (5.0 DISCONNECT 0x8E
Session taken over) and its will does not go out: the id changed hands,
and the will would speak for its new holder. The newcomer gets a new
session (session present 0), whatever its clean-start flag. A user that
only the rule for a role holding none admits (nothing reserves the id),
or only a bare '*' (which admits the same ids), does not displace: it is
refused as below. Both users are decided by the grants as they are when
the CONNECT meets the session, read at once: a grant change landing while
the CONNECT waits for the id decides it too. The owner is the session's
user: a connection live under the id of another user of its name (the
owner's name dropped and created again, the new user's session made on
another node) says nothing of whether the owner may keep the id. A
session that cannot be
discarded (its deletes reach no quorum) refuses the CONNECT as server
unavailable (0x88 / 0x03): the newcomer gets nothing of it, a connection
live under the id has been ended all the same, and the newcomer's next
CONNECT discards it again. A subscription the displaced connection was
making at that very moment can outlive the discard: the newcomer's session
may then be routed messages on its filter, only those its own grants let
it receive. Displacements are counted in
skaidb_mqtt_sessions_displaced_total.
First use decides between users that may both use the id: the session belongs to the user that made it, and another user's CONNECT under its id is refused (0x85 / 0x02) while the owner may keep it.
Before the first client-id grants, see what is in use: SELECT auth_user,
client_name FROM drivers WHERE endpoint = 'mqtt' lists the live
connections, SELECT "role", client_id FROM _mqtt.sessions the stored
sessions. A role's first client-id grant confines it, so its connections
under other ids end at their next check; a grant that reserves ids ends,
at their next check, the connections of other users under them unless a
grant admits those users too. On a cluster, make client-id grants once
every member runs a release that knows them: a member on an older release
cannot parse GRANT or REVOKE CONNECT, and the statement fails naming
it, though the others applied it (see
QUERY_SYNTAX.md). Such a member also
takes a displacement's discard as a plain one: it does not end a
connection live there under the id, and that connection's will goes out
when it ends. Refused CONNECTs are
counted in skaidb_mqtt_connect_refused_total{reason}: client_id (no
grant admits the id to the role, or another role's grant reserves it),
session_owner (another user's session holds it and may keep it),
unavailable (the grants, the session's owner or the subscriptions the
CONNECT routes the id from could not be read, or the session the CONNECT
displaces could not be discarded).
Sessions & QoS
Full QoS 0/1/2 in both directions. Persistent sessions (3.1.1
CleanSession=0, 5.0 Session Expiry Interval > 0) keep their
subscriptions, unacknowledged deliveries and offline queue in
_mqtt.* tables:
- QoS 1/2 publishes to a persistent session are written to
_mqtt.queuebefore the publisher's ack — the ack is the durability promise. QoS 0 to a live subscriber never touches storage. - Resumption replays the backlog in order: unacknowledged legs are retransmitted with DUP=1 under their original packet ids, and the QoS 2 PUBREL leg resumes as PUBREL (recorded durably before it is first sent) — exactly-once holds across reconnects and broker restarts.
- Offline queues are bounded (
mqtt.max_queued_per_session); sessions expire aftermqtt.session_expiry_max_secsoffline (5.0 clients may request less, and a persistent session's DISCONNECT may revise it). After a 5.0 CONNECT with no session expiry, a DISCONNECT carrying one other than 0 is a protocol error (DISCONNECT 0x82, and the will goes out), and one of 0 leaves whatever is stored under the client id as it is. A session its client resumes as its expiry elapses is kept. Each node counts the session's expiry down from its own record of it, and before it discards the session it looks again, one CONNECT under the client id at a time on that node, and reads the session's_mqtt.sessionsrow: a login there that its record does not know is a CONNECT through another node (whose notice it missed), and the session is kept, counted down from the row's times. A CONNECT through the node while it discards the session waits, then starts a new session. A CONNECT through another node can still lose the session in the moment between that CONNECT's decision and its row write (see the stale discard under Clustering); so can one through a node on an older release, which records no login. - A clean start discards the session under its client id: its
subscriptions, its shared-subscription (
$share) memberships and its queue — on every member, including a session made on another node that the clean start's node knows only by its_mqtt.sessionsrow, and a connection still open under the id that stores nothing (no session expiry; CleanSession=1 on 3.1.1), which the clean start takes over: the new connection receives nothing of what that one subscribed to. A delayed will of the session it discards never goes out (see the wills below). A CONNECT without a clean start that finds no stored session to resume starts a new one (Session Present 0); a connection it takes over that stores nothing ends its session there too, its subscriptions with it. - A session belongs to the user that made it, among the users allowed its
client id (see Client ids) — the user, not its name: a user dropped and
created again under the name is another user, whatever its password, and
gets nothing of the dropped one's. A login whose user is dropped, or
dropped and created again, before its session is set up is refused (5.0
0x87, 3.1.1 0x05). Its CONNECT under the dropped user's
client id discards that session — subscriptions, queue, delayed will —
and starts clean (Session Present 0); a connection of the dropped user
still open under the id is ended (5.0 0x8E) and its will does not go
out — but where that connection stores nothing and the session stored
under the id is another user's (one made on another node), the CONNECT
of the user made again there, persistent or not, is refused (5.0 0x85,
3.1.1 0x02) as any CONNECT meeting that user's session is, unless it
displaces it: it ends nothing, and the dropped user's connection stays
until it ends at its next publish, subscribe, ping or delivery; and a
re-authentication (5.0 AUTH) proving the new user on a connection of
the dropped one ends it (0x87). A node whose copy of the
user is older than a session's user — it missed the drop and the
re-creation — refuses that user's CONNECT under the id (5.0 0x85, 3.1.1
0x02) until it catches up. A user created by an older release has no
creation stamp: a login of it records the version of the copy of the
user its password (or certificate, or Kerberos principal) was checked
against, and its sessions are no one's once the user of its name is one
created after that copy, or the name is dropped — on a node that had
missed the drop and the re-creation when the login happened too, once it
catches up. A session recorded with neither — of a configured account,
or stored by an older release — is no one's once the user of its name is
one created more than twice
cluster.max_clock_skew_ms, plus 100 ms, after the session's last login (for a row an older release wrote, its last disconnect); otherwise, and whenevercluster.max_clock_skew_msis 0, it is matched by name. Its next CONNECT records the stamp. The configured superuser's sessions are always its own. A second CONNECT of the same user with the same client id takes the session over and disconnects the first (5.0 reason 0x8E), on whichever node it lives. The node the session leaves writes nothing of it back when the old connection ends — no session row, no offline mark: the session is the new connection's. A CONNECT of another user under that client id is refused (5.0 0x85 Client Identifier not valid, 3.1.1 0x02 identifier rejected): it does not resume the session, wipe it with a clean start or end its connection — unless the session's owner may no longer use the id and a grant gives it to the newcomer, which then displaces the session (see Client ids). A CONNECT whose session's owner cannot be read — its_mqtt.sessionsrow is unreachable atmqtt.state_consistency, as while a cluster cannot make a quorum (see CLUSTER_OPERATIONS.md) — is decided by the node's own record of the session when that record names the connecting user and the session has not expired by it. A node records a session made or resumed through it, every session stored when it started, and one whose row it has read since. Such a CONNECT goes on there as at any time: it resumes the session, or takes its own connection still open there over. Anything else is refused as server unavailable (0x88 / 0x03): a clean start, whose discard of the session needs the quorum too; a session the node's record says is another user's (another user of the same name included), or past its expiry — the expiry discards it once the row can be read; one the node knows only from another node's notices (made through another node since this one started, its row never read here); and a client id the node records nothing under — a new one, or one whose connections store nothing (no persistence), its own connection still open there included; and so is such a CONNECT whose session's subscriptions the node must route the client id from and cannot read either (what the node routes under the id was made for another session too, below). The record can lag behind another node's discard, takeover or displacement of the session, which the unread row would have shown: such a CONNECT follows the record. While the broker serves without its stored state, such a CONNECT is refused too when the node knows of a session under the id only from another node's notices (its owner unknown there); with nothing of a session under the id on the node, it starts a new session, and what the tables hold under the id is superseded when the stored state merges in. When the node already knows the session's rows cannot reach their quorum — too few of their replicas are left once the nodes that have failed repeatedly and not answered since are set aside (their circuits open; the breaker's re-test brings each back as soon as it answers) — the CONNECT waits on none of them: the session row is not read (the CONNECT is decided as above), it is written on this node only (the others get it by hinted handoff, as a write that missed its level), and its subscriptions are not read (as when they cannot be). A resume through the node holding its record then answers in milliseconds. The first CONNECTs after nodes stop answering (before they have failed repeatedly) still wait for those statements to fail: 20 to 30 seconds. - What is stored under a client id — subscriptions, queue, inbound QoS 2
ids, a delayed will — is the session of the user its
_mqtt.sessionsrow names, and a CONNECT decides it by that row, not by what the node it reaches holds: the node's own record of the session can lag behind another node's discard, takeover or displacement of it (the notices between nodes are dropped when a link is full), and a connection live on the node that stores nothing (no persistence) answers for itself alone. The CONNECT reads the row once, atmqtt.state_consistency: always, unless a connection live on the node that stores something answers for the id and the CONNECT leaves what is stored as it is (that connection's owner refuses it, or it is the same user's with no persistence and no clean start). A session the row says is another user's is met as that user's: the CONNECT is refused unless it displaces it (see Client ids) or that user is no one's now, whatever the connection live on the node (one of another user of that user's name included), and resumes, wipes or writes its own row over nothing of it. Refused, it leaves a connection live on the node as it was — its record of the session, its routing. The user the row names meets the session as its own: where the node holds a record of it naming another user, that record and what the node routes under the id are made again from the row and the session's subscriptions — that user's queue, inbound QoS 2 ids and subscriptions, none of another user's — and the session is resumed; a record of that user takes the row's inbound QoS 2 ids when the row shows the session was used through another node since (a login the record does not know), as does a record of no user known there (another node's notices made it), and one that a subscription's notice alone made takes the row's expiry and disconnect time too. Subscriptions that cannot be read refuse such a CONNECT as server unavailable (0x88 / 0x03) before anything is done. A connection live on the node that stores something answers for what it stores until the CONNECT acts on it — its record and routing stay its own until the CONNECT ends it or takes it over — and with no row too (its subscriptions and queue are under the id whether its row was written or not): ended, they are discarded with it on every node; taken over by its user, they are resumed. Otherwise, with no row there is nothing stored to resume: the node's record of the id goes, and the CONNECT starts a new session (Session Present 0) — a row that cannot be read is not missing, and leaves the record as it is (above). While the broker serves without its stored state, its record of a session made since answers for it (the row is behind it). - A connection that stores nothing (CleanSession=1 on 3.1.1, no session expiry on 5.0) is sent only what its own subscriptions route, and its end removes only those, never a newer connection's under the client id: a client that reconnects the moment its connection drops keeps what it subscribes to on the new connection, and a session a CONNECT resumes over such a connection, ending it, keeps its subscriptions. On the node the connection ends on, its end and a CONNECT under the client id take turns: the CONNECT waits for an end that came first, and an end that came after a CONNECT waits for it and is taken over by it — a delayed will of that connection then never goes out (see the wills below). A stored session under its client id keeps its subscriptions apart from the connection's: what they route is queued for the session, as for any offline session, and never sent on that connection — the connection's own user's session, which a 5.0 CONNECT with no clean start and no session expiry leaves as it is (Session Present 0), and another user's session made under the id on another node (see Clustering). A connection that takes a client id over from a connection that stores nothing gets nothing of what that connection subscribed: those subscriptions route to no one, and go when it ends. A 5.0 CONNECT with no clean start and no session expiry that takes over its user's live persistent connection leaves that session stored and offline from the takeover: it counts down to its expiry, and what its subscriptions route meanwhile is queued for it.
- An operator frees a client id another user holds by connecting under it
as the superuser with a clean start and no session expiry
(CleanSession=1 on 3.1.1; on 5.0 a clean start with Session Expiry 0 —
with an expiry, the superuser's own session then holds the id): the
session's subscriptions and queue are wiped and a live connection under
it is ended — a session made on another node too, one this node knows
only by its
_mqtt.sessionsrow included. A node that cannot read the session's row refuses the release as server unavailable (above): the wipe needs the quorum. The superuser never resumes another user's session: its CONNECT without a clean start is refused like any other user's while the session's owner may keep the id, and displaces the session (discarded, never resumed — see Client ids) once the owner may no longer use it. With authentication off every client is the superuser, so nothing of this applies.
Retained messages are cached in memory and persisted write-behind
(~100 ms batches) to _mqtt.retained — a crash may lose the last
≤100 ms of retained churn, matching ecosystem practice. Wills fire on
every abnormal disconnect and after a 5.0 DISCONNECT with reason 0x04
(Disconnect with Will Message), as after a dropped connection — never
after any other DISCONNECT — except a displaced connection's (see Client
ids) and a dropped user's (dropped, or dropped and created again under its
name, when it would go out), honor the 5.0 Will Delay Interval, cancel on
reconnect, and survive broker restarts. A will is checked when it goes
out: its topic grants then, and its user not dropped.
A delayed will goes out when its delay passes or its session ends, whichever comes first (MQTT 5 §3.1.3.2.2) — unless a new connection under the client id comes first: any CONNECT accepted under the id cancels it [MQTT-3.1.2-8], on whichever node the will waits, as Mosquitto 2.0 does — one that resumes the session within the delay, a clean start, which discards the session (§3.1.2.4), and a 5.0 CONNECT with no session expiry over the stored session, which resumes nothing. A cancelled will stays cancelled when the node it waited on restarts inside the delay: the CONNECT leaves none in the session's row — a resume writes the row anew, a clean start deletes it, and a CONNECT that resumes nothing clears the will from it, whichever node the will waits on (on a cluster, but for two cases named below). A device that reconnects with a clean start inside its will's delay is not announced gone — the moment its old connection drops included: on the node that connection ends on, the new CONNECT waits for that end, and cancels the will it arms.
A connection still open under a client id (half-open, say) that a newer connection under the id takes over, on any node, sends a will without a delay at the takeover, with a clean start or without, whatever either session stores: its network connection closed ([MQTT-3.1.2-8]; the takeover note of MQTT 5 §3.1.4). It never sends a delayed will: the newer connection came within its delay [MQTT-3.1.2-8]. (Mosquitto 2.0 sends no will at a takeover that resumes the session, for 3.1.1 too, whose [MQTT-3.1.2-8] publishes the will whenever the network connection closes without a DISCONNECT.) A device whose reconnect over its own half-open connection should not announce it gone sets a Will Delay Interval.
On a cluster a delayed will waits on the node its connection ended on,
which sends it when its delay ends; a node that expires the session first
sends it instead (below). Either way it goes out at most once: it is kept
in the session's row, and a node takes it out of the row before it sends
it — of the nodes that try at once, one does, and the others send
nothing. A node takes out only the will it holds or read, by its exact
text: a newer will in its place — the device came back and dropped
again on another node — is that node's, and stays. A CONNECT under the
client id on any node cancels it — through the notices of that CONNECT,
which the nodes drop when a link is full, and through the session's row,
which a resume, a clean start and a CONNECT that resumes nothing each
leave without the will: its node, whose notices were dropped, finds its
will no longer in the row at its delay's end and sends nothing. A will
whose CONNECT's notices reach its node in the few milliseconds the old
connection's end there takes to arm it still goes out at its delay's
end. A will that goes out while its connection's end is still writing it
into the row is taken out of the row again once that write lands. A row
that cannot be written (the cluster cannot make a quorum) sends the will
all the same, and the row is cleared of that will alone after it: a will
is sent twice rather than lost. It is kept in
the session's _mqtt.sessions row with the node's name and the id of the
node's data directory (which the directory keeps, in mqtt_dir_id; a
backup never carries it, so a directory restored from one makes an id of
its own, and a node restored from it on its own host arms its wills again
by its name; a copy made by other means, a clone or an rsync, carries it:
see Backups on a cluster),
and the node that starts over that row arms it again: under that
name, or over that data directory, whatever name it starts under — a
standalone server's directory started as a cluster member included. No
other node does. While the node is down, a will waiting on it waits in
its row, and goes out once the node is back — unless a CONNECT under the
client id comes first, which leaves no will in the row, or the other
nodes expire the session meanwhile: the first of them to expire it sends
the will from its row, then discards the session. Such a will has lost
the time it waited past its delay's end, as one armed again from its row
has (below). A will whose delay is at least its session's expiry is due
when the session expires instead: every node counts the expiry down, and
the first to get there — the node the will waits on, or another — sends
it, once. A node expiring a session whose row it cannot read or write
discards nothing, and tries again a second later.
A will an older release armed names no node: every node that starts over
its row arms it again, and the first of them to take it out of the row
at its delay's end sends it; a clean start cancels it on each.
On a cluster a will a CONNECT cancelled can stay in the session's row in three cases, for the node it waits on to arm again if it restarts inside the delay. A CONNECT under the client id made through another node in the milliseconds the old connection's end takes to write the will into the row — a resume, a clean start, or one that resumes nothing — comes before that write, which then lands over what the CONNECT did with the row; the will is cancelled on its node all the same, and that node takes it out of the row again once the write lands, unless the CONNECT's notices reach it only after that. And a node serving without its stored state (see Clustering): a will waiting on it goes back into the row when that state merges in, with the rest of what it kept of the session meanwhile, whatever a CONNECT on another node did; a CONNECT that resumes nothing made on it clears a will waiting on another node only when it reads the session's row, which it does not once a CONNECT there since its start has told it whose the session is. And a CONNECT that resumes nothing through a node that cannot read the session's row — the cluster cannot make a quorum, and the node's own record of the session answers for it (see Sessions & QoS) — has read no row, and clears no will from it.
A will that goes out at a takeover on a cluster — one without a delay — is sent by the node that held the old connection once the takeover's notices reach it, after the newer connection's CONNACK: it can reach subscribers after the device's first publish on its new connection, so a retained status topic can read "offline" with the device connected, on some nodes or all, until the topic's next publish. A Will Delay Interval avoids it: a delayed will never goes out at a takeover.
A will's PUBLISH carries the will's message properties and nothing else:
Payload Format Indicator, Message Expiry Interval, Content Type,
Response Topic, Correlation Data and User Properties. The Will Delay
Interval is the broker's to act on and never goes out — a PUBLISH may not
carry it, and a strict 5.0 client drops its connection over one that
does. The will's Message Expiry Interval is its lifetime from when it
goes out, as a client's PUBLISH's is from when it arrives, however late
the broker sends it (a burst of wills at once included). Only a will that
waited in its session row past its delay's end — armed again after a
restart, or once the broker can read its stored state again — has lost
that wait: it carries what is left of its lifetime, and one whose whole
lifetime ran out there is delivered to no one (counted once as
skaidb_mqtt_messages_dropped_total{reason="expired"}). A will's
topic-to-table capture runs before its lifetime is looked at, as a
client's PUBLISH's does: such a will, and one with a Message Expiry
Interval of 0 (delivered to no one, as a PUBLISH with one is), are still
captured.
MQTT 5.0 specifics
Server capabilities are advertised in CONNACK (Receive Maximum, Topic
Alias Maximum 64, Maximum Packet Size, Assigned Client Identifier, capped
Session Expiry). Message Expiry is honored end-to-end (queued copies
expire in place; deliveries carry the remaining interval, in whole
seconds rounded up — a message delivered within a second of its
publication carries its whole interval; retained messages expire).
Subscription options (No Local, Retain As Published, Retain Handling),
subscription identifiers, inbound topic aliases, request/response and
user-property pass-through, and shared subscriptions
($share/{group}/{filter}, round-robin preferring live members) are all
supported. Egress honors the client's Maximum Packet Size by dropping,
never truncating. A delivery carries the message's own properties —
Payload Format Indicator, Message Expiry Interval (what is left of it),
Content Type, Response Topic, Correlation Data, User Properties — and the
subscription's identifiers, nothing else: a property a publisher sent
that a PUBLISH to a subscriber may not carry (a Session Expiry Interval,
a Will Delay Interval, its own Topic Alias or Subscription Identifier)
is not passed on, live, queued or retained.
Clustering
Enable [mqtt] on every member; clients may connect to any node.
Publishes fan out to peers over the internode transport and each node
delivers to its own connected clients; sessions resume on any node
(replicated state). QoS 1/2 to a subscriber on another node — or on a
node that has died — rides _mqtt.queue, so acknowledged messages are
never lost to a node failure. Cluster notes:
- Shared-subscription round-robin is cluster-approximate (the origin node picks the member); members that must receive across nodes should use persistent sessions.
$SYStopics are per-node.mqtt.acl_defaultis per-member configuration, not replicated: set the same value on every member (see Topic ACLs).- Users replicate like every catalog change, and each member decides who owns a session by its own copy of the user: one that has not applied a drop, or a re-creation, yet ends nothing of the dropped user's until it has (a node's CONNECT of the user made again still discards the dropped user's stored session on every member, and ends its connections). A session records which copy of the user its login was checked against, so a login on such a member — the dropped user's, with its password — is the dropped user's on every member, and no one's wherever the user made again is known, that member included once it catches up. A member on an older release records neither a creation stamp nor a copy with the sessions it makes and sends none to its peers: such a session is matched by its login time, else by name, until its next CONNECT on an upgraded member. Such a member also decides its own CONNECTs by what it holds, as that release does: through it, a connection there that stores nothing, or its record of a session that missed another node's notice, can still hand a user another user's stored session, or wipe it. An upgraded member decides by the session's row whatever such a member's notices left in its own record — a takeover that names no user, a subscription of a session it knows no user of.
- A member that missed a user's drop and then takes the user created
again under the name takes the new user's grants — its topic grants
included — and the memberships in it that roles hold on the other
members right after the new user reaches it: it asks every other member
at once, and takes them from each one holding the new user as soon as
its answer arrives. A copy of a role whose name, or a membership in it,
is a different user on the two members (another user of that name, also
dropped and created again while that member missed it), that holds a
membership in a role that member lacks, that reaches through its
memberships a role whose copy differs on the two members (one still
holding there another user that member missed the drop of), or that a
role there reaches while it does not reach it on the other member (one
that member missed a
REVOKE ROLEof), and the drop of a role that a role there still holds, come with its next schema sync instead, as does everything when no member holding the new user answers within the internode I/O bound, and a member on an older release waits for that too: until then the new user, and a role left without topic grants, has none there, which underacl_default = "open"is every topic (see Topic ACLs, and QUERY_SYNTAX.md). - Client-id grants replicate like every grant, and each member decides by its own copy of them: the CONNECTs it accepts, the connections it holds, and whether a peer's CONNECT displaced a session connected here. A member that has not applied a grant change yet decides by the grants it holds: it can accept a CONNECT the others would refuse, or let a user that may no longer use an id displace another user's session that still may — two users allowed one id, with the change in flight. A displacement that discards a stored session ends its connection on every member, its will not sent there either (the discard reaches them, as below, and says it displaced); that of a session storing nothing (no persistence) ends it on a member once that member's grants say the newcomer displaced it — on a member that has not applied the grant change yet the connection stays up until then, or until its own next check ends it, and then its will goes out as for any connection ended over its id.
- Two users can hold one client id on two nodes: a connection that
stores nothing (no persistence) live on one, and another user's
persistent session made under the id on another node, where the id was
free. Each is sent only what its own subscriptions route: a node holds
the stored session's subscriptions — made by its CONNECTs there, its
state load, or the other nodes' notices — apart from those of a
connection live there that stores nothing. A publish through any node
that matches the stored session's subscriptions is queued for it, and
delivered at its resume or on the node it is live on; it is never sent
on the other user's connection, whose acknowledgement — or, with its
grants refusing the topic, whose refusal — would delete it from the
session's queue. A shared subscription (
$share) counts each session's membership as a member of its own: the stored session's, behind such a connection, is an offline member, and a message the group picks it for is queued for it. A SUBSCRIBE of that connection to a filter the stored session holds makes a subscription of its own (under Retain Handling 1 the retained messages go out to it), and its UNSUBSCRIBE and its end remove only its own. That connection's own user's next CONNECT under the id meets the stored session as the other user's, on the node where the connection is live too (the session's row decides, see Sessions & QoS): it resumes, wipes or writes its row over nothing of it, and is refused unless it displaces it. A node on an older release routes by the client id alone: there the other user's connection is sent the stored session's messages, until the node is upgraded. _mqtt.*tables default towitness = false(transient operational state; witnesses skip them). They are ordinary replicated tables otherwise, soBACKUP TO/BACKUP CLUSTER TOinclude them — retained messages, persistent sessions, subscriptions and offline queues restore with the rest of the node.- Cross-node QoS 2 degrades to effectively-once at the internode hop (documented, per the RFC; the queue-row dedup makes duplicates rare).
- The node a session is connected to decides what is stored for it: a
peer's late offline notice for a session connected here is ignored,
and a connection whose session another node took over or discarded
leaves the stored state to that node when it ends — so does one whose
node never heard of it (the notices between nodes are dropped when a
link is full) once the session's row names another user: nothing is
written back over it or discarded, and the connection's will goes as at
a takeover. A CONNECT through a node that missed such a notice decides
what is stored under the client id by its row, too (see Sessions &
QoS). A peer's discard of
what is stored under a client id (a clean start, a release, an expiry or
a displacement made there) ends a connection live here under it (5.0
0x8E Session taken over): it would receive nothing more here, and its
client reconnects — to resume nothing, or to be refused, as the grants
say. Its will goes out as at a takeover, as the same release or clean
start made here sends it — one without a delay, a delayed one never —
unless the discard was a displacement; a delayed will of the session
waiting here is cancelled. A member on an older release arms every will
in the
_mqtt.sessionsrows again when it starts, as that release does: a will waiting on another member then goes out from both at its delay's end. Such a member sends the will of a connection live there at once at a peer's discard of its session, delayed or not, as that release does: a clean start on an upgraded node over a device's half-open connection on an older one announces the device gone, when the clean start's node holds the session's bookkeeping (the device subscribed, or its session went offline before: every node then tracks it). A clean start of a session its node knows only by its row (a publish-only device's, never offline) sends an older member no discard it reads: that member takes the connection over on the CONNECT's notice, as that release does, and sends no delayed will. A 5.0 CONNECT with no session expiry and no clean start over the stored session, made on a node on an older release, leaves the delayed will in the session's row, as that release does: a will waiting on that node goes out at its delay's end, and the node another waits on arms it again if it restarts inside the delay. A node whose record of a session missed its resumption through another node reads the row before its expiry discards the session, and keeps it (see Sessions & QoS); one on an older release does not. When only a stale discard reaches a connected session (a node expiring the session under the client id in the moment between this CONNECT's decision and its row write, or an older one's), its row stays as its CONNECT wrote it, with no node counting down its expiry, until the same user's next CONNECT (the client's reconnect), the operator's release of the id, or a member's restart. - A member's MQTT listeners open when the member starts, whether or
not the broker state is reachable yet. At start the broker creates
the
_mqttschema (a quorum DDL) and reads its state tables. When that succeeds the state is loaded before the first client is accepted. On the first member of a cluster to boot — a cold start of the whole cluster, or a restart while the others are down — neither can succeed (DDL quorum not met: 1/2 members applied,read quorum not met); the broker then serves without its stored state and merges it in as soon as it is readable. It logsmqtt: broker state is not available yet (…) — accepting connections without it; stored retained messages and sessions are merged in as soon as the cluster can serve them, retries every 250 ms backing off to 5 s (the cause is logged again once a minute), and on success logsmqtt: broker state available after N attemptsandmqtt: broker state merged — …. Meanwhile devices connect, publish and subscribe as usual; what they do not get until the merge is what only the tables hold — retained messages stored before the restart, a resumed session (session presentis 0 and the client starts a new one), queued offline messages. Nothing is lost or brought back by the merge: - a retained message stored before the restart and untouched since is served again from the merge on;
- one cleared meanwhile stays cleared (the clear is held and deletes the stored row), one replaced keeps the new payload, a new one is written — retained changes are held in memory until the merge and flushed right after it (a stored row written by another member AFTER the local change wins over it);
- a stored session whose client did not connect meanwhile is loaded and its subscriptions route into its queue again;
- a client that started a new session meanwhile supersedes its stored namesake: the old session row, its subscriptions and its older queue rows are deleted, and the session and subscriptions it has now are written (with a delayed will armed here meanwhile: one a CONNECT through another node cancelled since goes back into the session's row, see Sessions & QoS).
A retained change whose table write fails later (the cluster briefly without a write quorum) is kept and retried after a second rather than dropped. SQL and REST on the member are unaffected by any of this.
Topic → table capture (the sink)
Config-driven rules capture matching publishes into tables — many topics to one table, with wildcard captures as column/label values:
[[mqtt.sink]]
filter = "home/+/+/state" # + captures: room, device
table = "iot.sensor_state"
mode = "row" # JSON payload fields → columns
topic_columns = ["room", "device"]
[[mqtt.sink]]
filter = "zigbee2mqtt/+/SENSOR"
table = "iot.metrics"
mode = "timeseries" # numeric JSON leaves → samples
series = ["device"] # capture label names
row mode inserts one row per message: JSON object fields become columns
(non-JSON payloads land in a payload bytes column), plus the captures,
topic, and ts. timeseries mode flattens numeric JSON leaves into
the remote_write fast path (each leaf a series named by its dotted path,
string fields and captures as labels), auto-creating the TS table — MQTT
telemetry becomes PromQL-queryable with zero glue services (see
TIMESERIES.md / GRAFANA.md).
The sink enforces the publishing user's Insert privilege on the
target table and the read-only gate, exactly like remote_write. With
ack_on_sink = true the publisher's ack is gated on the table write (5.0
answers 0x97 on failure — a durable ingest API). Out-of-order-window TS
drops are counted (skaidb_mqtt_sink_dropped_total{reason="ooo"}), not
fatal. Sink rules are runtime-mutable.
$SYS topics
A Mosquitto-compatible subset is published every 10 s per node
(mqtt.sys_topics_enabled, default on): version, uptime,
clients connected/total, messages received/sent, subscription and
retained counts. $SYS values are retained in cache only and are never
matched by a plain # subscription (per spec). A role holding SUBSCRIBE
grants needs one that names the tree ('$SYS/#') — a # grant does not
reach it — or SUBSCRIBE ON *; a role with none is decided by
mqtt.acl_default.
The $ tree is broker-owned, whatever a client's ACL allows and
including a superuser: a PUBLISH from a client to any $-prefixed topic
is refused and the connection dropped; a CONNECT carrying a will on one
is refused (3.1.1 0x05, 5.0 0x90 Topic Name invalid), and a stored will
on one never goes out; PUBLISH from SQL refuses one too. So nothing can
pin attacker-chosen values into the retained cache and feed them to
whatever monitors $SYS or reads $stream. The stats publisher above
and the $stream tail write through an internal path that never passes
these checks.
Operational notes
- MQTT connections appear in the
driversconnections registry (endpointmqtt) and the UI. - Metrics:
skaidb_connections_{total,active}{endpoint="mqtt"},skaidb_mqtt_packets_total{type,dir},skaidb_mqtt_connect_total{outcome},skaidb_mqtt_connect_refused_total{reason},skaidb_mqtt_sessions_displaced_total,skaidb_mqtt_sessions_superseded_total{cause},skaidb_mqtt_messages_dropped_total{reason},skaidb_mqtt_sink_*,skaidb_mqtt_acl_closed— seeMETRICS.md. - Broker-state writes use
mqtt.state_consistency(defaultquorum). - Admission. A publish's topic→table capture runs as a client
statement in the workload manager's client lane (the same shedding
and admission tiers as a driver write, never the protected or the
background lane): under memory or disk pressure the sink insert is
refused like any client write and a QoS 1/2 publisher gets PUBACK
reason
QUOTA_EXCEEDED(MQTT 5) so it retries later, while the broker's own routing still delivers the message; a QoS 0 publish is delivered and its capture dropped, counted inskaidb_mqtt_sink_*. A device flood therefore degrades like any client flood and cannot starve compaction, hints or the control plane. - Graceful shutdown DISCONNECTs clients (5.0 reason 0x8B) and flushes dirty broker state; wills are not published on server shutdown.
- Idle parking (epoll). A connection is served by a reader thread
and a writer thread while it is talking; once it has been quiet for
mqtt.idle_park_secs(default 2), its socket moves to the broker's epoll reactor and both threads exit. The reactor resumes it on the next byte (a ping, a publish) on a fresh thread — the same loop, same session — and closes it at its keep-alive deadline if nothing arrives; the writer is respawned by the next message queued for it. Ten thousand idle devices therefore cost ten thousand registered descriptors, not threads; active connections keep the thread-per-connection path with its blocking, simple code.idle_park_secs = 0disables parking; on Windows there is no epoll reactor and every connection keeps its thread pair. Counters:skaidb_mqtt_parked_readers(gauge),skaidb_mqtt_parks_total{side},skaidb_mqtt_wakes_total{side}. - Every limit is enforced from the first byte (max packet size checked before a body is buffered; bounded outboxes, queues, retained store, topic shape, subscriptions per session).
- Packet size:
mqtt.max_packet_bytes(default 1 MiB) bounds a control packet's Remaining Length — for a PUBLISH that is the payload plus the topic name and a few header bytes — identically on every transport (TCP, TLS, WebSocket) and at every QoS, retained messages included. A packet over the limit ends the connection: a 5.0 client receives DISCONNECT with reason 0x95 (Packet too large), a 3.1.1 client is closed. The broker reads and drops the oversized body first (for up to 5 s) so the client gets the reason rather than a connection reset, logs one line naming the client and the size, and counts it inskaidb_mqtt_messages_dropped_total{reason="too_large"}. A transport error that drops a client (a TLS record the session refuses, say) is logged as well. - Deliberate deferrals: MQTT-SN/QUIC, MQTT 5 across bridges (retain-as-published).
Home Assistant quick start
Point the HA mqtt integration (or zigbee2mqtt's mqtt.server) at
mqtt://<node>:1883 with a database user's credentials. Discovery,
retained state, availability (LWT), and QoS 0/1/2 work out of the box;
after a broker restart HA re-reads its retained discovery topics from
skaidb's replicated store.