Skip to main content

WebSockets vs HTTP Polling vs Server-Sent Events: Real-Time Features Explained

In this article

There are three ways to get live updates into a browser without the visitor pressing refresh. HTTP polling has the page ask the server for news on a timer. Server-sent events (SSE) keep one ordinary HTTP response open and let the server push lines down it, one way. WebSockets open a persistent two-way connection over which either side can send at any moment. They are not rivals so much as tools for different jobs, and picking the heaviest one by default is the most common mistake.

The short version: poll when an update every half minute or so is fine and the page is simple. Use SSE when the server needs to push to the browser but the browser has nothing to say back, such as notifications, progress bars and live dashboards. Use WebSockets when traffic flows both ways and delay matters, such as chat, collaborative editing and live bidding. In Django, polling is just a view; SSE needs the app running under ASGI; WebSockets need ASGI plus Django Channels, which is the standard route.

How HTTP polling works

The web runs on request and response: the browser asks, the server answers, the connection is done. The server cannot speak unless spoken to. Polling fakes a live page by having a few lines of JavaScript ask again every few seconds: "any new messages?", "is the order dispatched yet?". Most answers are "no".

The costs follow from that. The delay a user sees is the length of the timer, so a page polling every thirty seconds shows news up to thirty seconds late. And every empty answer still costs a full request. A thousand visitors polling every three seconds is twenty thousand requests a minute, nearly all of them returning nothing. Each one spends the phone's battery and the server's time on headers.

Long polling softens this: the server holds the request open until it has something to say or a timeout passes, then the browser immediately asks again. It cuts the empty answers but keeps a connection busy per visitor, and it is fiddly to run behind proxies with their own timeouts.

Polling still has a place. It works with any hosting, needs no special server, and plays well with HTTP caching. A status endpoint that returns a 304 Not Modified when nothing has changed costs very little, as our guide to the web's caching layers explains. An admin dashboard refreshed every minute, or an order tracking page checked every half minute, is correctly built with polling.

How server-sent events work

SSE is the option most people have not heard of and the one that fits the most cases. The browser opens one request with the EventSource API, the server replies with a response of type text/event-stream and simply never finishes it. Whenever something happens the server writes a few lines ("data: order dispatched") down the open response and the browser's event handler fires. If the connection drops, the browser reconnects on its own and sends the id of the last event it saw, so the server can resume where it left off. That reconnection logic is built into every modern browser; with WebSockets you write it yourself.

The limits are that SSE is one way (the browser talks back through ordinary requests, which is fine for most apps), and it carries text rather than binary. On HTTP/1.1 a browser allows only a handful of open connections to one host, so several SSE tabs can starve each other. Under HTTP/2 that limit effectively disappears. In Django an SSE endpoint is an asynchronous StreamingHttpResponse running under an ASGI server, with no extra library.

How WebSockets work

A WebSocket starts life as a normal HTTP request carrying an Upgrade header. The server answers 101 Switching Protocols and from then on the same connection carries small frames in both directions until one side closes it. There are no headers per message and no waiting for the other side, so a message costs a few bytes and arrives within milliseconds. That is what chat, multiplayer games, collaborative documents and live auctions need.

The price is operational. A WebSocket is a connection the server has to keep open, so the server must be able to hold thousands of idle connections cheaply, which Django's traditional WSGI setup cannot. Load balancers and proxies need their idle timeouts raised above your heartbeat interval or they will cut connections that look quiet. The client has to detect a dropped connection and reconnect with backoff. And authentication happens at connection time, on the upgrade request, with an origin check so another website cannot open a socket to your server from a visitor's browser.

The three compared

AttributeHTTP pollingServer-sent eventsWebSockets
DirectionBrowser asks, server answersServer pushes; browser replies by normal requestsBoth ways on one connection
Delay before an update showsUp to the polling intervalUnder a secondMilliseconds
Server cost when nothing happensA full request per visitor per intervalOne idle connection per visitorOne idle connection per visitor
ReconnectionNot neededBuilt into the browser, resumes from last eventYou write it
Works through proxies and CDNsEverywhereAlmost everywhere; buffering proxies can delay itNeeds explicit support and longer timeouts
What Django needsA normal viewASGI server, async streaming viewASGI server plus Django Channels and Redis
Best forDashboards, order status, anything slow-changingNotifications, progress, live feeds, scoresChat, collaboration, bidding, games

Choosing for a real feature

  • Live availability on a booking page. Slots change a few times an hour. Poll every thirty seconds, or use SSE if you want the slot to grey out the moment someone else takes it. The real protection against two people booking one slot is in the database, not the connection, as a custom booking system's double-booking rules show. A travel agency website taking bookings against live availability is the same case with a different resource.
  • Progress of a long job. A PDF being generated, an import running, a report compiling. SSE: the background job posts progress, the browser shows a bar, the connection closes when it is done.
  • Notifications in a web app. "Your invoice was paid", "a new lead arrived". SSE. The browser never needs to send anything on that channel.
  • Support chat or an internal messaging tool. WebSockets. Both sides send, typing indicators and read receipts need low delay, and users keep the tab open for hours.
  • Collaborative editing or a live auction. WebSockets, with the server as the referee for who said what first.
  • A dashboard of yesterday's numbers. No live connection at all. Load it once; nothing changes until tomorrow.

Note what is missing from that list: server to server. When another system needs to tell your server something, the answer is a webhook, not a WebSocket; what webhooks are and how they work covers that case.

Real time in Django: Channels

Django was designed around the request and response cycle and runs under WSGI, where each request is handled and finished. WebSockets need a process that holds connections open, which means running Django under ASGI with a server such as Daphne or Uvicorn. Django Channels is the library that teaches Django to speak WebSocket on top of that. The rest of the site keeps working exactly as before; Channels only takes over the socket routes.

Channels adds two ideas. A consumer is the WebSocket equivalent of a view: it accepts the connection, receives messages and sends them. A channel layer, backed by Redis, lets any process in your deployment send a message to any open connection. That means a background job that has just finished an order can push an update to the customer's browser even though a different process holds that socket. A minimal consumer that lets a customer watch one order:

class OrderStatusConsumer(AsyncJsonWebsocketConsumer):
    async def connect(self):
        self.group = f"order_{self.scope['url_route']['kwargs']['order_id']}"
        if not self.scope["user"].is_authenticated:
            await self.close()
            return
        await self.channel_layer.group_add(self.group, self.channel_name)
        await self.accept()

    async def disconnect(self, code):
        await self.channel_layer.group_discard(self.group, self.channel_name)

    async def order_update(self, event):
        await self.send_json(event["data"])

A Celery task then calls group_send on the channel layer with a type of "order.update" and the new status, and every browser watching that order receives it. The same pattern, with a group per chat room instead of per order, is most of a chat feature.

What it costs to run

Polling costs nothing extra to operate. SSE and WebSockets both mean long-lived connections, and that changes the deployment:

  • An ASGI server.
  • Redis if you use Channels.
  • A load balancer configured for long connections.
  • Heartbeats so dead connections are noticed.
  • Monitoring of how many sockets are open.

On a site with a few hundred concurrent users this is modest. On one with many thousands it is the thing that decides when you need a second server, which our guide to load balancing walks through. On our web platform builds we add a live channel in a later stage, once the feature that needs it exists. That is because an SSE feed or a WebSocket is easy to add to a Django app built sensibly, and pointless to build before there is anything to push.

Questions people ask

Are WebSockets faster than HTTP?

For a stream of small messages, yes: no headers per message and no waiting to be asked. For loading a page or fetching a record, ordinary HTTP is just as fast and far simpler. The speed difference only matters once messages are frequent and delay is noticeable.

Does Django support WebSockets?

Yes, through Django Channels running under an ASGI server. Core Django handles SSE on its own with an asynchronous streaming response. Both need the app deployed under ASGI rather than the older WSGI setup.

What is long polling?

A form of polling where the server holds each request open until it has something to say or a timeout passes, then the browser immediately asks again. It reduces empty responses compared with plain polling but still costs a request per update and is awkward behind proxies. SSE is usually the better choice where long polling would once have been used.

Should a chat feature use WebSockets or polling?

WebSockets if the chat is a core part of the product and people keep it open. For a low-volume contact widget where a reply within half a minute is fine, polling is cheaper to build and run, and nobody will notice the difference.

How we decide on our own builds

We ask two questions: does the browser need to send as well as receive, and would a delay of half a minute annoy anyone? Two "no" answers mean polling. One "yes", on the delay, means SSE. "Yes" to both means WebSockets and Channels. The decision rarely takes longer than that, and it keeps most apps on the simplest option that works, which is the one that is still running quietly in three years.