Skip to content

fix(telemetry): instrument v3 API routes with tracing - #4468

Merged
gergely-kurucz-konghq merged 7 commits into
mainfrom
fix/telemetry-instrument-v3-endpoints-with-tracing
Jun 3, 2026
Merged

gergely-kurucz-konghq merged 7 commits into
mainfrom
fix/telemetry-instrument-v3-endpoints-with-tracing

Conversation

@gergely-kurucz-konghq

@gergely-kurucz-konghq gergely-kurucz-konghq commented Jun 1, 2026 •

Copy link
Copy Markdown
Contributor

What

Instruments the v3 API with OpenTelemetry HTTP tracing/metrics (on par with v1), gives server spans meaningful low-cardinality names, and adds an optional per-operation child span behind a global toggle.

Why

v3 routes had no otelhttp instrumentation (the v3 group was registered before the telemetry middleware), and server spans had empty/unhelpful names — making v3 traces hard to find and group. We also wanted handler-vs-middleware timing visibility without inflating span volume across the whole API.

How

  • v3 instrumentation: materialize the router-hook middlewares once and apply the same slice to both the v3 and v1 groups (hooks run once; no double side effects).
  • Span name: METHOD /route/{template} from the chi route pattern (r.Pattern → chi RouteContext → fallback). Unresolved mount wildcards (/api/v3/*) are skipped.
  • http.route attribute + metric label: the exact route template — the canonical low-cardinality routing dimension. url.path is path-only (no query string).
  • Cardinality bounding: the fallback path masks ULIDs, UUIDs, numeric ids, and over-long opaque segments to :id, and truncates pathologically deep paths — so unmatched/scanner traffic can't blow up span-name cardinality.
  • Per-operation child span: application-level span named after the operation (e.g. list-customers), nested under the server span, exposing the middleware-vs-handler split. Off by default, enabled via telemetry.trace.operationSpans, since it adds a span to every request.

Note on otelhttp v0.68: the span name is set at span start (and re-set on a post-handler pass when r.Pattern is set), so naming is done in WithSpanNameFormatter rather than via a post-start SetName (a no-op in this chi setup).

Summary by CodeRabbit

  • Improvements
    • Enhanced OpenTelemetry instrumentation for richer request tracing and reduced span cardinality by masking dynamic path segments.
    • Normalized server span naming and improved URL-path attribution for clearer traces.
  • New Features
    • Optional per-operation child spans (disabled by default) for more granular application-level tracing.
  • Improvements
    • Consolidated middleware collection so routing groups share consistent middleware.
  • Tests
    • Added tests validating path masking and truncation behavior.

The v3 router group was registered before RouterHooks.Middlewares were
applied, so v3 routes had no otelhttp instrumentation while v1 did. Apply
the hook middlewares to the v3 group as well (via collectMiddlewareHooks),
giving v3 the same tracing and metrics as v1.

Span naming:
- Server span is named "METHOD /route/{template}" from chi's resolved
  route pattern, which is already available when otelhttp's
  WithSpanNameFormatter runs. Path params render as "{param}", so both
  ULID ids and arbitrary entity keys collapse to a low-cardinality name.
  Falls back to a ULID-collapsed raw path for unmatched routes (404s).
- The exact template is also recorded on the http.route attribute and
  metric label (the canonical low-cardinality routing dimension).
- Each handler opens an application-level child span named after its
  operation (httptransport.WithOperationName), nested under the server
  span and parenting downstream DB spans. The server span captures the
  full HTTP-boundary timing (incl. middleware); the operation span
  captures app logic — the delta surfaces middleware overhead.

Note: otelhttp fixes the span name at tracer.Start, and a post-start
SetName on the server span is a no-op in this chi setup, which is why the
name is derived in the formatter rather than after routing.
@coderabbitai

coderabbitai Bot commented Jun 1, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds low-cardinality server span naming and explicit http.route attribution, exposes a global toggle and handler-level per-operation spans, materializes router-hook middlewares for reuse, and adds config + tests for low-cardinality path behavior.

Changes

OpenTelemetry Span Instrumentation and Middleware Hook Collection

Layer / File(s) Summary
Server span naming with low-cardinality path transformation
app/common/telemetry.go, app/common/telemetry_test.go
Telemetry router hook records http.route from Chi, uses r.URL.Path for URLPath, replaces in-handler span naming with otelhttp.WithSpanNameFormatter, and adds lowCardinalityPath to mask ULID/UUID/digit/long tokens to :id. Tests for masking and truncation added.
Operation-span toggle and handler-level spans
app/common/telemetry.go, pkg/framework/transport/httptransport/handler.go
NewTracerProvider enables the global operation-span toggle at init; EnableOperationSpans added and ServeHTTP starts a per-operation child span when operationNameFunc is set and the toggle is enabled, setting semconv.HTTPRouteKey.
Middleware hook collection infrastructure
openmeter/server/server.go
Introduces middlewareCollector and collectMiddlewareHooks to materialize config.RouterHooks.Middlewares into a flattened []server.MiddlewareFunc which is prepended to v3 middleware and applied to v1 registrations.
Telemetry config default
app/config/telemetry.go
Adds OperationSpans bool to TraceTelemetryConfig and sets Viper default telemetry.trace.operationSpans = false.

🎯 3 (Moderate) | ⏱️ ~25 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately reflects the main changes: applying OpenTelemetry instrumentation to v3 API routes through improved telemetry setup and span naming.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/telemetry-instrument-v3-endpoints-with-tracing

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (2)
openmeter/server/server.go (2)

108-108: ⚖️ Poor tradeoff

Heads-up on the slog.Default() fallback.

This mirrors the existing v1 setup, so no behavior regression — but as per coding guidelines, production initialization shouldn't lean on slog.Default() as a fallback; the logger should be injected via config/provider inputs. If you do the shared-builder extraction above, that's a natural spot to thread an explicit *slog.Logger through instead.

As per coding guidelines: "In production constructors and initialization, do not use slog.Default() as a fallback; require a *slog.Logger in config/provider inputs and inject it explicitly".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@openmeter/server/server.go` at line 108, The code currently uses
slog.Default().Handler() inside server.NewRequestLoggerMiddleware which relies
on a global fallback; change the constructor/initialization to accept and
propagate an explicit *slog.Logger from your config/provider and pass its
Handler to NewRequestLoggerMiddleware instead of calling slog.Default(), e.g.,
add a logger field to the shared builder/provider and thread that *slog.Logger
into the call site so NewRequestLoggerMiddleware receives an injected logger
handler rather than using slog.Default().

95-110: ⚡ Quick win

Nice fix wiring v3 into the same instrumentation! Consider sharing the standard middleware chain.

The construction here works (you're appending to a freshly returned slice, so no aliasing surprises 👍). One thing worth tidying: the standard chain (RealIP, RequestID, the contextx attrs wrapper, request logger, Recoverer) is now defined twice — here for v3 and again in the v1 group at Lines 167-178. They're identical today, but they can quietly drift apart later. Extracting a tiny builder keeps both groups honest.

♻️ One shared builder for both groups
func standardMiddlewares() []server.MiddlewareFunc {
	return []server.MiddlewareFunc{
		middleware.RealIP,
		middleware.RequestID,
		func(h http.Handler) http.Handler {
			return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
				ctx := r.Context()
				ctx = contextx.WithAttrs(ctx, server.GetRequestAttributes(r))

				h.ServeHTTP(w, r.WithContext(ctx))
			})
		},
		server.NewRequestLoggerMiddleware(slog.Default().Handler()),
		middleware.Recoverer,
	}
}

Then here:

-	v3Middlewares := append(collectMiddlewareHooks(config.RouterHooks.Middlewares), []server.MiddlewareFunc{
-		middleware.RealIP,
-		middleware.RequestID,
-		func(h http.Handler) http.Handler {
-			return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
-				ctx := r.Context()
-				ctx = contextx.WithAttrs(ctx, server.GetRequestAttributes(r))
-
-				h.ServeHTTP(w, r.WithContext(ctx))
-			})
-		},
-		server.NewRequestLoggerMiddleware(slog.Default().Handler()),
-		middleware.Recoverer,
-	}...)
+	v3Middlewares := append(collectMiddlewareHooks(config.RouterHooks.Middlewares), standardMiddlewares()...)

And the v1 group can reuse it via for _, mw := range standardMiddlewares() { r.Use(mw) }.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@openmeter/server/server.go` around lines 95 - 110, Extract the duplicated
standard middleware slice into a single helper (e.g. standardMiddlewares()) that
returns []server.MiddlewareFunc containing middleware.RealIP,
middleware.RequestID, the contextx.WithAttrs wrapper,
server.NewRequestLoggerMiddleware(slog.Default().Handler()), and
middleware.Recoverer; then replace the inline slice usage in v3Middlewares
(currently built with append(collectMiddlewareHooks(...),
[]server.MiddlewareFunc{...}...)) and the identical middleware list used for the
v1 router group by calling/iterating over standardMiddlewares() (use append(...,
standardMiddlewares()...) for v3 and for v1 call r.Use for each mw from
standardMiddlewares()) so both groups share the same source of truth.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@app/common/telemetry.go`:
- Line 289: The span attribute is using r.URL.String() which can include the
query string; update the span.SetAttributes call in the telemetry wrapper (the
line with span.SetAttributes(semconv.URLPath(r.URL.String()),
semconv.HTTPRoute(routePattern))) to pass semconv.URLPath(r.URL.Path) instead to
record only the path component (avoiding query-derived cardinality and PII
leakage) while keeping semconv.HTTPRoute(routePattern) unchanged.
- Around line 298-311: The span-name formatter currently reads
chi.RouteContext() too early (otelhttp.WithSpanNameFormatter runs before routing
completes) so RoutePattern() is usually empty; update the logic so the route
template is resolved after routing (e.g., set the span name inside
middleware/after calling next.ServeHTTP or rely on chi's middleware that sets
the template) rather than in otelhttp.WithSpanNameFormatter, and ensure
lowCardinalityPath can handle non-ULID param placeholders; also change any
semconv.URLPath usage to use r.URL.Path (not r.URL.String()) to avoid including
query params. Reference: otelhttp.WithSpanNameFormatter, lowCardinalityPath,
chi.RouteContext/RoutePattern, and semconv.URLPath.

---

Nitpick comments:
In `@openmeter/server/server.go`:
- Line 108: The code currently uses slog.Default().Handler() inside
server.NewRequestLoggerMiddleware which relies on a global fallback; change the
constructor/initialization to accept and propagate an explicit *slog.Logger from
your config/provider and pass its Handler to NewRequestLoggerMiddleware instead
of calling slog.Default(), e.g., add a logger field to the shared
builder/provider and thread that *slog.Logger into the call site so
NewRequestLoggerMiddleware receives an injected logger handler rather than using
slog.Default().
- Around line 95-110: Extract the duplicated standard middleware slice into a
single helper (e.g. standardMiddlewares()) that returns []server.MiddlewareFunc
containing middleware.RealIP, middleware.RequestID, the contextx.WithAttrs
wrapper, server.NewRequestLoggerMiddleware(slog.Default().Handler()), and
middleware.Recoverer; then replace the inline slice usage in v3Middlewares
(currently built with append(collectMiddlewareHooks(...),
[]server.MiddlewareFunc{...}...)) and the identical middleware list used for the
v1 router group by calling/iterating over standardMiddlewares() (use append(...,
standardMiddlewares()...) for v3 and for v1 call r.Use for each mw from
standardMiddlewares()) so both groups share the same source of truth.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 805d079e-fd90-48b4-b2d1-9aa10a0a50cb

📥 Commits

Reviewing files that changed from the base of the PR and between 8bca288 and 07e1d55.

📒 Files selected for processing (3)
  • app/common/telemetry.go
  • openmeter/server/server.go
  • pkg/framework/transport/httptransport/handler.go

Comment thread app/common/telemetry.go Resolved
Comment thread app/common/telemetry.go Resolved
Use r.URL.Path instead of r.URL.String() for the url.path span attribute
to avoid query-string cardinality and potential PII in traces.

@mark-vass-konghq mark-vass-konghq left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I didn’t find a clear merge-blocking bug. Possible improvements I’d consider

Comment thread app/common/telemetry.go Resolved
Comment thread openmeter/server/server.go Resolved
Comment thread openmeter/server/server.go Resolved
Comment thread app/common/telemetry.go Resolved
Build the hook middleware slice a single time and apply it to both the v3
and v1 groups, instead of re-invoking the hook functions per group. Avoids
running hook bodies twice — harmless for telemetry, unsafe for future hooks
with construction side effects.
otelhttp's post-handler pass surfaces r.Pattern as the sub-router mount
prefix ("/api/v3/*"), which leaked into v3 span names. Skip any "*"-bearing
route from all sources (r.Pattern, chi RoutePattern) and fall back to the
ULID-collapsed path. Also document otelhttp's two-pass formatter behavior.
lowCardinalityPath only masked ULIDs, so arbitrary slugs/keys/tokens from
v3 (mount-wildcard fallback) and unmatched/scanner traffic leaked into span
names. Also mask UUIDs, numeric ids, and over-long opaque segments, and
truncate pathologically deep paths. Add unit tests.
The application-level per-operation child span was emitted for every
httptransport handler with an operation name — v1/v2/v3 alike — adding a
span to nearly every request. Make it a global, default-off switch
(telemetry.trace.operationSpans) applied once at trace init via
httptransport.EnableOperationSpans, so the extra span volume is a
deliberate per-env opt-in. The http.route attribute is still set regardless.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (2)
app/common/telemetry_test.go (1)

13-65: ⚡ Quick win

Add one test around the actual formatter path selection.

These cases pin lowCardinalityPath, but the fragile bit in this PR is the WithSpanNameFormatter decision tree (r.Pattern vs chi RoutePattern vs wildcard skip vs fallback). A small request-level test around NewTelemetryRouterHook would give you coverage for the behavior that actually fixes v3 naming. As per coding guidelines, **/*_test.go: "Make sure the tests are comprehensive and cover the changes."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@app/common/telemetry_test.go` around lines 13 - 65, Add a test that exercises
the formatter selection logic in NewTelemetryRouterHook: create a chi router
with routes that set r.Pattern and some that rely on chi's RoutePattern (use
route parameters and a wildcard route), install NewTelemetryRouterHook (or call
WithSpanNameFormatter path selection) and send test requests to verify the
produced span name uses the correct formatter (lowCardinalityPath vs
pattern-based vs skipped wildcard) — assert the final span name equals the
expected string for each case; reference NewTelemetryRouterHook,
WithSpanNameFormatter, lowCardinalityPath, r.Pattern and RoutePattern in the
test so it covers the decision tree described in the review.
pkg/framework/transport/httptransport/handler.go (1)

35-39: ⚡ Quick win

Please add a unit test for the global toggle behavior.

This change is broad enough that it’s worth pinning both modes: with EnableOperationSpans(false) no extra child span should be created, and with it enabled you should get exactly one operation child span under the server span. That keeps this package-level switch from becoming order-dependent or silently regressing later. As per coding guidelines, **/*_test.go: "Make sure the tests are comprehensive and cover the changes."

Also applies to: 105-115

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pkg/framework/transport/httptransport/handler.go` around lines 35 - 39, Add a
new *_test.go that verifies the package-level toggle by calling
EnableOperationSpans(false) and EnableOperationSpans(true), resetting
operationSpansEnabled as needed between cases, then exercising the HTTP handler
code path that produces a server span (e.g., invoking the handler's ServeHTTP or
the function that starts the server span) while using an in-memory/testing
OpenTelemetry exporter/tracer to capture spans; assert that when disabled there
are zero operation child spans under the server span and when enabled there is
exactly one operation child span. Ensure the test isolates global state
(restore/reset operationSpansEnabled) and uses deterministic span collection so
it fails if the toggle is order-dependent or regresses.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@app/common/telemetry_test.go`:
- Around line 13-65: Add a test that exercises the formatter selection logic in
NewTelemetryRouterHook: create a chi router with routes that set r.Pattern and
some that rely on chi's RoutePattern (use route parameters and a wildcard
route), install NewTelemetryRouterHook (or call WithSpanNameFormatter path
selection) and send test requests to verify the produced span name uses the
correct formatter (lowCardinalityPath vs pattern-based vs skipped wildcard) —
assert the final span name equals the expected string for each case; reference
NewTelemetryRouterHook, WithSpanNameFormatter, lowCardinalityPath, r.Pattern and
RoutePattern in the test so it covers the decision tree described in the review.

In `@pkg/framework/transport/httptransport/handler.go`:
- Around line 35-39: Add a new *_test.go that verifies the package-level toggle
by calling EnableOperationSpans(false) and EnableOperationSpans(true), resetting
operationSpansEnabled as needed between cases, then exercising the HTTP handler
code path that produces a server span (e.g., invoking the handler's ServeHTTP or
the function that starts the server span) while using an in-memory/testing
OpenTelemetry exporter/tracer to capture spans; assert that when disabled there
are zero operation child spans under the server span and when enabled there is
exactly one operation child span. Ensure the test isolates global state
(restore/reset operationSpansEnabled) and uses deterministic span collection so
it fails if the toggle is order-dependent or regresses.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 7bec728e-eb89-4ae8-aa00-85e878481e77

📥 Commits

Reviewing files that changed from the base of the PR and between e494cd9 and 155b1fa.

📒 Files selected for processing (5)
  • app/common/telemetry.go
  • app/common/telemetry_test.go
  • app/config/telemetry.go
  • openmeter/server/server.go
  • pkg/framework/transport/httptransport/handler.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • openmeter/server/server.go

Comment thread app/common/telemetry.go Resolved
@gergely-kurucz-konghq
gergely-kurucz-konghq merged commit 55a9972 into main Jun 3, 2026
31 checks passed
@gergely-kurucz-konghq
gergely-kurucz-konghq deleted the fix/telemetry-instrument-v3-endpoints-with-tracing branch June 3, 2026 13:51

This branch was previously deployed

1 inactive deployment
dev — 155b1fa1 Deployed Jun 3, 2026 by gergely-kurucz-konghq via Migration Checks #14800
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

release-note/misc Miscellaneous changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants