Websocket server id based sticky sessions using HAProxy

This is a socket.io based example to showcase basic stickyness by server ID.

Let’s write a simple socket.io server.

var app = require(‘express’)();

var server = require(‘http’).Server(app);

var io = require(‘socket.io’)(server,{cors:{

origin: ‘*’ }});



socket.emit(‘announcements’,{message : ‘User has joined to 8200’});


console.log(‘A client has sent us thsi’,data.message);




Copy the project and run the same code 2 different ports. Since docker wasn’t installed on my machine, I had to do this. If dockerized then just run this on 2 diff ports with the same image.

Coming to HAproxy configuration:

frontend Local_Server
bind localhost:80
mode http
default_backend my_web_servers
# Any URL beginning with socket.io will be flagged as ‘is_websocket’
acl is_websocket path_beg /socket.io
acl is_websocket hdr(Upgrade) -i WebSocket
acl is_websocket hdr_beg(Host) -i ws
use_backend websockets if is_websocket

stats enable
stats hide-version
stats realm Haproxy\ Statistics
stats uri /haproxy?stats
stats auth 123:123

backend my_web_servers
# balance source
hash-type consistent
hash-balance-factor 125

server sockerserver1 localhost:8200
server sockerserver2 localhost:8400

backend websockets
balance leastconn
cookie SERVERID insert indirect nocache
# hash-type consistent
# hash-balance-factor 125
server ws-server1 localhost:8200 weight 1 maxconn 1024 check cookie s1
server ws-server2 localhost:8400 weight 1 maxconn 1024 check cookie s2
server ws-server3 localhost:8600 weight 1 maxconn 1024 check cookie s3

Ignore the commented lines, we’ll take it up in next post.

So please go through the above haproxy config for front and backend in detail. I assume you’ve some knowledge of HAProxy.

I’ll directly jump on to websockets section:

  • balance leastconn: says connect to server whichever has least connections
  • cookie serverid says, connection once established will always be connected to same server using server id. HAProxy, appends server id to connected requests and it remembers the same when connection comes back with the same ID.
  • server ws-server1: I just appended my server ID’s for each server.

This is a very simple example of websocket connections to same server using server id.

Next session will be on application-cookie-id based sticky sessions. Meanwhile, Have Fun :-)

Techie, Sportsman, Explorer. Little by little becomes a lot :) Topics I’m happy to discuss: Product, Chatbots, CxPaaS, DevOps. https://github.com/preethamslab