Skip to content

SSE with Django — Complete Guide to Server-Sent Events

DodaTech Updated 2026-06-28 4 min read

In this tutorial, you will learn about SSE with Django. We cover key concepts, practical examples, and best practices to help you master this topic.

SSE with Django implements real-time server-to-client streaming using StreamingHttpResponse, async views, and Django channels for scalable event delivery in Python web applications.

What You'll Learn

  • Implementing SSE with Django StreamingHttpResponse
  • Using async Django views for SSE
  • Scaling SSE with Django Channels

Why It Matters

Django is synchronous by default, which conflicts with SSE streaming. Understanding how to work within Django's request-response model while maintaining persistent streaming connections is essential for Django-based real-time features.

Real-World Use

Durga Antivirus Pro Django admin dashboard uses SSE to stream live system metrics. The StreamingHttpResponse keeps the connection open, pushing CPU, memory, and threat detection metrics to the browser every 2 seconds.

flowchart LR
    B["Browser"] --> D["Django View"]
    D --> S["StreamingHttpResponse"]
    S --> M["Metrics Generator"]
    M -->|"Every 2s"| B
    style S fill:#dbeafe,stroke:#2563eb

Code Examples

# Django SSE with StreamingHttpResponse
from django.http import StreamingHttpResponse
from django.views import View
import json
import time
import psutil

class MetricsSSEView(View):
    def get(self, request):
        def event_stream():
            while True:
                data = json.dumps({
                    'cpu': psutil.cpu_percent(),
                    'memory': psutil.virtual_memory().percent,
                    'timestamp': time.time(),
                })
                yield f"event: metrics\ndata: {data}\n\n"
                time.sleep(2)

        response = StreamingHttpResponse(
            event_stream(),
            content_type='text/event-stream',
        )
        response['Cache-Control'] = 'no-cache'
        response['X-Accel-Buffering'] = 'no'
        return response

Expected output: Django streams metrics via SSE; browser receives events every 2 seconds.

# Django async SSE view
from django.http import StreamingHttpResponse
import asyncio
import json

async def async_event_stream():
    counter = 0
    while True:
        counter += 1
        data = json.dumps({'count': counter, 'timestamp': asyncio.get_event_loop().time()})
        yield f"data: {data}\n\n"
        await asyncio.sleep(1)

async def async_sse_view(request):
    response = StreamingHttpResponse(
        async_event_stream(),
        content_type='text/event-stream',
    )
    response['Cache-Control'] = 'no-cache'
    return response

Expected output: Django async SSE view handles streaming without blocking the event loop.

# Django Channels WebSocket vs SSE selector
from django.http import StreamingHttpResponse
from django.views import View

class NotificationSSEView(View):
    def get(self, request):
        def event_stream():
            # Poll for new notifications
            last_id = 0
            while True:
                notifications = get_notifications(request.user, since=last_id)
                for notif in notifications:
                    last_id = notif.id
                    yield f"id: {notif.id}\nevent: notification\ndata: {json.dumps(notif.to_dict())}\n\n"
                time.sleep(5)

        return StreamingHttpResponse(event_stream(), content_type='text/event-stream')

Expected output: Django polls for new notifications and pushes them to connected SSE clients.

Common Mistakes

1. Blocking the Event Loop with Synchronous Sleep

Using time.sleep() in a sync view blocks the Django Process. Use async views or run in a separate thread.

2. Forgetting Cache-Control Header

Django middleware may cache SSE responses. Always set Cache-Control: no-cache.

3. No nginx Proxy Configuration

If using nginx, disable buffering for SSE endpoints (proxy_buffering off) to avoid delayed delivery.

4. Connection Leaks on Disconnect

Django does not automatically detect client disconnects in StreamingHttpResponse. Check response.streaming flag or use async.

5. Process Exhaustion from Long-Running Connections

Each SSE connection occupies a Django process/thread. Use async views or a dedicated server for SSE scaling.

Practice Questions

  1. What Django class is used for SSE streaming?
  2. Why does time.sleep() cause problems in Django SSE views?
  3. How do async Django views improve SSE performance?
  4. Why is the Cache-Control header important for SSE?
  5. How does Django handle client disconnect detection?

Answers:

  1. StreamingHttpResponse, which yields data in chunks without closing the connection.
  2. time.sleep() blocks the entire Django process/thread, preventing it from handling other requests.
  3. Async views release the thread during I/O waits (await asyncio.sleep), allowing other requests to be processed.
  4. Without no-cache, Django or proxy middleware may buffer the entire stream before sending.
  5. Django does not detect disconnects in sync StreamingHttpResponse; async views allow proper disconnect handling.

Challenge: Build a Django SSE dashboard that streams three data types: system metrics (every 2s), recent alerts (on new data), and connection heartbeats (every 30s). Use async views and handle client disconnect cleanup.

FAQ

Can Django handle many SSE connections simultaneously?

: Sync Django is limited by process/thread count. Use async views, Daphne/Uvicorn, or Django Channels for scale.

Does Django Channels support SSE?

: Channels supports Websocket natively; SSE can be layered on top of Channels using the HTTP layer.

What is the best production setup for Django SSE?

: Django + Gunicorn (async workers) + nginx (with buffering disabled) + Redis for cross-process event distribution.

How do you broadcast events to multiple SSE clients in Django?

: Use Redis pub/sub or Django Channels group send to push events to all connected SSE clients.

Can Django SSE be used with Django REST Framework?

: Yes, use a custom renderer or StreamingHttpResponse in an APIView for DRF compatibility.

Mini Project

Build a Django SSE notification system: users subscribe to their notification stream via SSE, the server pushes new notifications in real time, and the frontend displays them with toast notifications. Use async views for non-blocking streaming.

What's Next

Learn about SSE with Spring Boot for Java-based SSE, or explore SSE performance optimization for scaling production deployments.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro