The Fix
Upgrade to version 0.29.0 or later.
Based on closed Kludex/starlette issue #2093 · PR/commit linked
Production note: Watch p95/p99 latency and retry volume; timeouts can turn into retry storms and duplicate side-effects.
@@ -170,6 +170,8 @@ async def body_stream() -> typing.AsyncGenerator[bytes, None]:
if body:
yield body
+ if not message.get("more_body", False):
+ break
import logging
from time import sleep
from starlette.applications import Starlette
from starlette.background import BackgroundTasks
from starlette.middleware import Middleware
from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
from starlette.requests import Request
from starlette.responses import JSONResponse, Response
from starlette.routing import Route
logging.basicConfig(
level=logging.INFO,
format="[%(asctime)s] [%(levelname)s] %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
class CustomMiddleware(BaseHTTPMiddleware):
async def dispatch(
self, request: Request, call_next: RequestResponseEndpoint
) -> Response:
return await call_next(request)
def create_task(request: Request) -> JSONResponse:
logging.info("Entered POST method")
tasks = BackgroundTasks()
tasks.add_task(background_task)
message = {"status": "Task created"}
return JSONResponse(message, background=tasks, status_code=201)
def background_task() -> None:
logging.info("Started background task")
sleep(10)
logging.info("Finished background task")
routes = [Route("/task", endpoint=create_task, methods=["POST"])]
middleware = [Middleware(CustomMiddleware)]
app = Starlette(routes=routes, middleware=middleware)
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.29.0 or later.\nWhen NOT to use: This fix should not be used if the application relies on the previous sequential execution behavior.\n\n
Why This Fix Works in Production
- Trigger: `HTTPMiddleware` breaks `BackgroundTasks` in the same connection
- Mechanism: The HTTPMiddleware caused BackgroundTasks to execute sequentially in the same connection due to improper handling of the body stream
- Why the fix works: Stops the body stream in case more_body is False, resolving the issue where BackgroundTasks were executed sequentially in the same connection. (first fixed release: 0.29.0).
- If left unfixed, this can cause silent data inconsistencies that propagate (bad cache entries, incorrect downstream decisions).
Why This Breaks in Prod
- The HTTPMiddleware caused BackgroundTasks to execute sequentially in the same connection due to improper handling of the body stream
- Production symptom (often without a traceback): `HTTPMiddleware` breaks `BackgroundTasks` in the same connection
Proof / Evidence
- GitHub issue: #2093
- Fix PR: https://github.com/kludex/starlette/pull/2194
- First fixed release: 0.29.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.43
Verified Execution
We executed the runnable minimal repro in a temporary environment and captured exit codes + logs.
- Status: PASS
- Ran: 2026-02-11T16:52:29Z
- Package: starlette
- Fixed: 0.29.0
- Mode: fixed_only
- Outcome: ok
Logs
Discussion
High-signal excerpts from the issue thread (symptoms, repros, edge-cases).
“@Kludex Is it ok to PR regarding this issue for a review?”
“You mean that you want to create a PR? Yeah, go ahead.”
“Is anyone working on this issue? It's quite important for us and I think whether it is necessary to fix it myself or someone is…”
“@nikita-b No one is working on this issue. Go ahead. 🙏”
Failure Signature (Search String)
- `HTTPMiddleware` breaks `BackgroundTasks` in the same connection
- Which results in a sequential execution of background tasks (and read timeout from the client as a consequence):
Copy-friendly signature
Failure Signature
-----------------
`HTTPMiddleware` breaks `BackgroundTasks` in the same connection
Which results in a sequential execution of background tasks (and read timeout from the client as a consequence):
Error Message
Signature-only (no traceback captured)
Error Message
-------------
`HTTPMiddleware` breaks `BackgroundTasks` in the same connection
Which results in a sequential execution of background tasks (and read timeout from the client as a consequence):
Minimal Reproduction
import logging
from time import sleep
from starlette.applications import Starlette
from starlette.background import BackgroundTasks
from starlette.middleware import Middleware
from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
from starlette.requests import Request
from starlette.responses import JSONResponse, Response
from starlette.routing import Route
logging.basicConfig(
level=logging.INFO,
format="[%(asctime)s] [%(levelname)s] %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
class CustomMiddleware(BaseHTTPMiddleware):
async def dispatch(
self, request: Request, call_next: RequestResponseEndpoint
) -> Response:
return await call_next(request)
def create_task(request: Request) -> JSONResponse:
logging.info("Entered POST method")
tasks = BackgroundTasks()
tasks.add_task(background_task)
message = {"status": "Task created"}
return JSONResponse(message, background=tasks, status_code=201)
def background_task() -> None:
logging.info("Started background task")
sleep(10)
logging.info("Finished background task")
routes = [Route("/task", endpoint=create_task, methods=["POST"])]
middleware = [Middleware(CustomMiddleware)]
app = Starlette(routes=routes, middleware=middleware)
What Broke
Clients experienced read timeouts when executing multiple background tasks in the same connection.
Why It Broke
The HTTPMiddleware caused BackgroundTasks to execute sequentially in the same connection due to improper handling of the body stream
Fix Options (Details)
Option A — Upgrade to fixed release Safe default (recommended)
Upgrade to version 0.29.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/2194
First fixed release: 0.29.0
Last verified: 2026-02-09. Validate in your environment.
When NOT to Use This Fix
- This fix should not be used if the application relies on the previous sequential execution behavior.
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
- Make timeouts explicit and test them (unit + integration) to avoid silent behavior changes.
- Instrument retries (attempt count + reason) and alert on spikes to catch dependency slowdowns.
Version Compatibility Table
| Version | Status |
|---|---|
| 0.29.0 | Fixed |
Related Issues
No related fixes found.
Sources
We don’t republish the full GitHub discussion text. Use the links above for context.