IMD SolutionComputing LibraryShop main store

How-to

PLC MQTT failover to a redundant second broker

Edge computing and IIoT Published 8 min read

Short answer

Yes, with limits. A PLC MQTT client can switch to a second broker without anyone touching it, provided the library supports a second broker destination and you program the trigger, the reconnect sequence and the subscriber-side recovery yourself. Two independent brokers share no sessions, subscriptions or retained messages, so this is failover with a computable gap, not hot standby.

On this page
  1. What a second broker gives you, and what it does not
  2. Check the library before you build anything
  3. Prepare both broker destinations
  4. The failover sequence, step by step
  5. Switch time for a 30 s keepalive client with three 10 s retries
  6. Bring the subscribers with you
  7. Test the failure modes you expect
  8. Questions asked

Yes — a PLC publishing over MQTT can carry on by itself on a second broker, but only because you built the switch. The client library must accept a second broker destination, and your program has to detect the failure, close out the dead connection, connect to broker 2 and restore the session. Two independent brokers share nothing, so this is failover with a gap you can compute and measure, not hot standby. Keep interlocks and machine control independent of broker availability: redundant telemetry is not a safety function. Below: the architecture decision, the library checks, the sequence, and one switch-time calculation with the numbers you control.

What a second broker gives you, and what it does not #

The PLC stays a client in this design. It does not need to become a broker; it needs two configured broker destinations and program logic that chooses between them. What no client logic can do is merge the two servers into one service: an MQTT session, its subscriptions and its retained messages live on the server where they were created, and nothing in the protocol copies them across. MQTT 3.1.1 ties cleanup to keepalive too — the broker must close a connection that has seen no packet for one and a half times the negotiated keepalive — so a client that vanishes leaves its session behind on broker 1 until that timer expires.

Hot standby means the backup holds synchronized state at all times. Two brokers installed side by side are not that. A bridge — two Mosquitto brokers forwarding chosen topics to each other — keeps a warm copy of the data, but it is replication you configure, queue and test, with loop-prevention rules of its own.

Arrangement What moves at failure What you do not get
One broker, automatic reconnect Client retries the same destination No service while that broker is down
Two brokers, client failover Client selects broker 2 after a trigger you define Shared session, subscription or retained state; a gap you must measure
Bridged pair or broker cluster Topics replicate, or one endpoint survives Replication behavior belongs to the platform; verify state handling, not just connectivity
Client connected to both at once Data reaches two receivers concurrently Duplicate handling and doubled connection resources to design

The decision: if the process tolerates seconds to about a minute without telemetry, build client failover. It lives in the PLC program you already maintain, and it fails in ways you can bench-test. Reserve clusters and bridges for a gap budget near zero.

Check the library before you build anything #

Confirm the library exposes two broker connections with separate status and error outputs. Multiple destinations are usually supported; automatic switchover is not a library feature to assume — it is logic you write and commission unless the release notes say otherwise. Follow the same path you would to set up the MQTT Client SL library on a CODESYS controller: one broker, publish and receive proven, before redundancy enters the picture.

Match the library revision to the controller. In current vendor stacks a newest release sometimes supports only the newer controller family, and TLS support can differ between families in the same range; the compatibility list for the exact revision decides, not the family name. If broker 2 sits across an untrusted network, both brokers get TLS and the certificate handling your controller supports.

Keep MQTT and Sparkplug separate. A generic MQTT library does not become Sparkplug B by publishing to similarly named topics. If the receiver expects Sparkplug, prove birth and death behavior in an interoperability test, or put a gateway that implements it explicitly in the path.

Prepare both broker destinations #

Give both brokers identical client-facing configuration: same client ID — legal, because the servers are independent — same credentials, same topic permissions, same will message. Commission each broker alone from the PLC, publishing and subscribing with the final credentials, before any switching logic runs.

Place broker 2 so it shares no failure mode with broker 1: different host, different power feed, different switch. A second broker process on the same machine survives a crashed process, not a dead machine — which is the case you are designing for. When the standby lives at the plant rather than in the cloud, a fanless industrial mini PC in another cabinet is a common host. The placement trade-offs are the ones behind running an MQTT broker in the PLC or on a separate device: separation of failure modes is the whole point.

Know whether each broker persists sessions and retained messages across a restart; that decides what subscribers see when broker 1 returns.

The failover sequence, step by step #

  1. Commission both brokers singly, with final credentials, topics and wills. Redundancy testing starts after both paths work alone.
  2. Define the unhealthy condition from the library's connection status and error outputs, and verify in the bench test that a stopped service and a powered-off host both produce it. A dead host sends nothing, so detection comes from your supervision, not the network.
  3. Set the trigger as numbers: fail over after N failed reconnect attempts or T seconds unhealthy, whichever comes first. One rule, one owner, written down.
  4. Gate the logic so no connect operation starts while one is active, and close the failed connection exactly the way the library requires. Half-open connections are how PLC communications blocks get stuck.
  5. Switch the destination, connect to broker 2, and rebuild the session: it is empty, so re-subscribe every topic, re-publish retained state, and send the full birth sequence if you run Sparkplug.
  6. Decide the gap policy explicitly: backfill from controller memory, or resume with current values. Either way the receiving system must know a hole exists.
  7. Fail back deliberately — manual command or a hold of several minutes, never the first successful ping of broker 1 — or the client bounces while broker 1 restarts, doubling reconnects and duplicates.
  8. Record the measured gap from the subscriber's timestamps. That number, not the estimate, is what you quote.

Switch time for a 30 s keepalive client with three 10 s retries #

