IMD SolutionComputing LibraryShop main store

How-to

Buffer MQTT data in Node-RED during an internet outage

Edge computing and IIoT Published 9 min read

Short answer

The MQTT out node's in-memory store dies with the process, so an internet outage loses every sample the flow produces while disconnected. Stamp each sample at acquisition, derive a broker-up flag from the MQTT node status, and persist the queue in a file-backed context store with a capped size. Drain it oldest-first over QoS 1 when the connection returns.

On this page
  1. Why do queued MQTT messages vanish during an internet outage?
  2. Which failure cases must the buffer cover?
  3. How do I stamp each sample with its acquisition time?
  4. How do I flag when the broker connection drops?
  5. How do I make the queue survive a gateway restart?
  6. What order do live and queued samples drain in?
  7. How big should the queue be for a four-hour outage?
  8. How do I prove the buffer works before the first real outage?
  9. Questions asked

An internet outage does not have to cost you pump-station data. The stock MQTT out node cannot do the job on its own: it checks the connection at publish time, and the underlying client's in-memory outgoing store disappears with the Node-RED process. Build three pieces into the flow instead: an acquisition timestamp on every sample, a broker-up flag driven by the MQTT node's own status, and a bounded queue persisted through a file-backed context store. When the flag returns, drain the queue oldest-first with QoS 1 publishes, and size it as sample rate times the longest outage the project must cover. That covers every case where the gateway stays powered; a power failure with no UPS loses the samples before they reach the gateway, and no local buffer can recover them.

Why do queued MQTT messages vanish during an internet outage? #

Because the MQTT out node relies on the underlying client's in-memory store, whose default policy, es6-map, holds only in-flight QoS 1 and 2 messages and dies with the Node-RED process; samples your flow creates while the node is disconnected are never queued at all.

The out node checks the connection at the moment it hands a message over, and beneath it the client library manages QoS 1 and 2 retransmission in an outgoing store. That store exists to retransmit messages the client has already accepted, not to archive a flow's output, so three consequences follow:

  • A QoS 1 publish that is in flight survives a short broker drop, but not a Node-RED or gateway restart.
  • Samples the flow produces while the node reports disconnected never enter any queue.
  • QoS 0 adds no guarantee on top: a publish in flight when the link dies is simply gone, the same loss window covered in covering the QoS 0 loss window in Sparkplug MQTT transmission.

Nor does the broker backfill the gap. A broker queues messages only for a subscriber that disconnected cleanly with a persistent session; it has no store for a publisher that is offline, so records the gateway never managed to send exist nowhere on it. Read how offline message delivery differs between a broker queue and standard QoS before trusting either half alone.

Which failure cases must the buffer cover? #

Two failures hide in the requirement: losing the internet and losing gateway power. The buffer covers the first and a UPS-backed second; when power fails with no UPS, the gateway never receives the samples, and no local log can bring them back.

Sort the four cases before writing code, because they need different mechanisms:

Failure at the pump station Gateway still receives PLC data? What preserves the record
Internet or broker unreachable, gateway powered Yes The file-backed context queue, drained on reconnect
Gateway power loss, gateway and PLC network on UPS Yes, for the UPS runtime The same queue; disk persistence covers a UPS that runs out mid-outage
Gateway power loss, no UPS No Nothing local. The samples never reach the gateway, so the gap closes only if the PLC buffers
Node-RED restart with samples queued Yes, after the restart Only a file-backed store keeps them; memory context is cleared

Mark each case the customer expects to survive as covered or not before building. If only the gateway sits on the UPS and the PLC or the switch between them does not, the second row degrades: the local log stops at the moment the devices feeding it stop.

How do I stamp each sample with its acquisition time? #

Stamp the value in the flow immediately after the PLC read, before any branching, using Date.now() as epoch milliseconds in UTC; a sample stamped at publish time after reconnect carries the recovery time instead of the process time and corrupts downstream trends.

Put the stamping function directly after the PLC read so the live path and the queue path carry the same object:

msg.payload = { ts: Date.now(), values: msg.payload };
return msg;

ts is epoch milliseconds in UTC; let the subscriber convert to local time. The consumer then tells replayed from live records only by the age of ts, and trend or totalizer tools see one shape. The gateway clock is the time source: with the internet down, NTP is unreachable and the clock free-runs, and after a power loss it can start wrong until the first sync after reconnect. Decide up front whether records stamped before that first successful sync carry a quality flag; the acquisition timestamps make any drift visible downstream, which is what you want.

How do I flag when the broker connection drops? #

