Skip to content

fix(aiohttp): keep keep-alive connector config when a session is rebuilt - #34962

Merged
yassin-berriai merged 1 commit into
litellm_internal_stagingfrom
litellm_aiohttp_keepalive_session_factory
Jul 28, 2026
Merged

yassin-berriai merged 1 commit into
litellm_internal_stagingfrom
litellm_aiohttp_keepalive_session_factory

Conversation

@yassin-berriai

@yassin-berriai yassin-berriai commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • AIOHTTP_SO_KEEPALIVE stopped applying after an aiohttp session rebuild
  • Rebuilt sessions used aiohttp defaults, not the configured connector
  • Keepalive timeout silently dropped from 120s to 15s

How it solves it:

  • Build the configured session factory once and inject it into the transport
  • Every session rebuild goes through that factory

Relevant issues

Fixes #33567

Linear ticket

Resolves LIT-4674

Pre-Submission checklist

Please complete all items before asking a LiteLLM maintainer to review your PR

  • I have added meaningful tests
  • My PR passes all CI/CD checks (e.g., lint, format, unit tests)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • I have received a Greptile Confidence Score of at least 4/5 before requesting a maintainer review (Greptile reviews automatically once the PR is opened; only comment @greptileai to re-request a review after pushing changes)

Delays in PR merge?

If you're seeing a delay in your PR being merged, ping the LiteLLM Team on Slack (#pr-review).

Screenshots / Proof of Fix

The observable is a kernel socket option on the connection litellm actually holds open to the provider, so the proof reads it off the pooled socket after a real, paid OpenAI call rather than off a mock. The script drives the production functions directly (_initialize_shared_aiohttp_session -> _create_aiohttp_transport -> httpx.AsyncClient), because a session rebuild has no HTTP surface a curl could show

# socket_proof.py
import asyncio, os, socket
os.environ["AIOHTTP_SO_KEEPALIVE"] = "true"
os.environ["AIOHTTP_TCP_KEEPIDLE"] = "45"

import httpx, litellm
from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler
from litellm.proxy.proxy_server import _initialize_shared_aiohttp_session

print("litellm loaded from:", os.path.dirname(litellm.__file__))
KEEPIDLE_OPT = getattr(socket, "TCP_KEEPIDLE", None) or getattr(socket, "TCP_KEEPALIVE", None)

async def main():
    shared = await _initialize_shared_aiohttp_session()
    transport = AsyncHTTPHandler._create_aiohttp_transport(shared_session=shared)
    await shared.close()   # force the rebuild path

    client = httpx.AsyncClient(transport=transport)
    r = await client.post(
        "https://api.openai.com/v1/chat/completions",
        headers={"Authorization": "Bearer " + os.environ["OPENAI_API_KEY"]},
        json={"model": "gpt-5.1", "messages": [{"role": "user", "content": "say ok"}]},
        timeout=60,
    )
    print("HTTP", r.status_code, (await r.aread())[:60].decode())

    for key, deq in transport.client.connector._conns.items():
        for proto, _ in deq:
            sock = proto.transport.get_extra_info("socket")
            print("pooled socket ->", key.host)
            print("  SO_KEEPALIVE  =", sock.getsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE))
            print("  TCP keepidle  =", sock.getsockopt(socket.IPPROTO_TCP, KEEPIDLE_OPT))
    await client.aclose()

asyncio.run(main())

Before, at d91fd084f7 (current litellm_internal_staging), with AIOHTTP_SO_KEEPALIVE=true and AIOHTTP_TCP_KEEPIDLE=45 exported:

$ PYTHONPATH="$PWD" python socket_proof.py
litellm loaded from: /Users/.../litellm
HTTP 200 {
  "id": "chatcmpl-E6fmRIC2vcERnXFE17I578zib4vb8",
pooled socket -> api.openai.com
  SO_KEEPALIVE  = 0
  TCP keepidle  = 7200

The socket carrying real traffic has keepalive off and the kernel's 2-hour idle default, so the env var bought nothing

After, at d2b7341137 (this PR), same command and same env:

$ PYTHONPATH="$PWD" python socket_proof.py
litellm loaded from: /Users/.../litellm
HTTP 200 {
  "id": "chatcmpl-E6g0ooaKvmifaeqVKxkrR7TPKiMeH",
pooled socket -> api.openai.com
  SO_KEEPALIVE  = 8
  TCP keepidle  = 45

Keepalive is on and the idle-before-first-probe is the configured 45s, which is what makes the kernel reset a middlebox idle timer before the flow is reaped

The same build serving normal traffic end to end, live proxy at d2b7341137 on port 4674 with AIOHTTP_SO_KEEPALIVE=true:

$ curl -s http://127.0.0.1:4674/v1/chat/completions \
    -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H "Content-Type: application/json" \
    -d '{"model":"gpt-5.1","messages":[{"role":"user","content":"reply with the single word: keepalive"}]}'
{
  "id": "chatcmpl-E6g1I2b9Y7nSFDYVIupu54nTgdSaB",
  "model": "gpt-5.1",
  "content": "keepalive",
  "usage": {"completion_tokens": 11, "prompt_tokens": 14, "total_tokens": 25}
}

Type

🐛 Bug Fix

Changes

LiteLLMAiohttpTransport only remembered a session factory when it was constructed with a callable. _create_aiohttp_transport passes a concrete ClientSession on the shared-session path, so that transport had no factory, and each of the five session-rebuild sites in aiohttp_transport.py fell back to a bare aiohttp.ClientSession() carrying aiohttp's default connector. That dropped the keepalive socket factory behind AIOHTTP_SO_KEEPALIVE/AIOHTTP_TCP_KEEPIDLE, along with keepalive_timeout (120s -> aiohttp's 15s), ttl_dns_cache, limit/limit_per_host, enable_cleanup_closed and trust_env. A rebuild fires whenever the session is closed or belongs to a different or closed event loop, and the replacement is cached on the transport, so a single rebuild disabled stale-socket protection for every later request that transport served

The fix builds the session factory once in _create_aiohttp_transport and injects it into both the shared-session and new-session transports through a new session_factory argument, then routes every rebuild through self._client_factory. The factory now always exists, which also removes the repeated hasattr(self, "_client_factory") and callable(...) branching and a redundant in-function ClientSession import. Behavior is unchanged for a transport built with no factory at all: it still falls back to ClientSession

The rebuild also fixes an ownership hole that Greptile caught. A replacement session is reachable only from the transport, yet owns_session stayed False on the shared-session path, so aclose() left the replacement and its connector open. Rebuilding now transfers ownership to the transport, and the reverse case is handled too: a rebuild no longer closes a session the transport does not own, so one transport hitting a stale event loop cannot close the proxy-wide shared session out from under every other transport holding it

Worth noting for the linked issue: the reporter's reading that the factory is never wired into the Azure/OpenAI path is not quite right, the first session on every path does get it (http_handler.py); what was broken is that every rebuild threw it away. The reporter's second ask, an env-tunable keepalive timeout, already exists as AIOHTTP_KEEPALIVE_TIMEOUT and is left at its 120s default here since lowering it changes pooling for everyone

litellm/proxy/proxy_server.py::_initialize_shared_aiohttp_session still rebuilds the same connector kwargs independently, and it has already drifted: it never passes trust_env, so the proxy's shared session ignores litellm.aiohttp_trust_env / AIOHTTP_TRUST_ENV, and it never calls _get_ssl_connector_kwargs, so litellm.force_ipv4's local_addr never reaches that connector either. Both are silent. Collapsing the two builders into one helper is the right fix for that, but it is a separate change and is not needed here, since the transport now rebuilds from its own configured factory

Final Attestation

  • The tests check the right things, including the edge cases, and regressions in the respective real-world customer use-cases are not possible after this PR

@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

@greptile-apps

greptile-apps Bot commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

The PR preserves configured aiohttp connector behavior when sessions are rebuilt.

  • Injects the configured session factory into transports that begin with a shared session.
  • Centralizes session rebuilding and transfers ownership of replacement sessions to the transport.
  • Avoids closing proxy-owned shared sessions during stale-loop recovery.
  • Adds regression coverage for connector configuration and rebuilt-session ownership.

Confidence Score: 5/5

The PR appears safe to merge.

The previously reported cleanup defect is fixed: replacement sessions become transport-owned and are closed by transport cleanup, while the original shared session remains externally owned and is not closed during rebuilding.

Important Files Changed

Filename Overview
litellm/llms/custom_httpx/aiohttp_transport.py Centralizes session replacement through the configured factory and correctly updates ownership while preserving externally owned sessions.
litellm/llms/custom_httpx/http_handler.py Builds one configured session factory and supplies it to both shared-session and newly created transports.
tests/test_litellm/llms/custom_httpx/test_aiohttp_so_keepalive.py Verifies that rebuilding a shared session retains the keepalive socket factory and timeout.
tests/test_litellm/llms/custom_httpx/test_aiohttp_transport.py Covers factory-based rebuilding, replacement ownership, cleanup, and preservation of unowned shared sessions.

Reviews (2): Last reviewed commit: "fix(aiohttp): keep keep-alive connector ..." | Re-trigger Greptile

@codecov

codecov Bot commented Jul 28, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

LiteLLMAiohttpTransport only stored a session factory when it was constructed
with a callable. A transport built around an already-created ClientSession (the
proxy's shared session) had no factory, so every session-rebuild site fell back
to a bare aiohttp.ClientSession() with aiohttp's default connector. That silently
dropped the keep-alive socket factory behind AIOHTTP_SO_KEEPALIVE, plus
keepalive_timeout (120s -> 15s), ttl_dns_cache, the connector limits and
trust_env. The rebuilt session is cached on the transport, so one rebuild
disabled stale-socket protection for every later request on it.

Build the configured session factory once in _create_aiohttp_transport and
inject it into both the shared-session and new-session transports, and route
every rebuild through it.

A rebuilt session is reachable only from the transport, so the transport takes
ownership of it: aclose() now closes the replacement instead of leaking it, and
a rebuild no longer closes a session the transport does not own.

Resolves LIT-4674
@yassin-berriai
yassin-berriai force-pushed the litellm_aiohttp_keepalive_session_factory branch from 6df8bd9 to d2b7341 Compare July 28, 2026 17:35
@yassin-berriai

Copy link
Copy Markdown
Contributor Author

Good catch on the ownership hole, that was real and is fixed in d2b7341137.

Rebuilding now goes through a single _rebuild_session() that sets _owns_session = True, because a replacement session is reachable only from the transport regardless of what it was handed originally, so aclose() closes it instead of leaking it and its connector. I also closed the mirror-image case you did not name: the stale-event-loop branch used to close the old session unconditionally, which meant one transport hitting a loop mismatch would close the proxy-wide shared session out from under every other transport still holding it. That close is now gated on _owns_session too.

Two regression tests cover both directions, and both fail on the previous commit: test_rebuilt_session_becomes_transport_owned (rebuild then aclose(), replacement must be closed) and test_stale_loop_rebuild_does_not_close_unowned_session (rebuild off a stale loop, the unowned shared session must stay open).

Please re-review the current head d2b7341

@codspeed

codspeed Bot commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing litellm_aiohttp_keepalive_session_factory (d2b7341) with litellm_internal_staging (b930e2f)

Open in CodSpeed

@yassin-berriai

Copy link
Copy Markdown
Contributor Author

@greptileai please review the current head d2b7341 - the previous review is pinned to 6df8bd9bb5, which was replaced by the ownership fix described above

@yassin-berriai
yassin-berriai enabled auto-merge (squash) July 28, 2026 22:50
@yassin-berriai
yassin-berriai merged commit caede1c into litellm_internal_staging Jul 28, 2026
77 checks passed
@yassin-berriai
yassin-berriai deleted the litellm_aiohttp_keepalive_session_factory branch July 28, 2026 23:18
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.

[Bug]: AIOHTTP_SO_KEEPALIVE / keepalive socket factory not wired into aiohttp_transport.py — stale-socket fast-fail on Azure/OpenAI calls (1.90.0)

3 participants