Skip to content

SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.

fix: cache memory leak (#10967)

Tushar Vats1bd4ca88de73
diff --git a/pkg/cache/memorycache/provider.go b/pkg/cache/memorycache/provider.go
index c51c6057d4..b5a1f49eeb 100644
--- a/pkg/cache/memorycache/provider.go
+++ b/pkg/cache/memorycache/provider.go
@@ -64,7 +64,8 @@ func New(ctx context.Context, settings factory.ProviderSettings, config cache.Co
o.ObserveInt64(telemetry.setsRejected, int64(metrics.SetsRejected()), metric.WithAttributes(attributes...))
o.ObserveInt64(telemetry.getsDropped, int64(metrics.GetsDropped()), metric.WithAttributes(attributes...))
o.ObserveInt64(telemetry.getsKept, int64(metrics.GetsKept()), metric.WithAttributes(attributes...))
- o.ObserveInt64(telemetry.totalCost, int64(cc.MaxCost()), metric.WithAttributes(attributes...))
+ o.ObserveInt64(telemetry.costUsed, int64(metrics.CostAdded())-int64(metrics.CostEvicted()), metric.WithAttributes(attributes...))
+ o.ObserveInt64(telemetry.totalCost, cc.MaxCost(), metric.WithAttributes(attributes...))
return nil
},
telemetry.cacheRatio,
@@ -79,6 +80,7 @@ func New(ctx context.Context, settings factory.ProviderSettings, config cache.Co
telemetry.setsRejected,
telemetry.getsDropped,
telemetry.getsKept,
+ telemetry.costUsed,
telemetry.totalCost,
)
if err != nil {
@@ -112,11 +114,13 @@ func (provider *provider) Set(ctx context.Context, orgID valuer.UUID, cacheKey s
}
if cloneable, ok := data.(cachetypes.Cloneable); ok {
+ cost := max(cloneable.Cost(), 1)
+ // Clamp to a minimum of 1: ristretto treats cost 0 specially and we
+ // never want zero-size entries to bypass admission accounting.
span.SetAttributes(attribute.Bool("memory.cloneable", true))
- span.SetAttributes(attribute.Int64("memory.cost", 1))
+ span.SetAttributes(attribute.Int64("memory.cost", cost))
toCache := cloneable.Clone()
- // In case of contention we are choosing to evict the cloneable entries first hence cost is set to 1
- if ok := provider.cc.SetWithTTL(strings.Join([]string{orgID.StringValue(), cacheKey}, "::"), toCache, 1, ttl); !ok {
+ if ok := provider.cc.SetWithTTL(strings.Join([]string{orgID.StringValue(), cacheKey}, "::"), toCache, cost, ttl); !ok {
return errors.New(errors.TypeInternal, errors.CodeInternal, "error writing to cache")
}
@@ -125,15 +129,15 @@ func (provider *provider) Set(ctx context.Context, orgID valuer.UUID, cacheKey s
}
toCache, err := provider.marshalBinary(ctx, data)
- cost := int64(len(toCache))
if err != nil {
return err
}
+ cost := max(int64(len(toCache)), 1)
span.SetAttributes(attribute.Bool("memory.cloneable", false))
span.SetAttributes(attribute.Int64("memory.cost", cost))
- if ok := provider.cc.SetWithTTL(strings.Join([]string{orgID.StringValue(), cacheKey}, "::"), toCache, 1, ttl); !ok {
+ if ok := provider.cc.SetWithTTL(strings.Join([]string{orgID.StringValue(), cacheKey}, "::"), toCache, cost, ttl); !ok {
return errors.New(errors.TypeInternal, errors.CodeInternal, "error writing to cache")
}
diff --git a/pkg/cache/memorycache/provider_test.go b/pkg/cache/memorycache/provider_test.go
index 0b2c988f4a..f9586f257c 100644
--- a/pkg/cache/memorycache/provider_test.go
+++ b/pkg/cache/memorycache/provider_test.go
@@ -31,6 +31,10 @@ func (cloneable *CloneableA) Clone() cachetypes.Cacheable {
}
}
+func (cloneable *CloneableA) Cost() int64 {
+ return int64(len(cloneable.Key)) + 16
+}
+
func (cloneable *CloneableA) MarshalBinary() ([]byte, error) {
return json.Marshal(cloneable)
}
@@ -165,6 +169,45 @@ func TestSetGetWithDifferentTypes(t *testing.T) {
assert.Error(t, err)
}
+// LargeCloneable reports a large byte cost so we can test ristretto eviction
+// without allocating the full payload in memory.
+type LargeCloneable struct {
+ Key string
+ CostHint int64
+}
+
+func (c *LargeCloneable) Clone() cachetypes.Cacheable {
+ return &LargeCloneable{Key: c.Key, CostHint: c.CostHint}
+}
+
+func (c *LargeCloneable) Cost() int64 { return c.CostHint }
+
+func (c *LargeCloneable) MarshalBinary() ([]byte, error) { return json.Marshal(c) }
+
+func (c *LargeCloneable) UnmarshalBinary(data []byte) error { return json.Unmarshal(data, c) }
+
+func TestCloneableExceedingMaxCostIsRejected(t *testing.T) {
+ const maxCost int64 = 1 << 20 // 1 MiB
+ const oversize int64 = 2 << 20 // 2 MiB, larger than the entire cache
+
+ c, err := New(context.Background(), factorytest.NewSettings(), cache.Config{Provider: "memory", Memory: cache.Memory{
+ NumCounters: 10 * 1000,
+ MaxCost: maxCost,
+ }})
+ require.NoError(t, err)
+
+ orgID := valuer.GenerateUUID()
+ const key = "oversize-key"
+ assert.NoError(t, c.Set(context.Background(), orgID, key,
+ &LargeCloneable{Key: key, CostHint: oversize}, time.Minute))
+
+ // Ristretto rejects any entry with cost > MaxCost (policy.go:100). Probe
+ // ristretto directly to confirm no admission, instead of relying on metrics.
+ cc := c.(*provider).cc
+ _, ok := cc.Get(strings.Join([]string{orgID.StringValue(), key}, "::"))
+ assert.False(t, ok, "entry with Cost() > MaxCost must be rejected")
+}
+
func TestCloneableConcurrentSetGet(t *testing.T) {
cache, err := New(context.Background(), factorytest.NewSettings(), cache.Config{Provider: "memory", Memory: cache.Memory{
NumCounters: 10 * 1000,
diff --git a/pkg/cache/memorycache/telemetry.go b/pkg/cache/memorycache/telemetry.go
index 811acf3828..791b48b3a3 100644
--- a/pkg/cache/memorycache/telemetry.go
+++ b/pkg/cache/memorycache/telemetry.go
@@ -7,17 +7,18 @@ import (
type telemetry struct {
cacheRatio metric.Float64ObservableGauge
- cacheHits metric.Int64ObservableGauge
- cacheMisses metric.Int64ObservableGauge
- costAdded metric.Int64ObservableGauge
- costEvicted metric.Int64ObservableGauge
- keysAdded metric.Int64ObservableGauge
- keysEvicted metric.Int64ObservableGauge
- keysUpdated metric.Int64ObservableGauge
- setsDropped metric.Int64ObservableGauge
- setsRejected metric.Int64ObservableGauge
- getsDropped metric.Int64ObservableGauge
- getsKept metric.Int64ObservableGauge
+ cacheHits metric.Int64ObservableCounter
+ cacheMisses metric.Int64ObservableCounter
+ costAdded metric.Int64ObservableCounter
+ costEvicted metric.Int64ObservableCounter
+ keysAdded metric.Int64ObservableCounter
+ keysEvicted metric.Int64ObservableCounter
+ keysUpdated metric.Int64ObservableCounter
+ setsDropped metric.Int64ObservableCounter
+ setsRejected metric.Int64ObservableCounter
+ getsDropped metric.Int64ObservableCounter
+ getsKept metric.Int64ObservableCounter
+ costUsed metric.Int64ObservableGauge
totalCost metric.Int64ObservableGauge
}
@@ -28,62 +29,67 @@ func newMetrics(meter metric.Meter) (*telemetry, error) {
errs = errors.Join(errs, err)
}
- cacheHits, err := meter.Int64ObservableGauge("signoz.cache.hits", metric.WithDescription("Hits is the number of Get calls where a value was found for the corresponding key."))
+ cacheHits, err := meter.Int64ObservableCounter("signoz.cache.hits", metric.WithDescription("Hits is the number of Get calls where a value was found for the corresponding key."))
if err != nil {
errs = errors.Join(errs, err)
}
- cacheMisses, err := meter.Int64ObservableGauge("signoz.cache.misses", metric.WithDescription("Misses is the number of Get calls where a value was not found for the corresponding key"))
+ cacheMisses, err := meter.Int64ObservableCounter("signoz.cache.misses", metric.WithDescription("Misses is the number of Get calls where a value was not found for the corresponding key"))
if err != nil {
errs = errors.Join(errs, err)
}
- costAdded, err := meter.Int64ObservableGauge("signoz.cache.cost.added", metric.WithDescription("CostAdded is the sum of costs that have been added (successful Set calls)"))
+ costAdded, err := meter.Int64ObservableCounter("signoz.cache.cost.added", metric.WithDescription("CostAdded is the sum of costs that have been added (successful Set calls)"))
if err != nil {
errs = errors.Join(errs, err)
}
- costEvicted, err := meter.Int64ObservableGauge("signoz.cache.cost.evicted", metric.WithDescription("CostEvicted is the sum of all costs that have been evicted"))
+ costEvicted, err := meter.Int64ObservableCounter("signoz.cache.cost.evicted", metric.WithDescription("CostEvicted is the sum of all costs that have been evicted"))
if err != nil {
errs = errors.Join(errs, err)
}
- keysAdded, err := meter.Int64ObservableGauge("signoz.cache.keys.added", metric.WithDescription("KeysAdded is the total number of Set calls where a new key-value item was added"))
+ keysAdded, err := meter.Int64ObservableCounter("signoz.cache.keys.added", metric.WithDescription("KeysAdded is the total number of Set calls where a new key-value item was added"))
if err != nil {
errs = errors.Join(errs, err)
}
- keysEvicted, err := meter.Int64ObservableGauge("signoz.cache.keys.evicted", metric.WithDescription("KeysEvicted is the total number of keys evicted"))
+ keysEvicted, err := meter.Int64ObservableCounter("signoz.cache.keys.evicted", metric.WithDescription("KeysEvicted is the total number of keys evicted"))
if err != nil {
errs = errors.Join(errs, err)
}
- keysUpdated, err := meter.Int64ObservableGauge("signoz.cache.keys.updated", metric.WithDescription("KeysUpdated is the total number of Set calls where the value was updated"))
+ keysUpdated, err := meter.Int64ObservableCounter("signoz.cache.keys.updated", metric.WithDescription("KeysUpdated is the total number of Set calls where the value was updated"))
if err != nil {
errs = errors.Join(errs, err)
}
- setsDropped, err := meter.Int64ObservableGauge("signoz.cache.sets.dropped", metric.WithDescription("SetsDropped is the number of Set calls that don't make it into internal buffers (due to contention or some other reason)"))
+ setsDropped, err := meter.Int64ObservableCounter("signoz.cache.sets.dropped", metric.WithDescription("SetsDropped is the number of Set calls that don't make it into internal buffers (due to contention or some other reason)"))
if err != nil {
errs = errors.Join(errs, err)
}
- setsRejected, err := meter.Int64ObservableGauge("signoz.cache.sets.rejected", metric.WithDescription("SetsRejected is the number of Set calls rejected by the policy (TinyLFU)"))
+ setsRejected, err := meter.Int64ObservableCounter("signoz.cache.sets.rejected", metric.WithDescription("SetsRejected is the number of Set calls rejected by the policy (TinyLFU)"))
if err != nil {
errs = errors.Join(errs, err)
}
- getsDropped, err := meter.Int64ObservableGauge("signoz.cache.gets.dropped", metric.WithDescription("GetsDropped is the number of Get calls that don't make it into internal buffers (due to contention or some other reason)"))
+ getsDropped, err := meter.Int64ObservableCounter("signoz.cache.gets.dropped", metric.WithDescription("GetsDropped is the number of Get calls that don't make it into internal buffers (due to contention or some other reason)"))
if err != nil {
errs = errors.Join(errs, err)
}
- getsKept, err := meter.Int64ObservableGauge("signoz.cache.gets.kept", metric.WithDescription("GetsKept is the number of Get calls that make it into internal buffers"))
+ getsKept, err := meter.Int64ObservableCounter("signoz.cache.gets.kept", metric.WithDescription("GetsKept is the number of Get calls that make it into internal buffers"))
if err != nil {
errs = errors.Join(errs, err)
}
- totalCost, err := meter.Int64ObservableGauge("signoz.cache.total.cost", metric.WithDescription("TotalCost is the available cost configured for the cache"))
+ costUsed, err := meter.Int64ObservableGauge("signoz.cache.cost.used", metric.WithDescription("CostUsed is the current retained cost in the cache (CostAdded - CostEvicted)."))
+ if err != nil {
+ errs = errors.Join(errs, err)
+ }
+
+ totalCost, err := meter.Int64ObservableGauge("signoz.cache.total.cost", metric.WithDescription("TotalCost is the configured MaxCost ceiling for the cache."))
if err != nil {
errs = errors.Join(errs, err)
}
@@ -105,6 +111,7 @@ func newMetrics(meter metric.Meter) (*telemetry, error) {
setsRejected: setsRejected,
getsDropped: getsDropped,
getsKept: getsKept,
+ costUsed: costUsed,
totalCost: totalCost,
}, nil
}
diff --git a/pkg/cache/rediscache/provider_test.go b/pkg/cache/rediscache/provider_test.go
index 9ab3f0ec33..0e141b6585 100644
--- a/pkg/cache/rediscache/provider_test.go
+++ b/pkg/cache/rediscache/provider_test.go
@@ -29,6 +29,10 @@ func (cacheable *CacheableA) Clone() cachetypes.Cacheable {
}
}
+func (cacheable *CacheableA) Cost() int64 {
+ return int64(len(cacheable.Key)) + 16
+}
+
func (cacheable *CacheableA) MarshalBinary() ([]byte, error) {
return json.Marshal(cacheable)
}
diff --git a/pkg/query-service/model/cacheable.go b/pkg/query-service/model/cacheable.go
index 9feba2b2d8..f215405c9a 100644
--- a/pkg/query-service/model/cacheable.go
+++ b/pkg/query-service/model/cacheable.go
@@ -41,6 +41,11 @@ func (c *GetWaterfallSpansForTraceWithMetadataCache) Clone() cachetypes.Cacheabl
}
}
+func (c *GetWaterfallSpansForTraceWithMetadataCache) Cost() int64 {
+ const perSpanBytes = 256
+ return int64(c.TotalSpans) * perSpanBytes
+}
+
func (c *GetWaterfallSpansForTraceWithMetadataCache) MarshalBinary() (data []byte, err error) {
return json.Marshal(c)
}
@@ -66,6 +71,16 @@ func (c *GetFlamegraphSpansForTraceCache) Clone() cachetypes.Cacheable {
}
}
+func (c *GetFlamegraphSpansForTraceCache) Cost() int64 {
+ const perSpanBytes = 128
+ var spans int64
+ for _, row := range c.SelectedSpans {
+ spans += int64(len(row))
+ }
+ spans += int64(len(c.TraceRoots))
+ return spans * perSpanBytes
+}
+
func (c *GetFlamegraphSpansForTraceCache) MarshalBinary() (data []byte, err error) {
return json.Marshal(c)
}
diff --git a/pkg/types/cachetypes/cacheable.go b/pkg/types/cachetypes/cacheable.go
index db587552e3..b36fea8766 100644
--- a/pkg/types/cachetypes/cacheable.go
+++ b/pkg/types/cachetypes/cacheable.go
@@ -18,6 +18,10 @@ type Cloneable interface {
// Creates a deep copy of the Cacheable. This method is useful for memory caches to avoid the need for serialization/deserialization. It also prevents
// race conditions in the memory cache.
Clone() Cacheable
+ // Cost returns the weight of this entry for cost-based cache accounting
+ // and eviction. Typically derived from the approximate retained byte size,
+ // but the value represents cache cost, not literal bytes.
+ Cost() int64
}
func NewSha1CacheKey(val string) string {
diff --git a/pkg/types/querybuildertypes/querybuildertypesv5/cached.go b/pkg/types/querybuildertypes/querybuildertypesv5/cached.go
index ad2c615c09..f374a764e4 100644
--- a/pkg/types/querybuildertypes/querybuildertypesv5/cached.go
+++ b/pkg/types/querybuildertypes/querybuildertypesv5/cached.go
@@ -59,3 +59,21 @@ func (c *CachedData) Clone() cachetypes.Cacheable {
return clonedCachedData
}
+
+// Cost approximates the retained bytes of this CachedData for use as the
+// ristretto cache cost. The dominant contributor is the serialized bucket
+// values (json.RawMessage); other fields are fixed-size or small strings.
+func (c *CachedData) Cost() int64 {
+ var size int64
+ for _, b := range c.Buckets {
+ if b == nil {
+ continue
+ }
+ // Value is the bulk of the payload
+ size += int64(len(b.Value))
+ }
+ for _, w := range c.Warnings {
+ size += int64(len(w))
+ }
+ return size
+}