Skip to content

perf: cache trust proxy lookups in req.ip, protocol and host - #7519

Open
Abdel-Monaam-Aouini wants to merge 2 commits into
expressjs:masterfrom
Abdel-Monaam-Aouini:perf/cache-req-getters
Open

Abdel-Monaam-Aouini wants to merge 2 commits into
expressjs:masterfrom
Abdel-Monaam-Aouini:perf/cache-req-getters

Conversation

@Abdel-Monaam-Aouini

Copy link
Copy Markdown
Contributor

When trust proxy is a subnet list (e.g. loopback, 10.0.0.0/8), the trust check on the socket address is slow (~1us), and req.protocol, req.host and req.hostname each repeat it. req.ip runs proxy-addr on every access (~2us). Middleware like logging or rate limiting often reads these more than once per request.

This keeps the result on the request and reuses it while its inputs are the same:

  • the trust check for the socket address is shared by protocol, secure, host, hostname and subdomains (key: trust function and socket address)
  • req.ip (key: trust function, socket address and X-Forwarded-For)

If any of those change, it is computed again, so the returned values are the same as before. req.ips is not changed because it returns an array.

Micro benchmark per access with trust proxy set to loopback, 10.0.0.0/8:

  • req.ip: ~2150ns -> ~64ns
  • req.protocol: ~1080ns -> ~140ns
  • req.host: ~1110ns -> ~100ns

With trust proxy off or true these were already cheap (10-250ns), so there is not much difference there.

Added tests for repeated reads, the trust function being called once, and the cache refreshing when the socket address, headers or trust proxy setting change.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant