BackgroundTask starts before the response has been sent when BaseHTTPMiddleware is in the stack
With a BaseHTTPMiddleware anywhere in the stack, a BackgroundTask attached to a response starts running before the last byte of the response has been sent to the client. The background docs state:
A background task should be attached to a response, and will run only once the response has been sent.
Version: starlette 1.6.0 Python: 3.13.14
Repro
Raw ASGI harness with a deliberately slow send (simulates a slow client). A pass-through BaseHTTPMiddleware is enough to trigger it; without any middleware the docs are honored.
import asyncio, warnings
warnings.simplefilter("ignore")
from starlette.applications import Starlette
from starlette.background import BackgroundTask
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.responses import PlainTextResponse
from starlette.routing import Route
events = []
async def bg():
events.append(("background-done", asyncio.get_running_loop().time()))
async def homepage(request):
return PlainTextResponse("hello", background=BackgroundTask(bg))
async def passthrough(request, call_next):
return await call_next(request)
app = Starlette(routes=[Route("/", homepage)])
app = BaseHTTPMiddleware(app, dispatch=passthrough)
async def main():
scope = {"type": "http", "method": "GET", "path": "/", "headers": [],
"query_string": b"", "root_path": "", "scheme": "http",
"server": ["t", 80], "client": ("t", 1), "http_version": "1.1"}
async def receive():
await asyncio.sleep(3600)
async def send(message):
events.append((message["type"], asyncio.get_running_loop().time()))
await asyncio.sleep(0.15) # slow client
await app(scope, receive, send)
for name, t in sorted(events, key=lambda e: e[1]):
print(f" {name:<30} @{t:.3f}")
asyncio.run(main())
Actual ordering (deterministic across runs):
http.response.start @t+0.000
http.response.body(more=True) @t+0.155
background-done @t+0.155 <-- task finished HERE
http.response.body(more=False) @t+0.310 <-- last byte only here
Why it happens
When BaseHTTPMiddleware wraps the app, the inner Response.__call__ hands its final message into the middleware's memory stream and then runs the background task immediately — while the outer _StreamingResponse created from the buffered messages is still forwarding bytes to the real send. Without the middleware, the inner response is the outermost sender and runs the task after the final message.
Impact
Tasks that assume "response fully delivered" (e.g. logging request completion, cache invalidation after streaming, metrics that should not overlap body transfer) start early under this common middleware setup. With large/slow bodies the gap can be significant.
Suggested direction: defer await response(background=...)-style execution in BaseHTTPMiddleware._StreamingResponse until its own final send completes (or document the caveat explicitly).
Happy to work on a fix PR if maintainers consider this worth aligning with the documented contract.
Reproduced on starlette==1.6.0, and traced it down to a more specific root cause than the write-up above suggests — worth correcting before anyone designs a fix around it.
_StreamingResponse.background is dead code. It's set to None in __init__ and never reassigned anywhere in middleware/base.py:
self.background = None # __init__
...
if self.background: # __call__ — always False
await self.background()
So the background task the OP observes running early isn't the outer _StreamingResponse running one prematurely — it's the inner endpoint's Response.__call__ running its own .background, completely independent of the outer forwarding loop:
# starlette/responses.py, Response.__call__
await send({"type": "http.response.start", ...})
await send({"type": "http.response.body", "body": self.body})
if self.background is not None:
await self.background() # <- fires here
Here send is send_no_error, writing into the anyio.create_memory_object_stream() between the inner app and BaseHTTPMiddleware's consumer — and that stream is a rendezvous channel (max_buffer_size defaults to 0), so send() unblocks the instant the outer side's receive() picks the message up, not when the real client has received anything.
Instrumented trace confirms it precisely — self.background() fires at the exact same tick the real transport merely accepts the first chunk into its (slow) send, well before that chunk is delivered and two full sends before the actual final byte goes out:
[REAL client send] http.response.body accepted-by-real-transport @…7311
[inner Response] about to fire self.background() @…7311 <- same tick
[background task] running @…7311
[REAL client send] http.response.body FULLY DELIVERED @…8875 <- +156ms later
[REAL client send] http.response.body FULLY DELIVERED @…3.0436 <- final byte, +313ms later
So this isn't "the background executes slightly early relative to the outer response" — the outer response's own background slot is unused entirely, and the inner response never even knows it's being proxied.
Why the suggested fix in the issue body wouldn't work as stated: deferring _StreamingResponse.background() changes nothing, since it's never populated. A real fix needs one of:
- Strip
.backgroundoff the inner response before itsResponse.__call__runs, and attach it to the constructed_StreamingResponseinstead — butcall_nextnever sees the concreteResponseobject, only the ASGI messages it emits, so this needs either a new sentinel message type carrying the background reference through the stream, or some other channel back to the realResponseinstance. - Give the rendezvous channel real backpressure — don't let the inner side's
send()for the final body message unblock until the outer side's realsend()for that same message has actually completed, not just been picked up by the consuming generator. This keeps the existing "background runs after my own sends return" contract inResponse.__call__correct without touching it, at the cost of a slowerbody_stream()in the streaming case.
(2) seems like the smaller, more contained change, but I don't have visibility into whether that backpressure would interact badly with the debug-message branch (http.response.debug) or http.response.pathsend, so I'd rather flag both directions than guess at a PR here.
Happy to put a PR together for whichever approach you'd prefer.