marstek-venus-rs485-node-red icon indicating copy to clipboard operation
marstek-venus-rs485-node-red copied to clipboard

Strategy flows re-read static configuration from Home Assistant on every pass — caching cuts control loop latency by ~50% on low-power hardware

Open satscan1 opened this issue 3 months ago • 0 comments

Opening this as an issue first, per the contributing guidelines, before proposing anything.

Summary

The strategy flows read configuration values from Home Assistant on every control pass using api-current-state nodes. These values (Kp, Ki, Kd, dampening, hysteresis, idle time, target grid consumption, and the Dynamic strategy settings) only change when the user moves a slider.

On low-power hardware these reads dominate the control loop duration. Replacing them with cached values plus a server-state-changed watcher roughly halved our control loop latency. Measured on two strategy flows, over 1,419 and 1,013 passes respectively.

Environment

Synology DS224+ (Intel Celeron J4125, 4 cores @ 2.0 GHz), Home Assistant VM, Node-RED 5.0.4 add-on, HBC v4.15.0, ~2,980 HA entities.

A J4125 is slow by modern standards and Node-RED is single-threaded, so the benefit of this scales with how slow the host is. On faster hardware it may be barely noticeable — which may be why it has not surfaced before. I am reporting it because the effect here was large.

Measurements

Home Assistant itself is fast:

Operation p50 max
WebSocket call_service, no state change 1 ms 4 ms
WebSocket call_service, real state change 4 ms 27 ms
WebSocket call_service to ESPHome/RS485 entity 4 ms 4 ms
REST GET /api/states/<entity> 6 ms 10 ms

The flow is not. I instrumented Strategy Self-consumption by prepending a single timestamp line to existing function nodes (no structural change), measured across many passes:

Segment What is in between Time
Advanced settings → Set: Error signal 2× api-current-state 112–158 ms
Set: Error signal → Derivative final value function nodes only 1–11 ms
Derivative final value → Calculate corrections function nodes only 0–1 ms
Calculate corrections → Output dampening function node 1 ms
Output dampening → Output failsafe 3× api-call-service + smooth on side branches 118–145 ms
Output failsafe → Load distribution direct wire 1 ms

Function nodes cost 0–1 ms. Segments containing HA nodes cost roughly 50–70 ms per node.

A correction to my own first interpretation, in case it saves someone the detour. I initially assumed this was ~50 ms of CPU time per HA node, and expected that batching the write nodes would help. A follow-up measurement disproves that: across 280 intervals between consecutive writes within a single pass, 63 were under 10 ms, minimum 1 ms. If each api-call-service consumed 50 ms of event-loop time, two writes could not land 1 ms apart — yet they do, 63 times.

So the ~50 ms is latency, not CPU time. Writes that share a branch point already overlap, so batching them merges waiting that is already concurrent. Not worth pursuing.

Sequential reads are different: each api-current-state waits for the previous one to return. That is where the time actually goes, and that is what caching removes.

Incidentally, in Self-consumption three of the eight PID write targets (error_deviation, pid_output_deviation, is_charging) were never written at all during a 77-pass measurement window — possibly worth a look separately.

What I changed

I replaced the api-current-state config-read nodes with function nodes that keep the same node id, position, group and wiring, so the flow topology is unchanged. Each reads its value from a global cache and writes it to exactly the same destination as before (flow context or msg). Each has a fallback value in case the cache is empty, so no node can emit undefined.

Cache invalidation is one server-state-changed node per flow, listening to the relevant entities with outputInitially: true, feeding a small function that does global.set("cfg_" + entity_id, payload).

Strategy Self-consumption — 8 nodes:

input_number.house_target_grid_consumption_in_w
input_number.house_battery_control_hysteresis_in_w
input_number.house_battery_control_kp
input_number.house_battery_control_ki
input_number.house_battery_control_kd
input_number.house_battery_control_idle_time
input_number.house_battery_control_error_signal_dampening
input_number.house_battery_control_pid_output_dampening

Strategy Dynamic — 8 nodes:

input_select.house_battery_strategy_dynamic_data_source
input_select.house_battery_strategy_dynamic_default
input_select.house_battery_strategy_dynamic_cheapest
input_select.house_battery_strategy_dynamic_expensive
input_select.house_battery_strategy
input_number.house_battery_strategy_dynamic_threshold_delta
input_number.house_battery_strategy_dynamic_cheapest_hrs
input_number.house_battery_strategy_dynamic_expensive_hrs

Still uncached in our installation: Timed (20 read nodes) and the Start flow (26).

Results

Self-consumption, strategy execution time from the built-in execution_start/execution_end markers, 1,419 passes over 13.8 hours:

before after caching
p50 ~0.78 s 0.014 s
p90 — 0.703 s
p99 — 0.861 s
passes > 1 s — 4 of 1,419 (0.3%)

The distribution is bimodal: 73% of passes complete in milliseconds (strategy exits early — deadband, or nothing to do), the remainder sit around 0.6–0.8 s. Worth knowing if you measure this yourself; small samples are misleading here.

Dynamic, measured as the interval between the recorder entries of error_signal (start of the PID chain) and pid_output (end), 1,013 passes over five hours:

Self-consumption before caching (72 passes) Dynamic with caching (1,013 passes)
p50 337 ms 170 ms
p90 452 ms 264 ms
p95 — 340 ms
p99 — 479 ms
> 1 s 0 3 (0.30%)

(This second method measures only the segment between the first and last PID write, so it is a lower bound, not the full pass. The two tables are not directly comparable with each other.)

Stability over ~20 hours: 101 log lines, zero heap errors, zero process restarts, no drift over time. Before this work the same installation was hitting JavaScript heap out of memory — though that had a separate root cause on our side, unrelated to HBC.

The cache survives a Home Assistant restart without a Node-RED restart, and invalidation was verified live (changing hysteresis from 0 to 30 W propagated within seconds).

Suggested improvement

Read configuration values into flow context via server-state-changed watchers at flow level, and have the strategy flows read from context instead of querying Home Assistant on every pass.

Happy to open a PR if you think the approach fits, or to test a variant of your own design on this (deliberately slow) hardware.

Methodological note

Node-RED's status stream to the editor is batched — in one capture, 215 of 319 inter-node deltas were exactly zero, arriving in blocks of 13 nodes sharing a timestamp. Node status timing cannot be used to profile per-node duration. All numbers above come from Date.now() timestamps written inside function nodes, or from recorder timestamps.

satscan1 avatar Aug 24 '26 16:08 satscan1