MQTT

MQTT Overview

RESTHeart

Preview

The restheart-mqtt module bridges an external MQTT broker into RESTHeart: incoming topic messages become Server-Sent Events, REST responses, MongoDB documents, or input to your own plugins.

It connects to any MQTT 3.1.1 or 5.0 broker — Mosquitto, HiveMQ, EMQX — using hivemq-mqtt-client 1.4.1, and exposes what it receives through ordinary RESTHeart plugins.

From MQTT topics to REST, SSE, MongoDB and your own plugins
Note
Brokers that require mutual TLS with a client certificate — AWS IoT Core among them — are not supported. The module exposes only trust-store settings (tls, tls-trust-store, tls-trust-store-password), never a key store or a client certificate.

The module is not bundled with RESTHeart: you add it to an instance. Quick start runs it in a couple of minutes, Installing puts it into your own instance, and Not bundled says why it is separate.

Quick start

You need Docker and nothing else. The module’s archive carries the plugin together with a two-container demo — RESTHeart and a Mosquitto broker, no MongoDB — where the module is already enabled and an ACL is in place. There is nothing to build and nothing to configure:

curl -LO https://github.com/SoftInstigate/restheart/releases/latest/download/restheart-mqtt.zip
unzip restheart-mqtt.zip
cd restheart-mqtt
docker compose up

That is the module of the latest RESTHeart release, and the demo runs it on softinstigate/restheart:latest, the same release. The module is part of RESTHeart releases from 9.17.1.

Wait for RESTHeart started, and find this line a little above it:

mqtt module active: mqtt-client, mqtt-router, mqtt-sse, mqtt-topic-authorizer, mqtt-connector; inactive: mqtt-rest, mqtt-mongo-writer

In a second shell, open a stream. Nothing is printed yet: it is waiting for a message.

curl -N -u admin:secret 'http://localhost:8080/mqtt-sse?topic=sensors/temp'

In a third shell, from the same directory, publish one:

docker compose exec mosquitto mosquitto_pub -t sensors/temp -m '{"value": 21.5}'

The second shell prints it:

id:sensors/temp-1794844590179-0
event:mqtt-message
data:{"value": 21.5}

docker compose down stops it. The demo binds host ports 8080 and 1883. Its whole configuration is the RHO block of docker-compose.yml, in the directory you unpacked: a working example to start from.

The demo brings its own broker and has no database. To connect the module to the broker and the MongoDB you already have, see Your own broker and Your own MongoDB.

The MQTT Tutorial continues from here: the topic ACL, REST polling, and MongoDB persistence with docker-compose-mongodb.yml, which is in the archive too.

Installing

To add the module to your own RESTHeart, download the archive of the same release as your RESTHeart and unpack it into the instance’s plugins directory:

curl -LO https://github.com/SoftInstigate/restheart/releases/latest/download/restheart-mqtt.zip
unzip restheart-mqtt.zip -d /opt/restheart/plugins/

That address is the latest release. For another one, put its version in place of latest/download: https://github.com/SoftInstigate/restheart/releases/download/9.17.1/restheart-mqtt.zip.

With the Docker image, unpack it anywhere and mount the directory as a subdirectory of the image’s plugins directory:

docker run -p 8080:8080 \
  -v "$PWD/restheart-mqtt:/opt/restheart/plugins/restheart-mqtt:ro" \
  softinstigate/restheart

Either way you get:

plugins/restheart-mqtt/
├── restheart-mqtt.jar
├── lib/                              hivemq-mqtt-client and its 13 transitives
├── restheart-mqtt-default-config.yml the sample configuration, every key commented
├── docker-compose.yml                the demo of "Quick start"
├── docker-compose-mongodb.yml        the same demo with MongoDB
├── mosquitto.conf                    the demo broker's configuration
├── LICENSE.txt
└── COMM-LICENSE.txt

The module’s own directory is deliberate, not an accident of packaging. PluginsScanner scans the plugins directory two levels deep and treats any lib path segment as classpath-only, never scanning it for plugins, so both the jar and its dependencies are picked up from there. Keeping lib/ inside the module’s own directory rather than merging it into the shared plugins/lib is what stops this module’s Netty and RxJava from mixing with other plugins' dependencies.

Configuring

Installed, the module is dormant: nothing connects and no endpoint exists until you enable it. RESTHeart takes configuration as overrides of its defaults, in a file passed with -o or in the RHO environment variable — see RESTHeart Configuration.

An override file. This one connects to a broker and streams sensors/# to users with the admin role:

/mqtt-client:
  enabled: true
  broker-url: "tcp://localhost:1883"

