Caching in JavaScript (Node.js): Redis and Other Tools
Caching is one of the most effective ways to improve the performance of web applications on Node.js. It reduces response time, lowers the load on databases, and decreases infrastructure costs. In this article, we will cover the main caching tools in the Node.js environment: Redis, Memcached, and built-in in-memory caching. You will learn when to choose which tool and see working code examples.
Why is caching needed in Node.js?
Node.js is single-threaded but asynchronous. Every request to a database or external API involves waiting (I/O). A cache allows you to store the result of an expensive operation (e.g., a complex SQL query or HTML parsing) and serve it instantly. Main use cases:
- Storing database query results (especially aggregating ones)
- Caching external API responses (weather, exchange rates)
- Storing user sessions
- Temporary storage of computed data (e.g., template rendering)
1. Redis — The King of Caching
Redis is an in-memory data store often used as a cache. It runs in a separate process, supports complex data structures (strings, hashes, lists, sets), and has built-in TTL (time-to-live) mechanisms.
Installation and Connection
To work with it, you need a running Redis server (locally or in Docker). In Node.js, use the redis package:
npm install redisExample: Caching Data with TTL
const redis = require('redis');const client = redis.createClient();
client.on('error', (err) => console.error('Redis error:', err));
// Async function to get data with cachingasync function getCachedData(key, fetchFunction, ttlSeconds = 60) { // Try to get from cache const cached = await client.get(key); if (cached) { return JSON.parse(cached); }
// If not, call the expensive function const freshData = await fetchFunction();
// Save to cache with TTL await client.setEx(key, ttlSeconds, JSON.stringify(freshData)); return freshData;}
// Usage: cache the result of a database queryconst users = await getCachedData('users:list', () => db.query('SELECT * FROM users'), 120);Advantages of Redis
- High performance (millions of operations per second)
- Support for TTL, pub/sub, transactions
- Persistence (can save to disk)
- Suitable for distributed systems (multiple Node.js servers)
Disadvantages
- Requires a separate server/container
- Consumes RAM
- Overkill for simple single-threaded applications
2. Memcached — Lightweight and Fast
Memcached is another popular in-memory cache, but simpler than Redis: only strings, no persistence, no complex structures. Ideal for simple data caching.
Installation and Example
npm install memcachedconst Memcached = require('memcached');const memcached = new Memcached('localhost:11211');
async function getCachedData(key, fetchFunction, ttlSeconds = 60) { return new Promise((resolve, reject) => { memcached.get(key, async (err, data) => { if (data) return resolve(JSON.parse(data));
const freshData = await fetchFunction(); memcached.set(key, JSON.stringify(freshData), ttlSeconds, (err) => { if (err) reject(err); resolve(freshData); }); }); });}When to use Memcached?
- Only a simple key-value cache is needed
- No data persistence required after restart
- Resources are limited (Memcached is lighter than Redis)