Troubleshooting
Why buffered MQTT replay freezes on an edge gateway
Short answer
Replaying one large buffered text file line by line overwhelms the gateway's script and MQTT publish loop, so the script stalls. Store each message as its own numbered file, recover the next write index from the highest existing filename at startup, and pace each publish against the broker's documented inbound limits instead of pausing on a debugger breakpoint.
On this page
When replaying a store-and-forward buffer freezes the script while live publishing works, the cause is pacing, not the connection: the loop reads and publishes hundreds of messages back to back, the outbound queue fills, and the runtime stops. Fix it by storing each message as its own numbered file, recovering the write index from the highest existing filename after a restart, and pacing each publish instead of controlling the rate with a debug breakpoint.
The symptoms that point at this fault are specific: live telemetry reaches the broker, the buffered file builds correctly during the outage, but line-by-line replay stalls partway through, and stepping through with a breakpoint lets every line send. If live publishing also fails, this is a different fault — resolve the link, DNS and credentials first, as covered in buffering MQTT data in Node-RED during an internet outage.
Where the replay actually stops #
Work the boundaries in order, and separate a successful file read from a confirmed publish:
- Network path. If live telemetry also fails, fix the link, name resolution and session before touching the replay code. Read the endpoint, port, TLS and authentication settings from the deployed configuration, not from a guessed copy.
- Connection status at replay time. Record the client's status immediately before replay starts and again where replay stops. In this script family, the MQTT STATUS keyword returning 5 is the connected condition; if it falls to anything else during a fast replay, the broker or gateway dropped the session.
- The publish loop itself. If live messages work but uninterrupted replay stalls, capture the runtime's own error text at the stall point. The failure usually carries no readable code, and without that message you cannot separate a file-access fault from an execution fault from an MQTT backpressure fault.
- The receiver. Publish one saved message through the same topic and connection live telemetry uses, then confirm it in the receiving application. A readable file and a returned publish call each prove less than one payload visible at the other end.
The deciding test: if a breakpoint pause at the publish statement sends every line, the payloads and the connection are proven good and the fault is rate. That is the case this article fixes.
The broker's publish limits set your replay rate #
A replay is a burst publish, and the broker caps bursts. For Azure Event Grid's MQTT broker, the documented per-session limits are 1,000 inbound publishing messages each second, 1 MB of inbound bandwidth each second, and 1,000 inbound in-flight messages. Exceeding any of them raises a quota-exceeded failure on the session — the broker-side metric names it as a QuotaExceeded condition. A replay that fires hundreds of publishes with no acknowledgement handling runs straight into the in-flight cap; one that sends large payloads runs into the bandwidth cap. The same reasoning applies on any broker with documented inflight or rate limits: read them, then pace the replay below the tightest one.
Worked example: replaying a 4,000-message backlog at the Event Grid limits #
Inputs. Buffer content from an outage: 4,000 saved messages (counted from the buffer directory), averaging 2 KB each (2,048 bytes, measured from a sample of stored payloads). Broker limits from the Azure Event Grid MQTT documentation: 1,000 messages each second, 1 MB (1,000,000 bytes) inbound bandwidth each second, 1,000 in-flight messages, all per session.
Rule. The sustainable replay rate is the smallest of the three caps: the message rate cap, the bandwidth cap converted to a message rate, and the in-flight cap converted to an acknowledgement-pacing rule.
Arithmetic.
- Total backlog: 4,000 messages × 2,048 bytes = 8,192,000 bytes.
- Bandwidth cap as a message rate: 1,000,000 bytes each second ÷ 2,048 bytes each message = about 488 messages each second. This binds before the 1,000-message rate cap.
- Minimum drain time: 8,192,000 bytes ÷ 1,000,000 bytes each second = about 8.2 seconds.
- In-flight rule: keep outstanding unacknowledged publishes at or below 1,000; with a batch of 500 and a wait for acknowledgement before the next batch, you never approach the cap.
Result and decision. Replay this backlog in acknowledged batches of 500 messages with no artificial timer, which drains it in roughly 8 seconds and stays under every documented limit. Above roughly 488 messages each second at this payload size, the bandwidth cap binds, not the message-rate cap; a heavier payload lowers that number proportionally. Never race ahead of the acknowledgements — unacknowledged publishes count against the in-flight cap even when the wire is idle.
Store each message as its own numbered file #
The single-large-file design is the root of the stall: parsing a growing file line by line, one binary handle on the whole file, and no per-message retry boundary. The fix stores each message in its own numbered text file, so replay becomes open, read, publish, confirm, delete — one record at a time, each with its own retry boundary, and a file is erased only after its publish completed without error.
The HMS script examples take exactly this shape. The save function MQTT_SaveMQTTEvent builds the filename from the prefix MsgDBPath$ and the sequence number indexbufferfile%, opens the file for binary output, writes the payload, closes the handle, and only then increments indexbufferfile%, guarded by MaxNumberBufferFiles% so the buffer stops accepting rather than overwriting. Commission it with three checks:
- Disconnect MQTT in the test setup, generate several events, and read each file back: one intended payload per file, no write replacing an older queued record.
- Verify how the prefix and the number join into the path before relying on any substring parsing of filenames.
- Remember the guard bounds sequence allocation, not the number of files present: deleting old records does not reclaim their numbers while the index keeps climbing.
The same per-record store-and-forward discipline is what makes MQTT store-and-forward backfill after a connection outage deterministic on any gateway.
Recover the write index after a restart #
Initializing indexbufferfile% to 0 is correct only for an empty buffer. The stored files survive the script; the variable does not. Restarting with pending files and writing 0.txt again silently replaces the oldest unsent event — the exact data-loss mode the buffer exists to prevent.
The recovery function MQTT_CheckLastFileNameOfBuffer% in the published examples scans candidate filenames, takes the number from the highest existing one, and returns that number plus one, returning 0 for an empty buffer. Call it in the initialization section and assign its result to indexbufferfile% before enabling capture. Then test it: create pending files, stop and restart the script, generate one new event, and confirm the new filename follows the highest pending number and every pre-restart payload is byte-identical. If the recovered index has reached MaxNumberBufferFiles%, apply the chosen full-buffer policy — never reset the index to reclaim space.
Replay without a blocking pause #
The final replay routine reads the connection status, opens the next numbered file, reads its payload, publishes it, and retires the file only on a clean publish — paced by the batch-and-acknowledge rule from the worked example, not by a debugger pause:
- Confirm the client status is the connected value (5 in this script family) before replay starts.
- Take the next file in sequence; if none exists, replay is done.
- Read the payload and publish it on the live topic and connection.
- On a clean publish, delete the file; on any error, leave it and retry it on the next pass.
- After each acknowledged batch, check the status again before the next batch — a status drop mid-replay means the batch drained into a dead session.
A fixed timer works as a cruder alternative when the runtime offers no acknowledgement callback, but size it below the bandwidth-derived rate — about 488 messages each second at 2 KB payloads here — and expect slower recovery after long outages. What never works is the breakpoint: it proves the design while someone holds it open and fails the moment the session closes.
For choosing where each record lives and when it counts as delivered end to end, choosing an edge data path for periodic records sets out the storage-side trade-offs that pair with the replay logic above.
Questions asked
Why does pausing at a debug breakpoint let the buffered messages go through?
The pause throttles the publish loop to a rate the runtime and the broker can absorb. It proves the stored payloads and the connection are good, and that the fault is pacing, not content. A breakpoint is acceptable as a one-off diagnostic, never as the running replay design: it sends data only while someone watches the debugger, and it stops entirely when the session ends.
What MQTT connection status value should the replay treat as connected?
In the script family this article describes, the MQTT STATUS keyword returns 5 when the client is connected. Read STATUS immediately before replay starts and again when replay stops, and compare: if the status drops from 5 during a fast replay, the gateway or the broker dropped the session, and the queue drained into a dead connection until the next reconnect.
What happens when the buffer reaches its maximum file count?
The save function logs that the event was not saved and discards the payload, so the oldest data ends where the newest begins: nowhere. Decide the full-buffer policy before the first outage: either size MaxNumberBufferFiles% for the longest connection loss you expect plus margin, or deliberately overwrite the oldest records and accept the gap. Resetting the index silently is not a policy, it is data loss.