{"record":{"id":"d052c15373419ffc","repo":"aio-libs/aiohttp","slug":"session-and-connector-have-to-use-same-event-loop","errorCode":null,"errorMessage":"Session and connector have to use same event loop","messagePattern":"Session and connector have to use same event loop","errorType":"exception","errorClass":"RuntimeError","httpStatus":null,"severity":"error","filePath":"aiohttp/client.py","lineNumber":377,"sourceCode":"                DeprecationWarning,\n                stacklevel=2,\n            )\n\n        if connector is None:\n            connector = TCPConnector(ssl_shutdown_timeout=ssl_shutdown_timeout)\n        # Initialize these three attrs before raising any exception,\n        # they are used in __del__\n        self._connector = connector\n        self._loop = loop\n        if loop.get_debug():\n            self._source_traceback: traceback.StackSummary | None = (\n                traceback.extract_stack(sys._getframe(1))\n            )\n        else:\n            self._source_traceback = None\n\n        if connector._loop is not loop:\n            raise RuntimeError(\"Session and connector have to use same event loop\")\n\n        if cookie_jar is None:\n            cookie_jar = CookieJar()\n        self._cookie_jar = cookie_jar\n\n        if cookies:\n            self._cookie_jar.update_cookies(cookies)\n\n        self._connector_owner = connector_owner\n        self._version = version\n        self._json_serialize = json_serialize\n        self._json_serialize_bytes = json_serialize_bytes\n        self._raise_for_status = raise_for_status\n        self._auto_decompress = auto_decompress\n        self._trust_env = trust_env\n        self._requote_redirect_url = requote_redirect_url\n        self._read_bufsize = read_bufsize\n        self._max_line_size = max_line_size","sourceCodeStart":359,"sourceCodeEnd":395,"githubUrl":"https://github.com/aio-libs/aiohttp/blob/d041d4d0fd48c3f0832084d33be16cf1c4835f85/aiohttp/client.py#L359-L395","documentation":"Raised by ClientSession.__init__ after the connector is captured: connector._loop must be the same running loop as the session's. Connectors cache connections per event loop; cross-loop use would corrupt connection state and break asyncio primitives.","triggerScenarios":"Constructing a BaseConnector (e.g. TCPConnector) in one thread/loop and passing it to a ClientSession created in another. Creating the connector at module import time (no running loop) and then using it inside an async function in a different loop.","commonSituations":"Background-thread workers each calling asyncio.run with a shared connector. Test fixtures that build a connector in setUp but create the session in an async test on a fresh loop. Mixing uvloop and the default loop in the same process.","solutions":["Create both the connector and the session inside the same async function / same loop.","If you must reuse a connector across requests, do not share it across threads; give each thread its own connector.","Drop the explicit connector argument and let ClientSession build a fresh TCPConnector on the current loop."],"exampleFix":"// before\nconnector = TCPConnector()  # built outside async / in another loop\nasync def main():\n    session = ClientSession(connector=connector)\n// after\nasync def main():\n    connector = TCPConnector()\n    session = ClientSession(connector=connector)","handlingStrategy":"validation","validationCode":"import asyncio\nfrom aiohttp import ClientSession, BaseConnector\n\ndef assert_same_loop(connector: BaseConnector) -> None:\n    running = asyncio.get_running_loop()\n    if connector._loop is not running:\n        raise RuntimeError(f'connector loop {connector._loop!r} != running {running!r}')","typeGuard":"import asyncio\n\ndef connector_matches_running_loop(connector) -> bool:\n    return connector._loop is asyncio.get_running_loop()","tryCatchPattern":"try:\n    session = ClientSession(connector=connector)\nexcept RuntimeError as e:\n    if 'same event loop' in str(e):\n        # rebuild connector on the current loop\n        connector = TCPConnector()\n        session = ClientSession(connector=connector)\n    else:\n        raise","preventionTips":["Construct the connector and session in the same async function.","Never share connectors across threads; create per-worker.","Avoid module-level connector singletons."],"tags":["event-loop","client-session","connector","concurrency"],"backgroundTag":null,"analyzedSha":"d041d4d0fd48c3f0832084d33be16cf1c4835f85","analyzedAt":"2026-08-11T20:44:15.550Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}