The Fix
Upgrade to version 0.21.0 or later.
Based on closed Kludex/starlette issue #1438 · PR/commit linked
@@ -4,12 +4,13 @@
from starlette.requests import Request
from starlette.responses import Response, StreamingResponse
-from starlette.types import ASGIApp, Receive, Scope, Send
+from starlette.types import ASGIApp, Message, Receive, Scope, Send
import traceback
import anyio
from starlette.applications import Starlette
from starlette.background import BackgroundTasks
from starlette.middleware import Middleware
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.responses import Response
from starlette.routing import Route
async def passthrough(request, call_next):
return await call_next(request)
async def _sleep(identifier, delay):
print(identifier, "started")
try:
await anyio.sleep(delay)
print(identifier, "completed")
except BaseException:
print(identifier, "error")
traceback.print_exc()
raise
async def response_with_sleeps(request):
background_tasks = BackgroundTasks()
background_tasks.add_task(_sleep, "background task 1", 2)
background_tasks.add_task(_sleep, "background task 2", 2)
return Response(background=background_tasks)
application = Starlette(
middleware=[
Middleware(BaseHTTPMiddleware, dispatch=passthrough),
],
routes=[
Route("/", response_with_sleeps),
],
)
Re-run the minimal reproduction on your broken version, then apply the fix and re-run.
Option A — Upgrade to fixed release\nUpgrade to version 0.21.0 or later.\nWhen NOT to use: This fix should not be applied if the application does not use BaseHTTPMiddleware.\n\n
Why This Fix Works in Production
- Trigger: background task 1 started
- Mechanism: Background tasks are cancelled due to improper handling of client disconnection in BaseHTTPMiddleware
- Why the fix works: Replaces task cancellation in BaseHTTPMiddleware with a mechanism to handle http.disconnect, preventing background tasks from being cancelled when the client disconnects. (first fixed release: 0.21.0).
- If left unfixed, this can cause silent data inconsistencies that propagate (bad cache entries, incorrect downstream decisions).
Why This Breaks in Prod
- Shows up under Python 3.9 in real deployments (not just unit tests).
- Background tasks are cancelled due to improper handling of client disconnection in BaseHTTPMiddleware
- Surfaces as: background task 1 started
Proof / Evidence
- GitHub issue: #1438
- Fix PR: https://github.com/kludex/starlette/pull/1715
- First fixed release: 0.21.0
- Reproduced locally: No (not executed)
- Last verified: 2026-02-09
- Confidence: 0.85
- Did this fix it?: Yes (upstream fix exists)
- Own content ratio: 0.40
Discussion
High-signal excerpts from the issue thread (symptoms, repros, edge-cases).
“Thanks for the precise report @jhominal :) I've implemented a solution on #1441. Let's see how the discussion around that goes.”
“I looked the code that BaseHTTPMiddleware and StreamingResponse use the same task_group, when one scope receive http.disconnect, task_group cancel all taskes. But I don't know…”
“The PR that solves the issue has all the details. EDIT: My PR had some regressions. I've closed it.”
“The background tasks need to be shielded.”
Failure Signature (Search String)
- background task 1 started
Error Message
Stack trace
Error Message
-------------
background task 1 started
background task 1 error
Traceback (most recent call last):
File "/Users/jean/PycharmProjects/starlette-bg-cancelled/./repro.py", line 19, in _sleep
await anyio.sleep(delay)
File "/Users/jean/PycharmProjects/starlette-bg-cancelled/venv/lib/python3.9/site-packages/anyio/_core/_eventloop.py", line 69, in sleep
return await get_asynclib().sleep(delay)
File "/usr/local/Cellar/[email protected]/3.9.6/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/tasks.py", line 654, in sleep
return await future
asyncio.exceptions.CancelledError
Minimal Reproduction
import traceback
import anyio
from starlette.applications import Starlette
from starlette.background import BackgroundTasks
from starlette.middleware import Middleware
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.responses import Response
from starlette.routing import Route
async def passthrough(request, call_next):
return await call_next(request)
async def _sleep(identifier, delay):
print(identifier, "started")
try:
await anyio.sleep(delay)
print(identifier, "completed")
except BaseException:
print(identifier, "error")
traceback.print_exc()
raise
async def response_with_sleeps(request):
background_tasks = BackgroundTasks()
background_tasks.add_task(_sleep, "background task 1", 2)
background_tasks.add_task(_sleep, "background task 2", 2)
return Response(background=background_tasks)
application = Starlette(
middleware=[
Middleware(BaseHTTPMiddleware, dispatch=passthrough),
],
routes=[
Route("/", response_with_sleeps),
],
)
Environment
- Python: 3.9
What Broke
Background tasks fail to complete when the client disconnects, leading to incomplete processing.
Why It Broke
Background tasks are cancelled due to improper handling of client disconnection in BaseHTTPMiddleware
Fix Options (Details)
Option A — Upgrade to fixed release Safe default (recommended)
Upgrade to version 0.21.0 or later.
Use when you can deploy the upstream fix. It is usually lower-risk than long-lived workarounds.
Fix reference: https://github.com/kludex/starlette/pull/1715
First fixed release: 0.21.0
Last verified: 2026-02-09. Validate in your environment.
When NOT to Use This Fix
- This fix should not be applied if the application does not use BaseHTTPMiddleware.
Verify Fix
Re-run the minimal reproduction on your broken version, then apply the fix and re-run.
Did This Fix Work in Your Case?
Quick signal helps us prioritize which fixes to verify and improve.
Prevention
- Capture the exact failing error string in logs and tests so you can reproduce via a minimal script.
- Pin production dependencies and upgrade only with a reproducible test that hits the failing path.
Version Compatibility Table
| Version | Status |
|---|---|
| 0.21.0 | Fixed |
Related Issues
No related fixes found.
Sources
We don’t republish the full GitHub discussion text. Use the links above for context.