[Bug]: Sustained high CPU (160-180%+) scaling with fleet size — per-agent-report full registry rebuild + redundant websocket JSON re-derivation
Describe the bug
Found while investigating #1966: once the disk-write side was under control, Pulse was still sitting at a sustained 160-180%+ CPU (load average ~10-11) on an otherwise idle homelab install — 12 LXCs, 3 VMs, 1 PBS, 1 Docker host, several Pulse Unified Agents, one TrueNAS system. No user activity, no alert churn.
This isn't a fixed overhead — the mechanisms below all scale with monitored fleet size and connected-agent count, so it gets worse exactly as the estate you're monitoring gets bigger. Confirmed live on a modified branch with pprof goroutine dumps and Go runtime metrics (/debug/pprof/goroutine, the /metrics endpoint), then verified each mechanism against the current main source directly.
Three distinct, additive mechanisms, in rough order of measured impact:
1. Every accepted agent report fully rebuilds the canonical resource registry, from scratch, synchronously.
MonitorAdapter.replaceRegistryLocked (internal/unifiedresources/monitor_adapter.go) discards the entire in-memory registry and rebuilds it from the full state snapshot on every single accepted agent report (host, Docker, and Kubernetes agent handlers all call this — 8+ call sites in internal/monitoring/monitor_agents.go plus kubernetes_agents.go), not incrementally and not just for the one resource that changed. On this fleet (~1069 resources once Docker containers, k3s pods/deployments, and TrueNAS datasets are counted), that rebuild does:
registry.List()for a "before" snapshot, purely to feed an audit-trail diff — deep-clones every resource (cloneResource, ~20 nested sub-clones each:internal/unifiedresources/clone.go).- A full
IngestSnapshotWithStaleThresholdspass, which clones again on ingest. rebuilt.List()for the "after" snapshot, same deep-clone cost, again purely for the diff.- Every
Nodes()/VMs()/Hosts()/etc. accessor (internal/unifiedresources/registry.go,withViewCache) unconditionally takes the registry's exclusive write lock just to check whether its cached views are stale, even when they aren't — serializing every concurrent reader behind whichever caller happens to be checking freshness.
A goroutine dump caught this mid-rebuild (ResourceRegistry.List → cloneResource, triggered from ApplyDockerReport) at the same moment three other goroutines were blocked on the same view-cache lock, each trying to do their own per-report rebuild concurrently.
2. The websocket layer redundantly re-derives data it already has, on every broadcast.
Every individual agent check-in also calls Hub.BroadcastCurrentState() (internal/websocket/hub.go), and — once clear of the existing 100ms coalesce window — that triggers a full rebuild of the frontend state plus a JSON round-trip over every resource: marshal the whole state, unmarshal it back apart into fields, unmarshal the resources array again, then unmarshal each individual resource a third time just to read its id field for the client delta-baseline computation (internal/websocket/state_delta.go, extractKeyedEntries). That id was already known in Go before the state was ever marshaled — encoding/json never reorders a slice, so the array's marshal order always matches the source slice's order.
3. Combined effect.
Runtime metrics on the unmodified path: ~1.14M allocations/sec, ~230MB/s allocated, GC running ~4x/sec, sustained 163-181% CPU with load average 10-11, on the fleet described above.
To reproduce
There's no discrete UI action — this is continuous background cost proportional to fleet size and agent check-in frequency, so the way to see it is direct measurement rather than a click-path:
- Run Pulse against a moderately large fleet (dozens of guests/containers across a few Proxmox nodes, plus several Pulse Unified Agents and/or a TrueNAS instance) so there's steady agent check-in traffic.
- Watch
top/ps -o pcpuon the Pulse process, oruptime's load average, over several minutes with no user interaction. - If pprof is reachable (
/debug/pprof/goroutine?debug=2, gated behind admin auth), a goroutine dump reliably catches at least one goroutine insideResourceRegistry.List/cloneResourceorwebsocket.extractKeyedEntries/createJSONMergePatch— these are quick, synchronous, and run often enough that a snapshot has good odds of landing inside one. - The Prometheus
/metricsendpoint (loopback-bound, no auth) exposesgo_memstats_alloc_bytes_totalandgo_memstats_mallocs_total— sampling those a minute apart gives a direct allocation-rate reading.
Expected behavior
CPU usage and allocation rate that scale with actual state changes, not with the volume of unrelated agent check-ins restating data that hasn't changed. Fleet size should mostly cost memory and occasional poll work, not continuous full-registry teardown-and-rebuild on a per-report basis.
Additional actionable topics
None — this is one bug with three additive mechanisms in the same causal chain (agent report → full registry rebuild → redundant websocket re-derivation), not three unrelated issues.
Pulse version
Confirmed against main by direct source inspection (all three mechanisms are present, unrelated to the #1966 branch). Live-measured on a modified build derived from main around the v6.4.5-rc.2 timeframe. Have not yet reproduced the raw numbers against an unmodified stable tag specifically, but nothing about these code paths is version-specific — they're structural.
Agent version
Pulse Unified Agent, various recent versions (not agent-specific — the server-side handling of accepted reports is what's costly, regardless of agent version).
Installation type
ProxmoxVE LXC
Relevant logs or diagnostics
Runtime metrics (/metrics, loopback), unmodified path, steady state over a 60s sampling window:
go_memstats_alloc_bytes_total: ~230 MB/s allocated
go_memstats_mallocs_total: ~1.14M allocations/sec
go_gc_duration_seconds_count: ~3.9 GC cycles/sec
process_cpu_seconds_total: 163-181% average CPU
uptime load average: ~10-11 (4 vCPU LXC)A goroutine dump (/debug/pprof/goroutine?debug=2) caught the call chain below live, mid-rebuild, more than once across several samples. Line numbers here are re-verified directly against current main (the dump itself was taken against a locally modified branch, so I didn't want to paste its raw, now-slightly-stale numbers):
internal/unifiedresources.(*ResourceRegistry).List(...)
internal/unifiedresources/registry.go:1276
internal/unifiedresources.(*MonitorAdapter).replaceRegistryLocked(...)
internal/unifiedresources/monitor_adapter.go:311 (before := registry.List() at :317;
the second clone, rebuilt.List(), at :356)
internal/unifiedresources.(*MonitorAdapter).replaceRegistry(...)
internal/unifiedresources/monitor_adapter.go:301
internal/unifiedresources.(*MonitorAdapter).PopulateSnapshotAndSupplemental(...)
internal/unifiedresources/monitor_adapter.go:523
internal/monitoring.(*Monitor).updateResourceStore(...)
internal/monitoring/monitor.go:5109
internal/monitoring.(*Monitor).refreshUnifiedResourceStoreAfterAgentStateChange(...)
internal/monitoring/monitor.go:5189
internal/monitoring.(*Monitor).ApplyDockerReport(...)
internal/monitoring/monitor_agents.go:2703
internal/api.(*DockerAgentHandlers).HandleReport(...)
internal/api/docker_agents.go:135...concurrently with three other goroutines blocked in withViewCache (internal/unifiedresources/registry.go:5627) waiting on the same exclusive lock, called from findLinkedProxmoxEntityWithHints (internal/monitoring/monitor_agents.go:4545, per-host-report Proxmox-entity linking) and the backup poller.
I've explored and locally validated fixes for all three mechanisms:
- Narrowing
withViewCacheto a read lock in the common (clean) case, instead of unconditionally taking the exclusive lock just to check freshness. - Coalescing concurrent registry-rebuild triggers — a caller that finds a rebuild already running marks that another pass is needed once it finishes, instead of starting its own redundant one (the uncontended case stays synchronous and immediate, unchanged).
- Replacing the redundant deep-clone diff snapshots (
registry.List()called twice, purely to feed the audit-trail diff) with a cheap read-only shallow copy — safe there specifically because neither snapshot is reachable by any other mutator during that window. - Reading resource/infrastructure/alert ids directly from the Go value being marshaled instead of re-deriving them from JSON a second time.
- Widening
BroadcastCurrentState's 100ms debounce to a proper rate limit (~2s) per org, since independently-scheduled agents rarely land within 100ms of each other, so the debounce alone wasn't coalescing anything in practice.
Live-tested, before/after on the same fleet: CPU dropped from the 163-181% baseline down to a stable 144-152%, allocation rate down from ~1.14M/sec to ~0.85-0.90M/sec. Not attaching a patch here — happy to open a PR if that's a useful next step once this is triaged, following the same process as #1966.
Confirmations
- I verified the exact Pulse version and image reference from the running instance.
- I searched existing issues for duplicates.
Source: rcourtman/Pulse