Managed MQTT Cloud

MQTT Threshold Alerts: Get Notified When Values Go Out of Range

Learn how to raise alerts when MQTT sensor values leave a safe range: rules in the ConnectMQ portal, a Node-RED flow for notifications, and a Python alerter with hysteresis and debounce to avoid alert storms.

MQTT threshold alerts dashboard with a temperature line crossing a red limit and an alert entry appearing in the log
Run this on your own MQTT brokerGet a private, managed MQTT broker on the Free plan and start from ready-made code samples.
Try it free Code samples No card required

MQTT threshold alerts tell you the moment a temperature, pressure or level reading leaves its safe range, without anyone staring at a dashboard. In this tutorial you will publish realistic sensor data, create threshold alert rules in the ConnectMQ portal, build an equivalent alert in Node-RED that can notify people, and add hysteresis and debounce so a value hovering at the limit does not flood you with alerts.

How MQTT Threshold Alerts Work

MQTT itself has no notion of an alert. A threshold alert is a subscriber that watches one or more topics, extracts a numeric value from each payload and compares it with a limit. When the comparison flips from normal to abnormal, it raises an alert; when it flips back, it clears the alert. Where that subscriber runs is the main design choice:

Approach Where it runs Strengths Limitations
Broker portal rules In your managed broker's portal No extra infrastructure; alerts log next to the data Delivery channels limited to what the portal offers
Node-RED flow A Node-RED instance you host Visual, flexible, many notification nodes You run and monitor Node-RED
Custom service Your own code Full control over logic and delivery Most engineering and maintenance
Device-side logic On the sensor or PLC Works offline, fastest reaction Rules spread across firmware

Many teams combine them: portal rules for quick visibility, plus a Node-RED or custom alerter where they need to page someone. Safety-critical interlocks always belong in the local control system, never in a cloud alert.

Step 1: Publish Sensor Data

You need a stream of numbers with occasional excursions. This script publishes temperature and pressure for a tank every two seconds and drifts out of range now and then. Install the client with pip install "paho-mqtt>=2.0".

import json
import math
import random
import time

import paho.mqtt.client as mqtt

# Production: your ConnectMQ broker on 8883 with TLS and portal credentials.
# Quick test: the public broker on 1883 with a unique client ID.
HOST, PORT = "broker.connectmq.com", 1883
ROOT = "connectmq/demo/a7f3q2/factory1/utilities/tank1"

client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, client_id="tank1-sim-a7f3q2")
# For your private broker:
# client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, client_id="YOUR_CLIENT_ID")
# client.username_pw_set("YOUR_USERNAME", "YOUR_PASSWORD")
# client.tls_set()
# PORT = 8883
client.connect(HOST, PORT, keepalive=60)
client.loop_start()

t = 0
while True:
    temperature = 60 + 15 * math.sin(t / 30) + random.uniform(-1, 1)
    pressure = 4.0 + random.uniform(-0.2, 0.2) + (1.5 if random.random() < 0.03 else 0)
    payload = {"temperature": round(temperature, 2),
               "pressure": round(pressure, 2),
               "ts": int(time.time())}
    client.publish(f"{ROOT}/telemetry", json.dumps(payload), qos=1)
    t += 1
    time.sleep(2)

The temperature swings slowly between about 45 and 75 degrees, crossing a 70 degree limit regularly, while pressure occasionally spikes above 5 bar. Change the a7f3q2 part of the topic to your own random string, because the public area is visible to everyone.

Step 2: Create Threshold Alert Rules in the ConnectMQ Portal

The ConnectMQ portal includes threshold alert rules and an alerts log, so you can watch values without deploying anything else. Point the simulator at your own broker (the commented lines above), then:

  1. Sign in at the portal and open your broker.
  2. Confirm the data is arriving by finding factory1/utilities/tank1/telemetry in the live topic explorer.
  3. Create a threshold alert rule for that topic on the temperature field, with an upper limit of 70.
  4. Create a second rule on the pressure field with an upper limit of 5.
  5. Leave the simulator running and open the alerts log. Within a minute or two, temperature excursions appear as the sine wave peaks, and occasional pressure spikes appear as well.

Keep your payloads as flat JSON with numeric fields, as in the simulator. Values buried in nested strings or sent as "70.4 C" are much harder for any alerting tool to evaluate. The portal's dashboard and devices view show the same tank alongside the alerts, which helps when you need context about what else was happening on the line.

Step 3: Build Notifying Alerts in Node-RED

When an alert must reach a phone, a chat channel or a ticketing system, Node-RED is a practical companion to the broker. Configure an mqtt-broker config node with your broker host, port 8883 with TLS enabled, and the credentials from the portal. Then wire this flow:

  1. mqtt in subscribed to factory1/utilities/+/telemetry, output "a parsed JSON object".
  2. function node with the threshold logic below.
  3. Your notification node of choice: email, a chat integration or an HTTP request to an incident tool.
// Node-RED function node: threshold alert with hysteresis per tank
const HIGH = 70;      // raise when temperature goes above this
const CLEAR = 67;     // clear only when it falls below this
const tank = msg.topic.split("/")[2];
const value = Number(msg.payload.temperature);
if (Number.isNaN(value)) return null;

const key = `alarm_${tank}`;
const active = context.get(key) || false;

if (!active && value > HIGH) {
    context.set(key, true);
    msg.payload = { tank, state: "ALARM", temperature: value, limit: HIGH };
    return msg;
}
if (active && value < CLEAR) {
    context.set(key, false);
    msg.payload = { tank, state: "CLEARED", temperature: value };
    return msg;
}
return null;

