Skip to content

cache tracers on package level to avoid repeated global lookup - #19695

Closed
jan--f wants to merge 3 commits into
prometheus:prep-release-3.15.0-rc.0from
jan--f:perf/tracing-hotpath-tracers
Closed

jan--f wants to merge 3 commits into
prometheus:prep-release-3.15.0-rc.0from
jan--f:perf/tracing-hotpath-tracers

Conversation

@jan--f

@jan--f jan--f commented Sep 14, 2026

Copy link
Copy Markdown
Contributor

The spans added in #19410 call otel.Tracer("") inline, which locks and
looks up the global provider on every span, and build span attributes
(AST serialization, URL redaction, timestamp formatting) even when no
tracer is installed. Use a cached package-level tracer and only set
attributes when span.IsRecording() is true, in promql, scrape and rules.

Checking if this addresses the prombench regression observed in #19669.

Which issue(s) does the PR fix:

Release notes for end users (ALL commits must be considered).

Reviewers should verify clarity and quality.

[PERF] Cache tracers and skip building span attributed when tracing is disabled.

The spans added in prometheus#19410 call otel.Tracer("") inline, which locks and
looks up the global provider on every span, and build span attributes
(AST serialization, URL redaction, timestamp formatting) even when no
tracer is installed. Use a cached package-level tracer and only set
attributes when span.IsRecording() is true, in promql, scrape and rules.

Signed-off-by: Jan Fajerski <[email protected]>
Assisted-by: opencode (claude-opus-4-8)
Use a cached package-level tracer instead of calling otel.Tracer("")
inline, and guard span attribute construction with span.IsRecording(),
in storage/remote, util/stats and web/api/v1.

Signed-off-by: Jan Fajerski <[email protected]>
Assisted-by: opencode (claude-opus-4-8)
Name each cached tracer after its package instead of using an empty
instrumentation scope name, so exported spans are attributed to the
package that created them.

Signed-off-by: Jan Fajerski <[email protected]>
Assisted-by: opencode (claude-opus-4-8)
@jan--f

jan--f commented Sep 14, 2026

Copy link
Copy Markdown
Contributor Author

/prombench v3.14.0

@prombot

prombot commented Sep 14, 2026

Copy link
Copy Markdown
Contributor

⏱️ Welcome to Prometheus Benchmarking Tool. ⏱️

Compared versions: PR-19695 and v3.14.0

After the successful deployment (check status here), the benchmarking results can be viewed at:

Available Commands:

  • To restart benchmark: /prombench restart v3.14.0
  • To stop benchmark: /prombench cancel
  • To print help: /prombench help

@jan--f

jan--f commented Sep 14, 2026

Copy link
Copy Markdown
Contributor Author

cc @prymitive

Comment thread promql/engine.go
NewRangeQuery(ctx context.Context, q storage.Queryable, opts QueryOpts, qs string, start, end time.Time, interval time.Duration) (Query, error)
}

var tracer = otel.Tracer("github.com/prometheus/prometheus/promql")

@bwplotka bwplotka Sep 14, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

NOTE: I was surprised too (I thought global tracer is generally a recommended pattern), but apparently this won't work well without hot reloading for tracing providers in ApplyConfig (AI hinted but I verified). As a consequence promql engine tracing provider won't be updated after the first update.

The one-shot behaviour is NOT in the public godoc: otel.SetTracerProvider only says "registers tp as the global trace provider". It is stated only in internal comments: "It is guaranteed by the caller that this happens only once" — https://github.com/open-telemetry/opentelemetry-go/blob/v1.46.0/internal/global/trace.go#L51-L74
and the delegateTraceOnce in https://github.com/open-telemetry/opentelemetry-go/blob/v1.46.0/internal/global/state.go#L85-L91

Repro test:

const scope = "github.com/prometheus/prometheus/otelswap"

// cachedTracer mimics a package-level `var tracer = otel.Tracer(...)`: it is
// resolved at init time, before any TracerProvider is installed.
var cachedTracer = otel.Tracer(scope)

// TestGlobalDelegationIsOneShot shows that otel.SetTracerProvider only re-points
// already-created tracers on its first call.
//
// NOTE: OTel's global state is process-wide and cannot be reset, so this has to
// be the only test in the package that installs a TracerProvider.
func TestGlobalDelegationIsOneShot(t *testing.T) {
	ctx := context.Background()

	exp1 := tracetest.NewInMemoryExporter()
	tp1 := sdktrace.NewTracerProvider(sdktrace.WithSyncer(exp1))

	// First install: the cached tracer is retroactively re-pointed at tp1.
	otel.SetTracerProvider(tp1)

	startEnd(ctx, cachedTracer, "cached/first")
	startEnd(ctx, otel.Tracer(scope), "inline/first")
	require.Equal(t, []string{"cached/first", "inline/first"}, spanNames(exp1))

	// Second install, exactly what tracing.Manager.ApplyConfig does on reload.
	exp2 := tracetest.NewInMemoryExporter()
	tp2 := sdktrace.NewTracerProvider(sdktrace.WithSyncer(exp2))
	otel.SetTracerProvider(tp2)

	exp1.Reset()
	startEnd(ctx, cachedTracer, "cached/second")
	startEnd(ctx, otel.Tracer(scope), "inline/second")

	// An inline lookup follows the new provider...
	require.Equal(t, []string{"inline/second"}, spanNames(exp2))
	// ...while the cached tracer still writes to the *previous* provider.
	require.Equal(t, []string{"cached/second"}, spanNames(exp1))

	// Now shut the old provider down, which ApplyConfig does before installing a
	// new one. Spans from the cached tracer now go nowhere at all.
	require.NoError(t, tp1.Shutdown(ctx))
	exp1.Reset()
	exp2.Reset()

	_, span := cachedTracer.Start(ctx, "cached/third")
	// The span is still sampled and recorded, so the cost of building
	// attributes is still paid...
	require.True(t, span.IsRecording())
	span.End()

	// ...but it is exported nowhere.
	require.Empty(t, spanNames(exp1))
	require.Empty(t, spanNames(exp2))
}

@bwplotka bwplotka Sep 14, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@dashpole confirmed, and more important -- global provider is not always recommended.

The global is for convenience, similar to a global prometheus registry. It supports delegating only once to handle races between init functions or package import ordering (so otel.Tracer() and otel.SetTracerProvider() can race, but still work). It isn't meant for repeated applyconfig.

@bwplotka bwplotka left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This adds a subtle bug I think. We can also run microbenchmarks but it's unlikely this is a reason for the overhead. We're likely hitting #18046

Commented on the 3.15 PR prombench

@bwplotka bwplotka mentioned this pull request Sep 14, 2026

@bwplotka bwplotka left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With confirmation, I think we shouldn't make this change unless we want to fix the tracer swapability - playing with small microbenchmark

Comment thread promql/engine.go
// n.String() serializes the AST node, so only build it when the
// span is actually recorded.
selectSpan.SetAttributes(
attribute.String("selector", n.String()),

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Those optimizations are pretty nice, just the global cache is tricky

@jan--f
jan--f deleted the branch prometheus:prep-release-3.15.0-rc.0 September 14, 2026 14:55
@jan--f jan--f closed this Sep 14, 2026
@bboreham

Copy link
Copy Markdown
Member

/prombench cancel

@prombot

prombot commented Sep 30, 2026

Copy link
Copy Markdown
Contributor

Benchmark cancel is in progress.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants