Apache PLC4X Tutorial: Stream PLC Tags to MQTT and Kafka

Apache PLC4X Tutorial: Stream PLC Tags to MQTT and Kafka

Apache PLC4X Tutorial: Stream PLC Tags to MQTT and Kafka

Last Updated: November 2026

Every factory pays the same hidden tax. A Siemens line speaks S7, a legacy press speaks Modbus, a packaging cell speaks EtherNet/IP, and a newer robot cell speaks OPC UA. Getting one tag out of each usually means a vendor gateway, a per-tag licence and a Windows box nobody wants to patch. This guide shows the open-source alternative: a plc4x plc to mqtt kafka pipeline, where Apache PLC4X reads every controller through one API and your own service fans the data out to a message broker and an event log.

The timing matters. PLC4X reached 1.0.0 as its current stable release, and that release changed Maven coordinates, tag array syntax, configuration names and security defaults. Most tutorials still show 0.x code that will not compile or resolve against it. Everything below targets 1.0.0, and anything I could not verify against the official documentation is labelled as such.

You will leave with a working mental model of the driver architecture, runnable Java for Modbus and S7 reads and subscriptions, a gateway that publishes to MQTT and Kafka with bounded back-pressure, the Kafka Connect option, and the failure modes that sink real deployments.

What this covers: the fragmentation problem, how PLC4X drivers work, 1.0 migration changes, Modbus and S7 code, the gateway design, Kafka Connect versus embedded publishing, store-and-forward buffering, security, and an honest list of gotchas.

Context and Background

Operational technology never agreed on a wire protocol. Modbus, from 1979, still carries an enormous share of industrial traffic because it is trivial to implement and royalty-free. Siemens controllers speak S7comm over ISO-on-TCP, Rockwell speaks EtherNet/IP with the CIP object model, Beckhoff speaks ADS, and modern assets add OPC UA on top. A plant with five machine builders therefore needs five client stacks to read five temperatures.

OPC UA was meant to end this, and for new equipment it largely has. Our comparison of OPC UA and MQTT Sparkplug B covers where each fits. But OPC UA does not retrofit a 2008 Modbus press or an S7-300 that will run untouched for another decade. For that installed base you either buy a gateway per protocol or write protocol clients yourself.

Proprietary gateways are costly in ways the price list hides. Many license by tag count or connection, so the bill grows with your data ambitions. Each runs on its own host with its own patch cycle, and each becomes a single point of failure that IT did not choose and cannot easily monitor. Four protocols can mean four fragile boxes whose only job is translating wire formats.

Apache PLC4X is the third option. It is an Apache Software Foundation project providing a unified, driver-based API for industrial protocols, with Java as the most complete binding and Go, Python and C implementations alongside. You program against a PlcConnection, and a driver handles Modbus, S7, EtherNet/IP, ADS, OPC UA and others behind it. The difference from a gateway is scope: PLC4X is a library you embed, so it gives you read, write and subscribe, and leaves payload shaping, transport and buffering to you.

That is more work upfront and far more flexible afterwards. It fits an event-driven architecture where PLC data lands in MQTT for the operational namespace and in Kafka for analytics, rather than in one vendor’s historian. If your goal is the namespace itself, read our unified namespace architecture guide; this post is the plumbing underneath it.

One property explains why a single library can cover so many protocols. PLC4X drivers are generated from protocol descriptions rather than hand-written per language, so the Java and Go drivers decode a frame the same way because they descend from one specification. That consistency is the reason a tag decoded correctly in a prototype behaves the same in production, and it is why new protocols arrive as descriptions rather than parallel rewrites.

Reference Architecture: One Gateway, Two Sinks

The core design is an edge gateway process that embeds PLC4X, reads tags from many PLCs on a schedule or by subscription, normalises them into one payload shape, and publishes the same record to an MQTT broker for live consumers and to Kafka for durable replay. PLC4X handles protocols; your code owns shaping, buffering and delivery.

Apache PLC4X architecture for plc4x plc to mqtt kafka streaming from Modbus and S7 PLCs

Figure 1: PLC4X reads heterogeneous PLCs through drivers, a normaliser shapes the record, and a dual publisher feeds MQTT and Kafka.

Figure 1 shows the flow. On the left, Modbus and S7 controllers sit on the OT network. The PLC4X driver layer turns tag addresses into wire frames and wire bytes into typed values. A normaliser attaches asset identity and a timestamp, and a bounded queue decouples slow brokers from the poll loop. A dual publisher then writes to MQTT and Kafka. The key point is that protocol difference ends at the driver layer: everything to its right is protocol-agnostic.

Why the gateway sits in OT, not IT

PLCs have small connection tables and no security model worth the name. Many S7 and Modbus devices accept only a handful of concurrent clients and offer no authentication on the field protocol. So the only host that should talk to them is one gateway, placed on the OT network, which initiates outbound connections through a firewalled boundary to the central broker. That keeps controllers unreachable from the IT side and makes the gateway the single audited crossing point.

