Caching in JavaScript (Node.js): Redis and Others
Caching is one of the key tools for improving the performance of web applications on Node.js. It helps reduce server response time, decrease the load on databases and external APIs, and improve the user experience. In this article, we will look at popular libraries and approaches to caching: from built-in solutions to the powerful Redis.
Why is caching needed in Node.js?
Without caching, each request to the server can lead to repeated computations, database queries, or calls to external services. This increases response time and resource consumption. A cache stores frequently requested data in fast storage (RAM or in-memory database), which allows you to:
- Speed up responses — reading from memory is 100-1000 times faster than from disk.
- Reduce load — the database processes fewer requests.
- Save budget — fewer resources on cloud services.
1. Redis — Industry Standard
Redis is a high-performance in-memory data store that supports data structures (strings, hashes, lists, sets). For Node.js, the redis or ioredis package is used.
Installation and Connection
npm install redisconst redis = require('redis');const client = redis.createClient({ url: 'redis://localhost:6379'});
client.on('error', (err) => console.error('Redis Client Error', err));client.connect();Basic Operations
// Write with TTL (time-to-live)await client.setEx('user:123', 3600, JSON.stringify({name: 'Alice', role: 'admin'}));
// Readconst cached = await client.get('user:123');if (cached) { console.log('From cache:', JSON.parse(cached));} else { // query to DB}Advanced Features
- Pattern-based invalidation — deleting all keys with the prefix
user:*. - Pub/Sub — notifications about cache changes between instances.
- Redis Cluster — horizontal scaling.
2. node-cache — In-Memory Cache Without External Dependencies
For small projects or prototypes, the node-cache library is suitable. It works within a single Node.js process and does not require installing Redis.
Installation
npm install node-cacheUsage Example
const NodeCache = require('node-cache');const myCache = new NodeCache({ stdTTL: 600, checkperiod: 120 });
// Save datamyCache.set('posts:recent', postsData, 3600);
// Readconst cached = myCache.get('posts:recent');if (cached) { return cached;} else { const fresh = await fetchPostsFromDB(); myCache.set('posts:recent', fresh); return fresh;}Features
- Simple TTL (time-to-live) configuration.
- Automatic cleanup of expired entries.
- Not suitable for distributed systems (data lives only in one process).
3. memory-cache — Lightweight Alternative
memory-cache is another simple in-memory cache for Node.js. It features a minimalistic API.
const cache = require('memory-cache');
// Writecache.put('api:weather', weatherData, 300000); // 5 minutes
// Readconst data = cache.get('api:weather');if (!data) { // re-request}4. Caching Strategies
The choice of strategy depends on the data type and requirements for freshness:
- Cache-Aside (Lazy Loading) — the application first checks the cache, on a miss it loads the data and saves it to the cache. The most popular approach.
- Write-Through — data is written