← Articles
MQTT/12 min read/— views

How to Keep MQTT Store-and-Forward From Punching Holes in Your Historian

Why an MQTT edge gateway loses data during a WAN outage, and how to buffer with source timestamps, sequence numbers and a replay policy that holds.

MQTTSCADAHistorianNetworkingTroubleshooting

The publish worked. The history still has a hole.

You reconnect the WAN after a two-hour outage, the edge gateway goes green, and the live dashboard fills right in. A week later someone pulls a shift report and finds a flat line from 02:00 to 04:00 — the exact window a compressor tripped. The publish call never failed loudly. The broker was simply unreachable, the gateway had nowhere to put the samples, and nobody had written down what should happen in that gap.

Store-and-forward is the part of an MQTT pipeline that decides whether that hole exists. It is a data contract, not something you get for free from the broker. MQTT's own session persistence doesn't save you here: a persistent session with QoS 1/2 only queues messages a broker is holding for a subscriber that will reconnect. When the publisher's broker is unreachable, there is no session to fall back on — the edge gateway has to buffer to its own storage. The spec is explicit about which side it covers. MQTT 5.0 (OASIS Standard) §3.1.2.4 Clean Start and §3.1.2.11.2 Session Expiry Interval describe the session a client resumes, and the clean-session flag in 3.1.1 does the same; §3.1.2.11.2 also states that if the Session Expiry Interval is absent the value 0 is used, so nothing is retained by default. No clause covers the publisher's outage. The gateway has to fill that gap itself.

So a useful edge design answers these questions before the first outage:

  • Which messages are buffered?
  • How long can the buffer hold normal traffic?
  • Are timestamps captured at the device, edge gateway, or broker?
  • How does the receiver detect gaps and duplicates?
  • What happens when the link returns and old data arrives quickly?
  • Which data is allowed to be dropped first when storage is full?

If these rules are not written, the site may have a nice live dashboard and a broken historical record.

The publish returns success while the broker reads nothing

I measured whether the first paragraph is a claim or a fact. Using only the Python standard library: an MQTT 3.1.1 publisher, and a stub broker that sends CONNACK and then stops calling recv(). That is the common WAN failure — no FIN, no RST, just silence.

SO_SNDBUF (bytes)        : 2626560
PUBLISH packet bytes     : 220        (42 B topic + 177 B JSON payload)
QoS 0 accepted by kernel : 12221 publishes (2688620 bytes) in 67 ms, zero errors
broker application read  : 0 bytes

12,221 QoS 0 publishes returned success. 2.69 MB went out. The broker application read 0 bytes. The gateway code saw no exception, no error return, no log line. All of it sat in the kernel send buffer, and it dies with the socket.

The number 12,221 is not the point — it falls out of this loopback socket's SO_SNDBUF of 2,626,560 bytes, and a real WAN link is far smaller. The point is that it is not zero. On a tag publishing once a second, that is 3 h 23 min of nothing but "publish succeeded."

The same script carries a control: with the broker alive, 10 QoS 0 publishes all arrived. And on the same dead link, a QoS 1 publish gets no PUBACK — the publisher finds out immediately. The difference is the QoS, not the network.

# stub broker: send CONNACK, then never call recv() again
c.recv(4096); c.sendall(b"\x20\x02\x00\x00")   # CONNACK, return code 0
held.append(c)

# publisher: go non-blocking and count what the kernel accepts
s.setblocking(False)
ok = 0
while True:
    try:
        s.sendall(publish_pkt(topic, sample, qos=0)); ok += 1
    except BlockingIOError:
        break        # the first moment the publisher learns anything

A successful sendall() means the kernel took the bytes. It does not mean the broker did. QoS 0 gives you no signal that separates the two.

Decide which data deserves buffering

Not every MQTT message needs the same persistence. Treat data classes differently.

Data classBuffer ruleNotes
Process values for historianBuffer with source timestamp and quality.Usually the highest volume. Compression may happen before publish or at the historian.
Alarm and event messagesBuffer with event timestamp, state, and acknowledgement context.Do not collapse active and return-to-normal into one final state.
Equipment state changesBuffer in order with sequence number.MES and downtime systems often depend on transitions.
Heartbeat or availabilityUsually not buffered for long.Old heartbeat messages can confuse recovery logic.
HMI commandsNormally not store-and-forward.A delayed command can be dangerous unless explicitly designed as a queued job.
Configuration changesBuffer or journal carefully.Include user, time, old value, new value, and result.

For SCADA, the dangerous mistake is buffering everything equally. A week of heartbeat messages can crowd out one hour of production measurements if the queue is not prioritized.

Use source timestamps, not reconnect timestamps

When a gateway reconnects, it may publish thousands of old samples in a short burst. The receiving historian must store those samples at the time they were measured, not at the time they were delivered.

Each buffered message should include:

  • Source timestamp.
  • Gateway receive timestamp if different.
  • Quality or reason code.
  • Sequence number or monotonic counter per topic, asset, or stream.
  • Payload schema version.
  • Optional publish attempt count for diagnostics.

Avoid using only broker arrival time for historical data. Broker time is useful for transport diagnostics, but it is not the process time.

Add sequence numbers for gap detection

Timestamps alone are not enough. Two samples can share a timestamp, clocks can move, and some devices report only coarse time. A sequence number lets the receiver see missing or duplicated messages.

A practical sequence design:

  • Keep a separate counter per logical stream, such as one equipment unit or one tag group.
  • Increment for every published data message in that stream.
  • Persist the counter across gateway restart if possible.
  • Include a boot id or session id if the counter resets on restart.
  • Let the receiver tolerate duplicates but flag gaps.

Assume duplicates. MQTT 5.0 §4.3.2 "QoS 1: At least once delivery" redelivers whenever an ACK is uncertain, so the same sample lands twice after a flaky link; exactly-once is §4.3.3 "QoS 2: Exactly once delivery" and nothing else. The receiver needs an idempotency key, not an assumption that each message arrives once.

If you already run Sparkplug B, most of this is built in — but one piece of common wisdom about its QoS is wrong. Eclipse Sparkplug 3.0.0 requires QoS 0 for the data-carrying messages: NBIRTH, DBIRTH, NDATA and DDATA are all QoS 0 with retain false (tck-id-payloads-ndata-qos, tck-id-payloads-ndata-retain, tck-id-payloads-dbirth-qos, tck-id-payloads-ddata-qos). QoS 1 appears in exactly two places: the NDEATH registered as the Will in the CONNECT packet (tck-id-payloads-ndeath-will-message-qos, retain false) and the host application's STATE message (tck-id-payloads-state-birth, QoS 1 with retain true). Sparkplug deliberately does not delegate delivery reliability to the broker. It catches loss with seq continuity and rebirth instead. Which means the silent QoS 0 failure measured above is the default behaviour of a Sparkplug deployment, and without seq checking on the receiver you have no way to see it.

seq rides on every payload. The range is 0–255, and 255 is followed by 0 (tck-id-payloads-sequence-num-incrementing); NDEATH is the one exception (tck-id-payloads-sequence-num-always-included). For NBIRTH the requirement is filed as tck-id-payloads-sequence-num-zero-nbirth, but the normative sentence only says "between 0 and 255 (inclusive)." Implementations generally use 0. A non-zero NBIRTH seq still passes the TCK, so do not hardcode a comparison against 0 on the host side. bdSeq must match between the Will registered in the CONNECT packet and the NBIRTH (tck-id-payloads-nbirth-bdseq-repeat, tck-id-payloads-ndeath-bdseq), and it rolls at 255 as well. The host uses it to match a death certificate received via Last Will back to the birth that opened that session.

Mind the idempotency key here. The advice that asset + stream + seq is enough circulates widely, but Sparkplug's seq is 8 bits, so the same key repeats every 256 messages — every 4 min 16 s at one message per second. Deduplicating a two-hour replay on that key keeps 256 of 7,200 messages and discards the rest as duplicates. To handle replay, put bdSeq and the source timestamp in the key as well, or keep your own wider stream counter alongside Sparkplug's. Rolling your own JSON avoids the problem entirely if you start with a 64-bit counter.

Example diagnostic fields:

{
  "asset": "compressor-01",
  "stream": "process-values",
  "seq": 1842331,
  "bootId": "gw-a-20260618-0915",
  "sourceTs": "2026-06-18T09:24:12.350Z",
  "quality": "good"
}

The exact field names are less important than making the rule consistent and testable.

Size the buffer from real traffic

Do not size the buffer from tag count alone. Use message size, publish rate, compression behavior, and outage expectation.

A simple estimate is:

buffer size = average payload bytes × messages per second × outage seconds × safety factor

Put the measured numbers in and the scale shows up immediately. The PUBLISH packet measured above was 220 bytes (42-byte topic plus a 177-byte JSON payload, one value). Eight hundred tags on a one-second cycle is 176,000 bytes per second. A two-hour outage is 7,200 × 176,000 = 1,267,200,000 bytes, about 1.27 GB. A 1.5 safety factor puts it at 1.9 GB. The store-and-forward allocation sites usually hand out is a few hundred megabytes. That difference is the flat line in the shift report. A Sparkplug protobuf payload carries the same value in less space than JSON, but leave that gain out of the arithmetic until you have measured your own payload.

Then add overhead for queue metadata, indexes, filesystem block size, and retained diagnostic records. The per-message ceiling is worth knowing too: an MQTT packet's Remaining Length is a Variable Byte Integer of at most 4 bytes, capped at 268,435,455 bytes (MQTT 5.0 §1.5.5), and brokers normally restrict it further with Maximum Packet Size. If TLS certificates, broker addresses, or store files live on the same small disk, leave space for operating system logs too.

Field checks:

  • Measure payload size with real JSON, Sparkplug, or binary payloads.
  • Test the worst scan class, not only average production load.
  • Confirm what happens when the gateway restarts with a non-empty queue.
  • Confirm queue write performance on the actual industrial PC or embedded gateway.
  • Watch disk wear if the gateway uses flash storage.

Control the replay rate

When the network returns, an edge gateway may flood the broker. That can overload the broker, historian connector, rules engine, or database.

Use a recovery policy:

  • Limit replay messages per second.
  • Send critical events before low-value samples if priorities are supported.
  • Preserve per-stream order.
  • Keep live data visible while old buffered data drains.
  • Expose queue depth, oldest sample age, and replay status as SCADA diagnostics.
  • If you replay at QoS 1, keep the in-flight count under the broker's Receive Maximum. MQTT 5.0 §3.1.2.11.3 sets the default to 65,535 when the property is absent, but real brokers are often configured far lower — read the value and match it.
  • Check that replay does not starve the Keep Alive. §3.1.2.10 requires the server to close the connection if no packet arrives within one and a half times a non-zero Keep Alive period. A publish loop draining a large queue that never gets to PINGREQ drops the link again mid-recovery.

Operators should be able to tell the difference between "the link is back and the buffer is draining" and "the plant is producing old values right now."

Common failure modes

  • Buffered messages are stored with reconnect time, creating a false production spike in the historian.
  • Alarm active and clear messages are collapsed, so nobody sees the trip that happened during the outage.
  • The queue is FIFO only, and low-value high-rate tags delay important state changes.
  • Gateway restart deletes the buffer because the queue was kept only in memory.
  • Duplicate messages create duplicate MES events because the receiver has no idempotency key.
  • The gateway fills its disk and then loses both buffered data and current diagnostics.
  • The broker accepts the burst, but the downstream historian connector drops records silently.

Commissioning tests

Run store-and-forward tests before the system is handed to operations.

TestExpected result
Broker stopped for a short outageGateway buffers selected streams and reports queue depth.
Broker restoredData replays with original source timestamps and in stream order.
Gateway restarted during outagePersistent queue survives or the documented loss alarm is raised.
Queue reaches warning thresholdSCADA diagnostic alarm appears before data is lost.
Queue reaches full thresholdDrop policy follows the documented priority rule.
Duplicate replay simulatedReceiver ignores or marks duplicates without double-counting events.
Clock shifted on gatewayReceiver flags bad time or uses quality rules instead of corrupting history.

Capture broker logs, gateway logs, and historian records from the same test window. The useful evidence is not only that messages arrived, but that they arrived with the right time, order, quality, and count.

Practical project rule

For every MQTT edge pipeline, publish a diagnostic topic or tag set for buffer health. At minimum include connection state, queue depth, oldest queued timestamp, dropped message count, replay active flag, and last successful publish time. If the SCADA screen cannot show buffer health, the site will discover store-and-forward problems only after someone opens the historian and finds missing data.