This is also why connection reuse matters more than in ordinary client code. If twenty analytics services each opened their own S7 session, the controller would run out of slots and start refusing the control system’s own engineering tools. One gateway holding one session per PLC, and serving everyone through the broker, is both a security and a stability decision.

The three verbs and what they cost the PLC

PLC4X exposes three operations: read, write and subscribe. Reads are the workhorse and cost the PLC one request-response per poll. Subscriptions come in three flavours in the 1.0 API: change of state, cyclic with a duration, and event. Whether a subscription is real push or emulated depends on the driver.

Modbus has no server push, so a Modbus subscription is polling in disguise, and the 1.0 release notes list a plc4j-utils-subscription-emulation module among new artifacts for exactly this purpose. S7-300 and S7-400 support cyclic subscriptions natively per the S7 protocol page, while S7-1200 and S7-1500 are documented as basic PUT/GET read and write without event and alarm services. Always check isSubscribeSupported() on the connection metadata, and plan your polling interval as if you are polling, because on many devices you are.

Why publish to both MQTT and Kafka

MQTT and Kafka solve different problems, and treating them as rivals is the usual mistake. MQTT is a lightweight publish-subscribe protocol: ideal for many small devices, retained last-value messages, and live dashboards. Kafka is a partitioned, replicated log: ideal for replay, stream processing and fan-out to storage with retention measured in days.

Publishing to both from the gateway gives you a live path with last-value semantics and a durable path with replay. If you would rather run the bridge as infrastructure than as application code, our MQTT to Kafka bridge tutorial covers that topology. The trade-off between embedding both publishers in the gateway and bridging downstream is covered in the deeper analysis section below.

What Changed in PLC4X 1.0

Before any code, understand what the 1.0.0 release broke, because it explains most “this tutorial does not work” reports. These points come from the official release notes and download page.

First, the Java baseline moved to Java 21 for the drivers, while the plc4j-api module stays at Java 17 so that alternative driver implementations can target it. Builds moved to Maven 4. If your edge image is on an older JDK, upgrade it before anything else.

Second, Maven coordinates changed. Transports moved from plc4j-transport-* to plc4j-transports-*. Tools became plc4j-tools-*, covering capture-replay, connection-cache and object-property mapping. The old plc4j-scraper was replaced by plc4j-tools-event-pump, and plc4j-scraper-ng was removed without replacement. Any pom.xml copied from a 0.12 tutorial will fail to resolve these.

Third, configuration vocabulary was normalised. Millisecond-valued options now end in -ms, TLS settings sit under a tls. prefix, and old names are rejected rather than deprecated. That is why the S7 option is now cotp.remote-rack instead of the older remote-rack, and why Modbus uses request-timeout-ms.

Fourth, array notation changed everywhere. In 1.0, [n] means a single element and counts are expressed as ranges such as [0..3]. Old forms are rejected with an error naming the new form, which is helpful but will still stop a service at startup if you carry old tag strings forward.

Fifth, security defaults tightened. The OPC UA driver now defaults to the Basic256Sha256 policy instead of no security and refuses to send credentials over an unprotected channel. The plc4x proxy driver defaults to TLS and requires credentials, and the TLS transport verifies that the certificate matches the host. These are good changes, but they mean an OPC UA connection that worked unauthenticated on 0.13 may now fail until you configure certificates.

Finally, connection creation moved to a new factory interface. The current getting-started page obtains connections through PlcDriverManager.getDefault().getConnectionFactory().getConnection(url), which is what the code below uses. The older getConnectionManager() call from 0.x tutorials is not the documented path in 1.0.

Project Setup and Dependencies

You need JDK 21 and Maven. The only mandatory PLC4X artifact is plc4j-api; each protocol is a separate runtime dependency so the jar carries only what you use. That keeps the footprint small on a DIN-rail edge computer with limited flash.

<properties>
  <maven.compiler.release>21</maven.compiler.release>
  <plc4x.version>1.0.0</plc4x.version>
</properties>
<dependencies>
  <dependency>
    <groupId>org.apache.plc4x</groupId>
    <artifactId>plc4j-api</artifactId>
    <version>${plc4x.version}</version>
  </dependency>
  <dependency>
    <groupId>org.apache.plc4x</groupId>
    <artifactId>plc4j-driver-modbus</artifactId>
    <version>${plc4x.version}</version>
    <scope>runtime</scope>
  </dependency>
  <dependency>
    <groupId>org.apache.plc4x</groupId>
    <artifactId>plc4j-driver-s7</artifactId>
    <version>${plc4x.version}</version>
    <scope>runtime</scope>
  </dependency>
  <dependency>
    <groupId>org.eclipse.paho</groupId>
    <artifactId>org.eclipse.paho.mqttv5.client</artifactId>
    <version>1.2.5</version>
  </dependency>
  <dependency>
    <groupId>org.apache.kafka</groupId>
    <artifactId>kafka-clients</artifactId>
    <version>4.0.0</version>
  </dependency>
  <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.17.2</version>
  </dependency>
</dependencies>

The S7 dependency and plc4j-api:1.0.0 coordinates are confirmed on the official getting-started page. The Modbus artifact name follows the same plc4j-driver-<protocol> pattern, but I did not find it spelled out in the 1.0 documentation I could fetch, so confirm it against Maven Central when you build. The Paho, Kafka client and Jackson versions are ones I know to exist; pick newer patch releases if your policy allows.

A practical tip before you touch hardware: you do not need a PLC to follow this tutorial. A Modbus TCP simulator such as pymodbus or diagslave gives you a register map on your laptop, and the Mosquitto broker below covers MQTT. For S7, the Snap7 server library can emulate a data block. Never point an experimental polling loop at a production controller.

For the broker, a minimal Mosquitto 2 configuration is enough for a lab. Version 2 refuses remote connections unless you declare a listener, and anonymous access must be enabled explicitly. This is for a development machine only.

# mosquitto.conf  (lab only: no auth, no TLS)
listener 1883
allow_anonymous true
persistence true
persistence_location /mosquitto/data/
docker run --rm -p 1883:1883 \
  -v "$PWD/mosquitto.conf:/mosquitto/config/mosquitto.conf" \
  eclipse-mosquitto:2

For Kafka, use the quickstart in the official Apache Kafka documentation to start a single KRaft node. Kafka 4.0 removed ZooKeeper mode entirely, so any current quickstart is KRaft-only. If you are still on an older cluster, our Kafka KRaft migration guide explains the upgrade path.

Reading Modbus and S7 Tags

Reading is where the single API pays off. The two examples below differ only in the connection string and address syntax, which is the whole point of using PLC4X for a mixed fleet.

A Modbus read with correct addressing

The Modbus connection string format is modbus-tcp:tcp://host:port?options, where transport and port are optional. Useful options from the protocol page include default-unit-identifier (default 1), request-timeout-ms (default 5000) and default-payload-byte-order (default BIG_ENDIAN). The last one matters enormously, as the gotchas section explains.

import org.apache.plc4x.java.DefaultPlcDriverManager;
import org.apache.plc4x.java.api.PlcConnection;
import org.apache.plc4x.java.api.messages.PlcReadRequest;
import org.apache.plc4x.java.api.messages.PlcReadResponse;
import org.apache.plc4x.java.api.types.PlcResponseCode;
import java.util.concurrent.TimeUnit;

public class ModbusReader {
    public static void main(String[] args) throws Exception {
        String url = "modbus-tcp:tcp://192.168.0.10:502"
                   + "?default-unit-identifier=1&request-timeout-ms=3000";

        try (PlcConnection conn = DefaultPlcDriverManager.getDefault()
                .getConnectionFactory().getConnection(url)) {

            if (!conn.getMetadata().isReadSupported()) {
                throw new IllegalStateException("Driver cannot read");
            }

            PlcReadRequest request = conn.readRequestBuilder()
                .addTagAddress("motorTemp", "holding-register:101:REAL")
                .addTagAddress("runState",  "coil:2:BOOL")
                .build();

            PlcReadResponse response = request.execute().get(5, TimeUnit.SECONDS);

            for (String tag : response.getTagNames()) {
                if (response.getResponseCode(tag) == PlcResponseCode.OK) {
                    System.out.printf("%s = %s%n", tag, response.getObject(tag));
                } else {
                    System.out.printf("%s FAILED: %s%n", tag, response.getResponseCode(tag));
                }
            }
        }
    }
}

Note one detail that trips almost everyone. Modbus addresses in PLC4X are one-based, as in device manuals, and the driver subtracts one before putting them on the wire. So holding-register:101:REAL sends address 100. Whether you meant 100 or 101 depends on whether your vendor manual documents zero-based or one-based numbering, and an off-by-one here reads the neighbouring register and produces plausible, wrong numbers.

Also note the data type. A REAL spans two consecutive 16-bit registers. Coils and discrete inputs support only BOOL; asking for another type returns an UNSUPPORTED response code rather than throwing. Register areas can be written with the prefixes holding-register:, input-register:, coil: and discrete-input:, or the classic 4x, 3x, 0x and 1x notations. Arrays now use the 1.0 range syntax, for example holding-register:20[0..9]:UINT for ten registers.

An S7 read

The S7 connection string is s7://host?options. Rack and slot now carry the cotp. prefix, for example s7://192.168.0.20?cotp.remote-rack=0&cotp.remote-slot=1. Tag addresses follow TIA Portal notation: %DB1.DBX0.0:BOOL is a bit, %DB10.DBW20:INT is a 16-bit integer, %I0.0:BOOL is an input bit and %MD100:DINT is a marker double word. The page also shows a short data-block form, %DB5:10:INT.

import org.apache.plc4x.java.DefaultPlcDriverManager;
import org.apache.plc4x.java.api.PlcConnection;
import org.apache.plc4x.java.api.messages.PlcReadResponse;
import org.apache.plc4x.java.api.types.PlcResponseCode;
import java.util.concurrent.TimeUnit;

public class S7Reader {
    public static void main(String[] args) throws Exception {
        String url = "s7://192.168.0.20?cotp.remote-rack=0&cotp.remote-slot=1";

        try (PlcConnection conn = DefaultPlcDriverManager.getDefault()
                .getConnectionFactory().getConnection(url)) {

            PlcReadResponse r = conn.readRequestBuilder()
                .addTagAddress("setpoint", "%DB1.DBD4:REAL")
                .addTagAddress("running",  "%DB1.DBX0.0:BOOL")
                .addTagAddress("cycles",   "%DB1.DBD8:DINT")
                .build()
                .execute()
                .get(5, TimeUnit.SECONDS);

            for (String tag : r.getTagNames()) {
                System.out.printf("%s -> %s (%s)%n", tag,
                    r.getResponseCode(tag) == PlcResponseCode.OK ? r.getObject(tag) : "n/a",
                    r.getResponseCode(tag));
            }
        }
    }
}

The S7 protocol page states the support matrix plainly. S7-300 and S7-400 have full support, including cyclic subscriptions. S7-1200 and S7-1500 are supported through the basic PUT/GET read and write mechanism, without event and alarm services. S7-200, S7-200 Smart and LOGO are supported when you set controller-type explicitly and, for the S7-200 family, the TSAP values the page describes.

The PUT/GET point deserves emphasis because it is the number-one reason an S7-1200 or S7-1500 integration “connects but returns errors”. Those controllers must be configured in TIA Portal to permit PUT/GET access from a remote partner, and data blocks you read by absolute offset must have optimized block access disabled. Neither the S7 protocol page nor the getting-started page mentions this, so treat it as field knowledge from Siemens’ own TIA Portal behaviour, not as PLC4X documentation. I have not verified it against a specific TIA Portal release here.

Checking response codes properly

The response carries a code per tag, not only per request. A batch read of fifty tags can succeed for forty-nine and fail for one with an invalid address. Treating the request as all-or-nothing hides real signal, and it makes one typo in a tag list silence an entire machine.

The robust pattern is to publish the tags whose code is OK, log the others with the tag name and code, and keep going. In the gateway below this becomes a metric: tags failing per cycle, per PLC. A sudden jump from zero to three usually means a project download changed a data block layout.

Subscriptions instead of polling

The 1.0 getting-started page documents three subscription registrations: addChangeOfStateTagAddress, addCyclicTagAddress (which needs a Duration) and addEventTagAddress. You register a handler on the resulting handle and receive values as they arrive. The sketch below follows that documented shape; as always, check isSubscribeSupported() first.

import org.apache.plc4x.java.api.messages.PlcSubscriptionRequest;
import org.apache.plc4x.java.api.messages.PlcSubscriptionResponse;
import java.time.Duration;

if (!conn.getMetadata().isSubscribeSupported()) {
    throw new IllegalStateException("No subscription support, fall back to polling");
}

PlcSubscriptionRequest sub = conn.subscriptionRequestBuilder()
    .addCyclicTagAddress("temp", "%DB1.DBD4:REAL", Duration.ofMillis(1000))
    .addChangeOfStateTagAddress("alarm", "%DB1.DBX0.1:BOOL")
    .build();

PlcSubscriptionResponse subResp = sub.execute().get();
subResp.getSubscriptionHandle("temp").register(event ->
    event.getTagNames().forEach(t ->
        System.out.println(t + " = " + event.getObject(t))));
subResp.getSubscriptionHandle("alarm").register(event ->
    System.out.println("ALARM " + event.getObject("alarm")));

I derived this snippet from the documented method names rather than compiling it against 1.0.0, so verify the handle and event accessors in your IDE. The design lesson holds regardless: change-of-state subscriptions are cheap for sparse signals such as alarms and state flags, while a cyclic subscription on an emulated driver is just polling with extra steps.

A Gateway That Publishes to MQTT and Kafka

PLC4X gateway sequence for plc4x plc to mqtt kafka showing read, normalise, MQTT publish and Kafka send

Figure 2: One poll cycle, from the PLC read through normalisation to the two acknowledged publishes.

Figure 2 traces one cycle. The scheduler fires, the PLC4X driver issues the read, and the PLC answers with raw values. The gateway then turns the response into a record, hands it to a bounded queue, and a publisher thread writes it to MQTT at QoS 1 and to Kafka with a producer acknowledgement. The loop never waits for a broker on the read path; it waits only on the queue, which is what enforces back-pressure.

The record shape

Decide the payload before writing publishers. A consistent envelope makes downstream consumers dull, which is the goal. This one carries identity, a gateway-side timestamp, per-tag quality, and the values.

{
  "site": "plant1",
  "asset": "press01",
  "ts": "2026-11-09T03:12:44.512Z",
  "tags": {
    "motorTemp": { "v": 71.4, "q": "OK" },
    "runState":  { "v": true, "q": "OK" }
  }
}

The timestamp is the moment the gateway received the response, not the moment the value changed on the PLC, because Modbus and basic S7 reads carry no source timestamp. Say so in your schema documentation, since analysts will otherwise treat it as event time. Per-tag quality lets a consumer distinguish a stale or failed tag from a legitimate value, which matters when a bad address would otherwise publish a default zero.

Topic and key design

For MQTT, build topics from the asset hierarchy: plant1/line2/press01/telemetry. Keep the hierarchy shallow and stable, because renaming a topic later breaks every subscriber. If you plan to adopt Sparkplug B with its spBv1.0/<group>/DDATA/<node>/<device> structure, read our comparison of Sparkplug B and plain MQTT topics first, because Sparkplug adds birth and death certificates and sequence numbers that a plain JSON topic does not have.

For Kafka, use the asset identifier as the record key. Kafka guarantees ordering only within a partition, and keying by asset sends all records for press01 to the same partition, preserving their order. Topics can be per area or one shared plc.telemetry topic; start with one and split only when retention or access control demands it.

The gateway code

The class below holds long-lived connections, polls on a fixed schedule, and pushes records through a bounded queue to a publisher thread. It uses the Paho MQTT v5 client and the plain Kafka producer. It is deliberately compact; production code adds configuration loading, metrics and reconnect backoff.

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.kafka.clients.producer.*;
import org.apache.plc4x.java.DefaultPlcDriverManager;
import org.apache.plc4x.java.api.PlcConnection;
import org.apache.plc4x.java.api.messages.PlcReadResponse;
import org.apache.plc4x.java.api.types.PlcResponseCode;
import org.eclipse.paho.mqttv5.client.*;
import org.eclipse.paho.mqttv5.common.MqttMessage;

import java.time.Instant;
import java.util.*;
import java.util.concurrent.*;

public class Gateway {
    static final ObjectMapper JSON = new ObjectMapper();
    // Bounded queue: when full, the poller blocks briefly and then drops.
    static final BlockingQueue<Map<String, Object>> QUEUE = new ArrayBlockingQueue<>(10_000);

    public static void main(String[] args) throws Exception {
        PlcConnection plc = DefaultPlcDriverManager.getDefault().getConnectionFactory()
            .getConnection("modbus-tcp:tcp://192.168.0.10:502?request-timeout-ms=3000");

        MqttClient mqtt = new MqttClient("tcp://localhost:1883", "gw-plant1-01");
        MqttConnectionOptions mo = new MqttConnectionOptions();
        mo.setAutomaticReconnect(true);
        mo.setCleanStart(false);
        mqtt.connect(mo);

        Properties kp = new Properties();
        kp.put("bootstrap.servers", "localhost:9092");
        kp.put("key.serializer",   "org.apache.kafka.common.serialization.StringSerializer");
        kp.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
        kp.put("acks", "all");
        kp.put("enable.idempotence", "true");
        kp.put("linger.ms", "50");
        KafkaProducer<String, String> kafka = new KafkaProducer<>(kp);

        ExecutorService publisher = Executors.newSingleThreadExecutor();
        publisher.submit(() -> {
            while (true) {
                Map<String, Object> rec = QUEUE.take();
                String body = JSON.writeValueAsString(rec);
                String asset = (String) rec.get("asset");
                MqttMessage m = new MqttMessage(body.getBytes());
                m.setQos(1);
                mqtt.publish("plant1/line2/" + asset + "/telemetry", m);
                kafka.send(new ProducerRecord<>("plc.telemetry", asset, body),
                    (md, ex) -> { if (ex != null) System.err.println("kafka: " + ex); });
            }
        });

        ScheduledExecutorService poller = Executors.newSingleThreadScheduledExecutor();
        poller.scheduleAtFixedRate(() -> {
            try {
                PlcReadResponse r = plc.readRequestBuilder()
                    .addTagAddress("motorTemp", "holding-register:101:REAL")
                    .addTagAddress("runState",  "coil:2:BOOL")
                    .build().execute().get(3, TimeUnit.SECONDS);

                Map<String, Object> tags = new LinkedHashMap<>();
                for (String t : r.getTagNames()) {
                    boolean ok = r.getResponseCode(t) == PlcResponseCode.OK;
                    tags.put(t, Map.of("v", ok ? r.getObject(t) : "", "q", r.getResponseCode(t).name()));
                }
                Map<String, Object> rec = new LinkedHashMap<>();
                rec.put("site", "plant1");
                rec.put("asset", "press01");
                rec.put("ts", Instant.now().toString());
                rec.put("tags", tags);
                if (!QUEUE.offer(rec, 200, TimeUnit.MILLISECONDS)) {
                    System.err.println("queue full, dropping record");
                }
            } catch (Exception e) {
                System.err.println("poll failed: " + e);  // reconnect logic goes here
            }
        }, 0, 1000, TimeUnit.MILLISECONDS);
    }
}

Several choices here are deliberate. The PLC connection is opened once and reused, because opening a connection per poll exhausts the controller’s limited session slots. acks=all with idempotence enabled gives the Kafka path at-least-once delivery with no producer-side duplicates from retries; for stronger guarantees see our Kafka exactly-once semantics guide. Setting cleanStart(false) plus a stable client ID lets the broker keep session state across reconnects.

I wrote this class against the documented APIs of PLC4X, Paho and the Kafka client but did not compile and run it for this article. Treat it as a reference skeleton, run it against the simulators first, and expect to fix an import or accessor name. The behavioural design is the part to copy.

Why a single-threaded poller

Controllers handle requests serially, and one thread per PLC is the easiest way to guarantee you never overlap two requests on one session. For many PLCs, run one scheduled executor task per device rather than one thread per tag. The fixed-rate schedule has a catch: if a read takes longer than the interval, scheduleAtFixedRate bunches up executions afterwards. For slow devices prefer scheduleWithFixedDelay, which waits the full delay after each completion and cannot pile up.

Kafka Connect or an Embedded Gateway?

Decision flow comparing PLC4X Kafka Connect source connector with an embedded gateway for plc4x plc to mqtt kafka

Figure 3: Choosing between the Kafka Connect source connector and an embedded gateway based on where your backbone lives.

PLC4X also ships Kafka Connect connectors, and the choice between them and an embedded gateway is architectural, not cosmetic. Figure 3 walks the decision. If Kafka is your backbone and you want configuration-only ingestion managed with standard Connect tooling, the connector is attractive. If MQTT is your backbone, you need Sparkplug payloads, or you need custom buffering and shaping at the edge, the embedded gateway wins.

What the official docs say about the connector

The Kafka integration page names the classes org.apache.plc4x.kafka.Plc4xSourceConnector and org.apache.plc4x.kafka.Plc4xSinkConnector, and lists the uber jar as plc4j-apache-kafka-1.0.0-uber-jar.jar, built from the plc4x-extras repository. It describes standalone mode for testing, started with bin/connect-standalone.sh config/connect-standalone.properties config/plc4x-source.properties, and distributed mode for production. The source connector relies on the PLC4X scraper logic, and failed reads are backed off with randomised rates.

Here is the part you need to be careful about. The official page does not list the source and sink property names in prose; it points to sample files in the plc4x-extras repository. The REST examples on that page are incomplete, containing a placeholder where the properties should go. I could not retrieve the current 1.0 sample file, so I will not present a connector property list as verified.

What I could verify is an older sample source.properties from the project history, which contained five properties: a name, the connector.class, a topic, a queries string using the pattern test:unused#RANDOM/foo:INTEGER, and a rate in milliseconds. That is a simulated-driver example and may well differ from the current schema, so use it only as orientation.

# Orientation only: an OLD sample from the PLC4X repository history.
# Take the authoritative property list from the plc4x-extras sample
# files shipped with your connector version (plc4x-source.properties).
name=plc-source-test
connector.class=org.apache.plc4x.kafka.Plc4xSourceConnector
topic=test
queries=test:unused#RANDOM/foo:INTEGER,test:another#RANDOM/bar:STRING
rate=2000

The earlier version of this article showed a sources and jobs JSON schema with pollReturnInterval and bufferSize keys. I could not confirm those against the current documentation, so I have removed them rather than risk sending you to a configuration that does not exist. If you adopt the connector, copy the sample from the exact release you install.

The connector in production terms

Whatever the final property names, the operational model is standard Kafka Connect. You deploy a worker, install the plugin jar on every worker node in the plugin path, and manage connectors through the REST API at port 8083. Offsets and status live in Kafka’s internal Connect topics, and you monitor and restart through the same tooling as every other connector.

The documentation says the connector poll rate does not drive the PLC poll rate, which is a useful detail: Connect’s batching cadence and the controller’s scrape cadence are independent knobs, a controller-load decision and a broker-throughput decision respectively. Note also that the page’s description of distributed mode mentions ZooKeeper for connector state, wording that predates Kafka 4.0; in current Kafka, Connect stores its state in Kafka topics and there is no ZooKeeper to run.

The big limitation is what the connector does not give you. It targets Kafka only, so MQTT delivery needs a second hop, such as the bridge in our MQTT to Kafka bridge tutorial run in reverse, and edge store-and-forward during a WAN outage is not part of it. A Connect worker normally lives with the Kafka cluster, so the PLC polling would cross the OT/IT boundary, which contradicts the placement principle above.

The event pump as a middle path

The 1.0 release replaced the old scraper with plc4j-tools-event-pump, and this is the best building block if you want declarative scheduling without Kafka Connect. According to its documentation page, you define connections and batches in YAML, JSON or XML, load them with EventPumpFactory, and receive results through a TagBatchListener with onTagsFetched, onError and onFetchSkipped callbacks. It manages connections, backs off when a device is unreachable, and skips fetches when a device is too slow.

connections:
  - id: press01
    url: "modbus-tcp:tcp://192.168.0.10:502"

batches:
  - id: press-fast
    connectionId: press01
    tags:
      motorTemp: "holding-register:101:REAL"
      runState:  "coil:2:BOOL"
    trigger:
      type: timer
      intervalMillis: 500

This shape follows the documented YAML structure, adapted to a Modbus URL. The page states that the event pump has no built-in sinks, so your listener is where the MQTT and Kafka publish calls go, and that batches are read-only. It also notes that SubscriptionTrigger is a placeholder that throws UnsupportedOperationException, so for now the pump is timer-driven. In practice, the event pump replaces the hand-written scheduler in the gateway above while leaving publishing code unchanged, which is a sensible refactor once you have more than a few devices.

Reliability at the Edge: Buffering and Back-Pressure

Edge deployment of a PLC4X gateway with local disk buffer and store and forward across the OT to IT boundary

Figure 4: The gateway lives on the OT network, buffers locally, and forwards through a firewalled boundary.

Figure 4 shows where the gateway belongs. It sits on the OT VLAN next to the controllers, holds a local buffer, and reaches the central MQTT broker and Kafka cluster through a firewalled DMZ. When the link drops, the gateway keeps reading the PLC and persists messages locally, then replays them in order when the link returns.

Memory queue versus durable buffer

The ArrayBlockingQueue in the gateway code survives a slow broker but not a process restart or a long outage. Ten thousand records at one record per second per asset is about 2.8 hours for one asset, but only a minute or so for a plant publishing a hundred assets at ten Hz. Size the buffer against your worst realistic outage and your total rate, and write the arithmetic down.

For outages longer than memory allows, spill to disk. Options include an embedded queue such as a memory-mapped file queue, SQLite in WAL mode, or letting the MQTT client persist unsent messages. Whatever you choose, drain in order and tag replayed records so consumers can distinguish history from live data. Our MQTT store-and-forward guide compares these buffering strategies in depth.

Bound everything and choose what to drop

An unbounded queue turns a slow broker into an out-of-memory kill, which takes down polling and the buffer together. Bound every buffer, and decide in advance what to sacrifice when full. For process telemetry, dropping the oldest samples is usually right because the newest value matters most; for alarms and counters, dropping is unacceptable and you should block or spill instead.

A sensible split is two queues. Alarm and state-change records go to a durable, never-drop queue, and high-rate analogue samples go to a bounded drop-oldest queue. This costs a little code and avoids the worst outcome, which is losing the one alarm that explains the incident.

Delivery semantics end to end

MQTT QoS 1 gives at-least-once delivery between the gateway and the broker, meaning duplicates are possible after a retransmit. Kafka with acks=all and idempotence prevents duplicates from producer retries but not from your own replay logic. If a crash happens after publishing but before you mark a record as sent, the replay will duplicate it.

The practical answer is idempotent consumers. Include a monotonically increasing sequence number per asset in the record, and let consumers discard anything at or below the last number they processed. That is cheaper and more robust than chasing exactly-once across an unreliable network.

Securing the Pipeline

Industrial protocols were designed for isolated networks, so security is something you add around PLC4X, not something it provides on the field side. Modbus TCP has no authentication or encryption in the base protocol, although the PLC4X Modbus page lists tls and tls-psk transports for devices that support them. S7 over ISO-on-TCP is similarly unauthenticated on most deployed controllers.

That makes network placement your primary control. Keep PLCs on a segmented OT network, allow only the gateway to reach them, and permit only outbound connections from the gateway to the broker tier. The IT side should never initiate a session toward a controller. For zone and conduit thinking, the IEC 62443 series is the standard reference.

On the outbound side, secure what you control. Use TLS on both MQTT and Kafka connections, give the gateway its own broker credentials with publish rights limited to its own topic prefix, and give its Kafka principal write access to only the telemetry topic. A compromised gateway should be able to inject bad telemetry for its own assets and nothing more.

The 1.0 release moved defaults in the right direction for the protocols that support security. Its notes list the OPC UA driver defaulting to Basic256Sha256 and refusing to send credentials over an unprotected channel. If you ingest OPC UA through PLC4X, review OPC UA certificates and trust lists before the first connection, because trust-list handling is where migrations usually stall.

Lastly, protect the writes. PLC4X can write to controllers, and a gateway that only needs telemetry should not have a write path at all. Enforce read-only use by design: do not register write requests, and where the protocol allows it, use a PLC account or Modbus configuration that rejects writes.

Trade-offs, Gotchas, and What Goes Wrong

Byte and word order corrupt data silently. A Modbus REAL spans two registers, and vendors disagree on which word comes first. The driver’s default-payload-byte-order supports BIG_ENDIAN, LITTLE_ENDIAN, BIG_ENDIAN_BYTE_SWAP and LITTLE_ENDIAN_BYTE_SWAP, and a per-tag {byte-order: 'LITTLE_ENDIAN'} override exists. If a temperature reads as an absurd number, suspect word order before wiring. Validate against the PLC’s own display before trusting any decoded tag.

One-based Modbus addressing causes off-by-one reads. The driver subtracts one from register addresses, so the address you write is the manual’s address, not the wire offset. Check one known register against a diagnostic tool. The extended-register area is the documented exception, being zero-based and passed through unchanged.

Request size limits split your batches. The Modbus options max-registers-per-request (default 125) and max-coils-per-request (default 2000) cap how much one frame carries. A long register range becomes several requests, which affects timing and consistency. Values read in separate frames are not an atomic snapshot of the machine.

Controller session limits are real. Opening a connection per poll, or letting several services connect to the same PLC, exhausts slots. Symptoms are intermittent connection refused errors that correlate with deploys. Hold one connection per controller in one process.

S7 access settings block reads. On S7-1200 and S7-1500 you typically need PUT/GET permitted and, for absolute addressing, optimized block access disabled in the project. This is field experience from Siemens’ behaviour, not from PLC4X documentation, and I have not verified it against a specific TIA Portal version.

Timestamps are gateway time. Basic reads carry no source timestamp, so jitter and queueing delay get baked into event time. For motion control or sequence-of-events analysis, use hardware timestamping or controller-side buffering, not a polling gateway.

Polling frequency is not free. A 100 ms poll across hundreds of Modbus registers can saturate a slow serial-to-TCP converter. Match the interval to the physics of the signal, and prefer change-of-state subscriptions for sparse, event-like data on drivers that truly push.

Upgrade pain from 0.x is real. The 1.0 changes to coordinates, option names, array syntax and the Java baseline mean a mechanical upgrade will break at startup. Budget a day for a small gateway and test every tag string. The positive side is that old forms fail loudly with an error naming the new form instead of misbehaving.

Do not use this for control. A Java gateway on a general-purpose OS has garbage collection pauses and no real-time guarantees. It is for monitoring and analytics. Closed-loop control belongs in the PLC. If you need deterministic behaviour at the edge, see our real-time edge gateway tutorial.

Practical Recommendations

Start small and prove the data before scaling the architecture. Pick one PLC, one hundred tags at most, and a simulator or a read-only test window. Confirm addresses, types and word order against the controller’s own display, then add publishing.

Prefer the embedded gateway when MQTT is your operational backbone or when you need edge buffering, and prefer Kafka Connect only when Kafka is the single backbone and you accept its limits. Use the event pump for scheduling once you manage more than a handful of devices, and keep publishing code in your listener so the transport stays swappable.

Treat the record schema as a contract. Version it, include per-tag quality and a sequence number, and document that timestamps are gateway-side. Agree topic names with the consuming teams before the first message flows, because a rename later is a coordinated outage.

If your plant is mostly Modbus retrofit, our brownfield Modbus to unified namespace comparison weighs PLC4X against commercial edge gateways and shows when buying beats building.

Pre-production checklist:

  • JDK 21 on the edge image and 1.0.0 coordinates in the build.
  • One long-lived connection per PLC, reconnect with backoff.
  • Per-tag response code checked and exported as a metric.
  • Bounded queues, with a durable path for alarms and a drop-oldest path for analogue samples.
  • Idempotent consumers with a per-asset sequence number.
  • TLS and least-privilege credentials on MQTT and Kafka; no write path to the PLC.
  • Gateway on the OT network, outbound-only through a firewalled boundary.
  • Alerts on queue depth, publish failures and tags failing per cycle.

Frequently Asked Questions

What is Apache PLC4X used for?

Apache PLC4X is an open-source library that gives applications one API for reading, writing and subscribing to PLC data across protocols such as Modbus, S7, EtherNet/IP, ADS and OPC UA. Instead of integrating a separate client per vendor, you change a connection string and a tag address. It is typically embedded in an edge gateway or data pipeline that forwards controller data to brokers, historians or analytics systems.

Which version of PLC4X should I use in 2026?

Use the 1.0.0 release, which the official download page lists as the current stable version, with 1.1.0 shown as a pre-release. Version 1.0.0 requires Java 21 for the drivers, keeps the API module at Java 17, and renames several Maven artifacts and configuration options. Code written for 0.12 or 0.13 needs updating before it will build or connect.

Can PLC4X write directly to Kafka?

PLC4X ships Kafka Connect source and sink connectors, named Plc4xSourceConnector and Plc4xSinkConnector, that run inside a Connect worker. Alternatively, embed the PLC4X API in your own service and use a Kafka producer, which gives you control of payload shape and buffering. The connector is configuration-driven; the embedded approach is more flexible, especially if you also need MQTT.

How do I read an S7 PLC with PLC4X?

Add plc4j-driver-s7 as a runtime dependency, open a connection such as s7://192.168.0.20?cotp.remote-rack=0&cotp.remote-slot=1, and build a read request using TIA-style addresses like %DB1.DBD4:REAL. Check each tag’s response code. S7-1200 and S7-1500 controllers use PUT/GET access, which generally has to be enabled in the engineering project before reads succeed.

Does PLC4X support MQTT or Sparkplug B directly?

PLC4X is a protocol client for talking to controllers, not an MQTT publisher, so you add an MQTT client such as Eclipse Paho and publish the values yourself. Sparkplug B is a payload and topic specification layered on MQTT. You encode PLC4X values into Sparkplug metrics in your own code or with a Sparkplug library, handling birth and death messages and sequence numbers.

Should I poll or subscribe to PLC tags?

Use subscriptions where the driver provides true push, such as change-of-state on capable S7 controllers or OPC UA, because they reduce load for sparse signals. Use polling for Modbus, which has no native push and where subscriptions are emulated by polling anyway. Check isSubscribeSupported() and size your interval to the signal’s dynamics and the controller’s capacity.

Further Reading

By Riju — about

1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *