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]

fix(http_handler): guard sync client healing with a double-checked lock

mateo-berri118a9396bad8
diff --git a/litellm/llms/custom_httpx/http_handler.py b/litellm/llms/custom_httpx/http_handler.py
index 8c09a56d079..726392577e5 100644
--- a/litellm/llms/custom_httpx/http_handler.py
+++ b/litellm/llms/custom_httpx/http_handler.py
@@ -5,6 +5,7 @@ import os
import socket
import ssl
import sys
+import threading
import time
from collections.abc import Callable, Mapping
from typing import TYPE_CHECKING, Any, Final, Optional
@@ -1092,6 +1093,7 @@ class HTTPHandler:
self.ssl_verify = ssl_verify
self.disable_default_headers = disable_default_headers
self._owns_client = client is None
+ self._heal_lock = threading.Lock()
self._client = self.create_client() if client is None else client
def create_client(self) -> httpx.Client:
@@ -1118,7 +1120,9 @@ class HTTPHandler:
@property
def client(self) -> httpx.Client:
if self._owns_client and self._client.is_closed:
- self._client = self.create_client()
+ with self._heal_lock:
+ if self._owns_client and self._client.is_closed:
+ self._client = self.create_client()
return self._client
@client.setter
diff --git a/tests/test_litellm/llms/custom_httpx/test_http_handler.py b/tests/test_litellm/llms/custom_httpx/test_http_handler.py
index de9c281021d..35db698ad76 100644
--- a/tests/test_litellm/llms/custom_httpx/test_http_handler.py
+++ b/tests/test_litellm/llms/custom_httpx/test_http_handler.py
@@ -885,3 +885,42 @@ async def test_assigned_async_client_is_not_replaced():
replacement = MagicMock()
handler.client = replacement
assert handler.client is replacement
+
+
+def test_concurrent_sync_heal_creates_exactly_one_replacement():
+ class GatedHealHandler(HTTPHandler):
+ def __init__(self):
+ self.heal_started = threading.Event()
+ self.release_heal = threading.Event()
+ self.heal_calls = 0
+ super().__init__(timeout=7)
+
+ def create_client(self) -> httpx.Client:
+ if hasattr(self, "_client"):
+ self.heal_calls += 1
+ self.heal_started.set()
+ assert self.release_heal.wait(timeout=5)
+ return super().create_client()
+
+ handler = GatedHealHandler()
+ handler.client.close()
+
+ seen = []
+
+ def grab_client():
+ seen.append(handler.client)
+
+ first = threading.Thread(target=grab_client)
+ second = threading.Thread(target=grab_client)
+ first.start()
+ assert handler.heal_started.wait(timeout=5)
+ second.start()
+ second.join(timeout=0.3)
+ handler.release_heal.set()
+ first.join(timeout=5)
+ second.join(timeout=5)
+
+ assert handler.heal_calls == 1
+ assert seen[0] is seen[1]
+ assert not seen[0].is_closed
+ handler.close()