About Webserver Workers and StreamingHttpResponse

Both, WSGI and ASGI servers are supporting the streaming responses with StreamingHttpResponse, however if you have 1 worker running and the whole stream takes 4 seconds without asyncio.sleep(0) between chunks, then the next website visitor will be blocked for 4 seconds.

WSGI vs ASGI

Here is an example of WSGI stream view:

import time
from django.http import StreamingHttpResponse

def stream_view(request):
    def generate():
        for i in range(8):
            yield f"chunk {i}\n"
            # visual pause while streaming
            # blocks the entire worker thread for other visitors
            time.sleep(0.5)
    return StreamingHttpResponse(generate())

And here is an analogical example of ASGI stream view:

import asyncio
from django.http import StreamingHttpResponse

async def stream_view(request):
    async def generate():
        # release the event loop to handle other requests
        asyncio.sleep(0)
        for i in range(8):
            yield f"chunk {i}\n"
            # release the event loop to handle other requests
            # and show visual pause while streaming
            await asyncio.sleep(0.5)
    return StreamingHttpResponse(generate())

Tips and Tricks Programming Architecture Development Optimization Django 6.x Django 5.2 Gunicorn ASGI WSGI Uvicorn Daphne HTTP streaming