Opened 3 weeks ago

Closed 3 weeks ago

#37054 closed Cleanup/optimization (wontfix)

Precompute the Referrer-Policy header value during middleware initialization

Reported by: Mason Lyons Owned by: Mason Lyons
Component: HTTP handling Version: 6.0
Severity: Normal Keywords: middleware
Cc: Mason Lyons Triage Stage: Unreviewed
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

The SecurityMiddleware runs on every Django request and adds security headers to responses. The original process_response() method constructs the Referrer-Policy header by performing string operations on every request:

def process_response(self, request, response):
    # ... other headers ...
    if self.referrer_policy:
        # Support a comma-separated string or iterable of values to allow
        # fallback.
        response.headers.setdefault(
            "Referrer-Policy",
            ",".join(
                [v.strip() for v in self.referrer_policy.split(",")]
                if isinstance(self.referrer_policy, str)
                else self.referrer_policy
            ),
        )

Move the string manipulation to __init__() where it runs once when the middleware is initialized, storing the pre-computed value for use in process_response()

Change History (4)

comment:1 by Mason Lyons, 3 weeks ago

Has patch: set

comment:2 by Mason Lyons, 3 weeks ago

in reply to:  2 comment:3 by Natalia Bidart, 3 weeks ago

Replying to Mason Lyons:

PR available: https://github.com/django/django/pull/21146

Hello, thank you for your ticket. I understand the rationale in the report but the proposed change needs stronger justification and careful consideration of compatibility. Specifically:

  1. Performance evidence: this is a micro-optimization. Moving a small string normalization from process_response() to __init__() may reduce per-request work, but the cost is negligible relative to overall request handling. Please provide evidence of a measurable performance improvement in a production-grade Django setup (e.g., benchmarks under realistic load) to justify the change. Also consider registering a benchmark check in django-asv.
  2. Backward compatibility: the change is not backward compatible and introduces subtle behavior differences. Among others: generators would be consumed at initialization instead of on first request, changes to self.referrer_policy after initialization would no longer be reflected in responses, subclasses overriding process_response() or relying on self.referrer_policy being evaluated per request would observe different behavior, etc.

Given these points, I'll be closing the ticket accordingly.

comment:4 by Natalia Bidart, 3 weeks ago

Resolution: wontfix
Status: assignedclosed
Note: See TracTickets for help on using tickets.
Back to Top