DEV Community

Cover image for WebSockets: How Real-Time Applications Actually Work
Soumyajit Mukherjee
Soumyajit Mukherjee

Posted on

WebSockets: How Real-Time Applications Actually Work

Traditional HTTP works extremely well for many applications.

But what happens when the server needs to send information to the browser immediately?

Consider:

  • Chat applications
  • Live dashboards
  • Multiplayer games
  • Trading interfaces
  • Delivery tracking

Polling is one solution.

WebSockets provide another.

Traditional HTTP

A client might repeatedly ask:

Any new messages?
Enter fullscreen mode Exit fullscreen mode

Then:

Any new messages?
Enter fullscreen mode Exit fullscreen mode

Again:

Any new messages?
Enter fullscreen mode Exit fullscreen mode

This creates unnecessary requests.

WebSockets

With WebSockets, the client establishes a persistent connection.

Browser ←────────→ Server
        persistent
        connection
Enter fullscreen mode Exit fullscreen mode

Either side can send messages.

Node.js Example

Using a WebSocket library, a server can broadcast messages:

socket.on("message", (message) => {
  broadcast(message);
});
Enter fullscreen mode Exit fullscreen mode

The browser can listen:

socket.onmessage = (event) => {
  console.log(event.data);
};
Enter fullscreen mode Exit fullscreen mode

Why WebSockets Are Useful

They provide low-latency bidirectional communication.

For example, when someone sends a chat message:

User A
  ↓
Server
  ↓
User B
Enter fullscreen mode Exit fullscreen mode

User B doesn't need to repeatedly ask whether a message arrived.

Things to Consider

Persistent connections create additional operational concerns:

  • Connection management
  • Authentication
  • Reconnection
  • Scaling
  • Load balancing
  • Message ordering

When running multiple servers, messages may need to be distributed between instances.

Final Thoughts

WebSockets are powerful when your application genuinely needs real-time communication.

For normal CRUD applications, standard HTTP APIs are often simpler and sufficient.

Top comments (0)