From ddd7f0edcd31dd27b31ee9c54b5c22d44258d5d1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fabian=20St=C3=A4ber?= Date: Mon, 17 Oct 2022 20:50:50 +0200 Subject: [PATCH] Fix race condition with Exemplar in Counter (#1146) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Fix race condition with Exemplar in Counter Potential fix for #1145. Signed-off-by: Fabian Stäber * Fix race condition with Exemplar in Counter Signed-off-by: Fabian Stäber Signed-off-by: Fabian Stäber --- prometheus/counter.go | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/prometheus/counter.go b/prometheus/counter.go index de30de6da..3668a16b3 100644 --- a/prometheus/counter.go +++ b/prometheus/counter.go @@ -140,12 +140,13 @@ func (c *counter) get() float64 { } func (c *counter) Write(out *dto.Metric) error { - val := c.get() - + // Read the Exemplar first and the value second. This is to avoid a race condition + // where users see an exemplar for a not-yet-existing observation. var exemplar *dto.Exemplar if e := c.exemplar.Load(); e != nil { exemplar = e.(*dto.Exemplar) } + val := c.get() return populateMetric(CounterValue, val, c.labelPairs, exemplar, out) }