/mqtt-router:
  enabled: true

/mqtt-sse:
  enabled: true
  default-topic: "sensors/#"

/mqtt-topic-authorizer:
  acl:
    admin:
      - "sensors/#"
java -jar restheart.jar -o mqtt.yml

Two rules, and breaking either leaves the module off without an error:

  • Every key starts with a slash. In an override file a key is an absolute path into the configuration: /mqtt-client:, not mqtt-client:. For a key without the slash RESTHeart logs invalid override, path must be absolute at WARN and carries on without it.

  • One block per plugin. A block replaces that plugin’s whole configuration, so a second /mqtt-sse: block further down does not add to the first. To change a single key, use its full path instead: /mqtt-sse/default-topic: "sensors/#".

Every YAML example in these pages is written in this form and can go into an override file as it is. restheart-mqtt-default-config.yml, in the archive, is a complete override file with every key and its meaning.

RHO, the usual way with Docker, takes the same paths as path->value pairs separated by semicolons:

RHO='/mqtt-client/enabled->true;/mqtt-client/broker-url->"tcp://broker:1883";/mqtt-router/enabled->true;/mqtt-sse/enabled->true;/mqtt-topic-authorizer/acl->{"admin":["sensors/#"]}'

The docker-compose.yml of the archive is a complete example of it.

Then check the log. At startup mqtt-status prints one line saying what is active, or a warning for each thing that is configured but not running — see The traps. And the endpoints need an authenticated user: /mqtt-sse and /mqtt answer 401 without one. When RESTHeart runs with --standalone, its built-in admin user is disabled until it has a password, which is one more override: /fileRealmAuthenticator/users[userid='admin']/password: secret.

See Enablement for what each plugin’s switch does, and Configuration for every key.

Your own broker

The demo of the Quick start brings its own Mosquitto. To use the broker you already have, point mqtt-client at it. Nothing else in the module knows where the broker is:

/mqtt-client:
  enabled: true
  broker-url: "tcp://broker.example.com:1883"
  username: "iot"            # leave both out if the broker takes anonymous clients
  password: "s3cret"
  protocol-version: 5        # 3, the default, is MQTT 3.1.1
  • TLS: use the ssl:// scheme, for example ssl://broker.example.com:8883. For a certificate your JVM does not already trust, add tls-trust-store and tls-trust-store-password. A broker that requires a client certificate is not supported.

  • From a container, localhost is the container itself, not your machine. For a broker running on the Docker host use tcp://host.docker.internal:1883; on Linux also start the container with --add-host=host.docker.internal:host-gateway.

  • Check the log: Connected to MQTT broker tcp://…​ means it worked. Cannot connect to MQTT broker means the URL, the credentials or the network are wrong; RESTHeart keeps running and retries by itself.

The topics come from what you enable next: default-topic and the ?topic= parameter for mqtt-sse, subscriptions for mqtt-router, mongo-sink for the writer, and the acl that grants them. mqtt-client lists every connection key.

Your own MongoDB

Only mqtt-mongo-writer uses MongoDB, and it has no connection of its own: it writes through the one RESTHeart already has, the mclient connection.

  • If your RESTHeart already serves your MongoDB, there is nothing to connect. Enable the writer and say where each topic goes.

  • Otherwise give RESTHeart the connection string of your database, and do not start it with --standalone, which runs it without MongoDB.

/mclient/connection-string: "mongodb://user:password@db.example.com:27017"

/mqtt-mongo-writer:
  enabled: true
  mongo-sink:
    - topic: "sensors/#"
      database: "iot"
      collection: "sensor-events"

Each message on sensors/# becomes a document of iot.sensor-events. The database and the collection are created on the first write, and the writer touches no other collection, apart from mqtt-dead-letter in the same database for the documents MongoDB refuses. mqtt-mongo-writer describes the stored document and how to avoid duplicates with id-strategy.

Reading the stored messages through the REST API. RESTHeart serves one database by default, its own restheart, so GET /iot/sensor-events answers 404 until iot is mounted too. Mounting it, rather than writing the messages into restheart, keeps the device data apart from RESTHeart’s users and permissions:

/mongo/mongo-mounts:
  - what: /restheart
    where: /
  - what: /iot
    where: /iot

The list replaces the default one, which is why its first entry is repeated here. Then:

curl -u admin:secret 'http://localhost:8080/iot/sensor-events'

The collection is now an ordinary RESTHeart resource, with filters, paging and aggregations — see Read Documents — and the usual permissions decide who reads it. They also decide who writes to it: admin can, so give the clients that only consume the data a role that can only read.

