Skip to content

perf(apps): share one aiohttp session per event loop - #776

Draft
deanq wants to merge 7 commits into
mainfrom
deanq/SLS-1129-apps-session-reuse
Draft

deanq wants to merge 7 commits into
mainfrom
deanq/SLS-1129-apps-session-reuse

Conversation

@deanq

@deanq deanq commented Nov 29, 2026

Copy link
Copy Markdown
Member

Summary

The apps client created a new aiohttp.ClientSession for each request, so every call to a deployed function paid for a new connection. This shares one session per event loop.

Changes

  • New runpod/loop_session.py: one aiohttp.ClientSession per running event loop, closed when that loop shuts down, at exit, and never reused across a fork. aiohttp is imported when the first session is created.
  • targets.py, tasks.py and utils/network.py use it and pass timeouts per request.
  • The shared aiohttp session has no connection cap (aiohttp defaults to 100; per-call sessions had none) and no cookie jar, so a cookie set for one API key is never sent with another.
  • A session's entry is freed when its loop finalizes, so a sync caller using asyncio.run per job does not retain every loop. It resolves names with the system resolver, because aiohttp's aiodns resolver is cached per loop until the session closes.
  • wait_ready reads the /ping response body so the connection goes back to the pool.

Impact

Local HTTPS server, median per call:

Before After
async calls on one loop 1.44 ms 0.13 ms
sync .remote() 1.28 ms 0.22 ms

Notes

  • A loop closed with plain loop.close(), without shutdown_asyncgens(), cannot close its session. The session is marked closed when the next loop asks for one, so aiohttp logs nothing by default. Under -X dev or -W always, its pooled sockets still raise a ResourceWarning when they are garbage collected. asyncio.run() is not affected.

Tests

New tests/test_apps/test_session_reuse.py (8 tests) counts sessions and connections opened for repeated calls; they failed before (for example 5 sessions where 1 was expected). tests/test_loop_session.py checks that importing the module does not load aiohttp, that loops are freed after asyncio.run and after a plain loop.close() without aiohttp logging an unclosed session, that there is no connection cap, and that cookies are not carried between calls. Full suite passes.

runpod/loop_session.py and tests/test_loop_session.py are also added, byte-identical, by the management API session change, so the two merge in either order.

Copilot AI balanced review requested due to automatic review settings November 29, 2026 22:42

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The cache-hit path skips closed-loop cleanup, retaining closed loops, their sessions, and pooled sockets during session reuse.

1 open issue
What changed in this PR

This PR reduces connection setup overhead in the apps client by sharing one aiohttp session per event loop across requests, retries, and task polling.

Changes:

  • Adds lazy per-loop sessions with lifecycle cleanup, unlimited connections, and disabled cookie storage.
  • Updates apps transports to use shared sessions while preserving per-request timeouts.
  • Adds connection-reuse and lifecycle tests and updates existing transport mocks.
File Description
tests/​test_loop_session.py Tests lazy imports, loop cleanup, connection limits, and cookie isolation.
tests/​test_apps/​test_transport_parity.py Updates transport mocks to use the shared-session getter.
tests/​test_apps/​test_tasks.py Updates task timeout tests for shared sessions.
tests/​test_apps/​test_session_reuse.py Adds connection-reuse, shutdown, and fork tests.
runpod/​loop_session.py Implements per-loop session caching and lifecycle handling.
runpod/​apps/​utils/​network.py Uses shared sessions for JSON requests.
runpod/​apps/​tasks.py Reuses sessions for task requests and drains successful ping responses.
runpod/​apps/​targets.py Uses shared sessions for endpoint and API requests.

Review effort: Balanced

Comment thread runpod/loop_session.py Resolved
@deanq
deanq force-pushed the deanq/SLS-1129-apps-session-reuse branch 2 times, most recently from 6233f03 to 8130529 Compare November 30, 2026 18:59
deanq added 7 commits December 1, 2026 08:54
runpod.apps opened a new ClientSession, and so a new TCP and TLS
connection, for every request, retry and poll. Use one session per
running event loop for the invoke, lb http, task pod and status paths.

The session is closed when its loop shuts down (a sentinel async
generator finalized by asyncio.run/Runner), at exit for the long-lived
background loop behind the sync .remote() bridge, and is forgotten
without closing in a forked child. Timeouts moved from the session to
each request because the session is now shared.

wait_ready drains the /ping body so the connection returns to the pool
instead of being closed.
Importing runpod.loop_session no longer loads aiohttp, so modules that
import it at top level keep their lazy import savings.
The per-loop session map is weak-keyed, but each session references its
loop, so entries were never freed: a sync handler calling asyncio.run per
job retained every loop. The entry is now removed when the loop finalizes
its async generators, and entries of loops closed without finalization are
dropped on the next lookup. The connector uses the system resolver, since
aiohttp's aiodns resolver is cached per loop until the session closes.

The shared session now has no connection cap (aiohttp defaults to 100,
which queued fan-out that previously had one connector per call) and no
cookie jar, so cookies set for one API key are never sent with another.
A loop closed with loop.close(), without finalizing async generators,
had its session dropped while still open, so aiohttp logged unclosed
session and connector errors at garbage collection. The session's
connector is now closed synchronously, which needs no loop, before the
entry is dropped.
- Run closed-loop cleanup before the cache lookup, so a loop closed
  with plain loop.close() is released even when later calls reuse an
  existing session.
- Skip closing the session when its sentinel is finalized in a forked
  child, so the child never closes the parent's pooled sockets.
Keep tests/test_loop_session.py byte-identical to the copy in the
sibling session-reuse change so the two merge without conflicts.
@deanq
deanq force-pushed the deanq/SLS-1129-apps-session-reuse branch from 8130529 to 5858a6a Compare December 1, 2026 17:04

This branch has not been deployed

No deployments
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.

2 participants