Patch LB rack middleware to grab user id from session
What does this MR do and why?
Before deciding which replica to stick a request to, the load balancer calls sticking_namespaces to get the current user's ID for a Redis LSN lookup. This was done via warden.user.id, which as a side effect lazily loads and caches the full User record from a random unstuck replica before sticking has been established. Generally this is not an issue since user rows rarely change, but it's critical during onboarding when the onboarding_in_progress column flips from true to false right before a redirect.
The first solution involved calling user.reload after sticking, but this cleared ActiveRecord's association cache on the user object, causing previously warm associations to be re-fetched individually later in the request, adding extra queries that broke query threshold limits and caused test failures in other parts of the codebase.
The fix removes the reload entirely by changing how the user ID is obtained in sticking_namespaces: instead of warden.user.id, we read the ID directly from the raw Rack session via env['rack.session'].dig(Warden::SessionSerializer.new(env).key_for(:user), 0, 0). This means the User record is never loaded before sticking is established, so when Warden lazily loads it later in the request it comes from the correct caught-up replica from the start making the reload unnecessary and eliminating the extra queries.
References
https://gitlab.com/gitlab-org/gitlab/-/work_items/573726
Screenshots or screen recordings
| Before | After |
|---|---|
How to set up and validate locally
- Add the following debug statement in the
sticking_namespace(env)method to validate what the user id looks like from the warden session:
key = env['rack.session']&.dig(Warden::SessionSerializer.new(env).key_for(:user), 0, 0)
Rails.logger.debug("warden: #{key.inspect}")
- Start gdk
- enable gdk tail and grep for warden info:
tail -f log/development.log | grep "warden" - open http://127.0.0.1:3000/
- Observe
warden: user_idin console
MR acceptance checklist
Evaluate this MR against the MR acceptance checklist. It helps you analyze changes to reduce risks in quality, performance, reliability, security, and maintainability.