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]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
[Fix] - Sessions not being shared (#15388)
Alexsander Hamirc7234ba05324
diff --git a/litellm/constants.py b/litellm/constants.pyindex 7fe0e69a41f..d41266a0001 100644--- a/litellm/constants.py+++ b/litellm/constants.py@@ -87,6 +87,11 @@ MAX_TOKEN_TRIMMING_ATTEMPTS = int(########## Networking constants ##############################################################_DEFAULT_TTL_FOR_HTTPX_CLIENTS = 3600 # 1 hour, re-use the same httpx client for 1 hour+# Aiohttp connection pooling constants+AIOHTTP_CONNECTOR_LIMIT = int(os.getenv("AIOHTTP_CONNECTOR_LIMIT", 0))+AIOHTTP_KEEPALIVE_TIMEOUT = int(os.getenv("AIOHTTP_KEEPALIVE_TIMEOUT", 120))+AIOHTTP_TTL_DNS_CACHE = int(os.getenv("AIOHTTP_TTL_DNS_CACHE", 300))+########### v2 Architecture constants for managing writing updates to the database ###########REDIS_UPDATE_BUFFER_KEY = "litellm_spend_update_buffer"REDIS_DAILY_SPEND_UPDATE_BUFFER_KEY = "litellm_daily_spend_update_buffer"diff --git a/litellm/llms/custom_httpx/http_handler.py b/litellm/llms/custom_httpx/http_handler.pyindex 138c31ba716..1c8664e368a 100644--- a/litellm/llms/custom_httpx/http_handler.py+++ b/litellm/llms/custom_httpx/http_handler.py@@ -12,7 +12,12 @@ from httpx._types import RequestFilesimport litellmfrom litellm._logging import verbose_logger-from litellm.constants import _DEFAULT_TTL_FOR_HTTPX_CLIENTS+from litellm.constants import (+ _DEFAULT_TTL_FOR_HTTPX_CLIENTS,+ AIOHTTP_CONNECTOR_LIMIT,+ AIOHTTP_KEEPALIVE_TIMEOUT,+ AIOHTTP_TTL_DNS_CACHE,+)from litellm.litellm_core_utils.logging_utils import track_llm_api_timingfrom litellm.types.llms.custom_http import *@@ -651,7 +656,13 @@ class AsyncHTTPHandler:)return LiteLLMAiohttpTransport(client=lambda: ClientSession(- connector=TCPConnector(limit=0, **connector_kwargs), # 0 = unlimited connections per host+ connector=TCPConnector(+ limit=AIOHTTP_CONNECTOR_LIMIT,+ keepalive_timeout=AIOHTTP_KEEPALIVE_TIMEOUT,+ ttl_dns_cache=AIOHTTP_TTL_DNS_CACHE,+ enable_cleanup_closed=True,+ **connector_kwargs+ ),trust_env=trust_env,),)diff --git a/litellm/llms/custom_httpx/llm_http_handler.py b/litellm/llms/custom_httpx/llm_http_handler.pyindex ae449bbb15b..8eabdad3020 100644--- a/litellm/llms/custom_httpx/llm_http_handler.py+++ b/litellm/llms/custom_httpx/llm_http_handler.py@@ -13,13 +13,13 @@ from typing import (cast,)+from litellm._logging import verbose_loggerimport httpx # type: ignoreimport litellmimport litellm.litellm_core_utilsimport litellm.typesimport litellm.types.utils-from litellm._logging import verbose_loggerfrom litellm.litellm_core_utils.realtime_streaming import RealTimeStreamingfrom litellm.llms.base_llm.anthropic_messages.transformation import (BaseAnthropicMessagesConfig,@@ -240,6 +240,16 @@ class BaseLLMHTTPHandler:signed_json_body: Optional[bytes] = None,shared_session: Optional["ClientSession"] = None,):+ # PANIC: Ensure shared_session is being passed for connection reuse+ if shared_session is None and client is None:+ error_msg = (+ "PANIC: shared_session is None in async_completion! "+ "This means connection reuse is broken. Session should be passed from completion() -> async_completion(). "+ f"Provider: {custom_llm_provider}, Model: {model}"+ )+ verbose_logger.error(error_msg)+ raise ValueError(error_msg)+if client is None:verbose_logger.debug(f"Creating HTTP client with shared_session: {id(shared_session) if shared_session else None}"@@ -426,6 +436,7 @@ class BaseLLMHTTPHandler:),json_mode=json_mode,signed_json_body=signed_json_body,+ shared_session=shared_session,)if stream is True:diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.pyindex 366d3f57dc0..fabb84a4e5b 100644--- a/litellm/proxy/proxy_server.py+++ b/litellm/proxy/proxy_server.py@@ -28,6 +28,9 @@ from typing import (from litellm._uuid import uuidfrom litellm.constants import (+ AIOHTTP_CONNECTOR_LIMIT,+ AIOHTTP_KEEPALIVE_TIMEOUT,+ AIOHTTP_TTL_DNS_CACHE,BASE_MCP_ROUTE,DEFAULT_MAX_RECURSE_DEPTH,DEFAULT_SLACK_ALERTING_THRESHOLD,@@ -44,6 +47,7 @@ from litellm.types.utils import (from litellm.utils import load_credentials_from_listif TYPE_CHECKING:+ from aiohttp import ClientSessionfrom opentelemetry.trace import Span as _Spanfrom litellm.integrations.opentelemetry import OpenTelemetry@@ -559,7 +563,7 @@ async def proxy_shutdown_event():@asynccontextmanagerasync def proxy_startup_event(app: FastAPI):- global prisma_client, master_key, use_background_health_checks, llm_router, llm_model_list, general_settings, proxy_budget_rescheduler_min_time, proxy_budget_rescheduler_max_time, litellm_proxy_admin_name, db_writer_client, store_model_in_db, premium_user, _license_check, proxy_batch_polling_interval+ global prisma_client, master_key, use_background_health_checks, llm_router, llm_model_list, general_settings, proxy_budget_rescheduler_min_time, proxy_budget_rescheduler_max_time, litellm_proxy_admin_name, db_writer_client, store_model_in_db, premium_user, _license_check, proxy_batch_polling_interval, shared_aiohttp_sessionimport jsoninit_verbose_loggers()@@ -674,10 +678,38 @@ async def proxy_startup_event(app: FastAPI):## [Optional] Initialize dd tracerProxyStartupEvent._init_dd_tracer()+ ## Initialize shared aiohttp session for connection reuse+ try:+ from aiohttp import ClientSession, TCPConnector++ # Create connector with connection pooling settings optimized for long-lived connections+ connector = TCPConnector(+ limit=AIOHTTP_CONNECTOR_LIMIT,+ keepalive_timeout=AIOHTTP_KEEPALIVE_TIMEOUT,+ ttl_dns_cache=AIOHTTP_TTL_DNS_CACHE,+ enable_cleanup_closed=True,+ )++ shared_aiohttp_session = ClientSession(connector=connector)+ verbose_proxy_logger.info(+ f"SESSION REUSE: Created shared aiohttp session for connection pooling (ID: {id(shared_aiohttp_session)})"+ )+ except Exception as e:+ verbose_proxy_logger.warning(+ f"Failed to create shared aiohttp session: {e}. Continuing without session reuse."+ )+# End of startup eventyield- # Shutdown event+ # Shutdown event - close shared aiohttp session+ if shared_aiohttp_session is not None:+ try:+ await shared_aiohttp_session.close()+ verbose_proxy_logger.info("SESSION REUSE: Closed shared aiohttp session")+ except Exception as e:+ verbose_proxy_logger.error(f"Error closing shared aiohttp session: {e}")+await proxy_shutdown_event()@@ -955,6 +987,7 @@ worker_config = Nonemaster_key: Optional[str] = Noneotel_logging = Falseprisma_client: Optional[PrismaClient] = None+shared_aiohttp_session: Optional["ClientSession"] = None # Global shared session for connection reuseuser_api_key_cache = DualCache(default_in_memory_ttl=UserAPIKeyCacheTTLEnum.in_memory_cache_ttl.value)diff --git a/litellm/proxy/route_llm_request.py b/litellm/proxy/route_llm_request.pyindex e1a6ca2a2be..1ae87637be0 100644--- a/litellm/proxy/route_llm_request.py+++ b/litellm/proxy/route_llm_request.py@@ -55,6 +55,23 @@ def get_team_id_from_data(data: dict) -> Optional[str]:return None+def add_shared_session_to_data(data: dict) -> None:+ """+ Add shared aiohttp session for connection reuse (prevents cold starts).+ Silently continues without session reuse if import fails or session is unavailable.++ Args:+ data: Dictionary to add the shared session to+ """+ try:+ from litellm.proxy.proxy_server import shared_aiohttp_session+ if shared_aiohttp_session is not None and not shared_aiohttp_session.closed:+ data["shared_session"] = shared_aiohttp_session+ except Exception:+ # Silently continue without session reuse if import fails or session unavailable+ pass++async def route_request(data: dict,llm_router: Optional[LitellmRouter],@@ -86,6 +103,8 @@ async def route_request("""Common helper to route the request"""+ add_shared_session_to_data(data)+team_id = get_team_id_from_data(data)router_model_names = llm_router.model_names if llm_router is not None else []diff --git a/tests/test_litellm/test_acompletion_session_reuse_e2e.py b/tests/test_litellm/test_acompletion_session_reuse_e2e.pynew file mode 100644index 00000000000..499bcc6a9fc--- /dev/null+++ b/tests/test_litellm/test_acompletion_session_reuse_e2e.py@@ -0,0 +1,154 @@+"""+E2E tests for shared session reuse feature++WHAT THIS TESTS:+When you pass shared_session to acompletion(), it should flow through+the entire call chain so the same aiohttp.ClientSession is reused for+connection pooling.++WHY THIS MATTERS:+Without session reuse, every request creates new TCP/TLS connections,+wasting ~100-500ms per request. With reuse, connections are pooled and+subsequent requests are 40-60% faster.+"""+import os+import sys+import inspect++import pytest++sys.path.insert(0, os.path.abspath("../../.."))++import litellm+++# ============================================================================+# HELPER FUNCTION+# ============================================================================++def is_parameter_active_in_source(source_code: str, search_pattern: str) -> bool:+ """+ Check if a parameter/line exists in source code and is NOT commented out.++ Args:+ source_code: The source code to search+ search_pattern: The text pattern to look for (e.g., "shared_session=shared_session")++ Returns:+ True if pattern found and not commented out, False otherwise+ """+ lines = source_code.split('\n')++ for line in lines:+ if search_pattern in line:+ # Make sure it's not commented out+ stripped = line.strip()+ if not stripped.startswith('#'):+ return True++ return False+++# ============================================================================+# TEST 1: Check that the parameter exists in the API+# ============================================================================++def test_acompletion_accepts_shared_session():+ """Verify acompletion() has a shared_session parameter"""+ sig = inspect.signature(litellm.acompletion)++ assert 'shared_session' in sig.parameters, \+ "acompletion() missing shared_session parameter"++ # Should be optional (defaults to None)+ assert sig.parameters['shared_session'].default is None+++def test_completion_accepts_shared_session():+ """Verify completion() has a shared_session parameter"""+ sig = inspect.signature(litellm.completion)++ assert 'shared_session' in sig.parameters, \+ "completion() missing shared_session parameter"++ assert sig.parameters['shared_session'].default is None+++# ============================================================================+# TEST 2: Check that acompletion passes it to completion+# ============================================================================++def test_acompletion_passes_session_to_completion():+ """+ Verify that acompletion() includes shared_session in the kwargs+ it passes to completion()+ """+ source = inspect.getsource(litellm.acompletion)++ # Check for both possible quote styles+ found = (is_parameter_active_in_source(source, '"shared_session": shared_session') or+ is_parameter_active_in_source(source, "'shared_session': shared_session"))++ assert found, \+ "acompletion() doesn't include shared_session in completion_kwargs (or it's commented out)"+++# ============================================================================+# TEST 3: Check the handler methods accept it+# ============================================================================++def test_handler_completion_accepts_shared_session():+ """Verify BaseLLMHTTPHandler.completion() accepts shared_session"""+ from litellm.llms.custom_httpx.llm_http_handler import BaseLLMHTTPHandler++ sig = inspect.signature(BaseLLMHTTPHandler.completion)++ assert 'shared_session' in sig.parameters, \+ "Handler.completion() missing shared_session parameter"+++def test_handler_async_completion_accepts_shared_session():+ """Verify BaseLLMHTTPHandler.async_completion() accepts shared_session"""+ from litellm.llms.custom_httpx.llm_http_handler import BaseLLMHTTPHandler++ sig = inspect.signature(BaseLLMHTTPHandler.async_completion)++ assert 'shared_session' in sig.parameters, \+ "Handler.async_completion() missing shared_session parameter"+++# ============================================================================+# TEST 4: THE KEY TEST - Does handler.completion pass it to async_completion?+# ============================================================================++def test_handler_passes_session_to_async_completion():+ """+ 🔑 KEY TEST - Verifies the fix from commit f0d6d3dd++ The bug was: handler.completion() accepted shared_session but didn't+ pass it to async_completion(). This test ensures it's being passed.++ If this test fails, session reuse is BROKEN.+ """+ from litellm.llms.custom_httpx.llm_http_handler import BaseLLMHTTPHandler++ source = inspect.getsource(BaseLLMHTTPHandler.completion)++ # Check if shared_session is being passed (and not commented out)+ found = is_parameter_active_in_source(source, 'shared_session=shared_session')++ assert found, \+ """+ CRITICAL BUG DETECTED!++ shared_session is NOT being passed from completion() to async_completion()++ This means session reuse is BROKEN. Every request will create new+ connections instead of reusing them, causing 40-60% slower performance.++ FIX: In BaseLLMHTTPHandler.completion(), when calling self.async_completion(),+ add this parameter:+ shared_session=shared_session++ This was the bug fixed in commit f0d6d3dd - it may have regressed!+ """\ No newline at end of file