
Recall first from Topic design, security, and MQTT 5
- A stable device ID in the topic lets the broker enforce per-device permissions.
- Mutual TLS authenticates both ends of the connection, and topic ACLs authorize individual MQTT operations.
- MQTT 5 Response Topic identifies the reply destination and Correlation Data identifies the request.
Detect a lost connection and recover
5 min readA secured topic space still needs to stay connected and carry well-formed data; this lesson covers detecting offline devices, bridging, and payload design.
The Linux signal rules give you a repeatable failure to investigate. SIGKILL terminates a process without letting it catch the signal and run cleanup code. A device program killed this way cannot send an MQTT DISCONNECT. A surviving broker can detect the socket closure and tell a subscriber that the connection was lost. Killing the broker itself removes the process that would have sent that notification. Those two failures need different tests.
The message a client supplies in CONNECT for the broker to publish when an eligible connection loss occurs has a topic, payload, QoS and retain setting. For a device called pump-17, put the payload offline on devices/pump-17/status with QoS 1 and retain enabled. Once the client has connected successfully and finished any setup required to serve requests, it publishes online with the same QoS and retain setting on that topic. A new subscriber can then receive the stored status. On a planned shutdown, the client publishes retained offline, waits for the publish acknowledgement, and sends a normal DISCONNECT, which suppresses the Will.
A socket closure can reach the broker quickly. A network interruption can leave the socket open and silent. For this lab, use MQTT 3.1.1 with a nonzero Keep Alive, such as 10 seconds. If the broker receives no MQTT control packet from the client within one and a half times the Keep Alive interval, it must disconnect the client. Measure from the last packet the broker received when investigating that timeout. The time when a subscriber displays the Will also depends on delivery to the subscriber. With a clean disconnect, the explicit offline publish gives you a separate, deliberate transition.
Presence describes the connection seen by a particular broker. A sensor can stop producing fresh data while its MQTT client continues answering keepalive. A broker crash can also leave an old retained online value visible after restart if the broker restores stored messages. For operational monitoring, record the age of the last fresh heartbeat or sample and define when the status becomes stale. Choose the threshold from the expected publishing interval and the delays your system tolerates. Treat a stale device record as an observation that needs investigation. An explicit offline report gives you stronger evidence that a specific connection ended.
For the Paho C++ lab, use mqtt::async_client from <mqtt/async_client.h>. Set up mqtt::connect_options with set_mqtt_version(MQTTVERSION_3_1_1), set_keep_alive_interval, and set_will. For the Will, use mqtt::will_options with the status topic, offline, QoS 1, and retain enabled. Pass the payload as a std::string, as in mqtt::will_options("devices/pump-17/status", std::string("offline"), 1, true): with a plain string literal, the compiler on Ubuntu 24.04 (libpaho-mqttpp-dev) reported the constructor call as ambiguous. In a test built with g++ -std=c++17 -Wall -Wextra dev.cpp -lpaho-mqttpp3 -lpaho-mqtt3a, a client killed with SIGKILL caused Mosquitto 2.0.18 to publish the retained offline Will to a subscriber. Keep the same client ID for each attempt and give every simultaneously running device its own ID. Wait on the token returned by connect in your application worker. Once connected, publish retained online and wait on its token as well. Handle mqtt::exception from a failed operation and record whether the failure happened during connect or publish.
Register a mqtt::callback through set_callback. Have connection_lost signal the application worker with a thread-safe flag and a wakeup. Keep the callback short. The worker owns connection attempts and waits for token completion, since that completion can require the library thread that dispatches callbacks. Leave Paho automatic reconnect disabled when your worker manages retry. Use the same retry path for an initial connection failure and for a connection lost after startup.
Attempt one connection and wait for its result.
After a transient failure, pick a random delay within the current retry window. Use an interruptible timer based on
std::chrono::steady_clock.Grow the window after repeated failures up to a configured cap. An illustrative window starts at one second and doubles up to 30 seconds. Random delays spread attempts across devices recovering from the same outage.
After connection and successful online publication, resume telemetry. Reset the retry window after a stable interval so a connection that repeatedly drops just after opening cannot keep retrying at the shortest delay.
Report persistent configuration failures, such as rejected credentials, for correction. Keep only one connection attempt in flight. If the network drops between connection and online publication, retry the connection sequence and report online only after the publication succeeds. Decide what the client does with samples while disconnected, such as keeping a bounded queue or reporting the count it dropped.
{{< callout type="note" >}}
The lab uses two fault injections. Kill the device process with SIGKILL while Mosquitto and the subscriber stay up to verify the Will. Then restart the device and kill the lab broker while the device stays up to verify retry and recovery. During the second test the broker is unavailable to publish a Will, and the subscriber loses its connection too.
{{< /callout >}}
Forward telemetry from the local broker
3 min readA bridge gives devices a local MQTT endpoint and the site an independent cloud connection. A device publishes to Mosquitto on the gateway, where a local application can consume the data. Mosquitto opens a separate connection to the cloud broker and forwards selected topics over that link. When the site loses internet access, the local broker can continue receiving samples and publishing device Wills to local subscribers. The cloud stops receiving updates until its connection recovers.
Suppose the site is named plant-a. Configure the bridge to export devices/+/telemetry and devices/+/status and add the remote prefix sites/plant-a/. In Mosquitto's bridge topic syntax, topic devices/+/telemetry out 1 "" sites/plant-a/ selects outgoing telemetry at bridge QoS 1, uses an empty local prefix and adds the named remote prefix. In a test with two local Mosquitto brokers, a message published to the first broker on devices/pump-17/telemetry arrived at the second on sites/plant-a/devices/pump-17/telemetry. Note that a Mosquitto 2.x listener defined in a configuration file refuses anonymous clients unless you configure authentication or set allow_anonymous true for the lab. An equivalent rule for devices/+/status exports presence. The cloud receives this device's status at sites/plant-a/devices/pump-17/status. Configure the remote endpoint, TLS trust and bridge credentials for the cloud broker. If you later need commands to travel in the opposite direction, select a separate inbound command filter. Explicit directions and distinct topic sets help prevent repeated forwarding and topic collisions.
When the bridge drops, a previously retained cloud status can outlive the connection that carried it. A cloud dashboard needs evidence for both site connectivity and per-device freshness. If the remote broker detects loss of a bridge connection that registered a Will, it can publish that bridge's Will. A site can therefore be marked unreachable while the cloud's last known device state is still online. Track one timestamp for when the cloud last heard from the site and use the sample time to judge the age of resumed telemetry. A newly delivered batch may contain readings captured before the outage. Configure buffering within the broker's queue and persistence limits, and define what happens when those limits are reached. An acknowledgement to the device on the local connection confirms that hop. Cloud delivery needs its own evidence.
A browser can run an MQTT client implemented in JavaScript over a WebSocket endpoint provided by the broker or a compatible proxy. Use wss:// for a browser dashboard served over HTTPS. The client sends MQTT packets through WebSocket and still performs MQTT connection, subscription and message handling. Point it at the service's configured WebSocket host, port and path. A conventional TCP MQTT listener alone cannot accept a WebSocket handshake. Give the dashboard credentials scoped to the topics it needs to read.
MQTT-SN, or MQTT for Sensor Networks, serves constrained devices that can communicate over transports such as UDP. A sensor can register a topic name and then send a short topic ID in subsequent messages. An MQTT-SN gateway can translate between the sensor network and an MQTT broker. In this arrangement the gateway supports a different client protocol, the bridge forwards MQTT publications between brokers, and WebSocket carries MQTT packets to the browser.
Define a telemetry payload that can evolve
3 min readMQTT delivers payload bytes. A telemetry contract tells a consumer how to decode those bytes and what each field means. Choose one encoding for each documented stream. Define the capture timestamp format, the stable device identity, the measurement units and the schema version before connecting a second consumer. This example uses UTF-8 JSON for a temperature reading.
{
"schema_version": 1,
"device_id": "pump-17",
"sample_time": "2026-01-15T08:30:00Z",
"temperature_c": 23.4
}
Here sample_time is a UTC timestamp captured when the measurement was taken. The cloud can record its own ingestion timestamp when it accepts the message. After a network outage, the difference between the two helps explain delayed data. A device whose wall clock has yet to synchronise needs a contract for that condition. For example, allow sample_time to be null and count such records separately in time-based processing. Use a monotonic clock for elapsed time and retries. A monotonic clock reading has no shared UTC origin across devices. For deduplication when using a sequence counter that resets on reboot, combine it with a boot identifier and the stable device ID.
Assign the device ID at provisioning and keep it across reconnects, network address changes and restarts. Document whether IDs are globally unique or scoped to a site. This example scopes them to a site and includes the ID in both the topic and the payload so that an exported record still identifies its source. Validate that the ID agrees with the topic and enforce publish permissions against the authenticated client. A string in the payload is supplied by the sender. It cannot establish the sender's identity by itself.
JSON is easy to inspect with ordinary text tools and convenient when a gateway or browser processes modest telemetry. Text field names appear in each record. CBOR encodes values in binary and supports compact representations, including integer map keys if the contract defines their meanings. It can preserve a map-shaped record while reducing bytes on the link. Protocol Buffers uses numbered fields defined in a .proto schema and typically uses generated code to encode and decode messages. Both binary formats need a suitable decoder. Compare encoded size and decode cost using representative readings and realistic batches before changing an existing stream.
For a compatible change, add an optional field such as battery_mv. A version 1 consumer ignores fields it does not recognise, and an updated consumer handles older records that lack the field. Write that behaviour into the contract and test both directions. Renaming temperature_c, changing its type or reinterpreting its value as Fahrenheit breaks readers that still assume the old contract. Publish a new schema version and provide a migration path, for example a new topic for the incompatible stream while existing consumers still read version 1. With Protocol Buffers, keep each field number's meaning stable and reserve removed field numbers and names in the schema. With CBOR integer keys, give those keys the same long-term stability.
When you review a connection or payload design, ask which process observed the device, when the sample was captured and which contract decodes it. The next lesson, Modbus and CAN in the industrial stack, explains where gateway measurements can come from before the gateway sends them as MQTT telemetry.
Key takeaways
- The broker publishes the Will when it detects an eligible client disconnect.
- A retained online value records a previous publication and needs a freshness policy.
- A bridge connects two brokers and forwards selected topics independently of the device connection.
- Capture time and ingestion time answer different questions when telemetry is buffered.
Reflect
- Explain to a colleague, in two sentences: verify retained MQTT presence transitions during client loss and broker restart.
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- What surprised you when you ran the commands yourself?
On a real board
Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.
References and further reading
- Man pagesignal(7): signal handling and SIGKILL
- Man pagetcp(7): Linux TCP sockets
- Man pageclock_gettime(2): realtime and monotonic clocks
- Docsmosquitto.conf(5): bridge connections
Official documentation first. Links checked when the lesson was published.