Skip to content

eaxPLC runtime architecture

eaxPLCExplanationFreeProView as Markdown

Migrated page, not yet verified against the current code. Treat values, paths and examples as indicative until this notice is removed.

eaxPLC is a native Go IEC 61131-3 SoftPLC execution engine and embedded industrial Web Studio. It delivers sub-millisecond deterministic real-time control (1000 Hz / 1ms cycle target) with zero runtime heap allocations during cyclic logic execution.

The eaxPLC Studio structured text editor with a reactor heating program and the live value of each variable next to the code. The eaxPLC Studio structured text editor with a reactor heating program and the live value of each variable next to the code.

eaxPLC Studio: the Structured Text editor with live values next to the code.

The runtime is one process. The diagram shows its parts and what passes between them; the sections below take them one by one.

System architectureThe parts of the eaxPLC runtime
The parts of the eaxPLC runtimeOne process holds the runtime server, the compiler, the scan thread, the process image, the fieldbus drivers and the telemetry worker. The Web Studio in a browser and the outside clients reach the runtime through its server; the field devices are reached through the fieldbus drivers. Only the scan thread reads and writes the process image while the PLC runs: a new program, an outside write and a reader of live values all wait for a cycle boundary.Web Studioin a browser, servedby the runtimeRuntime serverHTTP and NATS API,OPC UA, Modbus TCPOutside clientsover OPC UA, ModbusTCP and NATSCompilerStructured Text tobytecodeScan threadone locked OS thread,one set per cycleProcess image%I, %Q and %MTelemetry workerchanges found off thescan thread; feedsthe cycle recorderFieldbus driversa worker per device,never waited forField devicesModbus TCP, EtherNet/IP,EtherCAT, CANopendeploylive valuesCMDwritesprogram textprogramsetCMDqueued writes,forcesreads,writesinputsto %ICMDoutputsfrom %QinputsCMDoutputscopy of the program'smemory, each cycle
Everything meets the scan thread at a cycle boundary: the scan never waits for the network, the Web Studio or a deploy.
  • Service or process
  • Data store
  • Field equipment
  • External system
  • Data or telemetry
  • Command to equipment
  • Configuration or deploy
Read as text

One process holds the runtime server, the compiler, the scan thread, the process image, the fieldbus drivers and the telemetry worker. The Web Studio in a browser and the outside clients reach the runtime through its server; the field devices are reached through the fieldbus drivers. Only the scan thread reads and writes the process image while the PLC runs: a new program, an outside write and a reader of live values all wait for a cycle boundary.

Parts

  • Web Studio (service or process): in a browser, served by the runtime
  • Runtime server (service or process): HTTP and NATS API, OPC UA, Modbus TCP
  • Outside clients (external system): over OPC UA, Modbus TCP and NATS
  • Compiler (service or process): Structured Text to bytecode
  • Scan thread (service or process): one locked OS thread, one set per cycle
  • Process image (data store): %I, %Q and %M
  • Telemetry worker (service or process): changes found off the scan thread; feeds the cycle recorder
  • Fieldbus drivers (service or process): a worker per device, never waited for
  • Field devices (field equipment): Modbus TCP, EtherNet/IP, EtherCAT, CANopen

Connections

  • Web Studio → Runtime server (configuration or deploy): deploy. The Web Studio sends the program text; the runtime server compiles it and publishes the result.
  • Runtime server → Web Studio (data or telemetry): live values. Over a WebSocket, 30 times a second: the values the Web Studio shows, copied by the scan thread at a cycle boundary.
  • Outside clients → Runtime server (command to equipment): writes. The OPC UA server, the Modbus TCP server and the UNS commands over NATS are part of the runtime server; their writes pass the same check as a write of the HTTP API.
  • Runtime server → Compiler (configuration or deploy): program text
  • Compiler → Scan thread (configuration or deploy): program set. A deploy publishes a new program set; the scan thread picks it up at the start of its next cycle.
  • Runtime server → Scan thread (command to equipment): queued writes, forces. A write is queued and applied on the scan thread at the start of a cycle, before the program runs.
  • Scan thread ↔ Process image (data or telemetry): reads, writes
  • Fieldbus drivers → Process image (data or telemetry): inputs to %I. Copied by the scan thread before the program runs.
  • Process image → Fieldbus drivers (command to equipment): outputs from %Q. Copied by the scan thread after the program has run.
  • Field devices → Fieldbus drivers (data or telemetry): inputs
  • Fieldbus drivers → Field devices (command to equipment): outputs
  • Scan thread → Telemetry worker (data or telemetry): copy of the program's memory, each cycle. The only telemetry work on the scan thread: a copy into a queue with one slot per cycle. When the queue is full the cycle is dropped and counted; the scan does not wait.

2.1 Adaptive Cyclic Scheduler (pkg/plc/scheduler.go)

Section titled “2.1 Adaptive Cyclic Scheduler (pkg/plc/scheduler.go)”
  • Runs in a dedicated OS thread locked via runtime.LockOSThread().
  • Thread priority escalation:
    • Windows: Calls winmm.dll!timeBeginPeriod(1) to configure 1ms multimedia clock resolution. With --rt-priority above 0 the scan thread runs at TIME_CRITICAL and the process priority class defaults to high; --rt-class normal keeps the normal class (the behaviour before), --rt-class realtime asks for realtime (administrator rights needed; Windows otherwise gives high). Why high by default: at each yield the scan goroutine hands its processor back to the Go scheduler, and another thread of the PLC process has to run to hand it back. At the normal class, with other processes busy, that took 2 to 20 ms and caused overruns, mostly just after a deploy; at the high class the yields take tens of microseconds.
    • Linux: Calls sched_setscheduler(0, SCHED_FIFO, &param) with priority 80+.
    • Linux, the scan’s CPU: chosen among the CPUs the process may use (its cgroup cpuset: in a container, --cpuset-cpus). --rt-cpu N outside them is refused with a log line, and the scan runs unpinned (rt_mode default, with the reason). Without --rt-cpu, an isolated CPU among them is used (linux_isolated); when the host isolates only CPUs the process may not use, the scan is pinned to one of its own CPUs if another is left (linux_allowed). A process with one CPU logs a warning (10 ms determinism needs at least two) and runs the loop with 2 Ps, unless GOMAXPROCS is set.
  • Cyclic Loop Steps:
    1. Fetch Active Program Set: Atomically loads the active program set via atomic.Pointer[ProgramSet], once for the whole cycle: every task and the main program of the cycle run from that one set.
    2. Read Physical / Simulated Inputs: Copies fieldbus input buffers into %I (offsets 0..1023).
    3. Apply Queued Outside Writes and Forces: Applies the outside writes queued since the previous cycle (section 2.3), then the active forces, so the program sees forced inputs and memory.
    4. Execute Logic: Evaluates bytecode using the zero-allocation VM.
    5. Write Physical / Fieldbus Outputs: Applies the forces again, so a forced output reaches the field whatever the program wrote, then flushes %Q (offsets 1024..2047) to I/O drivers.
    6. Telemetry Hook: Copies the memory ranges the program uses into a per-cycle queue, without waiting; the comparison with the previous cycle runs on a worker, off the scan thread (section 3).
    7. Drift Compensation: Calculates elapsed scan duration and adjusts next sleep interval.

The diagram places these steps on one cycle, with the three things that meet the scan thread from outside (sections 2.3 and 3).

TimelineOne scan cycle, and what happens around it
One scan cycle, and what happens around itThe scan thread fetches the active program set once at the start of the cycle, reads the inputs, applies the queued outside writes and the forces, executes the logic, writes the outputs, serves a pending read of the image, copies the bytes the program uses for telemetry and sleeps until the next period. Outside writes, a hot reload, the live-value readers and the change detection run outside the scan thread and meet it only at fixed points.SCANIDLEcycle startsnext cycle startsTHE SCAN THREADFetch the active program setone load for the whole cycle1Read inputsfieldbus buffers into %I2Apply queued writes and forcesbefore the program runs3Execute logicbytecode, no allocation4Write outputs%Q to the I/O drivers5Telemetry hookcopies the used ranges6Drift compensationsets the next sleep7Sleepuntil the next periodOUTSIDE THE SCAN THREADOutside writesruntime API, OPC UA, UNS,Modbus TCPqueuedHot reloadnew program set builtset publishedLive valuesIDE, telemetry sessionsimage copiedChange detectioncycle recorder; NATSonly when enableddiffs
Nothing outside the scan thread can interrupt a cycle: a write or a new program set waits for the start of a cycle.
  • Data or telemetry
  • Command to equipment
  • Configuration or deploy
  • Phase of the cycle
  • The program
  • Idle
Read as text

The scan thread fetches the active program set once at the start of the cycle, reads the inputs, applies the queued outside writes and the forces, executes the logic, writes the outputs, serves a pending read of the image, copies the bytes the program uses for telemetry and sleeps until the next period. Outside writes, a hot reload, the live-value readers and the change detection run outside the scan thread and meet it only at fixed points.

Time runs left to right: scan, then idle. The lengths are not to scale.

The scan thread

  • 1. Fetch the active program set: one load for the whole cycle
  • 2. Read inputs: fieldbus buffers into %I
  • 3. Apply queued writes and forces: before the program runs. A write checked against a program that no longer runs is dropped and audited. The forces come after the writes, so the program sees forced inputs and memory.
  • 4. Execute logic: bytecode, no allocation
  • 5. Write outputs: %Q to the I/O drivers. The forces are applied again first, so a forced output reaches the field whatever the program wrote.
  • 6. Telemetry hook: copies the used ranges. The image read a reader asked for is served first, at the boundary between the outputs and the hook. The hook only copies the bytes the program uses into a queue, one slot per cycle; when the queue is full the cycle is dropped and counted, and the scan never waits.
  • 7. Drift compensation: sets the next sleep
  • Sleep: until the next period

Outside the scan thread

  • Outside writes: runtime API, OPC UA, UNS, Modbus TCP (queued)
  • Hot reload: new program set built (set published)
  • Live values: IDE, telemetry sessions (image copied). The IDE and the telemetry sessions ask for the bytes they show; the scan copies them at a cycle boundary, after the outputs, so a value is never read half-written.
  • Change detection: cycle recorder; NATS only when enabled (diffs). A worker outside the scan thread compares the copies cycle by cycle. The cycle recorder sees every cycle; the changes are published on NATS only by the legacy telemetry, which is off unless the runtime is started with it.

Connections

  • Outside writes → Apply queued writes and forces (command to equipment). Queued at any time, applied at the start of a cycle.
  • Hot reload → Fetch the active program set (configuration or deploy). The fetch at the start of a cycle picks the new set up: a set published during a cycle runs from the start of the next one, without stopping the timer, and no cycle mixes two versions.
  • Write outputs → Live values (data or telemetry). The copy a reader asked for is made after the outputs are written.
  • Telemetry hook → Change detection (data or telemetry). The hook never blocks: a cycle is dropped and counted when the queue is full.

2.2 Linear Process Memory Image (pkg/plc/memory.go)

Section titled “2.2 Linear Process Memory Image (pkg/plc/memory.go)”
  • One contiguous byte array, allocated once at startup, in this order:
    • %I: inputs, from offset 0;
    • %Q: outputs, after the inputs;
    • %M: internal memory and the state of the function block instances, after the outputs;
    • the extended area (data blocks, recipe buffers), after %M, on the larger tiers.
  • Its size is set by the CPU tier, --cpu (GetCPUTierConfig): eaxCPU-100 64 KB, eaxCPU-300 512 KB, eaxCPU-500 4 MB, eaxCPU-700 32 MB, eaxCPU-900 64 MB. --mem <MB> sets a custom size instead (256 KB of %I, 256 KB of %Q, 8 MB of %M, the rest extended).
  • Without either flag, plc-runtime uses eaxCPU-100 (%I 4 KB, %Q 4 KB, %M 32 KB, extended 24 KB), or the saved data/cpu_config.json with --use-saved-cpu. plc-server uses data/cpu_config.json when it exists, otherwise the base layout of 6144 bytes: %I 0 to 1023, %Q 1024 to 2047, %M 2048 to 6143.
  • Memory access methods (ReadUInt8, WriteUInt8, ReadFloat32, WriteFloat32, etc.) are inlined by the Go compiler and perform direct boundary-checked pointer operations.
  • Direct bitwise addressing supports syntax %IX0.0 through %IX127.7, %QX0.0 through %QX127.7.

2.3 Lock-Free Hot Reload (pkg/plc/programset.go)

Section titled “2.3 Lock-Free Hot Reload (pkg/plc/programset.go)”
  • A deploy, and a test of an online change, build a new program set (ProgramSet): the programs of one compiled, linked text in link order with the main program last, the set’s version and hash, and its initialisation program. A set is never changed after it is published: a change publishes another set, and an untest publishes the accepted set again.
  • The active set is held in a SetHolder as an atomic.Pointer[ProgramSet]. Publish stores the new set. Publishers take a mutex among themselves; the scan never takes it, so the scan thread waits for no lock.
  • The scan loads the set once, at the start of a cycle (section 2.1, step 1). A set published during a cycle therefore runs from the next cycle on, and no cycle runs a mix of two versions: its tasks, its main program and its forces all come from the same set. The cycle timer is not stopped.
  • pkg/plc/hotreload.go keeps ProgramHolder, the one-program view of the same holder: its Swap publishes a set of one program. The runtime itself publishes whole sets.
  • Outside writes (runtime API, OPC UA, UNS, Modbus TCP) are queued and applied at the start of a cycle, before the program runs. Each carries the version of the program it was checked against; a write whose version no longer runs when its cycle comes is dropped and audited (WRITE_STALE_PROGRAM), never applied to a variable that moved or to a new VAR CONSTANT. See Constants, outside writes and forces.

2.4 Outside reads over Modbus TCP (pkg/protocols/modbus)

Section titled “2.4 Outside reads over Modbus TCP (pkg/protocols/modbus)”
  • While clients read, the scan copies the ranges they read at each cycle boundary, in one small copy per cycle (at most 256 KB). A read is answered at once from the last copy: all its values come from one cycle, at most about two cycles old (two cycle times and 2 ms).
  • A connection that wrote waits for a copy made at a boundary after its write, so its next read shows the write. A connection never reads an older image than one it already read.
  • A read waits for the next boundary, as every read did before, the first time a range is read, when the copy is older than two cycles, or when it asks for more than the copy holds. A stopped PLC is copied at once.
  • Reads are capped at 3,000 a second for the whole server; reads over the cap wait, none is refused. --modbus-max-reads N (on plc-server and plc-runtime) sets the cap: 0 means no limit, and a negative value stops the start-up with exit code 2. The reads answered from the copy are counted in eaxplc_modbus_server_snapshot_reads_total. Writes are never paced: they are checked, queued and applied at the next boundary (section 2.3).

  • The watchdog trips on consecutive_overruns overruns in a row (a cycle longer than 110 % of the period; 5 by default) or on one cycle longer than max_cycle_ms (by default the larger of 20 ms and 20 periods). A cycle is measured start to start. A trip sets the outputs to their safe values (all of %Q to 0, then the configured safe_outputs), writes them to the I/O at once and stops the program, on the scan thread itself; the trip is then reported off the scan thread. The configuration is read and changed at /api/plc/watchdog (a change needs an engineer and an e-signature) and kept in data/watchdog.json: on for a new project, off for an install that ran before without it.

  • What a trip record says. The tripping interval holds the previous cycle’s program execution, so each trip also reports how long the program ran in it and why the cycle was too long. The trip in last_trip (GET /api/plc/watchdog) carries period_ms, exec_ms, exec_known and cause, and, in microseconds, exec_us, start_late_us, budget_us and reason. The sentence that says which rule tripped (“cycle longer than the configured maximum” or “consecutive overruns”) is trigger; before 20 November it was called reason, and reason now holds the measured reason below.

    • exec_us: the program’s execution in the tripping interval (0 when it is not known);
    • budget_us: the limit that applied, max_cycle_ms for a long cycle, 110 % of the period for consecutive overruns;
    • start_late_us: how far the start slipped, the interval minus the larger of the program’s execution and the period, or 0 when that is not positive. With the execution unknown it is the interval beyond the period;
    • reason: late_start, long_execution, both or unknown. cause has the first, second and last of these. both is a long_execution trip whose start_late_us is also more than one whole period: the program ran past the budget and the start was late as well.

    cause and reason name the same thing:

    • long_execution: the program alone ran longer than the limit that tripped (max_cycle_ms for a long cycle, 110 % of the period for overruns);
    • late_start: the program fitted within that limit, and the rest of the interval was spent outside it (the OS handing the scan thread back, I/O): the cycle started late;
    • unknown: the execution time is not known (exec_known false, for the first measured cycle after a start or a resume; exec_ms is then 0).

    The fault message is written for operators. It names the rule that tripped and its limit first, then the cause with the numbers, for example “overrun watchdog: one cycle took 21.56 ms, over the 20.00 ms maximum (late start: the operating system held the scan back 20.56 ms; the program ran 0.002 ms) - outputs set to safe values, program stopped”. The overrun count is in the message only on a count trip: “5 consecutive overruns, each cycle over 1.10 ms (110 % of the 1.00 ms period); the last took 6.80 ms (…)”. The program’s execution is given in ms with 3 decimals, so a short program never reads “0 ms”. For both the cause reads “long execution and late start: the program ran …”. The wording can change again: tools must read the last_trip fields, which are unchanged, and not match the sentence. The Web Studio shows the trip in a banner at the bottom right, with the reason in words and the measured execution, start lateness, budget and period; it can be closed, and it comes back only for another trip. The header pill then reads WATCHDOG - STOP, with the banner’s words as its tooltip in the Studio’s language; other faults keep FAULT - STOP. GET /api/stats carries the same trip as watchdogTrip while the fault is in force, and null after an operator’s start cleared it. The same message is in the PLC’s fault (/api/stats fault), the WATCHDOG_TRIP audit record and the fault event the PLC publishes on NATS. The cause is reported only: it plays no part in the trip decision, and the thresholds and defaults are unchanged.

  • The “No real-time setup” warning. Without real-time scheduling, the OS can keep the scan thread from running for up to about 20 ms. A cycle trips when it lasts longer than max_cycle_ms, so one such delay longer than the headroom (max_cycle_ms minus the period) stops the PLC. The Web Studio shows an amber No real-time setup chip in the status bar when all of these hold: the watchdog is on with a maximum cycle, the scan thread runs without real-time scheduling, and the headroom is under 20 ms. With the default maximum cycle that is a scan faster than 950 Hz. The chip opens a card with the scan period, the maximum cycle, the real-time mode and priority, and the fixes, any one of which removes the warning:

    • start the PLC with real-time scheduling, --rt-priority (on Linux SCHED_FIFO needs CAP_SYS_NICE);
    • use a slower scan cycle;
    • raise max_cycle_ms to at least the period plus 20 ms.

    The same facts are read-only fields: rt_warning in GET /api/plc/watchdog and watchdogRT in GET /api/stats (active, watchdog_enabled, realtime, rt_mode, priority, period_ms, max_cycle_ms, headroom_ms, os_stall_ms). The warning changes nothing in the watchdog.

  1. Per-cycle copy (pkg/telemetry/snapshotter.go):
    • At the end of a scan the scan thread copies only the memory ranges the program uses into the free slot of a per-cycle queue; it never compares values.
    • A worker takes the slots in order and finds the changes, off the scan thread. The cycle recorder (section 5) reads the same queue.
    • When the queue is full the scan drops that cycle and counts it, rather than wait.
  2. SPSC Ring Buffer (pkg/telemetry/ringbuffer.go):
    • Cache-line padded (64 bytes) to prevent false sharing between producer and consumer.
    • Lock-free, zero-allocation circular buffer of the worker’s change frames.
    • Read only by the legacy NATS telemetry (item 4); without it the frames are discarded.
  3. WebSocket Telemetry Stream:
    • 30 ticks a second, each tick carries the values the open Web Studio shows, read by the PLC at a cycle boundary. The whole process image goes out on the first tick and then once a second.
  4. Legacy NATS telemetry (opt-in):
    • With --nats-legacy-telemetry, plc-server and plc-runtime also publish every cycle’s changes as JSON on plc.<id>.telemetry.delta (and .rungs.powerflow) and the whole image once a second on plc.<id>.telemetry.snapshot. Off by default in both: nothing in eaxScada or the Studio reads them.

eaxPLC exchanges process data with field devices through fieldbus masters and maps it to the %I and %Q areas:

Bus type Role
modbus_tcp Modbus TCP client (master)
ethernet_ip EtherNet/IP scanner (Class 1 implicit I/O)
ethercat EtherCAT master on raw Ethernet (Linux)
canopen CANopen master (SocketCAN, SLCAN adapters)
mqtt MQTT / Sparkplug B values as inputs (network I/O, not for safety functions)

The fieldbus configurator in eaxPLC Studio: a Modbus TCP and an EtherNet/IP bus, with the Modbus device and its I/O map. The fieldbus configurator in eaxPLC Studio: a Modbus TCP and an EtherNet/IP bus, with the Modbus device and its I/O map.

The fieldbus configurator: buses, devices and the I/O map in one document.
  • The scan never waits on the network. Each device runs in its own goroutine; the scan thread only copies between the devices’ process images and PLC memory: inputs before the program runs, outputs after. Images are handed over through lock-free triple buffers, so the scan does not block or allocate.
  • One configuration document. Buses, devices, parameters and the I/O mapping are one JSON document, validated as a whole, saved with the PLC and exportable.
  • Applied device by device. An Apply compares the new document with the running one and restarts only what changed: a Modbus TCP or EtherNet/IP device alone, an EtherCAT line, a CANopen bus or an MQTT connection as a whole, a bus whose own settings changed. Devices the change does not touch keep their connection and their process images, so the scan exchanges their I/O without a gap. Every device restarts only after a change of the PLC memory layout or when nothing was running. See Apply fieldbus changes without stopping the other devices.
  • EtherCAT master (pkg/fieldbus/ethercat): frames on raw Ethernet (EtherType 0x88A4), bus scan and addressing, reading the SII EEPROM, the EtherCAT state machine, SyncManager and FMMU configuration from the SII, and a cyclic logical read/write of the process image. Raw Ethernet needs Linux.

Which masters each eaxPLC edition includes is listed in Editions.


The cycle recorder keeps every scan cycle of the loaded program, whatever the program is, so the exact value of each variable can be read back at any recorded cycle.

  • Little work on the scan thread. The scan only copies the memory ranges the program uses into a per-cycle queue. A worker compares each cycle with the previous one and stores the words that changed, plus a full keyframe every 1000 cycles, so any cycle is rebuilt from the nearest keyframe and the changes after it.
  • Program variables, not raw memory. Variable names, IEC types and addresses come from the program’s symbol registry, so the recording is read by name.
  • Bounded. The history kept in memory is set in seconds (--dvr-seconds, default 600) and capped in megabytes (--dvr-max-mb); the oldest cycles go first. The cap bounds the memory the recording really holds: every array of the held blocks counts at its allocated size, and so do the evicted blocks kept for reuse. The automatic Go memory limit reserves exactly the cap for the recorder. With --audit-disk, closed blocks of cycles are also written to disk (--dvr-disk-mb).
  • Honest about gaps. Cycles the recorder could not keep are counted and shown as lost, and a restart of the cycle counter starts a new epoch: a cycle is identified by its epoch and its number.

eaxScada Studio shows the recording of the PLC it targets: a chart of the chosen variables over the recording, stepping cycle by cycle, the variables that changed in a cycle and every variable’s value at it.

The PLC cycle recorder in eaxScada Studio, stepped to cycle 2925 of a reactor program, where the temperature reaches its setpoint and heating gives way to the reaction phase: chart variables, the recording chart and every program variable at that cycle. The PLC cycle recorder in eaxScada Studio, stepped to cycle 2925 of a reactor program, where the temperature reaches its setpoint and heating gives way to the reaction phase: chart variables, the recording chart and every program variable at that cycle.

The cycle recorder in eaxScada Studio, stepped to the cycle where the reactor reaches its setpoint.