IMD SolutionComputing LibraryShop main store

Troubleshooting

Why Telegraf's MQTT consumer keeps disconnecting and reconnecting

Edge computing and IIoT Published 7 min read By IMD Solution engineering team

Short answer

A Telegraf MQTT consumer that reconnects within seconds is being disconnected, not dropping on its own: the broker or the path closes the session. Four closers explain a repeating loop: a TCP reset, a duplicate client_id displacing the session, a broker refusal at connect, or keepalive expiry at one and a half times the negotiated interval. Capture Telegraf, broker and TCP records together, read the close reason, then fix in order: client ID, broker, network, version.

On this page
  1. Is the break on the MQTT connection or on the InfluxDB output?
  2. What do you capture before changing any setting?
  3. Why does the fixed client ID start a disconnect loop?
  4. Why does the broker close the session right after TCP connects?
  5. How do you prove keepalive expiry with the arithmetic?
  6. Is Telegraf 1.20.4 itself the fault?
  7. What order do you apply the fixes in?
  8. Questions asked

Telegraf's MQTT consumer that reconnects within seconds is not losing network on its own schedule; something is closing the session. On this installation the consumer subscribes to vdcs/system/+ at tcp://172.29.60.10:1883 under the fixed identity telegraf_system_resource_art, while the writes to InfluxDB at http://172.29.60.9:8086 travel a separate HTTP connection that never sets the MQTT session's lifetime. Four closers explain a repeating loop: a TCP reset on the path, a duplicate client_id displacing the session, a broker refusal at connect, or keepalive expiry. Capture the close reason first, then fix in the order given below.

Is the break on the MQTT connection or on the InfluxDB output? #

The repeating break sits on the MQTT path to tcp://172.29.60.10:1883, not on the HTTP path to http://172.29.60.9:8086, whenever Telegraf logs connection lost or EOF; missing points with a quiet log point at the output instead. Two independent transactions are involved. The consumer holds one TCP session: it connects, subscribes to vdcs/system/+, and receives publications. The output side batches accepted metrics (metric_batch_size at 3000) and flushes them on its own interval to InfluxDB, and that flushing never opens, holds, or closes the MQTT session.

The signature of the MQTT-side break in the Telegraf log is Error in plugin: connection lost: EOF from the consumer. If the session stays up and points are still missing, the fault is on the output side — the namepass filter, the bucket, the token, or a write error — and the investigation continues where the Telegraf MQTT consumer connects but writes no data to InfluxDB. The similar address prefixes of the two destinations prove nothing about subnets; treat them as two separate paths.

What do you capture before changing any setting? #

Capture three timestamp-aligned records first: Telegraf's debug log, the broker's log, and a TCP capture between the Telegraf host and the broker, because the endpoint that sends the close or reset names the path you work on next.

  1. The Telegraf debug log with timestamps on — this configuration already runs with debug = true, so the connect, subscribe, and connection lost lines are being written now.
  2. The broker's log with timestamps: it states why it closed a session — a takeover, refused credentials, a timeout — and names the client ID involved.
  3. A TCP capture on the Telegraf host, filtered to the broker's address and port, recording which side sends the FIN or RST and whether retransmissions accumulate first.
  4. One time base: confirm both hosts pull time from the same NTP source, or the three records cannot be aligned to the second.

Read them together: a reset with no matching broker entry points at a path device; a broker FIN with a logged reason is a broker decision; unanswered packets and retransmissions are network loss; a clean connect followed by a close within one round trip is a refusal. A successful ping verifies neither the listener nor an established session, so it is not evidence either way.

Why does the fixed client ID start a disconnect loop? #

A second process or host connecting with the same client_id, here telegraf_system_resource_art, makes the broker drop the older session each time, so two auto-reconnecting instances can hand the session back and forth every few seconds. MQTT identifies a session by its client identifier, and the specification requires the broker to disconnect the existing client the moment a second connection presents the same identifier. Telegraf reconnects automatically, so a service instance plus a forgotten manual test run, a host agent plus a container, or primary and standby machines will seize the session in turn.

The broker log then shows the same identity arriving from two sources, alternating. Search the service manager, containers, scheduled jobs, and any interactive test process for a second copy of that ID; before stopping one, confirm which instance the live dashboard actually reads, so the spare is the one you stop. Keep exactly one live instance per client_id and give concurrent collectors distinct fixed IDs — the loop ends the moment the second connection stops.

Why does the broker close the session right after TCP connects? #

When the TCP handshake completes but the session still ends within a second or two, the close reason is in the broker log: an authentication or authorization refusal, a rejected identifier, or a policy limit on that listener. Refusals happen at connect time — wrong credentials, an ACL that denies the subscribe to vdcs/system/+, an identifier the broker's policy refuses (the case where Mosquitto 2.0 rejects a Telegraf MQTT output identifier), or a listener that drops the session after accepting it. The shape is distinctive: the handshake succeeds every time, the MQTT CONNECT goes out, the close follows within a round trip, and Telegraf retries into the next cycle.

Open the broker log at the disconnect second and read the named reason; fix that credential, ACL, or policy, then watch one full connect cycle with the subscription accepted. A refusal always names itself in the broker log; if the log instead shows the session accepted and subscribed, the close came from the network path or from keepalive, which comes next.

How do you prove keepalive expiry with the arithmetic? #

MQTT lets the broker close any session that stays silent for 1.5 times the negotiated keepalive, so a capture showing a close at that exact offset after the last control packet proves expiry rather than a network fault. The client declares a keepalive interval in its CONNECT packet, and the specification's grace is a fixed multiple of that interval; the multiplier is not adjustable. The configuration shown sets no keepalive, so the effective value is whatever the plugin put on the wire — read it from the CONNECT packet in the capture, not from assumptions.