Two things to know on a database RESTHeart has never used:

  • RESTHeart keeps its users and permissions in a database of its own, restheart, and creates there a user admin with password secret. Change that password.

  • From a container the same rule applies as for the broker: a MongoDB on the Docker host is mongodb://host.docker.internal:27017.

Both together, with the Docker image, the broker and the database being on the Docker host:

docker run -p 8080:8080 \
  -v "$PWD/restheart-mqtt:/opt/restheart/plugins/restheart-mqtt:ro" \
  -e RHO='/http-listener/host->"0.0.0.0";/mclient/connection-string->"mongodb://host.docker.internal:27017";/mqtt-client/enabled->true;/mqtt-client/broker-url->"tcp://host.docker.internal:1883";/mqtt-client/username->"iot";/mqtt-client/password->"s3cret";/mqtt-router/enabled->true;/mqtt-sse/enabled->true;/mqtt-mongo-writer/enabled->true;/mqtt-mongo-writer/mongo-sink->[{"topic":"sensors/#","database":"iot","collection":"sensor-events"}];/mqtt-topic-authorizer/acl->{"admin":["sensors/#"]}' \
  softinstigate/restheart

Which archive

Every RESTHeart release from 9.17.1 carries the module’s archive, restheart-mqtt.zip and restheart-mqtt.tar.gz, on its GitHub release, next to restheart.zip. The release workflow attaches it only after the module’s integration tests have passed against the core of that release. The name has no version in it, like restheart.zip: the release it belongs to gives the version.

To try what is on master before it is released, there is a snapshot build under the mqtt-snapshot pre-release. The module’s GitHub Actions workflow refreshes it on every push to master, under the same condition, and the notes of the pre-release record the commit it came from. It belongs in a RESTHeart built from master, which softinstigate/restheart-snapshot:latest is as a Docker image:

curl -LO https://github.com/SoftInstigate/restheart/releases/download/mqtt-snapshot/restheart-mqtt.zip
unzip restheart-mqtt.zip
cd restheart-mqtt
RESTHEART_IMAGE=softinstigate/restheart-snapshot:latest docker compose up

To build it yourself, see Building in the module’s README.

Install it into the RESTHeart of the same release. Each archive has only been tested against the core built alongside it. There is also a specific security reason never to put it into an older one. Per-topic authorization on /mqtt-sse needs RESTHeart to run the SSE handshake through WildcardInterceptor`s (`SseWildcardInterceptorsExecutor), and RESTHeart has that from 9.9.0: 9.8.x and every earlier version lack it.

Warning
On a RESTHeart older than 9.9.0, mqtt-topic-authorizer resolves but is never invoked on /mqtt-sse, so the endpoint is authenticated but not authorized per topic — a topic outside the ACL is silently accepted instead of rejected with 403.

What you get

Plugin Kind Default URI Enabled by default

mqtt-client

Provider<MqttClient>

—

No (Tier 1, the module switch)

mqtt-router

Provider<MqttMessageRouter>

—

No (gated explicitly, see below)

mqtt-connector

Initializer (AFTER_STARTUP)

—

Yes (connects the client, last of all)

mqtt-sse

SseService

/mqtt-sse

No (Tier 2)

mqtt-rest

JsonService

/mqtt

No (Tier 2)

mqtt-topic-authorizer

WildcardInterceptor

—

Yes (deliberately, fails closed)

mqtt-mongo-writer

Initializer (AFTER_STARTUP)

—

No (Tier 2)

mqtt-metrics-collector

Initializer (AFTER_STARTUP)

—

Yes (registers the router’s gauges)

mqtt-stats

JsonService

/mqtt/stats

No (Tier 2)

mqtt-status

Initializer (AFTER_STARTUP)

—

Yes (diagnostic sentinel)

How the pieces fit together:

flowchart LR
    broker[("MQTT broker")]
    mongo[("MongoDB")]
    callers(["HTTP clients"])

    subgraph rh["RESTHeart"]
        direction TB
        connector["<b>mqtt-connector</b><br><i>connects last, once every consumer exists</i>"]
        client["<b>mqtt-client</b><br><i>the broker connection</i>"]
        router["<b>mqtt-router</b><br><i>covering subscriptions, fan-out,<br>last-value cache</i>"]
        authz["<b>mqtt-topic-authorizer</b><br><i>per-topic ACL, fails closed</i>"]
        sse["<b>mqtt-sse</b><br><code>/mqtt-sse</code>"]
        rest["<b>mqtt-rest</b><br><code>/mqtt</code>"]
        writer["<b>mqtt-mongo-writer</b><br><i>durable listener</i>"]
        own["<i>your own plugin</i>"]
    end

    connector -.-> client
    broker ==> client
    client ==> router
    router --> sse
    router --> rest
    router --> writer
    router --> own
    writer --> mongo
    writer -.->|"acknowledged once buffered"| broker
    callers --> authz
    authz --> sse
    authz --> rest