Add a status node scoped to the MQTT out node, feed it into a one-line function that sets the brokerUp flag from msg.status.fill, and initialize the flag to false at startup; expect detection to lag a silent link failure by roughly one keepalive period.

The status node emits a message whenever the scoped node's state changes; the function turns it into a flow variable:

flow.set('brokerUp', msg.status.fill === 'green');
return null;

Confirm in a debug node what msg.status.fill and msg.status.text contain on your Node-RED version before relying on the color, and initialize brokerUp to false with an inject node at deploy so the flag has a defined value before the first status event arrives.

The flag is the client's view, and nothing in the protocol pushes news of a silent failure — a pulled cable upstream, a hung cellular modem — so detection waits for the keepalive you set in the MQTT broker configuration node. The client pings at that interval and the broker drops a silent connection after one and a half times it: with the keepalive at 30 seconds, detection lands at about 45 seconds worst case, and at 10 seconds it lands near 15. Samples published inside that lag window are the ones a QoS 1 retransmission has to catch, which is why the drain stage publishes with QoS 1.

How do I make the queue survive a gateway restart? #

Enable the localfilesystem context store in settings.js with a flushInterval of 5 seconds as a defensible example value; the queue then survives a Node-RED restart, while a hard power cut loses only the samples created since the last flush.

Memory context dies with the process, so the queue must live in the file-backed store declared in settings.js:

contextStorage: {
    default: { module: 'memory' },
    file: { module: 'localfilesystem', config: { flushInterval: 5 } }
}

The file store caches in memory and writes to disk on the flush interval, so the example 5 second interval at one record per second loses at most 5 records to a hard power cut — the ones created since the last flush. Shorter intervals narrow that window and multiply the writes: the store serializes its cached contents to disk on each flush, so a growing queue is rewritten on every tick and wears flash storage. Keep the queue capped and the interval as long as the loss tolerance allows, and read the sizing arithmetic in the section below before fixing a value. If the existing gateway cannot offer disk-backed storage through the cases in the table above, that is the moment to specify a fanless industrial mini PC with local disk storage for the cabinet instead of a repurposed office box.

What order do live and queued samples drain in? #

Route every sample through one gate function with two outputs: publish directly only when the broker is up and the queue is empty, and in every other case append to the queue first, so a live sample never overtakes a queued one.

The gate sits between the PLC path and the MQTT out node; pump/station is an example topic and MAX the cap sized in the section below:

const MAX = 15000;
const up = flow.get('brokerUp') === true;
const q = flow.get('queue', 'file') || [];
if (up && q.length === 0) {
    msg.topic = 'pump/station';
    msg.qos = 1;
    return [msg, null];
}
q.push(msg.payload);
if (q.length > MAX) { q.shift(); }
flow.set('queue', q, 'file');
return [null, null];

While the queue holds anything, every new sample appends and only the drain publishes. The drain is a second function fed by an inject node repeating every 250 milliseconds as an example tick rate; it pops the oldest record, rebuilds the message with the same topic and QoS 1, and returns null whenever the queue is empty or the flag is false, which makes the idle ticks costless:

const q = flow.get('queue', 'file') || [];
if (!flow.get('brokerUp') || q.length === 0) { return null; }
const record = q.shift();
flow.set('queue', q, 'file');
return { topic: 'pump/station', payload: record, qos: 1 };

At 4 ticks per second the drain empties a 14,400-record queue in about one hour; match the tick rate to the live sample rate so a reconnect never stampedes the broker. Node-RED runs function nodes on a single thread, so the gate and the drain cannot interleave mid-execution and the read-modify-write on the queue is safe between nodes. Order is the whole point: a live sample that overtakes the queue produces exactly the replay corruption described in why buffered MQTT records replay corrupt or out of order, and a drain that holds order delivers the backfill pattern in MQTT store and forward backfill after a connection outage.

How big should the queue be for a four-hour outage? #

Size the cap as sample rate times the longest outage you must cover: at one record per second and a four-hour outage that is 14,400 records, so cap the queue at 15,000 and expect roughly 3 MB per flush at 200 bytes per record.

Worked example, with illustrative inputs you replace with your own values:

  • Sample period: one combined record per second, so 1 record/s.
  • Outage to cover: 4 hours = 14,400 s.
  • Records to hold: 14,400 s × 1 record/s = 14,400 records.
  • Cap: 15,000 records, leaving 600 records — about 10 minutes — of headroom for a slow drain.
  • Bytes per flush: 15,000 × 200 bytes = 3,000,000 bytes, about 3 MB.
  • Write cost while records flow: 3 MB × 720 flushes per hour at the example 5 second interval ≈ 2.16 GB written per connected hour, enough to exhaust an SD card's endurance in weeks; at a 60 second interval the same queue writes 180 MB per connected hour and the power-cut loss window widens to 60 records.

