Building a scalable real-time application with Socket.io and Redis
Continuing from my previous story, “Start building a real-time application” where you discover different ways of building a real-time application here you dig deeper into server push concept where client and server connected via a long-lived web socket connection that acts a medium for communication.
As the title says we are using open-source, node.js based web sockets framework Socket.io for connecting clients and server for mutual data communication. Also, we are using Redis that helps in scaling the app as there is a max limit on the number of concurrent clients getting connected to single socket.io server.
Socket.IO enables real-time, bidirectional and event-based communication.
It works on every platform, browser or device, focusing equally on reliability and speed. Some of its features are Real-time analytics, Instant messaging and chat, Binary streaming and Document collaboration to name a few. It consists of:
- a Node.js server
- a Javascript client library for the browser (or a Node.js client)Socket.io has frontend library called socket.io-client for it to connect to the server.
Fortunately, there is already an open-source chat room demo in the socket.io examples, and this is a great starting point.
git clone git@github.com:socketio/socket.io.git
cd socket.io
npm install
cd examples/chat
npm install
npm start
http://localhost:3000, you should see the above screen.
Voila!! At this stage, we have a working real-time chat application. Socket.io can be configured to support multiple chat rooms as per your requirements with features like namespace and rooms.
For scaling the app, we can do vertical scaling / horizontal scaling. With vertical scaling, we will increase the capacity of the instance, with horizontal scaling we will duplicate the instances to increase the number of concurrent connections. Below you can find the architecture on horizontal scaling.
Instead of only scaling socket.io instance, we are using redis pub/sub service for maintaining the data sync across instances, so that change in one instance is reflected across instances keeping all clients at the same state. Also, we are using the sticky session in load balancers to connect the process that originated them. The integration of socket.io and redis is enabled via socket.io-redis adapter.
Reference: