Troubleshooting
Why buffered MQTT records replay corrupt or out of order
Short answer
Corrupt or out-of-order replay is caused by the buffer script, not by MQTT or the broker. The reader scans fixed blocks for one @ while the writer frames records with a five-byte delimiter, current data publishes before the backlog, and the file is erased before delivery is confirmed. Parse the full delimiter across block boundaries, replay the backlog first, and hold the buffer until your chosen confirmation stage is reached.
On this page
- Why does buffered MQTT data arrive corrupt or merged?
- How should the replay parser handle the delimiter?
- Why do current values reach Azure before the buffered backlog?
- Why is the buffer erased before delivery is confirmed?
- Does publishing at QoS 1 make replay safe?
- How do I test each replay stage separately?
- How much buffer capacity do I need?
- The decision
- Questions asked
If buffered MQTT records come back merged, truncated or with newer samples ahead of older ones, the fault is in the buffer script, not in MQTT, the broker or the cloud function. Three independent defects produce the symptom: the replay parser looks for a single @ inside arbitrary 1000-byte read blocks while the writer frames each record with a five-byte delimiter, the connected branch publishes current data before the saved backlog, and the script erases the buffer file immediately after issuing publish commands with no confirmation. Fix the framing, fix the order, and tie deletion to a real checkpoint.
Why does buffered MQTT data arrive corrupt or merged? #
The writer and the reader disagree about what separates one record from the next, and the reader's version silently destroys data. The save function appends each message followed by three @ characters, a carriage return and a line feed — five delimiter bytes. The replay function reads 1000 bytes at a time, searches that block for one @, publishes whatever accumulated before it, then clears its line buffer and discards the rest of the block.
That has two consequences you can predict without running it:
- If a 1000-byte block contains two complete records, the second record is dropped and the first is published with the next block's content glued to it.
- If the delimiter straddles a block boundary — say the three @ land at the end of one block and the CR LF at the start of the next — no delimiter is found and the records merge.
Because the blocks are fixed at 1000 bytes while record lengths are not, both cases occur routinely. Changing the read size does not fix this: it only moves where the boundaries fall. Reading one byte at a time removes the multi-record case but is slow enough to stall the gateway's script cycle during a large replay, and it still does not address ordering or deletion.
How should the replay parser handle the delimiter? #
Parse the exact five-byte sequence the writer stores, and carry parser state across reads so a delimiter split between two blocks is still recognized. A small state machine does it: keep a counter of consecutive matched delimiter bytes; on each byte read, advance the counter if the byte matches the next expected delimiter byte (position 1, 2 and 3 expect @, position 4 expects CR, position 5 expects LF), reset to zero on mismatch (with a partial-match caveat if the payload itself contains @), and on a full match publish the accumulated record and clear the buffer.
Process every byte in each block. When a match completes, publish the record and continue scanning the remaining bytes of the same block instead of discarding them, so multiple records in one read all survive.
To keep the gateway responsive during a large backlog, bound the work per replay cycle: read and publish a fixed budget of records, save the file offset as your checkpoint, and resume from that offset on the next cycle instead of draining the whole file in one synchronous call.
Why do current values reach Azure before the buffered backlog? #
Because the connected branch of the publish routine sends the two current payloads first and only then calls the saved-events replay. When the connection returns, every new sample reaches the broker before the samples recorded during the outage. A downstream plot or a database that inserts on arrival then shows a discontinuity even though every record eventually arrived.
If anything downstream depends on arrival order — insertion into a time-series table, a plot, a delta calculation between consecutive samples — reverse the sequence: replay the saved records first, then publish the current cycle's values. Note the flip side covered in MQTT store and forward backfill after a connection outage: once you replay first, the receiving function must accept out-of-timestamp-order batches gracefully, because replayed data is inherently older than live data on the same connection.
Why is the buffer erased before delivery is confirmed? #
The replay function deletes the buffer file immediately after the last publish command is issued — the deletion fires on submission, not on delivery. If the connection drops mid-replay or the receiving function fails, the records are gone and nobody downstream ever saw them.
Decide which stage counts as "delivered" and hold the checkpoint until that stage confirms:
- Local publish submission — weakest; the call returned, nothing more.
- Broker acknowledgment — achievable with QoS 1 publish, which makes the broker confirm each message at least once.
- Receiving function completion — needs an application-level acknowledgment path; the transport never reports it.
- Database commit — the stage your data actually needs, and the one an off-the-shelf MQTT client cannot prove on its own.
A practical compromise when no application acknowledgment exists: rename the buffer to a pending file before replay, delete it only after a post-replay verification pass (counts and timestamps compared downstream), and re-queue the pending file otherwise. Never treat QoS 1 as license to erase — see the next section.
Does publishing at QoS 1 make replay safe? #
No. QoS 1 gives you at-least-once delivery between the gateway and the broker, and Azure IoT Hub supports QoS 0 and QoS 1 but not QoS 2 — so QoS 1 is the strongest option the platform offers. But the corruption in this failure comes from record framing, which QoS cannot touch: a merged, truncated record is delivered perfectly intact as a corrupted message. Field experience bears this out — one test that switched the replay publish from QoS 0 to QoS 1 still produced bad data downstream.
QoS 1 also introduces duplicates: an acknowledged publish that the sender never saw the acknowledgment for gets resent. If your checkpoint logic can replay a record twice, the downstream path needs a stable record identity (a record ID inside each payload) so duplicates can be detected and dropped at the consumer. The QoS 0 window has its own failure mode with a different remedy, covered in covering the QoS 0 loss window in Sparkplug MQTT transmission.
How do I test each replay stage separately? #
Run the verification so each stage can pass or fail on its own, in this order:
- Disconnect the WAN and let several 120-second publishing cycles write to the buffer file.
- Before reconnecting, count complete five-byte delimiters in the file and confirm each stored record carries its original timestamp and payload.
- Reconnect and compare the stored-record count with the script's published-count log line.
- Check the first and last replayed timestamps at the receiver: buffered data must arrive before current data.
- Simulate a second interruption during replay and confirm unconfirmed records remain recoverable from the checkpoint.
- Compare unique record identities at the MQTT receiver, the cloud function and the database. The first stage where counts or contents diverge locates the remaining fault — local replay, transport, function parsing or database insertion.
How much buffer capacity do I need? #
Size the file from your measured serialized record size and your publishing cadence, not from a guess. The script in this class of setup caps the buffer at 20,000,000 bytes and stores two messages per 120-second cycle when disconnected.
Worked example, with the record size assumed: suppose the average serialized record including its five-byte delimiter measures 300 bytes. Then 20,000,000 divided by 300 gives about 66,666 buffered records. At two records every 120 seconds, that is one record per 60 seconds, so the buffer bridges roughly 66,666 times 60 seconds, about 4,000,000 seconds or 46 days. If your records average 600 bytes instead, the same cap holds about 23 days — the retention time halves as record size doubles.
Also check the publish side: a replay batch pushing thousands of records in one burst can exceed what the receiving function or broker accepts per connection window, which is one more reason to bound records per replay cycle rather than drain the file in one call.
One safety note: if any of these values feed an alarm or shutdown path, verify the end-to-end latency of the buffered path against that function's required response time before trusting replay to deliver it in time.
The decision #
Commit to three changes: parse the full five-byte delimiter with state carried across reads, replay saved records before publishing current data, and delete the buffer only when your chosen confirmation stage — for most data headed to SQL, a verified downstream insert — reports success. QoS 1 belongs on the replay publishes because the broker honors it and it removes transport loss; it does not excuse the other two fixes. If the gateway cannot sustain byte-wise parsing without stalling, bound records per cycle and resume from the checkpoint.
Questions asked
Why does my replayed MQTT data arrive merged or truncated?
The writer frames each record with three @ characters followed by carriage return and line feed, but the reader searches each block for a single @ and discards the remainder of that block. Records sharing a block get merged, and the tail of the last record in a block is lost. Parse the complete five-byte delimiter and continue scanning every remaining byte in each read.
Does switching the replay publish to QoS 1 fix the corruption?
No. QoS 1 changes only the transport: the broker acknowledges each message, which guards against transport loss. It cannot repair a parser that merges records, and it does not prove that an Azure function parsed the payload or that a database committed the row. One field test with QoS 1 still produced bad data, which confirms QoS alone is not the fix.
How long can a 20,000,000-byte buffer bridge an outage?
It depends on your serialized record size. As a worked example with a 300-byte average record including its delimiter, 20,000,000 divided by 300 is about 66,666 records. At two records every 120 seconds, that is roughly 46 days of storage. Measure your own record sizes and divide the same way; the answer moves proportionally with record size.
When can the script safely delete the buffer file?
Only after the confirmation stage you actually require is reached. Choose the boundary deliberately: local publish submission, a QoS 1 broker acknowledgment, completion of the receiving function, or a confirmed database commit. These are not equivalent, and no off-the-shelf callback in this class of script proves the database commit, so keep the checkpoint and unconfirmed tail until that stage reports success.