Course contentsShow
← Node.js
Lesson 968 of 1,9809. Authentication and Identity ManagementFree lesson

Using Redis for Session Management

Cache session data in an external store to support horizontal scaling.

In this lesson, you will learn how to leverage Redis as an external session store to enable seamless horizontal scaling in your Node.js applications.

The Scaling Bottleneck

When you store sessions in the local memory of a Node.js process, you create "sticky sessions." If your load balancer routes a user to a different server instance, that instance won't recognize the session, forcing the user to log in again. As we discussed in our exploration of distributed systems, this statefulness binds a user to a specific machine, preventing you from adding or removing servers dynamically.

Moving State Externally

To solve this, we move the session data out of the application's RAM and into an external, high-performance key-value store: Redis. Because Redis is accessible by every instance of your Node.js application, any server can retrieve the session data for any user.

By using a library like connect-redis alongside express-session, you offload the storage responsibility. Here is the architectural flow:

  1. A user logs in.
  2. The server creates a session object and generates a Session ID.
  3. The server saves the session data in Redis (using the Session ID as the key).
  4. The server sends the Session ID to the user as an HttpOnly cookie.
  5. On the next request, the server fetches the session data from Redis using the provided cookie ID.
const session = require('express-session');
const RedisStore = require('connect-redis')(session);
const { createClient } = require('redis');

const redisClient = createClient({ legacyMode: true });
redisClient.connect().catch(console.error);

app.use(session({
  store: new RedisStore({ client: redisClient }),
  secret: process.env.SESSION_SECRET,
  resave: false,
  saveUninitialized: false,
  cookie: { secure: true, httpOnly: true }
}));

Because Redis keeps data in memory, lookups are extremely fast, ensuring that authentication checks remain performant even as your traffic grows. By decoupling the session from the application instance, your backend becomes truly stateless regarding memory, allowing you to scale horizontally with ease.

Key Takeaway: Moving session storage to an external Redis instance breaks the dependency between user state and server memory, enabling horizontal scaling without sacrificing the user’s authentication experience.