HTTP Long Polling vs WebSockets


In a typical client to server model, to communicate with server, client opens a HTTP connection and sends the request over that connection to the server. Server process the request and sends the response back to the client. After that connection is closed. Next time client needs to communicate to the server, client will open a new HTTP connection with the server.

In applications, where client needs to repeatedly talk to server for updates in very small intervals of time, this can waste lot of resources.

For example, In chat applications client will periodically poll the server in very small intervals of time for the new messages, server might not have new messages all the time. This can lead to wastage of compute resources. We need ways to reduce the number of connections created between client and server.









To solve the above problem, there are two most popular solutions.

1. HTTP Long Polling

2. Websockets.

HTTP Long Polling

In HTTP Long polling, server holds the connection as long as it can until the new data is available or the timeout threshold is reached.

Once server sends the response back to the client, connection is closed and client creates a new connection. Difference between simple HTTP connection and HTTP long polling is the duration of the connection. Long polling connections tends to be alive for more duration then the simple HTTP connection.




WebSockets

Websockets connections are also built over TCP similar to HTTP connections but they are different from the HTTP connection.

Websocket connection is a duplex connection where both client and server can participate in sending data. Client initiates the connection with the server with the help of handshake mechanism. After accepting the connection, connection remains open until one of the client or server decides to close the connection.

In the chat application, once the websocket connection is established, server can send new messages to the client anytime a new message is available. Client does not need to initiate new connection everytime it is looking for new messages from the server.


Here is a websocket connection example in javascript. Client connects to websocket and on receiving the data, it logs the data.

const webSocket = new WebSocket("ws://localhost:443/");
webSocket.onmessage = (event) => {
const data = JSON.parse(event.data);
console.log("got the message from server ", data);
};




Comments

Popular posts from this blog

Just keep it simple and break it down

Data Structures and System Design Interview Prep Notes