python runtime_error ai_generated true

RuntimeWarning: coroutine 'send_email' was never awaited

ID: python/fastapi-background-task-not-awaited

Also available as: JSON · Markdown · 中文
80%Fix Rate
87%Confidence
0Evidence
2025-12-03First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
0.100.x active — — —
0.110.x active — — —

Root Cause

Passing an async function to BackgroundTasks.add_task without awaiting; or calling an async function directly in a sync route without scheduling.

generic

中文

将异步函数传给 BackgroundTasks.add_task 而未 await;或在同步路由中直接调用异步函数而未调度。

Workarounds

  1. 95% success
    In async route: `background_tasks.add_task(send_email, to, body)` — FastAPI awaits it after response.
  2. 85% success
    For sync routes, use a sync function or `asyncio.run(send_email(...))` (careful with loops) or offload to Celery.

Dead Ends

Common approaches that don't work:

  1. 80% fail

    Task may be cancelled when request ends; not tracked by FastAPI.

  2. 75% fail

    Requires a running event loop and proper thread context; often raises RuntimeError.