What Are WebSockets and How They Work

Intro to the WebSocket protocol
WebSocket is a communication protocol that enables two-way (full-duplex) communication between a web browser and server over a single TCP connection. Unlike the classic HTTP protocol where the client has to send a request to receive a response, WebSocket lets the server send data to the client whenever it has something new to deliver, without waiting for a request. This is revolutionary for web applications that require real-time updates.
Before WebSocket, developers used techniques like polling where the browser periodically sends requests to the server, for example every 2 seconds asking if there's new data, or long polling where the server holds the connection open until it gets new data. Both techniques are inefficient because they burn bandwidth on HTTP headers and load the server with unnecessary requests. WebSocket solves these issues by establishing a persistent connection with minimal overhead.
How WebSocket works
Handshake process
A WebSocket connection starts as a regular HTTP connection through a process known as the handshake. The client sends an HTTP request with special headers Connection Upgrade and Upgrade websocket signaling to the server the desire to switch to the WebSocket protocol. The server responds with status code 101 Switching Protocols if it supports WebSocket, upgrading the HTTP connection to WebSocket. From that moment on, both sides can freely send data without HTTP overhead.
Framing and data transfer
After the connection is established, data is exchanged through WebSocket frames that are significantly smaller than HTTP packets. Each frame contains only 2 to 14 bytes of overhead compared to hundreds of bytes in HTTP headers. WebSocket supports text messages in UTF-8 format and binary data. Messages can be fragmented into multiple frames for transferring large payloads. Control frames like ping and pong are used to check whether the connection is still active.
Closing the connection
Either side can initiate closing the WebSocket connection by sending a close frame. The closing process involves exchanging close frames where the side receiving the close frame responds with its own close frame, and after that the TCP connection is closed. The client side typically implements automatic reconnection in case of unexpected connection breaks with exponential backoff between attempts so the server isn't overwhelmed.
WebSocket applications in practice
Chat applications
Chat is the most obvious WebSocket application. When a user sends a message, it appears instantly to all participants in the conversation without refreshing the page. Modern chat applications like Slack, Discord, and Facebook Messenger use WebSocket for real-time message delivery. Beyond text, WebSocket enables sending typing indicators, read status, online and offline user status, and new message notifications. Implementing chat with polling would require thousands of HTTP requests per minute, while WebSocket does it with one open connection.
Real-time notifications
Notification systems on platforms like GitHub, Trello, or project tools use WebSocket to deliver notifications to users as soon as relevant activity happens. When someone comments on your pull request, WebSocket instantly delivers the notification to the browser without you needing to refresh the page. This is especially important for collaborative tools where multiple users work on the same project simultaneously because every change must be visible to all participants in real time.
Live dashboards and monitoring
Dashboards displaying real-time metrics like tracking site traffic, server monitoring, financial data, or IoT sensors use WebSocket for continuous chart and value updates. Instead of the dashboard refreshing the entire page every 5 seconds, WebSocket delivers only changed data, which significantly reduces server load and bandwidth consumption. Tools like Grafana and Kibana use WebSocket for live metric streaming.
Collaborative editing
Google Docs, Figma, and similar tools let multiple users edit the same document simultaneously thanks to WebSocket. Every change by one user instantly propagates to all other users. This requires sophisticated conflict resolution algorithms like Operational Transformation or CRDT algorithms that ensure document consistency even when two users simultaneously edit the same part of the text.
WebSocket in different programming languages
JavaScript and Node.js
In the browser, the WebSocket API is built-in and used directly without additional libraries. Creating a connection is simple with the new WebSocket constructor that takes the server URL. On the server side, popular Node.js libraries include ws which is minimal and fast, Socket.IO which adds automatic fallback to polling if WebSocket isn't available plus rooms for group messaging and automatic reconnection. Socket.IO is the most popular choice for JavaScript projects because it abstracts complexity and works reliably even on networks with restrictive firewalls.
Python and PHP
Python developers use libraries like websockets for async access or Django Channels which adds WebSocket support to the Django framework. Flask-SocketIO is a popular option for Flask applications. PHP traditionally isn't ideal for WebSocket because it's designed for the request-response model, but the Ratchet library and the Swoole extension enable WebSocket servers in PHP. Laravel uses Laravel Echo with Pusher or Socket.IO for real-time functionality, with Laravel Reverb as a self-hosted solution.
Hosting requirements for WebSocket applications
Server configuration
WebSocket applications have specific hosting requirements. Shared hosting usually doesn't support WebSocket because it requires long-lived connections that the shared environment can't manage efficiently. Virtual server hosting or a dedicated server is the minimum for production. The web server must be configured for WebSocket proxy - Nginx uses proxy_pass with upgrade headers, Apache uses mod_proxy_wstunnel. The firewall must allow WebSocket traffic, which typically uses ports 80 for ws and 443 for wss protocol.
Scaling WebSocket applications
Scaling WebSocket is more complex than scaling HTTP applications because every connection consumes memory on the server. One server can maintain anywhere from 10,000 to 100,000 simultaneous WebSocket connections depending on hardware and application. For a larger number of users, horizontal scaling with Redis pub/sub or a similar message broker is used to sync messages between server instances. The load balancer must support sticky sessions or IP hash so the WebSocket connection stays on the same backend server.
WebSocket security
WSS encryption
Just as HTTP has HTTPS, WebSocket has WSS (WebSocket Secure) which uses TLS encryption. Always use WSS in production because unencrypted WebSocket connections can be intercepted. Most modern browsers block ws connections from pages loaded over HTTPS, so WSS is practically mandatory. The SSL certificate you use for HTTPS automatically also covers WSS connections on the same domain.
Authentication and authorization
WebSocket doesn't support HTTP headers after the initial handshake, so authentication is usually handled by sending a token as a query parameter when establishing the connection or by sending an authentication message immediately after connecting. JWT tokens are a popular choice because the server can verify user identity without a database query. Authorization determines which channels or rooms a user can listen to and which messages they can send. On BeoHosting VPS plans you have full control over server configuration, which allows optimal WebSocket application setup with proper security and performance.
Conclusion
The WebSocket protocol is a fundamental technology for modern web applications that require real-time communication. From chat systems and notifications to collaborative tools and live dashboards, WebSocket enables experiences that classic HTTP simply can't provide. Understanding how WebSocket works, when to use it, and how to properly implement it is a key skill for every web developer who wants to build dynamic and interactive applications.
BeoHosting Team
10+ years of experience — Web hosting and infrastructure specialists
- Web Hosting
- WordPress Hosting
- VPS
- Dedicated Serveri
- Domeni
- SSL
- cPanel
- LiteSpeed
- Linux administracija
- DNS
Last updated: