CodePark/ questions / Real-time updates
START PRACTICINGPRACTICE
Frontend question · Frontend system design › Real-time updates

Compare short polling, long polling, Server-Sent Events and WebSockets. What are the trade-offs of each?

Each one trades simplicity against latency and server cost. Latency is the delay before the user sees new data.

Short polling asks the server every N seconds.

  • Pro: it is trivial and works everywhere.
  • Con: it wastes requests when nothing changed.
  • Con: it adds up to N seconds of latency.

Long polling sends a request, and the server holds it open until there is data or a timeout. The client then reconnects immediately.

  • Pro: latency is low.
  • Pro: it works through any HTTP infrastructure.
  • Con: each message costs a full request cycle.
  • Con: the server holds many open connections.

SSE (Server-Sent Events, the EventSource API) is a long-lived HTTP response. It streams text events from the server to the client only.

  • Pro: the browser reconnects automatically. It can send Last-Event-ID, so the server resumes from the right place.
  • Pro: it is simple and works well with proxies.
  • Con: it is one-way and text only. The client sends data to the server through normal requests.

WebSockets give a full-duplex connection, which means both sides can send at any time.

  • Pro: low overhead per message, binary support, and both directions.
  • Con: you must build reconnection, heartbeats, message acknowledgement and resubscription yourself.
  • Con: scaling is harder, because each connection holds state on one server. You need sticky routing or a pub/sub layer.

Sticky routing sends a client back to the same server each time. Pub/sub (publish/subscribe) is a message system that delivers each event to every server that needs it.

  • Short polling is simple but wasteful, with latency up to the polling interval.
  • Long polling has low latency, but costs one request per message.
  • SSE is one-way from server to client, reconnects automatically and resumes with Last-Event-ID.
  • WebSockets work in both directions, but you own reconnection and scaling.