mqtt-sse and mqtt-rest are both registered with secure = true: they require authentication, and mqtt-topic-authorizer then checks the requested topic filter against the ACL before either service sees the request.

Messages reach mqtt-mongo-writer through a durable listener, which acknowledges the broker once a message is in its buffer, on its way to MongoDB. See Durability and Operations for what that guarantees and what it does not.

Enablement

The module is dormant on installation, in two tiers.

Tier 1 — the module switch

mqtt-client is registered with enabledByDefault = false. Nothing else in the module can do anything until it is armed:

/mqtt-client:
  enabled: true
  broker-url: "tcp://broker:1883"

mqtt-router is registered with enabledByDefault = false too, and is enabled together with mqtt-client. It is not left to ProvidersChecker to follow the injection graph and switch it off on its own. ProvidersChecker does drop mqtt-router quietly when mqtt-client is disabled — the provider’s descriptor is still there, so it takes the "the provider is disabled" branch and logs at DEBUG. But dropping it makes mqtt-router absent from the set of valid providers, and every enabled plugin injecting it then hits the "no provider found" branch, at ERROR. mqtt-metrics-collector is enabledByDefault = true and injects mqtt-router, so an mqtt-router left enabled over a disabled mqtt-client produces an ERROR line on every startup for it, and one more for each Tier 2 plugin still switched on.

Enabling mqtt-client without mqtt-router leaves the module with no message routing, so enable both.

Tier 2 — opt-in surfaces

Arming Tier 1 alone exposes no HTTP endpoint. mqtt-sse, mqtt-rest, mqtt-mongo-writer and mqtt-stats are each independently registered with enabledByDefault = false, and are switched on one at a time as needed:

/mqtt-sse:
  enabled: true

/mqtt-rest:
  enabled: true

/mqtt-mongo-writer:
  enabled: true

/mqtt-stats:
  enabled: true

The authorizer stays on

mqtt-topic-authorizer stays enabled by default, regardless of the two tiers above, deliberately, not as an oversight. While every Tier 2 endpoint is off, the authorizer is simply never invoked and costs nothing. The moment one is turned on, the authorizer is already active and fails closed with no ACL configured, so a Tier 2 endpoint can never be reachable without topic authorization already in force — not even for a moment, and not even because an operator forgot a flag.

Four realistic configurations

Provider only

Inject mqtt-router from your own plugin, with no HTTP endpoint exposed at all:

flowchart LR
    broker[("MQTT broker")] ==> client["<b>mqtt-client</b>"] ==> router["<b>mqtt-router</b>"] --> own["<i>your plugin</i><br>injects mqtt-router"]
/mqtt-client:
  enabled: true
  broker-url: "tcp://broker:1883"

/mqtt-router:
  enabled: true

A worked example is in examples/mqtt-logger.

Live SSE

sequenceDiagram
    autonumber
    participant C as HTTP client
    participant A as mqtt-topic-authorizer
    participant S as mqtt-sse
    participant R as mqtt-router
    participant B as MQTT broker

    C->>A: GET /mqtt-sse?topic=sensors/%23
    Note over A: REQUEST_AFTER_AUTH<br>checks the topic filter against the ACL
    alt filter not granted
        A-->>C: 403, never reaches the router
    else filter granted
        A->>S: request continues
        S->>R: subscribe(filter, qos, listener)
        R->>B: SUBSCRIBE, unless an existing subscription already covers the filter
        S-->>C: 200, text/event-stream held open
        B->>R: message on the topic
        R->>S: listener invoked
        S-->>C: event: mqtt-message
    end
/mqtt-client:
  enabled: true
  broker-url: "tcp://broker:1883"

/mqtt-router:
  enabled: true

/mqtt-sse:
  enabled: true
  default-topic: "sensors/#"

/mqtt-topic-authorizer:
  acl:
    iot-reader:
      - "sensors/#"

REST polling

mqtt-rest only ever answers from the router’s last-message cache, so something has to prime it:

