Skip to content

Commit

Permalink
1 second caching for loadavg metric
Browse files Browse the repository at this point in the history
Signed-off-by: Shlomi Noach <[email protected]>
  • Loading branch information
shlomi-noach committed Nov 11, 2024
1 parent c2c3384 commit b3f3199
Showing 1 changed file with 20 additions and 1 deletion.
21 changes: 20 additions & 1 deletion go/vt/vttablet/tabletserver/throttle/base/self_metric_loadavg.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,17 @@ package base
import (
"context"
"runtime"
"sync/atomic"
"time"

"vitess.io/vitess/go/osutil"
)

var (
cachedLoadAvgMetric atomic.Pointer[ThrottleMetric]
loadAvgCacheDuration = 1 * time.Second
)

var _ SelfMetric = registerSelfMetric(&LoadAvgSelfMetric{})

type LoadAvgSelfMetric struct {
Expand All @@ -45,13 +52,25 @@ func (m *LoadAvgSelfMetric) RequiresConn() bool {
}

func (m *LoadAvgSelfMetric) Read(ctx context.Context, params *SelfMetricReadParams) *ThrottleMetric {
metric := &ThrottleMetric{
// This function will be called sequentially, and therefore does not need strong mutex protection. Still, we use atomics
// to ensure correctness in case an external goroutine tries to read the metric concurrently.
metric := cachedLoadAvgMetric.Load()
if metric != nil {
return metric
}
metric = &ThrottleMetric{
Scope: SelfScope,
}
val, err := osutil.LoadAvg()
if err != nil {
return metric.WithError(err)
}
metric.Value = val / float64(runtime.NumCPU())

cachedLoadAvgMetric.Store(metric)
time.AfterFunc(loadAvgCacheDuration, func() {
cachedLoadAvgMetric.Store(nil)
})

return metric
}

0 comments on commit b3f3199

Please sign in to comment.