DEV Community

Around IT In 256 Seconds

#21: SSE and WebSockets

HTTP is historically request-response-driven. This means a server is idle as long as no-one asks it to do something. Typically fetching data or accepting some form. In reality, we’d often like to receive data from the server without any request. Typically to subscribe for some server-side updates. For example, displaying a current price on the stock exchange that changes many times per second. Or when waiting for some asynchronous process to complete. Traditionally this could be achieved with a few hacks. The most obvious and the worst one is busy-waiting. You simply keep asking the server over and over again periodically. More frequent requests result in a lot of excessive network traffic. Less frequent requests increase latency, so it’s no longer real-time communication.

A slightly smarter approach is long-polling. In this implementation, you periodically ask the server whether there is some new data. To avoid excessive round-trips, the server doesn’t respond until some update is available. Or, after a timeout, it sends back an empty response and the loop continues.

Read more: https://256.nurkiewicz.com/21

Get the new episode straight to your mailbox: https://256.nurkiewicz.com/newsletter

Episode source