Repository navigation
[management] Fix data race on ctx in HTTP metrics middleware - #8627
Conversation
The context.AfterFunc callback read the local ctx while the handler reassigned it after ServeHTTP, so a request context cancelled as the handler finished raced with that write. Capture the request context in its own variable for the callback, use a separate variable for the post-ServeHTTP context, and stop the AfterFunc once the handler returns.
There was a problem hiding this comment.
Claude Code Review
This repository is configured for manual code reviews. Comment @claude review for a one-time review, or @claude review always to subscribe this PR to a review on every future push.
Tip: disable this comment in your organization's Code Review settings.
|
No actionable comments were generated in the recent review. Walkthrough
Merge Risk:
|
|



Describe your changes
The HTTP metrics middleware registers a
context.AfterFuncwhose callback reads the localctx(forcontext.Cause), while the handler reassignsctx = req.Context()afterServeHTTP. If the request context is cancelled as the handler finishes, the callback goroutine readsctxconcurrently with that write.go test -race -tags devcert -count=8 -run TestBrokerLimitsCallbacksPerClient ./management/internals/modules/mcpapi/reportsWARNING: DATA RACEathttp_api_metrics.go:207(write) vs:198(read) on main.The callback now captures the request context in its own variable, the post-
ServeHTTPcontext uses a separaterespCtx, and theAfterFuncstop function is called once the handler returns. Logging and metrics behaviour is unchanged.Verified: the reproduction above at
-count=50shows no race, andgo test -race -tags devcert ./management/server/telemetry/... ./management/internals/modules/mcpapi/...passes.Issue ticket number and link
None, trivial race fix.
Stack
Checklist
Documentation
Select exactly one:
Internal race fix with no user-facing change.
Docs PR URL (required if "docs added" is checked)
Paste the PR link from https://github.com/netbirdio/docs here:
https://github.com/netbirdio/docs/pull/__
Generated by Claude Code
Summary by CodeRabbit