Skip to content

[fix] use thread-local aiohttp.ClientSession, as it is not thread-safe#2565

Open
utterstep wants to merge 1 commit intoeternnoir:masterfrom
utterstep:thread-local-session-manager
Open

[fix] use thread-local aiohttp.ClientSession, as it is not thread-safe#2565
utterstep wants to merge 1 commit intoeternnoir:masterfrom
utterstep:thread-local-session-manager

Conversation

@utterstep
Copy link

Description

Fix thread-safety issue in async SessionManager.

SessionManager in telebot/asyncio_helper.py is currently a module-level singleton. Its session attribute (which is an aiohttp.ClientSession) was stored as a plain instance variable, meaning it was shared across all threads => when multiple threads each run their own event loop with separate AsyncTeleBot instances, they all use the same aiohttp.ClientSession — which is not thread-safe.

I encountered this issue myself – were getting unpredictable 2026-02-26 23:26:15,914 (asyncio_helper.py:103 workflow-exec_1) ERROR - TeleBot: "Unknown error: RuntimeError" errors in separate threads, each with its own eventloop and AsyncTeleBot instance local to this loop.

This PR wraps the session attribute in threading.local(), so each thread gets its own aiohttp.ClientSession, matching how the sync side already handles this via util.per_thread.

Describe your tests

Confirmed that multiple AsyncTeleBot instances running on separate threads with separate event loops no longer share aiohttp session state across threads.

Python version: 3.12

OS: macOS

Checklist:

  • I added/edited example on new feature/change (if exists) n/a, see below
  • My changes won't break backward compatibility
  • I made changes both for sync and async n/a, see below

No examples needed — this is an internal bugfix with no external API changes.

The sync side (apihelper.py) already uses util.per_thread for thread-local sessions, so no sync changes were needed.

@Badiboy
Copy link
Collaborator

Badiboy commented Feb 27, 2026

@utterstep Thank you.

@coder2020official LGTM.

This comment was marked as resolved.

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.

3 participants