The decision: on flash-backed storage run the 60 second interval and accept that 60-record loss window, or move the store to an append-only file or a small local database once rates or retention grow, because those append instead of rewriting — the trade-offs are compared in choosing an edge data path for periodic records.

How do I prove the buffer works before the first real outage? #

Prove the buffer with five forced failures before it faces a real one: a clock check, an unplugged uplink, a queued restart, a power cut, and a broker-side check that replayed records keep their original timestamps and order.

Run the tests on the data uplink only, never by interrupting a segment that also carries control or safety traffic, and do the power-cut test on a bench unit or inside a planned outage. Then work down the list and record each expected result:

  1. Inject one sample and confirm in a debug node that msg.payload.ts is a 13-digit epoch-millisecond value within about a second of the gateway clock.
  2. Unplug the uplink, confirm brokerUp flips to false within roughly one keepalive period, then let samples accumulate for ten minutes and watch the queue grow in the context sidebar under the file store.
  3. Restart Node-RED with the queue loaded and confirm every record comes back with its original ts value.
  4. Restore the link, confirm brokerUp returns to true, and confirm on a subscriber that queued records arrive oldest first, each carrying its acquisition timestamp, with no live record published until the queue is empty.
  5. Cut gateway power with records queued, reboot, and confirm the only missing records are those created since the last flush, a window equal to the flush interval.

Commit the design only when all five steps pass on the deployed hardware and store: on paper every buffer passes, and in the field the failures concentrate in step 3, where the queue still lives in the default memory store. In normal operation, publish the queue length itself as a topic so a stuck drain or a flapping uplink shows up as a number instead of a missing trend.

Questions asked

Does QoS 1 alone remove the need for a local buffer?

No. QoS 1 only retransmits messages the client has already accepted into its outgoing store, and that store is in-memory by default. It does nothing for samples the flow produces while the node reports disconnected, and nothing for a queue that died with a restart. The application-level queue plus QoS 1 publishing is what covers both halves.

Will the broker hold my data until the gateway reconnects?

Only for subscribers. A broker queues messages for a client with a persistent session that disconnected cleanly, and stops once a vanished session outlives the broker's session-expiry setting. For a publisher none of it applies: the broker queues nothing for a gateway that cannot connect, so unsent records exist nowhere but the local queue.

Will the subscriber receive duplicates when the queue drains?

Yes, occasionally. QoS 1 is at-least-once: if the link died after the broker received a publish but before the acknowledgement reached the gateway, the retransmission after reconnect delivers that record twice. Key the consumer's writes on the acquisition timestamp and topic so a repeat overwrites the original, which makes the whole replay idempotent.

When should I move from a context queue to a database?

When the sizing stops closing: sustained rates beyond roughly ten records per second, retention past a few hours, or several stations sharing one gateway. The context store rewrites one growing JSON structure on every flush, while an append-only file or a small database such as SQLite adds records without rewriting, keeping flash wear predictable.

How do I monitor the queue in normal operation?

Publish the queue length itself as an MQTT topic, for example pump/station/queue, from an inject node that reads the file store every minute. A length stuck above zero while the connection is up means the drain stage is stuck; a length that climbs steadily means the uplink is flapping. One topic usually catches a failing cellular link before anyone misses a trend.

Keep reading

  • Explainer

    Store-and-forward SQL buffering during MES outages

    Treat the MES requirement as a durable store-and-forward buffer, not a database mirror. Capture every record locally with its acquisition timestamp — a file for event-level data, a queue table or a local time-series store for measurement streams — and replay only what the remote SQL database has actually committed. Size the buffer from record rate, record size and outage duration; at the worked rates a 256 MB partition carries a 72-hour outage.

    Edge computing and IIoT

  • Selection guide

    Choosing an edge data path for periodic records

    For independent periodic samples, Tag Historian with Edge Sync Services is the reliable path and buffers 35 days locally. For one atomic row per collection cycle, use MQTT Transmission records landing in MQTT Recorder. For true transaction groups, license a standard gateway for that node.

    Edge computing and IIoT

  • How-to

    MQTT store and forward backfill after a connection outage

    Yes. Tag data collected on the edge during the outage fills the server gap after reconnection, but only when Store and Forward is enabled in MQTT Transmission on the edge and history is enabled on the receiving MQTT Engine tags. Matching historian database names on both systems does nothing.

    Edge computing and IIoT