Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

perf: add request.state caching to _safe_get_request_headers

Ryan Crabbee7175a52129b
diff --git a/litellm/proxy/common_utils/http_parsing_utils.py b/litellm/proxy/common_utils/http_parsing_utils.py
index e1bca6e905f..8d179a9caed 100644
--- a/litellm/proxy/common_utils/http_parsing_utils.py
+++ b/litellm/proxy/common_utils/http_parsing_utils.py
@@ -135,17 +135,29 @@ def _safe_set_request_parsed_body(
def _safe_get_request_headers(request: Optional[Request]) -> dict:
"""
- [Non-Blocking] Safely get the request headers
+ [Non-Blocking] Safely get the request headers.
+ Caches the result on request.state to avoid re-creating dict(request.headers) per call.
+
+ Warning: Callers must NOT mutate the returned dict — it is shared across
+ all callers within the same request via the cache.
"""
+ if request is None:
+ return {}
+ cached = getattr(request.state, "_cached_headers", None)
+ if cached is not None:
+ return cached
try:
- if request is None:
- return {}
- return dict(request.headers)
+ headers = dict(request.headers)
except Exception as e:
verbose_proxy_logger.debug(
"Unexpected error reading request headers - {}".format(e)
)
- return {}
+ headers = {}
+ try:
+ request.state._cached_headers = headers
+ except Exception:
+ pass # request.state may not be available in all contexts
+ return headers
def check_file_size_under_limit(