Node.js, the most popular runtime for scalable network applications, benefits excessively from distributed caching to store sessions. Modern web applications must manage user sessions effectively to provide smooth experiences on multiple servers. With NCache, a distributed in-memory cache for high-performance applications, Node.js applications are able to provide high availability, scalability, and lower latency.
This blog discusses why distributed caching is essential for session storage and how NCache is the ideal fit. It also provides a step-by-step guide to setting up session storage in NCache for Node.js applications.
Why Use Distributed Caching for Session Storage?
This section entails the challenges encountered with traditional ways of session storage and the benefits of using NCache in this regard.
Challenges of Traditional Session Storage
Typical session storage methods in Node.js applications include:
- In-memory session storage: Tied to a single instance, causing session loss upon restart.
- Database-backed session storage: Increases database load and slows down performance.
- File-based session storage: Limited scalability, and slower access times.
As applications scale horizontally across several servers, it becomes difficult to manage user sessions efficiently and consistently. Distributed caching addresses these concerns by providing faster access, fault tolerance, and scalability.
Advantages of Using NCache for Session Storage
NCache has the following advantages when used for storing sessions:
- High Availability & Fault Tolerance: NCache provides high availability and fault tolerance by replicating session data across many nodes, ensuring persistence even in case of a node failure.
- Improved Performance: In-memory caching eliminates any database dependency and allows for faster session retrieval.
- Scalability: Scales easily by adding cache nodes to manage increasing application traffic.
- Centralized Session Storage: Ensures session consistency across multiple servers, removing the necessity for sticky sessions.
- Optimized Resource Utilization: Automated expiration policies remove stale sessions for effective memory management.
- Multi-Site WAN Replication: NCache supports multi-site WAN replication, allowing for session data replication across geographically separated locations, providing high availability and disaster recovery.
Figure: Distributed cache.
Configuring NCache for Node.js Session Storage
Follow these steps to store and manage sessions in NCache using Node.js.
Step 1: Install NCache and Node.js Client
To install NCache and its Node.js client, follow these steps:
- Install NCache Server on Multiple Nodes
Run the following commands on each node to set up a distributed NCache cluster:
On Node 1:
1 |
docker run -d --name ncache-node1 -p 8250:8250 -p 9800:9800 alachisoft/ncache |
On Node 2:
1 |
docker run -d --name ncache-node2 -p 8250:8250 -p 9800:9800 alachisoft/ncache |
Once both nodes are running, configure them into a cache cluster using the NCache Management Center or CLI.
- Install NCache Node.js Client
To enable Node.js applications to interact with NCache, install the necessary client packages:
1 |
npm install ncache-client ncache-sessions express-session |
This package provides APIs for efficient session data storage and retrieval.
Step 2: Creating a Clustered Cache
A clustered cache maximizes availability and scalability by distributing cached data across multiple nodes. This enhances both performance and fault tolerance.
To set up a clustered cache:
- Ensure Network Connectivity: All cache nodes must communicate over the designated ports.
- Use NCache Management Center or CLI: Configure a clustered cache instance.
- Add Cache Nodes: Distribute data across multiple nodes.
- Monitor Cluster Health: Use NCache tools to check synchronization and availability.
Step 3: Configure NCache Session Store
Create a configuration file (config.json) with NCache settings:
1 2 3 4 5 6 |
{ "cacheName": "demoCache", "sessionTTL": 30, "sessionTag": "NodeJSSession", "disableTouch": false } |
Step 4: Integrate NCache with Express Session
Modify your server.js file to configure session handling:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
const express = require('express'); const session = require('express-session'); const NCacheSessionStore = require('ncache-sessions'); const app = express(); const cacheName = 'demoCache'; const sessionStore = new NCacheSessionStore({ cacheName }); app.use(session({ store: sessionStore, secret: 'your-secret-key', resave: false, saveUninitialized: true, cookie: { maxAge: 60000 } })); app.get('/', (req, res) => { req.session.views = (req.session.views || 0) + 1; res.send(`Session Views: {req.session.views}`); }); app.listen(3000, () => { console.log('Server running on port 3000'); }); |
Step 5: Run and Verify the Application
Start your application:
1 |
node server.js |
To verify the application, visit http://localhost:3000/ and refresh multiple times to see session persistence.
Step 6: Monitor and Manage Sessions
Session data monitoring and management are essential for optimal performance and identifying potential problems. The NCache Management Center provides a user-friendly interface for monitoring cache clusters, verifying session data, and dynamically managing cache settings.
Using the NCache Management Center
The NCache Management Center allows you to:
- Access the NCache Management Center: Open a browser and navigate to the NCache Management Center.
- Monitor Session Data: View active sessions, expiration times, and cache utilization in real-time.
- Manage Cache Settings: Configure cache properties such as expiration policies and eviction rules.
- View Cluster Health: Verify the synchronization status and confirm all nodes are functioning properly.
- Debugging and Logs: Utilize built-in logging features to track session operations and troubleshoot issues.
Conclusion
Node.js session storage in NCache offers performance, stability, and scalability, which is a better option compared to traditional session storage. With distributed caching, applications can provide smooth user experiences across multiple servers while reducing database load.
Explore NCache’s latest features and start optimizing your Node.js session management today!