Websocket API

Understand core concepts of WebSocket.

Bidirectional communication

HTTP-based communication requires a client to trigger the flow. Only the client can initiate an HTTP request to send or receive data from the server. The server can’t trace the client to send a message back to the client. It has to wait for the next HTTP request from the client. That’s because the server doesn’t have a reverse connection to the client.

This works well in many scenarios, which is why the REST API is so popular. However, there are times when such a design fails to deliver what we need. Consider, for example, a chat application. If we implement a chat application based on REST APIs, the server will have to hold new messages until the client makes an API call asking for it. The client must poll the server repeatedly to check for new messages. That’s inefficient and costly. We need a better way to implement such applications where the server sends a message to the client.

Chat with REST

Let's check the chat application in more detail. The sequence diagram below demonstrates the flow of messages when two clients, Tom and Jerry, try to chat over a REST API. The server can hold data and respond to any API request. It can’t contact the client unless the client asks for it.

In this case, any message sent from one client to another will have to wait on the server until the other client tries to pick it up. This increases the latency of communication. Additionally, it increases the cost because we have too many redundant poll API calls.

Get hands-on with 1400+ tech skills courses.