Building Hyper-Scaling WebSocket-based Web Applications
Building Hyper-Scaling WebSocket-based Web Applications
By: Aditya, Mayur, Navdeep
We just developed a WebSocket-based application that scales from a single node to ~35 nodes (but not limited to it), catering to around 2K users per second (again, not limited to). This blog explains our use case and how we handled WebSockets at scale.
Requirements
- Our clients (web clients / mobile apps) want to interact with our servers for a short duration (1–5 minutes), but in a very chatty manner. - Our servers do very heavy computation tasks (analytics/ML) and keep updating the client. Our client SDKs, based on the response from the user (probably human), again communicate with the server, and so on. - The most important constraint: the backend process started by the client is very specific to that client and has a long bootup time, so we need sticky sessions to ensure the same client always communicates with the same server throughout its session. - The number of clients increases particularly during the afternoon — hence the requirement for scale-in and scale-out. - Servers also expose REST APIs for non-interactive use cases. - Servers interact with the database for client authentication and updating client data.
Seems doable.
Picking the tools
- Chatty, bi-directional clients → WebSockets. - Clients active 1–5 minutes → keep state within the messages being passed between server and client. - Need sticky sessions for WebSockets (a WebSocket should always connect to the same server), connection drops since the state might still be on the previous server. - Auto-scalable orchestrator → Kubernetes. - Event-loop based webserver → Flask on Gunicorn.
The Webserver
In a WebSocket-based webserver, we need to start a Socket.IO listener with which any authenticated client can connect and start exchanging messages. The connection established is a TCP-based connection with a given timeout.
We use Flask-SocketIO on the server and the socket.io JS library on the client.
socketio = SocketIO() instantiates the socket object, our main socket on which we attach listeners (@socketio.on). Event listeners are functions like connect and handlemycustomevent. You can add as many as you want.
The client uses the argument passed to the decorator to emit to a particular event handler. In this case, 'mycustomevent' will route to Python's handlemycustomevent:
socket.emit('my_custom_event', { data: 'User Connected' });
Since our backend is doing pretty heavy computation in each socket session, we keep updating the client about progress with in-between updates:
emit('server_stage_response', {"completed_stage_1": "output_data"})
emit is special — it takes care of session management when multiple clients are connected. A client receives data via socket.on("<server side listener name>", callbackfunction).
Handling State
One of the major concerns of WebSockets is maintaining state — at what stage are both the server and client. We tackled this as follows:
- The state shared between client and server is kept updated in the messages themselves. - Every time the client sends data to the server, it also sends the steps it has completed along with the previous step information. Both server and client keep enriching the messages with the current step information.
This makes the whole application stateless — every request must contain all the context.
1st message from client to server:
{ "name": "john", "surname": "wick" }
2nd message reply from server to client:
{ "name": "john", "surname": "wick", "praise": "he is bad*** killer. stay away from him" }
Now the scenario where a connection drops off. The client now sends:
{ "name": "john", "surname": "wick", "praise": "he is a bad*** killer. stay away from his dog" }
The server will not add more praise to John Wick (though John has never failed to surprise. Eh?) since it's already added — the server will not re-process the praise step.
Maintaining state on the server side gives us more flexibility but comes with the task of handling state at scale. Hence, we chose in-memory state on both sides. This also solved the problem of reprocessing the same state inherently.
Event-based flow
Next, we had a requirement for multiple flows for different kinds of clients — instead of every client starting from scratch, some may want to start from the middle. To counter that, we needed an architecture where the client can communicate any state at any time and the server can start from that state — a good case of event-based architecture, where the event sent dictates the server's flow.
- The WebSocket client code uses a client-id, so each client is identified uniquely. The server can also use this unique client-id to differentiate its heavy-task actions for the same server. Another choice could have been sid (session-id from the Flask global context). - Sticky sessions come to the rescue in case of connection drops or even EngineIO HTTP polling. For REST APIs, the request can go to any running server as REST is independent of state. But our WebSocket request needs to go to the exact same server where the heavy task is running. - Server-side stage detection tries to detect the stage of the current heavy task running on the server. This is useful when the client and server have gone out of sync — we take the server-side state as ground truth (the real battle is happening on the server) and ask the client to resume from that state (possibly starting from scratch).
Learnings from the Webserver
- We use gevent-based Gunicorn workers, an async IO library. This might conflict with any IO library you use in your web service (HTTP requests, DB connections that don't have async IO implementations). A monkey patch is required to convert synchronous IO calls into async IO:
eventlet.monkey_patch(socket=False)
- Use reconnection on the client wherever possible instead of making a new client on disconnect — this saves bootstrap actions on the server:
socket.io.reconnect();
- Enforce yourself to use callback methods in emit — this makes your server more stateless. - Don't use socketio.emit unless you want to broadcast to all connections. - The same events can come twice or even 100 times — for example if a client is doing monkey testing. Handle duplicate messages. - Strict authorizations. We enabled authorization not only on new connections but also on certain event receptions, so no one abuses WebSockets. Though this is a costly operation. - Do not emit back any sensitive data sent by the client to the server. - We used a functional programming approach to write our server code, where based on the event higher-order functions are generated and executed. This made our code generate pure, immutable data and structures. - Event-based Python module picking made adding new modules very easy and 100% customizable. This is similar to OOP and the factory pattern, but the object is lost as soon as the server sends back the response — functions in our modules are more like independent, well-defined functions per module.
Infrastructure
Our infrastructure problem statements:
- WebSocket support - Sticky session - Hyper-scaling and cost-effective - Fault-tolerant - Infrastructure as Code (for reproducibility)
WebSocket support
Initially we picked Nginx but stickiness doesn't work in the open-source version. Our requirement was more of an edge proxy, so we chose Traefik, which inherently supports WebSockets, gRPC, and has good Kubernetes support. We created a repo with a working Let's Encrypt + Traefik ingress controller.
Sticky sessions
We needed cookie-based session stickiness since multiple client traffic can come from the same IP. The required K8s service manifest annotations:
traefik.ingress.kubernetes.io/affinity: "true" traefik.ingress.kubernetes.io/session-cookie-name: "tasty-cookie"
Hyper-scaling and cost-effective
When demand rises, we should horizontally scale out; when not, scale down gracefully.
- We use the GKE cluster auto-scaler, which adds nodes when pods can't be scheduled. - For the horizontal pod scaler, we use HPA (Horizontal Pod Autoscaler) — we created a repo for creating HPA on custom metrics.
Fault tolerance
We currently use Google Datastore given the very low amount of database interaction, and for computation we deployed node pools in two different zones. For latency, we need to choose the India region, so currently we are deployed in a single region and plan to use a separate region on a different cloud provider for heavy fault tolerance.
Infrastructure as Code
We use Terraform for even small changes in our infra and kubectl for every Kubernetes interaction.
Learnings from Infrastructure
- When downscaling, gracefully delete pods so you don't disrupt any running process. We use terminationGracePeriodSeconds, set to the maximum amount of time a single process can take. - The initial number of replicas should be set to a number that can handle traffic until the next replica becomes available.
Improvements
- Making WebSockets with stickiness work with Lambda functions (Knative?). - Service mesh (Maesh?) for inter-service communication and monitoring. - Use persistent queues and on-demand channel creation for client-server communications.
Lead Developer: Aditya
---
At Dataorc, scalability and fault tolerance are first-class citizens. While writing any code, we are always thinking that it needs to be deployed at thousands of endpoints and have the highest uptime. Above all, we believe there is no final solution. Ping us if you want to know more about the architecture or have any suggestions.