As applications grow, the database often becomes the primary bottleneck. Every time a user requests data, your backend queries the database, which can be slow and expensive. This is where Redis comes in.
What is Redis?
Redis (Remote Dictionary Server) is an open-source, in-memory data structure store. Because it stores data in RAM rather than on a physical disk, it can retrieve information in sub-millisecond speeds.
Why Caching Matters
Imagine a weather app. If 10,000 people in the same city check the weather, the data is exactly the same for all of them. Why query the database 10,000 times? Instead, you query it once, store the result in Redis, and serve it instantly to the next 9,999 users.
- Check if the data is in Redis (Cache Hit).
- If yes, return it immediately.
- If no (Cache Miss), query the main database.
- Store that query result in Redis for the next time.
Implementation Example
Using the redis library in Node.js, we can create a simple caching middleware:
const redis = require('redis');
const client = redis.createClient();
async function getCachedData(req, res, next) {
const { id } = req.params;
const data = await client.get(id);
if (data !== null) {
return res.json(JSON.parse(data)); // Return from cache
} else {
next(); // Move to database query
}
}
Cache Expiration (TTL)
Data shouldn't stay in the cache forever (or it becomes "stale"). Using Time-To-Live (TTL), we can tell Redis to delete a key after a certain amount of time, ensuring users eventually get updated information.
Conclusion
Redis isn't just for caching—it can handle session management, real-time leaderboards, and message queues. For any Node.js developer looking to build "production-grade" systems, mastering Redis is the next logical step.