Replace custom async_helpers.py with FastAPI BackgroundTasks / anyio
Problem
app/utils/async_helpers.py (~153 LOC) implements a custom bridge for running async coroutines from sync contexts — including manual event loop detection, daemon thread spawning, and custom error handlers. This pattern is fragile and a common source of hard-to-reproduce bugs (e.g. RuntimeError: This event loop is already running).
The primary use case is broadcasting SocketIO queue updates after synchronous service calls.
Affected Files
app/utils/async_helpers.py-
app/services/consultation_queue_service.py(callsrun_async_task())
Fix
- Use FastAPI's built-in
BackgroundTasksto dispatch the SocketIO broadcast after a response - Or adopt
anyio.from_thread.run_sync()/anyio.to_thread.run_sync()which is already a transitive dependency via FastAPI
References
- https://anyio.readthedocs.io/en/stable/threads.html
- FastAPI BackgroundTasks: https://fastapi.tiangolo.com/tutorial/background-tasks/
Effort
Medium (~2h)