File uploads and streaming responses
How does Django stream multipart uploads without exhausting RAM, and what changes inside middleware when a view returns StreamingHttpResponse?
Ordinary web endpoints buffer both halves of HTTP: a small form body fits cleanly in a QueryDict, and an HTML template renders into a single bytes buffer inside HttpResponse. Push past a few megabytes — uploading a high-resolution press photo on "/submit/" or exporting a million-row archive CSV — and buffering either direction in RAM turns one slow client into an out-of-memory worker crash.
Django splits streaming into two symmetric mechanisms: pluggable upload handlers on the way in, and StreamingHttpResponse on the way out. Both solve memory pressure cleanly, and both break assumptions that ordinary middleware relies on.
Streaming uploads: memory vs. temporary disk files
When HttpRequest encounters "multipart/, it calls HttpRequest, freezes the handler list inside an ImmutableList, and constructs MultiPartParser.
An upload handler is a subclass of FileUploadHandler that receives an incoming upload in 64 KiB chunks (chunk_size = 64 * 2**10) through four hooks: handle_raw_input, new_file, receive_data_chunk, and file_complete. By default, settings installs two handlers in order:
MemoryFileUploadHandlerruns first. Insidehandle_raw_input, it checks the total upload size (seeking the stream on ASGI’stempfilewhen possible, or trusting WSGI’s.SpooledTemporaryFile "CONTENT_LENGTH"). Ifcontent_length <= settings(.FILE_UPLOAD_MAX_MEMORY_SIZE 2.5 MiBdefault), it setsactivated = True. Whennew_filefires, it opens anio.BytesIObuffer and raisesStopFutureHandlersso no later handler sees the file, returning anInMemoryUploadedFilefromfile_complete.- When the upload exceeds
FILE_UPLOAD_MAX_MEMORY_SIZE,MemoryFileUploadHandlersetsactivated = Falseand passes every64 KiBchunk untouched toTemporaryFileUploadHandler, which creates aTemporaryUploadedFileon disk (FILE_UPLOAD_TEMP_DIR), writes chunks directly to disk as they arrive, rewinds withseek(0), and hands the open file handle back inFILES.
Test that exact threshold live with FILE_UPLOAD_MAX_MEMORY_SIZE = 1024:
Upload handlers (FILE_UPLOAD_MAX_MEMORY_SIZE) and StreamingHttpResponse lifecycle
small 512B upload (limit=1024) -> InMemoryUploadedFile size=512 handlers=['MemoryFileUploadHandler', 'TemporaryFileUploadHandler']
large 2048B upload (limit=1024) -> TemporaryUploadedFile size=2048 handlers=['MemoryFileUploadHandler', 'TemporaryFileUploadHandler']
StreamingHttpResponse: inverting middleware and teardown
On the outbound path, HttpResponse materializes its entire body into a list of bytes (_container) before leaving the view. StreamingHttpResponse sets streaming = True, holds a one-shot iterator (_iterator), and deliberately removes the content and text attributes (AttributeError on access).
Watch what changes inside WSGIHandler when a view returns a StreamingHttpResponse wrapping a three-chunk generator:
StreamingHttpResponse WSGI lifecycle:
01. view creates StreamingHttpResponse (generator not started)
02. middleware post-view sees streaming=True hasattr(content)=False
03. start_response status='200 OK'
04. WSGI server begins iterating response
05. generator yields chunk 1
06. generator yields chunk 2
07. generator yields chunk 3
08. WSGI server finished iterating (21 bytes), calling resp.close()
09. signal request_finished sender=WSGIHandler
Trace steps 01 through 09 carefully — every timing assumption from normal views has inverted:
- Middleware finishes before the generator runs line 1. In step
02, every middleware’s post-view code (our timing middleware,SessionMiddleware,GZipMiddleware,CommonMiddleware) has already returned, andstart_responsehas already committed HTTP"200 OK"headers to the wire (step03), while the generator has yielded zero bytes! - Body-inspecting middleware must branch on
streaming.CommonMiddlewarecannot compute"Content-Length","ETag"helpers cannot hash the body, and any custom middleware touchingHttpResponsewithout checking.content streamingwill crash withAttributeError. - Exceptions inside the generator cannot become
500HTML pages. Becausestart_response("200 OK", ...)already ran and everyconvert_exception_to_responsewall in the middleware onion has already unwound, an exception raised during step06escapes directly into the WSGI/ASGI server, which can only truncate or reset the TCP connection. request_finishedwaits until the final chunk finishes.HttpResponseBase(step.close 08) andrequest_finished(step09) run only after the WSGI/ASGI server exhausts the stream — meaning database connections stay checked out (and if the generator holds a DB cursor open,"ATOMIC_REQUESTS"has already committed before step05becauseBaseHandleronly wraps the view function returning the.make_view_atomic StreamingHttpResponse, not the generator’s iteration!).
FileResponse subclasses StreamingHttpResponse specifically for open file-like objects: it registers the file’s .close method inside _resource_closers so HttpResponseBase always closes it, computes "Content-Length", "Content-Type", and "Content-Disposition" in FileResponse, reads in 4 KiB chunks on WSGI (or hands file_to_stream directly to "wsgi), and bumps block_size to 64 KiB under ASGIHandler.
The silent memory blowup: sync streams under ASGI (and vice versa)
Look at lines 515–550 of django/ (StreamingHttpResponse and StreamingHttpResponse). A StreamingHttpResponse accepts either a synchronous iterator (def chunks(): yield ...) or an asynchronous iterator (async def chunks(): yield ...).
What happens if you return a synchronous generator inside StreamingHttpResponse and deploy your application under ASGIHandler (which consumes aiter(response))? Or return an async generator under WSGIHandler (which consumes iter(response))?
Test the sync-generator-under-ASGI case live on Django 6.1.3:
sync generator via StreamingHttpResponse.__aiter__ warning: StreamingHttpResponse must consume synchronous iterators in order to serve them asynchronously. Use an asynchronous iterator instead.
execution order (all chunks buffered before consumer-c1): gen-1 -> gen-2 -> gen-3 -> consumer-c1 -> consumer-c2 -> consumer-c3
Look at that execution order: gen-1 -> gen-2 -> gen-3 -> consumer-c1 -> consumer-c2 -> consumer-c3!
When StreamingHttpResponse catches TypeError on a synchronous iterator, it emits a Warning and executes await sync_to_async(list)(self — draining your entire generator into a Python list in memory before sending the first byte to the client! StreamingHttpResponse does the exact mirror image under WSGI for an async generator (async_to_sync(to_list)). A 2 GiB CSV export written as a synchronous generator streams cleanly in 64 KiB slices on Gunicorn (WSGI), then silently OOM-kills your container the afternoon you switch the Dockerfile to Uvicorn (ASGI).
Where uploads and streaming leak
- Match iterator mode to server mode. Under
ASGIHandler, streaming responses must pass anasync defgenerator; underWSGIHandler, they must pass a synchronous generator. Watch your logs for Django’s"must consume ... iterators"warning as a critical memory bug, not cosmetic noise. - Database transactions end before streaming starts. Wrapping a view in
djangoor.db .transaction .atomic "ATOMIC_REQUESTS"commits as soon as the view returnsStreamingHttpResponse— before the generator fetches row 1. If a streaming export needs snapshot isolation or a server-side cursor, open the transaction inside the generator itself. - Timing middleware lies about streaming endpoints. Our newsroom’s timing middleware measures the time until
StreamingHttpResponseis constructed (often< 1 ms), not the 30 seconds the server spends streaming chunks to a slow client.
With incoming requests parsed and streaming mechanics clear, we can step directly into the heart of BaseHandler: how Django compiles "urls.py" into executable matchers, in Compiling URLResolver and path converters.