Express.js Redis Caching
A cache is a fast storage area that holds copies of data the app needs often. Redis is an in-memory data store, which means it keeps data in RAM instead of on a disk. RAM answers in a fraction of a millisecond. An Express app that caches slow database results with Redis responds faster and puts less load on the database.
The Notebook Analogy
A student solves a hard math problem and writes the answer in a notebook. When the same question returns, the student reads the notebook instead of solving it again. The notebook is the cache. Solving the problem is the slow database query. Reading the notebook is the cache hit.
Cache Flow Diagram
Request GET /products
|
v
Check Redis for key "products"
|
+----+----+
| |
Found Missing
(hit) (miss)
| |
| v
| Query database
| |
| v
| Save result in Redis (60 seconds)
| |
v v
Send response to client
Key Terms
- Cache hit: Redis holds the data and returns it at once.
- Cache miss: Redis lacks the data, so the app queries the database.
- TTL: Time To Live. The number of seconds before Redis deletes the entry.
- Invalidation: removing stale cache entries after the source data changes.
Set Up Redis
Run Redis on a local machine, in a Docker container, or on a hosted service. Install the Node client in the project.
npm install redisConnect the Client
// config/redis.js
const { createClient } = require('redis');
const client = createClient({ url: process.env.REDIS_URL });
client.on('error', (err) => console.error('Redis error', err));
client.connect().then(() => console.log('Redis connected'));
module.exports = client;Cache a Route Response
The route below checks Redis first. A miss triggers the database call, and the result goes into Redis for 60 seconds.
const express = require('express');
const redis = require('./config/redis');
const Product = require('./models/productModel');
const app = express();
app.get('/products', async (req, res) => {
const key = 'products:all';
const cached = await redis.get(key);
if (cached) {
return res.json({ source: 'cache', data: JSON.parse(cached) });
}
const products = await Product.find();
await redis.set(key, JSON.stringify(products), { EX: 60 });
res.json({ source: 'database', data: products });
});Redis stores strings, so the code converts objects with JSON.stringify and JSON.parse. The EX option sets the TTL in seconds.
Build a Reusable Cache Middleware
A middleware function adds caching to any route without repeating code.
function cacheFor(seconds) {
return async (req, res, next) => {
const key = 'route:' + req.originalUrl;
const cached = await redis.get(key);
if (cached) {
return res.json(JSON.parse(cached));
}
const originalJson = res.json.bind(res);
res.json = (body) => {
redis.set(key, JSON.stringify(body), { EX: seconds });
return originalJson(body);
};
next();
};
}
app.get('/products', cacheFor(60), async (req, res) => {
res.json(await Product.find());
});The middleware wraps res.json. The wrapper saves each fresh reply in Redis before sending it.
Invalidate After Changes
A cache that never updates shows old data. Delete the related keys whenever data changes.
app.post('/products', async (req, res) => {
const product = await Product.create(req.body);
await redis.del('products:all');
res.status(201).json(product);
});Choose a TTL
| Data Type | Suggested TTL |
|---|---|
| Product catalog | 5 to 10 minutes |
| Trending posts | 30 to 60 seconds |
| Country or city lists | 24 hours |
| User balance or stock levels | Do not cache, or use a few seconds |
Best Practices
- Cache data that many users read and few users change.
- Name keys with a pattern such as users:42:profile.
- Set a TTL on every entry so memory never fills up.
- Keep private data, such as one user's orders, under keys unique to that user.
- Let the app work when Redis is down by falling back to the database.
Measure response times before and after caching. The numbers show whether the added setup pays off.
