
WebSockets vs Server-Sent Events vs Long Polling: Choosing the Right Real-Time Strategy
Real-Time Is a Spectrum Every real-time feature has different requirements. A collaborative document editor and a live sports scoreboard have nothing in common—except they both need updates without page refresh. Choosing the wrong transport layer wastes engineering time and creates reliability nightmares. The Three Options 1. Long Polling The oldest trick: client makes a request, server holds it open until data arrives (or timeout), client immediately re-requests. async function longPoll ( lastEventId : string ) { try { const response = await fetch ( `/api/events?after= ${ lastEventId } &timeout=30` ); const data = await response . json (); processEvents ( data . events ); longPoll ( data . lastEventId ); // immediately reconnect } catch ( error ) { await sleep ( 1000 ); // back off on error longPoll ( lastEventId ); } } Server: app . get ( ' /api/events ' , async ( req , res ) => { const { after , timeout = 30 } = req . query ; const events = await waitForEvents ( after , parseInt ( t
Continue reading on Dev.to
Opens in a new tab


