Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Dedup concurrent /api/state and /api/diagnostics with singleflight

rcourtman0b57527b29f7
diff --git a/internal/api/diagnostics.go b/internal/api/diagnostics.go
index 9a58a92669..49ba82e0c5 100644
--- a/internal/api/diagnostics.go
+++ b/internal/api/diagnostics.go
@@ -24,6 +24,7 @@ import (
"github.com/rcourtman/pulse-go-rewrite/pkg/proxmox"
"github.com/rs/zerolog/log"
"golang.org/x/crypto/ssh"
+ "golang.org/x/sync/singleflight"
)
// DiagnosticsInfo contains comprehensive diagnostic information
@@ -394,6 +395,12 @@ var (
diagnosticsCacheMu sync.RWMutex
diagnosticsCache = map[string]cachedDiagnosticsEntry{}
+ // diagnosticsComputeGroup dedupes concurrent cache-miss compute calls
+ // keyed by scope. Without this, N concurrent requests on cache miss
+ // each pay the full computeDiagnostics cost; with it, only the first
+ // goroutine runs and the rest wait on the shared result.
+ diagnosticsComputeGroup singleflight.Group
+
diagnosticsCacheHits = prometheus.NewCounter(prometheus.CounterOpts{
Namespace: "pulse",
Subsystem: "diagnostics",
@@ -729,19 +736,39 @@ func (r *Router) handleDiagnostics(w http.ResponseWriter, req *http.Request) {
ctx, cancel := context.WithTimeout(req.Context(), 30*time.Second)
defer cancel()
- start := time.Now()
- fresh := r.computeDiagnostics(ctx)
- diagnosticsRefreshDuration.Observe(time.Since(start).Seconds())
-
- diagnosticsCacheMu.Lock()
- cachedAt := time.Now()
- diagnosticsCache[scopeKey] = cachedDiagnosticsEntry{
- diag: fresh,
- cachedAt: cachedAt,
+ type diagResult struct {
+ diag DiagnosticsInfo
+ cachedAt time.Time
}
- diagnosticsCacheMu.Unlock()
- writeDiagnosticsResponse(w, fresh, cachedAt)
+ v, _, _ := diagnosticsComputeGroup.Do(scopeKey, func() (any, error) {
+ // Re-check cache inside the singleflight barrier: an earlier
+ // caller may have populated it between our miss above and us
+ // acquiring the singleflight slot.
+ diagnosticsCacheMu.RLock()
+ entry, ok := diagnosticsCache[scopeKey]
+ diagnosticsCacheMu.RUnlock()
+ if ok && !entry.cachedAt.IsZero() && time.Since(entry.cachedAt) <= diagnosticsCacheTTL {
+ return diagResult{diag: entry.diag, cachedAt: entry.cachedAt}, nil
+ }
+
+ start := time.Now()
+ fresh := r.computeDiagnostics(ctx)
+ diagnosticsRefreshDuration.Observe(time.Since(start).Seconds())
+
+ diagnosticsCacheMu.Lock()
+ cachedAt := time.Now()
+ diagnosticsCache[scopeKey] = cachedDiagnosticsEntry{
+ diag: fresh,
+ cachedAt: cachedAt,
+ }
+ diagnosticsCacheMu.Unlock()
+
+ return diagResult{diag: fresh, cachedAt: cachedAt}, nil
+ })
+
+ result := v.(diagResult)
+ writeDiagnosticsResponse(w, result.diag, result.cachedAt)
}
func writeDiagnosticsResponse(w http.ResponseWriter, diag DiagnosticsInfo, cachedAt time.Time) {
diff --git a/internal/api/router.go b/internal/api/router.go
index c8f3b8ca9d..4476f16ae3 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -64,8 +64,15 @@ import (
metricstore "github.com/rcourtman/pulse-go-rewrite/pkg/metrics"
"github.com/rcourtman/pulse-go-rewrite/pkg/reporting"
"github.com/rs/zerolog/log"
+ "golang.org/x/sync/singleflight"
)
+// stateComputeGroup dedupes concurrent /api/state callers per tenant. Without
+// it, N concurrent dashboards each rebuild + serialize the full 1.6 MB state
+// snapshot, serializing on the monitor lock. With it, only the first goroutine
+// per tenant runs and the rest reuse the already-encoded bytes.
+var stateComputeGroup singleflight.Group
+
// Router handles HTTP routing
type Router struct {
mux *http.ServeMux
@@ -5171,12 +5178,27 @@ func (r *Router) handleState(w http.ResponseWriter, req *http.Request) {
"Monitor not available", nil)
return
}
- frontendState := monitor.BuildFrontendState()
- if err := utils.WriteJSONResponse(w, frontendState); err != nil {
+ // Dedupe concurrent callers per tenant: only one goroutine builds +
+ // marshals the snapshot; the rest receive the shared byte slice.
+ orgID := GetOrgID(req.Context())
+ if orgID == "" {
+ orgID = "default"
+ }
+ v, err, _ := stateComputeGroup.Do(orgID, func() (any, error) {
+ frontendState := monitor.BuildFrontendState()
+ return json.Marshal(frontendState)
+ })
+ if err != nil {
log.Error().Err(err).Msg("Failed to encode state response")
writeErrorResponse(w, http.StatusInternalServerError, "encoding_error",
"Failed to encode state data", nil)
+ return
+ }
+
+ w.Header().Set("Content-Type", "application/json")
+ if _, err := w.Write(v.([]byte)); err != nil {
+ log.Error().Err(err).Msg("Failed to write state response")
}
}
diff --git a/internal/websocket/hub.go b/internal/websocket/hub.go
index bb628bddf6..14892f5229 100644
--- a/internal/websocket/hub.go
+++ b/internal/websocket/hub.go
@@ -801,10 +801,14 @@ func (h *Hub) HandleWebSocket(w http.ResponseWriter, r *http.Request) {
}
}
- // Create upgrader with our origin check
+ // Create upgrader with our origin check.
+ // Buffers are 64 KB: gorilla streams larger payloads across the buffer
+ // automatically, so the previous 4 MB allocation per connection was
+ // unnecessary overhead that scaled badly with concurrent clients
+ // (100 clients × 8 MB = 800 MB just in buffers).
upgrader := websocket.Upgrader{
- ReadBufferSize: 1024 * 1024 * 4, // 4MB to handle large state messages
- WriteBufferSize: 1024 * 1024 * 4, // 4MB to handle large state messages
+ ReadBufferSize: 64 * 1024,
+ WriteBufferSize: 64 * 1024,
CheckOrigin: h.checkOrigin,
EnableCompression: true,
}