How-to
Polling 100 Modbus TCP slave IDs from Node-RED without 100% CPU
Short answer
Drive one Modbus request per message with a rate-limited split node and keep one to four requests in flight per endpoint: a 5-second scan of 100 slave IDs is only 20 reads per second. Flush SQL Server inserts in batches of 50 to 200 rows through one persistent connection, off the polling path. The 100% CPU comes from a scan loop, overlapping scans or a retry backlog, not from the request rate.
On this page
- Attribute the CPU before touching the flow
- Confirm which topology serves the 100 IDs
- Drive the scan with a split node, not a loop
- Pace the scan with measured arithmetic
- Bound the retries and stop scans from overlapping
- Batch the SQL Server writes off the polling path
- Decide when the two workloads get separate machines
- Questions asked
Your load is small: a full scan of 100 slave IDs once per second is 100 requests per second, and once every 5 seconds it is 20, and Node-RED spends nearly all of that time waiting on sockets, because the runtime is single-threaded and a correct sequential flow does almost nothing between a request and its response. The 100% CPU on your machine comes from somewhere else: a loop in a function node, scans stacking on top of each other, retries with no bound, or row-by-row inserts into the co-hosted SQL Server. The fix is one request per message from a rate-limited split node, one to four requests in flight per endpoint, a gate that stops scan overlap, and inserts flushed in batches of 50 to 200 rows off the polling path.
Attribute the CPU before touching the flow #
Open Task Manager on the Windows Server machine and sort the processes by CPU. Two processes can own the top line, and they point to different fixes. The Node-RED runtime on top means the flow itself is spinning: a waiting loop, overlapping scans, or a retry queue growing faster than it drains. The SQL Server engine on top means the write pattern, one connection and one INSERT per row, or unrelated database work such as reports. Note which process it is; the sections below fix both, in that order of likelihood.
Confirm which topology serves the 100 IDs #
A Modbus TCP request travels to an IP address and a TCP port (conventionally 502, but the configured value wins) and carries a unit identifier in its header. That gives two possible layouts for IDs 1 to 100:
- Behind one gateway: every request goes to the gateway's single IP, and the gateway maps the unit identifier in each TCP request to the serial slave downstream, exactly the routing gateway manuals describe. One endpoint, 100 logical slaves.
- Native Modbus TCP devices: the slaves have their own addresses, so you face up to 100 endpoints, each serving whatever unit ID its documentation assigns.
Prove which one you have: send a controlled read to a known ID, then a second read to a different ID at the same IP address. Two valid answers from one address confirm the gateway case. A reachable gateway alone does not prove that every unit ID routes, so test the IDs individually before scheduling all of them; if the first works and the second does not, fix routing before touching timing.
Drive the scan with a split node, not a loop #
The single-endpoint version of this path, one client feeding one database, is walked in Modbus TCP data logging to a database from a plant PC; everything below is that flow with the scan machinery added. The register, function and quantity stay constant for every read; only the unit ID changes per message. Build it as:
- Trigger: an inject node at the scan period, feeding the overlap gate described further down.
- List builder: a function node that emits the 100 IDs as one array.
- Split: the core split node sends one message per array element, at a rate you set from the measured round-trip time.
- Unit ID: a change node moves the ID into the unit-identifier field your Modbus client node documents; most contrib clients read it from the incoming message.
- Client: one Modbus client configuration per endpoint from the previous section, never one per slave ID.
- Scan end: the split node stamps each message with its position in
msg.parts, so the response with index 99 closes the scan and clears the gate.
The list builder, with our own illustrative variable names:
// Illustrative scan-list builder - variable names are ours
const slaveIds = []; // type: array of numbers, starts empty
for (let id = 1; id <= 100; id++) {
slaveIds.push(id);
}
msg.payload = slaveIds; // msg.payload now carries the 100 IDs
return msg;
Deploy, trigger once, and check the count: the client receives 100 messages, the final response carries index 99, and the gate flag clears. Why not a loop: a while inside a function node that waits for a device response either spins, one core at 100%, or blocks the event loop so the response can never be delivered. That loop is the classic self-inflicted version of your symptom.
Pace the scan with measured arithmetic #
Sequential scan time is IDs multiplied by round-trip time per read. Measure the round trip first: inject one read to a live ID, run it ten times through the client to a debug node, and average the results. The worked example below uses 20 ms as its example input.
Worked example (example inputs, measure your own):
- Round trip measured: 20 ms per read.
- Sequential scan: 100 x 20 ms = 2000 ms = 2.0 s.
- Against a 5-second window: 2.0 s fits with 3.0 s of margin. Decision: sequential, one request in flight, split rate at one message per 25 ms (40 per second), giving a 2.5 s scan with headroom for slow IDs.
- Against a 1-second window: 2.0 s misses. With k requests in flight per endpoint the ideal scan is 2000 ms / k: k = 2 gives 1.0 s with zero margin, so any jitter breaks it; k = 4 gives 0.5 s with real margin. Decision: 4 in flight per endpoint, and only where the endpoint is a native Modbus TCP device.
- Behind one serial gateway, the TCP side can be parallel but the serial channel serves one transaction at a time, and no k fixes that. A read request is 8 bytes and a one-register response is 7 bytes, so 15 bytes, about 150 bits at 10 bits per byte. At 9600 bit/s that is 150 / 9600 = 15.6 ms of wire time per transaction before any turnaround delay. 100 x 15.6 ms = 1.56 s. Decision: a 1-second full scan through one 9600-bit/s serial channel is not achievable whatever Node-RED does, so spread the slaves across several gateways or commit to the slower window.
Modbus TCP pairs each response with its request by transaction identifier, a pairing the Modbus Messaging on TCP/IP Implementation Guide requires, so a few concurrent requests are protocol-legal, but many gateways and client nodes serve one transaction at a time regardless. Raise the in-flight count only against an endpoint tested to serve concurrently; the measurement behind that trade is covered in why parallel Modbus TCP clients beat one sequential poller.
Bound the retries and stop scans from overlapping #
Three settings keep the queue flat:
- Overlap gate: when the list builder runs, set a scan-in-progress flag in flow context and clear it when the response with index 99 lands or times out. The inject trigger checks the flag and drops itself while a scan is running. This one gate removes the most common cause of a queue that never drains.
- Finite timeout with a budget: start at 250 ms per read. Each dead ID then costs one timeout per scan, and ten dead IDs consume the whole margin of the slower case; that count is your alarm point, not a reason to raise the timeout.
- One attempt per scan: never retry inline. A failed ID is marked failed for this scan and tried again on the next one; an immediate retry loop against a dying device is exactly the backlog that pins the runtime.
Carry the unit ID, a status flag and the response timestamp with every reading, and store failures as failures; repeating the last value as if it were fresh hides a dead device inside a healthy-looking trend. One safety line: this flow is a monitoring layer with multi-second scans and skipped reads, so interlocks and shutdowns stay in the PLC, never here.
Batch the SQL Server writes off the polling path #
Nothing in the scan path waits on the database. Responses drop into a buffer, a context array or a join node collecting the scan's parts, and a flush runs when the buffer holds 50 to 200 rows or the scan ends; with 100 IDs that is one flush per scan either way. The flush sends one multi-row INSERT through the single connection the MSSQL node's configuration holds open. Never open a connection per row: the handshake and commit cost more CPU than the row itself, and a hundred of them per scan is how the database process reaches the top of the process list on a co-hosted machine. With an illustrative schema:
INSERT INTO dbo.SlaveReads (ScanNo, UnitId, ReadValue, ReadStatus, ReadAt)
VALUES (4102, 1, 237.5, 'ok', '2025-03-04 10:00:00.020'),
(4102, 2, 241.0, 'ok', '2025-03-04 10:00:00.045');
One tuple per reading, up to the batch size, in a single statement. For the query and connection wiring itself, passing PLC node data into a Node-RED MSSQL insert shows the single-row setup; keep that wiring and change only the statement to this multi-row form. Backpressure: cap pending flushes at two batches. Past the cap, drop the oldest batch and write the gap to the log, because a recorded gap in a trend beats a queue that grows until the runtime thrashes.
Decide when the two workloads get separate machines #
With the flow bounded, one machine carries this comfortably: the polling side waits on sockets, the database side does one small batch per scan, and both sit idle most of each cycle. Keep them together, because a second machine is not the fix for a flow bug. If SQL Server still owns the CPU after batching, the work is elsewhere (reports, other clients, index maintenance) and belongs to the database side. Only then split: move the scanning flow to its own machine near the gateway, where a fanless industrial mini PC fits that role, and leave SQL Server the server.
The decisions in one place: slower window, sequential with one request in flight; 1-second window, 4 in flight per endpoint on native TCP devices only; one serial gateway, the slower window or several gateways; writes through one connection in 50 to 200 row statements; and the process list before any tuning, because the CPU tells you which fix applies.
Questions asked
Should I build one Modbus client node per slave ID?
No. Configure one client per endpoint and let the unit identifier ride in each request message; behind a gateway, one client configuration serves all 100 IDs. A hundred client nodes means a hundred configurations to maintain and, depending on the package, a hundred sockets to the same device, a queue you cannot see or pace. The scan list and the split node are what scale, not the node count.
Which timestamp belongs in each logged row?
The response time of that reading, captured when the reply message arrives and stored per row. A single scan-start timestamp makes 100 rows look simultaneous when the scan actually spans two or more seconds, and any later average or correlation against PLC events inherits that error. Carry the response timestamp with the unit ID and the status so slow scans are visible in the data itself.
SQL Server still runs hot after batching. What else costs CPU per insert?
Look at the logging table's indexes and triggers. Every index is maintained by every insert, so a table carrying five indexes does five times the index work of one, and a trigger adds its own execution to each batch. Keep the live logging table lean and put heavy reporting indexes on a copy refreshed on a schedule; the insert path then costs close to the bare row write.
Can a higher in-flight count hide a slow slave?
No. Concurrency hides latency only while the endpoint actually serves transactions in parallel; requests to one gateway still serialize behind the slowest device, and a dying slave still times out on every attempt. Raising the in-flight count with a bad device on the bus mostly builds a bigger queue behind it. Fix, replace or split out the slow ID first, then tune concurrency against the measured scan time.