Skip to content

http: use sync.Map for request-scoped vars#7595

Open
mohammed90 wants to merge 1 commit intomasterfrom
concurrent-var-access
Open

http: use sync.Map for request-scoped vars#7595
mohammed90 wants to merge 1 commit intomasterfrom
concurrent-var-access

Conversation

@mohammed90
Copy link
Copy Markdown
Member

I received a report of a concurrent map read and map write failure at this line

if ip, ok := GetVar(r.Context(), ClientIPVarKey).(string); ok {
enc.AddString("client_ip", ip)
}

The only conceivable reason for it is due to how the cache handler creates data race between cache and upstream on the same http.Request object. I cannot think of any other scenario. Whether it's truly the culprit or not, we can resolve it for all cases by using sync.Map. I contemplated creating our own opaque map struct with a mutex, but the one of use cases listed in sync.Map documentation seems to apply to our scenario:

The Map type is optimized for two common use cases: (1) when the entry for a given key is only ever written once but read many times, as in caches that only grow, or (2) when multiple goroutines read, write, and overwrite entries for disjoint sets of keys. In these two cases, use of a Map may significantly reduce lock contention compared to a Go map paired with a separate Mutex or RWMutex.

Namely, the entry for a given key is written once and read many times. I searched the code base for SetVar and GetVar. I don't see cases of overwrite, but there are a couple multiple GetVar for the same key.

Assistance Disclosure

No AI was used.

Signed-off-by: Mohammed Al Sahaf <msaa1990@gmail.com>
@mohammed90 mohammed90 added the bug 🐞 Something isn't working label Mar 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug 🐞 Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant