How can I implement sticky sessions in a Node js app running in cluster mode ensuring the same client always hits the same server

0 votes
Can you help me with How I can implement sticky sessions in a Node.js app running in cluster mode, ensuring the same client always hits the same server?
Dec 16, 2024 in Node-js by Ashutosh
• 17,760 points
100 views

1 answer to this question.

0 votes

To implement sticky sessions in a Node.js app running in cluster mode, ensuring the same client always hits the same server, you can follow these steps.

Steps to Implement Sticky Sessions:

Cluster Setup:

Use the cluster module in Node.js to create multiple worker processes. Each worker can handle incoming requests independently. In a clustered environment, the operating system balances the load between the workers.

Example:

const cluster = require('cluster');

const http = require('http');

const os = require('os');

const app = require('express')();

if (cluster.isMaster) {

    // Fork workers for each CPU core

    const numCPUs = os.cpus().length;

    for (let i = 0; i < numCPUs; i++) {

        cluster.fork();

    }

    cluster.on('exit', (worker, code, signal) => {

        console.log(`Worker ${worker.process.pid} died`);

    });

} else {

    // Worker processes can share the same server

    http.createServer(app).listen(3000, () => {

        console.log(`Worker ${process.pid} started`);

    });

}

Sticky Sessions with Sticky-Session Library: To ensure the same client hits the same worker, you'll need sticky sessions. The sticky-session library helps achieve this by ensuring that requests from the same client go to the same worker process.

Install the sticky-session library:

npm install sticky-session

Then, modify the above code to use sticky-session:

const sticky = require('sticky-session');

const express = require('express');

const app = express();

app.get('/', (req, res) => {

    res.send('Hello World');

});

if (sticky.listen(app, 3000)) {

    console.log('Server started on port 3000');

}

Configure Load Balancer (Optional for Distributed Clusters): In a cloud or distributed environment, you may need a load balancer to route traffic. To maintain sticky sessions across multiple machines, configure the load balancer (e.g., Nginx, HAProxy) to support sticky sessions. This will route requests from the same client to the same Node.js worker process.

Session Management: Ensure that session data is shared across workers (since each worker is separate). You can use shared session storage like Redis, which ensures that when a client reconnects, their session is available to the worker handling the request.

Example using Redis session store:

npm install express-session connect-redis redis

const session = require('express-session');

const RedisStore = require('connect-redis')(session);

const redis = require('redis');

const client = redis.createClient();

app.use(session({

    store: new RedisStore({ client: client }),

    secret: 'mySecret',

    resave: false,

    saveUninitialized: true

}));
answered Dec 17, 2024 by Navya

Related Questions In Node-js

0 votes
1 answer

How can i get the extension of the image in node.js?

Hello @kar You can do the following to ...READ MORE

answered Jul 16, 2020 in Node-js by Niroj
• 82,840 points
2,215 views
0 votes
1 answer

How can I get the browser language in node.js?

Hello @kartik, You can use req.headers["accept-language"] to get the language/locale ...READ MORE

answered Oct 16, 2020 in Node-js by Niroj
• 82,840 points
4,481 views
0 votes
1 answer

How can I use an http proxy with node.js http.Client?

Hello @kartik, You can use request, I just found ...READ MORE

answered Jul 17, 2020 in Node-js by Niroj
• 82,840 points
10,739 views
0 votes
1 answer

How do I get the time of day in javascript/Node.js?

Hello @kartik, This function will return you the ...READ MORE

answered Sep 7, 2020 in Node-js by Niroj
• 82,840 points
1,275 views
0 votes
1 answer

How can I implement pagination for large datasets in an Express.js API?

Pagination is a technique used to divide ...READ MORE

answered Oct 25, 2024 in Web Development by kavya
248 views
0 votes
1 answer

How do you implement API request validation in Express using middleware?

1. Create Middleware Function :  - Define a ...READ MORE

answered Oct 25, 2024 in Web Development by kavya
206 views
0 votes
1 answer

How do I use ES6 features like destructuring in a Node.js application?

To use ES6 features like destructuring in ...READ MORE

answered Dec 17, 2024 in Node-js by Navya
92 views
0 votes
1 answer

How can I modify results in a read-only ng-app?

Modifying data within an AngularJS application that ...READ MORE

answered Feb 10 in Node-js by Navya
46 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP