Caching in JavaScript (Node.js): Redis and Other Tools
Caching is one of the key strategies for optimizing the performance of server-side applications in Node.js. It allows you to reduce the load on databases, decrease API response time, and cut infrastructure costs. In this article, we will cover the main caching tools for Node.js: Redis, Node-Cache (a built-in library), and Memcached, compare their approaches, and show real code examples.
Why is caching needed in Node.js?
Without a cache, every request to a popular resource can lead to multiple calls to the database or external APIs. A cache stores frequently requested data in fast storage (RAM), which provides:
- Reduced response time (latency) from 100-500 ms to 1-5 ms.
- Fewer requests to the database and external services.
- Increased server throughput (RPS).
1. Redis — The King of Caching
Redis is an in-memory key-value data store, often used as a cache, message broker, and database. In Node.js, the redis library (or ioredis) is used to work with Redis.
Installation and Connection
npm install redisconst redis = require('redis');const client = redis.createClient({ url: 'redis://localhost:6379'});
client.on('error', (err) => console.error('Redis Error:', err));await client.connect();
// Example of caching data with TTLasync function getCachedData(key) { const cached = await client.get(key); if (cached) return JSON.parse(cached);
const freshData = { message: 'Hello from DB', time: Date.now() }; await client.setEx(key, 60, JSON.stringify(freshData)); // TTL 60 sec return freshData;}Redis Features for Node.js
- TTL Support — automatic deletion of expired entries.
- Data Structures — strings, lists, sets, hashes, sorted sets.
- Pub/Sub — enables building real-time notification systems.
- Clustering — horizontal scaling without performance loss.
2. Node-Cache — Lightweight In-Memory Cache Without External Dependencies
Node-Cache is a simple library for caching data directly in the memory of a Node.js process. It is ideal for small projects, microservices, or when you don't want to set up Redis.
Installation and Example
npm install node-cacheconst NodeCache = require('node-cache');const myCache = new NodeCache({ stdTTL: 100, checkperiod: 120 });
// Save datamyCache.set('user:123', { name: 'Alice', role: 'admin' });
// Retrieve dataconst user = myCache.get('user:123');if (user === undefined) { // data not in cache — need to load from DB console.log('Cache miss');} else { console.log('Cache hit:', user);}
// Delete by keymyCache.del('user:123');
// Clear entire cachemyCache.flushAll();Pros and Cons of Node-Cache
- Pros: no external server required, simple API, automatic TTL cleanup.
- Cons: cache is stored only in one process — data is lost on server restart; cannot be used between multiple Node.js instances.
3. Memcached — Distributed Cache with Minimal Overhead
Memcached is another popular in-memory store optimized for caching. In Node.js, the memcached library is most commonly used.
Installation and Example
npm install memcachedconst Memcached = require('memcached');const memcac Also in library
OpenAI SDK for JavaScript (Node.js): Complete Guide with Examples
PHP Application Monitoring: A Complete Guide to Tools and Libraries
Swagger/OpenAPI Generation for Rust: Utoipa and Aide
PDF Generation in JavaScript (Node.js): Libraries and Tools for Creating PDF