Inputs, all of them yours to set:

  • Keepalive: 30 s, negotiated with both brokers.
  • Supervision timeout on an unanswered ping: 5 s, set in the PLC program. This is the example's assumption about the library; the outage test replaces it with the measured value.
  • Reconnect policy on broker 1: one attempt every 10 s, each allowed 5 s of connect timeout, failover after 3 failed attempts.
  • Broker 2 one switch hop away on the plant LAN: about 1 s to connect.
  • Session restore after connect, subscriptions plus birth sequence: about 1 s.

The rule in words: the gap is the time to notice the failure, plus the time spent proving broker 1 is gone, plus the time to rebuild the session on broker 2. Size it for the quiet case — no publish outstanding — because with traffic flowing the publish timeouts notice the failure sooner.

The arithmetic:

  • Notice: the keepalive expires at 30 s, and the unanswered ping costs 5 s more: 30 s + 5 s = 35 s.
  • Prove: three attempts at 5 s each, separated by two 10 s waits: (3 × 5 s) + (2 × 10 s) = 35 s, ending at 70 s.
  • Rebuild: 1 s to connect plus 1 s to restore.
  • Total: 35 s + 35 s + 1 s + 1 s = 72 s.

If the dead host answers with a TCP reset instead of silence, the attempts cost nothing and the gap shrinks; size for the silent case.

Decision: a line that tolerates a 90 s telemetry hole ships this configuration with margin. A 30 s requirement changes two numbers you own — a 10 s keepalive and a trigger after one failed attempt give 10 s + 5 s + 5 s + 1 s + 1 s = 22 s — at the cost of more frequent pings, which is trivial traffic. Below about 5 s, client failover is the wrong tool: use a broker platform whose endpoints share state, or buffer locally and forward on recovery.

Bring the subscribers with you #

A PLC that has moved to broker 2 is invisible to a SCADA or historian still subscribed to broker 1; the switch is half done until every consumer follows. Give the receiving system the same two destinations and the same trigger, and put its connection state on the operator screen.

Alarm on data age, not on connection state. A retained last-known value on broker 2 is only as fresh as the last publish before the failure, and after failback QoS 1 delivery can repeat messages — at-least-once is the contract — so downstream logic discards duplicates by timestamp. For Sparkplug, the retained STATE message and its will are per-broker facts: the rules behind why a broker rejects your Sparkplug client over its STATE will apply independently on each server, and a STATE left on broker 1 tells subscribers on broker 2 nothing.

Test the failure modes you expect #

Run each case and record the gap, the duplicate count and the subscriber state, all from timestamps:

  • Stop the broker 1 service: the clean case; sockets close and clients fail fast.
  • Power off the broker 1 host: the case that motivated this design; nothing is sent, and detection rests on your timers.
  • Pull the network path between PLC and broker 1: broker down and path down must produce the same recovery.
  • Fail back under load and confirm the historian does not double-store the overlap.

If the client never reaches either broker at all, that is a commissioning fault, not a failover fault — fix a PLC MQTT client that never reaches your broker first, then test redundancy against a working path.

Questions asked

Is a second broker the same as hot standby?

No. Hot standby means the backup holds synchronized state and takeover is invisible; two independent brokers keep separate sessions, subscriptions and retained messages, so the switchover shows up as a gap in the data. Build it as failover and judge it by the measured gap, not by an availability label. True standby behavior comes from a broker platform with replicated state, selected and verified as such.

What happens to messages sent during the switch?

Messages already accepted by broker 1 sit in its queues for subscribers still connected to it; nothing forwards them to broker 2 unless you built a bridge that does. Publishes the PLC attempts while between brokers fail at the client, unless your library buffers and replays them. Either buffer in the controller or resume with current values and mark the hole.

How do I stop the SCADA showing stale data after a failover?

Give the receiver both destinations and the same trigger as the PLC, put its connection state on the operator screen, and set a data-age alarm on the tag itself just above your measured gap. The trap is a dashboard calmly showing a retained value that is minutes old; an age alarm catches what the connection icon misses.

Should the client switch back to broker 1 automatically?

Not on the first sign of life. A restarting broker can accept connections before its persistence, bridges or downstream links are ready. Use a manual command or a hold of several minutes, and rebuild the session on failback exactly as on failover: the return trip needs its own outage test, not an assumption of symmetry.

Does Sparkplug B change the failover design?

Yes. The client must send its full birth sequence after connecting to broker 2, the retained STATE and its will behave independently per broker, and a primary host arrangement is a failover layer of its own on top. Some PLC MQTT libraries do not implement Sparkplug at all; prove that with an interoperability test, or route through a gateway that does, before you commit the architecture.

Keep reading

  • How-to

    Bridging OPC UA PLC data to MQTT with an edge PC

    Keep the OPC UA server on the PLC side and give MQTT publishing its own role on a separate edge PC that acts as the OPC UA client and MQTT publisher. Commission the two links independently — first a verified tag read, then a verified subscriber message — and only then widen the tag set.

    Edge computing and IIoT

  • Comparison

    PLC MQTT direct publishing versus an IoT gateway

    For publishing process data to an MQTT broker for web monitoring, put the MQTT client in a gateway and leave the S7-1500 out of broker session logic. Keep the LMQTT_Client block in the PLC only when publication must be coordinated with control logic or the gateway cannot meet your topic, payload and delivery requirements. A green MQTT status proves the broker connection only, never the S7 data behind it.

    Edge computing and IIoT

  • How-to

    Sending PLC data to an IoT hub without custom software

    You do not need custom software to move PLC data to an IoT hub: a configurable edge package with an S7, Modbus TCP or EtherNet/IP driver, a channel mapping and an MQTT publisher replaces hand-written acquisition code. Verify two things before you commit: the driver covers the protocol your controller actually speaks, and the publisher covers the destination's authentication and message format. Software still does the work — you configure it instead of writing it.

    Edge computing and IIoT