No filter node is needed after the function, because it only emits a message when the alarm state changes. The topic index [2] assumes topics like factory1/utilities/tank1/telemetry; adjust it to your hierarchy. Our Node-RED MQTT tutorial walks through installing Node-RED and configuring the broker node in detail.

Step 4: Stop Alert Storms with Hysteresis and Debounce

A naive "value greater than 70" check fires on every message while the value is high, and flaps on and off as noise pushes a reading back and forth across the limit. Two techniques fix that:

  • Hysteresis uses separate raise and clear thresholds (70 and 67 above), so noise around the limit cannot toggle the state.
  • Debounce requires the condition to persist, for example for three consecutive readings or 30 seconds, before raising the alert. It filters single-sample spikes caused by electrical noise.

The following Python alerter applies both and publishes alert state to its own retained topic, so dashboards and other systems can subscribe to alerts like any other data:

import json
import paho.mqtt.client as mqtt

HOST, PORT = "broker.connectmq.com", 1883
ROOT = "connectmq/demo/a7f3q2/factory1/utilities"
RULES = {"temperature": (70.0, 67.0), "pressure": (5.0, 4.6)}  # raise, clear
DEBOUNCE = 3

state = {}  # (tank, field) -> {"active": bool, "count": int}


def on_connect(client, userdata, flags, reason_code, properties):
    client.subscribe(f"{ROOT}/+/telemetry", qos=1)


def on_message(client, userdata, msg):
    tank = msg.topic.split("/")[-2]
    try:
        data = json.loads(msg.payload)
    except ValueError:
        return
    for field, (raise_at, clear_at) in RULES.items():
        value = data.get(field)
        if not isinstance(value, (int, float)):
            continue
        s = state.setdefault((tank, field), {"active": False, "count": 0})
        if not s["active"]:
            s["count"] = s["count"] + 1 if value > raise_at else 0
            if s["count"] >= DEBOUNCE:
                s["active"] = True
                publish_alert(client, tank, field, "ALARM", value, raise_at)
        elif value < clear_at:
            s["active"], s["count"] = False, 0
            publish_alert(client, tank, field, "CLEARED", value, clear_at)


def publish_alert(client, tank, field, status, value, limit):
    alert = {"tank": tank, "field": field, "status": status,
             "value": value, "limit": limit}
    print(alert)
    client.publish(f"{ROOT}/{tank}/alerts/{field}", json.dumps(alert),
                   qos=1, retain=True)


client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, client_id="alerter-a7f3q2")
client.on_connect = on_connect
client.on_message = on_message
client.connect(HOST, PORT, keepalive=60)
client.loop_forever()

Run it next to the simulator. You see one ALARM per excursion and one CLEARED when the value recovers, instead of dozens of messages.

Choosing Good Thresholds

Thresholds are a process decision, not an IT one. A short checklist helps:

  1. Start from equipment limits and process specifications, then set the alert below the hard limit to leave time to react.
  2. Use two levels where it helps: a warning and a critical alert.
  3. Set the clear threshold far enough from the raise threshold to swallow normal noise.
  4. Alert on silence too: a sensor that stops publishing is often more dangerous than a high value. The $SYS/broker/connection/{clientId}/state topic on ConnectMQ, or a Last Will message, tells you when a device drops off.
  5. Review alert history monthly and retire alerts nobody acts on.

Fixed limits are not the only option. A rate-of-change rule, such as temperature rising more than five degrees in a minute, often warns earlier than an absolute limit, because it catches a cooling failure while the value is still in range. These rules need state across messages, so they fit naturally in the Node-RED function or the Python alerter above: keep the previous value and timestamp per device and compare the slope with your limit. Start with simple thresholds, then add rate-based rules where the alerts log shows that excursions were obvious in hindsight.

For broader broker health signals such as connection counts and message rates, see our guide to MQTT broker monitoring, and use the MQTT broker management console article to see where alerts fit among other console features.

Set Up Threshold Alerts on ConnectMQ

Create a free broker at app.connectmq.com on the Serverless plan, no credit card required, and add your first threshold alert rule in minutes. ConnectMQ gives you a managed MQTT broker with the alerts log, topic explorer and dashboard in one portal. For a quick experiment first, run the simulator against the free public MQTT broker, and read the cloud MQTT broker guide when you plan for production.

Frequently Asked Questions

Can an MQTT broker send alerts by itself?

The MQTT protocol has no alerting, but some managed brokers add it in their portal. ConnectMQ provides threshold alert rules and an alerts log; for notifications to phones or chat, pair it with Node-RED or a small subscriber service.

What is hysteresis in threshold alerts?

It means using a different threshold to clear an alert than to raise it, for example raise above 70 and clear below 67. This prevents an alert from flapping when a noisy value hovers around the limit.

How do I alert when a sensor stops sending data?

Use a Last Will message or the broker's connection state topic to detect disconnects, and add a timeout in your alerter that fires if no message arrives within an expected interval.

Should safety alarms rely on MQTT threshold alerts?

No. Safety functions belong in the local control system. MQTT threshold alerts are for visibility and operational response, not for protective interlocks.

Related articles

BYOC MQTT Broker: Bring Your Own Cloud Explained

A BYOC MQTT broker runs in your cloud account but is operated by a provider. Learn how the model works, the responsibility split, and how to prepare your account for it.

7 min read

All articles →

Your private MQTT broker is a few clicks away

Create an account, get your broker credentials and connect your first device — no servers to install, patch or scale.