flowchart LR
    broker[("MQTT broker")] ==> client["<b>mqtt-client</b>"] ==> router["<b>mqtt-router</b>"]
    router --> cache[("last-message cache<br><i>in memory</i>")]
    caller(["HTTP client"]) -->|"GET /mqtt?topic=..."| rest["<b>mqtt-rest</b>"]
    rest --> cache
    rest -.->|"200 with the last message<br>404 if nothing cached yet"| caller
/mqtt-client:
  enabled: true
  broker-url: "tcp://broker:1883"

/mqtt-router:
  enabled: true
  last-message-cache: true
  subscriptions:
    - topic: "sensors/#"
      qos: 1

/mqtt-rest:
  enabled: true

/mqtt-topic-authorizer:
  acl:
    iot-reader:
      - "sensors/#"

MongoDB persistence

flowchart LR
    broker[("MQTT broker")] ==> client["<b>mqtt-client</b>"] ==> router["<b>mqtt-router</b>"]
    router -->|"durable listener"| writer["<b>mqtt-mongo-writer</b>"]
    writer --> buffer["buffer<br><i>bounded by capacity and max-bytes;<br>waits for room when full</i>"]
    buffer -->|"drain loop, batched"| mongo[("MongoDB<br><i>db.collection per sink</i>")]
    mongo -.->|"documents MongoDB refuses,<br>after drain.max-retries"| dlq[("dead-letter<br>collection")]
    writer -.->|"acknowledges each message<br>once buffered"| broker
/mqtt-client:
  enabled: true
  broker-url: "tcp://broker:1883"

/mqtt-router:
  enabled: true

/mqtt-mongo-writer:
  enabled: true
  mongo-sink:
    - topic: "sensors/#"
      database: "iot"
      collection: "sensor-events"

This last one also needs the mongoclient module configured and connected: mqtt-mongo-writer injects mclient rather than opening its own connection.

Using the client from your own plugin

Inject mqtt-router to subscribe to topics:

@RegisterPlugin(name = "my-service", description = "...", defaultURI = "/my-service")
public class MyService implements JsonService {
    @Inject("mqtt-router")
    private MqttMessageRouter router;

    @OnInit
    public void onInit() {
        router.subscribe("sensors/#", Qos.AT_LEAST_ONCE, msg ->
            LOGGER.info("{} -> {}", msg.getTopic(), msg.getPayload()));
    }
}

The router’s API is expressed entirely in this module’s own types (Qos, MqttMessage), so a plugin that only uses the router does not compile against HiveMQ at all. Inject mqtt-client instead when you deliberately want the raw HiveMQ client — to publish, or to reach protocol features the router does not expose.

subscribe registers a live listener: it never holds up an acknowledgement to the broker, and it is subject to max-inflight-messages-per-second. If your plugin stores messages and must not lose them, use subscribeDurable instead. Its listener receives the message and a taken callback to run once the message is safely stored; the router acknowledges the broker only after every durable listener has done so, and a message none of them took is redelivered after a crash.

Caution
Call taken exactly once, and do call it. An unacknowledged message occupies a slot in the broker’s in-flight window, so a listener that never calls back eventually stalls delivery to this client altogether.

Call unsubscribe or unsubscribeDurable when you are done. A listener that is never removed keeps being called, and keeps its filter subscribed on the broker.

Not bundled

restheart-mqtt does not ship with RESTHeart. It is installed separately — see Installing above.

This is deliberate. MQTT is far from RESTHeart’s habitual use cases, and hivemq-mqtt-client brings 13 transitive jars including RxJava and seven Netty modules: a second network stack and reactive runtime that exists nowhere else in a product built on Undertow/XNIO. Bundling it would add all of that to every RESTHeart installation, including the ones that never touch MQTT.

The module still lives in the RESTHeart monorepo, and its integration tests run against the core built alongside it.

Reporting bugs

Open an issue at SoftInstigate/restheart/issues. Almost every surprise in this module turns out to be a configuration one, so these make a report actionable:

  • the configuration of the mqtt-* blocks, or the RHO you ran with, with passwords removed;

  • the mqtt-status output from the startup log: the mqtt module active: … inactive: … line, or the warnings printed in its place;

  • the RESTHeart build you installed into — a release version, a snapshot image tag, or a commit — and the module’s: its release version, or for a snapshot the commit that the mqtt-snapshot release notes record;

  • the protocol details: protocol-version, the QoS the publisher used (mosquitto_pub defaults to 0), and the broker and its version;

  • the server log from startup to the failure, not only the error.

And if the documentation let you configure something wrongly without complaining, report that too: it is a bug in the docs.

License

Dual-licensed, like every other RESTHeart module: AGPL-3.0, or the RESTHeart COMMERCIAL LICENSE for those who need it.