Worked example, illustrative: the capture shows a keepalive of 30 s. The broker's grace is 30 s × 1.5 = 45 s. The client's last control packet leaves at 10:15:02 and the broker's FIN arrives at 10:15:47 — a gap of exactly 45 s — so the close is keepalive expiry, and the question becomes why the client went silent. Move either input and the close moves with it: a keepalive of 60 s gives a 90 s grace, and a loop that repeats in a few seconds can only be expiry if the CONNECT packet itself shows an interval near two seconds.

A stateful firewall or NAT with an idle timeout produces a similar shape but no close reason in the broker log. For that case keep the client's grace below the firewall's idle timeout, which means a shorter keepalive, not a longer one. Expiry proven: repair what stalled the client, or set the keepalive to fit the path, then confirm the next capture shows control packets inside the grace window.

Is Telegraf 1.20.4 itself the fault? #

Telegraf 1.20.4 (git: HEAD 34ad5aa1) is the client under test, but the version alone proves no defect: three issue reports describe this plugin losing sessions and failing to recover, and none names your build as confirmed affected. Issue 16293 on the Telegraf tracker describes frequent disconnects with Telegraf itself driving the library's connect and reconnect sequence; issue 8722 describes a consumer that reconnects after a network interruption but then only collects timeouts until Telegraf is restarted — one candidate for the silent client in the keepalive arithmetic; issue 7648 covers connections to a containerized broker that fail and never recover.

Save the active configuration; record the executable, broker, and protocol versions; then run a controlled comparison — same broker, subscription, payloads, and network path — with the old and new clients never sharing the client ID at the same time. Take the replacement release only from the vendor's distribution channel, and re-read the consumer's documented options for the release you pick. While the loop persists, protect the data at the sending end, as described where buffering MQTT messages while the broker connection is down.

What order do you apply the fixes in? #

Apply the fixes in one order: stop the competing client ID first, then correct what the broker log names, then the network path, and only then run the version comparison, because each earlier step removes a cause the later steps would blur. The decision for each case:

  • One identity from two sources in the broker log: keep one instance per client_id — stop the spare or give the second collector its own fixed ID; the loop ends with the second connection.
  • A named refusal at connect: correct the credential, ACL, or listener policy the log names, then confirm one clean connect with the subscription accepted.
  • Silence, then a close at the grace offset: repair the stalled client or set the keepalive to fit the path, then re-capture.
  • Retransmissions with no broker close reason: the path is dropping the flow — route, firewall state, or link errors; fix the path device, not Telegraf.
  • All records clean and the pattern persists: run the controlled version comparison, giving old and new clients distinct IDs so the test cannot cause takeovers itself.
  • Missing data with a stable session: the fault is the output side, and the loop was never the problem.

In every case the aligned records decide, not the interval between reconnects: the reconnect period is the symptom, the close reason is the diagnosis.

Questions asked

Does a bigger metric buffer protect the data during these disconnects?

No. The buffer sits on the output side: it holds metrics already received while the InfluxDB write path is down, and it has no effect on the MQTT session. If your publishers deliver one metric every 2 s, the configured buffer of 30000 metrics covers 30000 × 2 s = 60000 s, about 16.7 hours of write outage. During the loop the session still flaps; only buffering at the sending end protects the data path.

Should the fixed client ID be removed so a random one is generated?

Not for the production collector. A random ID is regenerated at every start: it prevents takeover collisions, but it also abandons any session state the broker queued for the old ID and makes the broker log harder to follow across restarts. Uniqueness stops the loop and stability keeps the session traceable, so each concurrent collector gets its own fixed, distinct ID instead.

How long must the capture run to be conclusive?

Long enough to hold at least two full disconnect cycles, so the gap before each close can be compared with the keepalive arithmetic. With a loop that repeats within seconds, ten minutes of aligned Telegraf, broker and TCP records is enough; rare breaks need the capture running across the quiet period plus two events. Confirm both hosts use the same NTP source first, or the timestamps will not line up.

Does a broker running in a container change the diagnosis?

It adds one suspect. One issue report describes connection failures against a containerized broker that never recover until restart, and a broker container that restarts closes every session each time, which reaches the client as a connection lost message. Check the container's restart count and published port mapping before blaming the network, and read its log the same way as a host-installed broker.

Keep reading

  • Explainer

    ThingsBoard concurrent MQTT sessions per device explained

    ThingsBoard admits one concurrent MQTT session per device token by default, so a second client such as the IoT Gateway displaces the first, for example a Node-RED telemetry publisher. Set ACTORS_MAX_CONCURRENT_SESSION_PER_DEVICE to 2, keep the client identifiers distinct, and let only one session subscribe to RPC or attribute updates.

    Edge computing and IIoT

  • Troubleshooting

    Why a Mosquitto broker logs malformed packet on a PLC MQTT client

    The malformed packet line is the broker's disconnect notice: Mosquitto received bytes from that client that do not decode as MQTT and closed that connection. It is a broker-side message, not a controller diagnostic. Make every client ID unique, correlate the line with the controller's Success, Error and Error Code status tags at the same attempt, then capture from the enable-bit trigger and decode the CONNECT before assigning a cause.

    Edge computing and IIoT

  • Troubleshooting

    Embedded MQTT client won't reconnect after a broker restart

    The sketch, not the broker, is at fault: it holds a half-open TCP socket from before the restart and calls connect() on it again. Confirm the broker with a second client, print client.state() after each failed connect to branch between a stale socket (negative) and a session refusal (positive), call client.disconnect() before every attempt, and space failed attempts about 5 seconds apart on a millis()-based timer.

    Edge computing and IIoT

Telegraf 401 on database creation failed: check the listener