Speed is what all web/mobile apps need. And with growing database size, the speed is the first thing that takes a hit. Comes cache to rescue.
A cache can be defined as storing data in RAM for quick access (faster than getting data from DB), also we can store the results for regular calculations in the cache to save time on recalculation again and again.
There are various types of available caches, you can research that for a more detailed understanding. We will not cover that in the scope of this article.
How to implement cache
Implementing a cache is more or less a kind of art, depending on your requirements and available methodologies. What I prefer is using Redis for cache. It's easy to use, fast and reliable.
Installation
npm install redis
Usage
const { createClient } = require("redis")
const cacheing = async () => {
let redisConfig = {
host: "localhost",
port: 6379,
username: "",
password: "",
database: 0
}
const client = createClient(redisConfig)
client.on("error", (err) => console.log("Redis Client Error", err))
await client.connect()
// setting cache
await client.set("key", "string_value")
// getting cache
const value = await client.get("key");
//If the key does not exist, the value will be null
}
OR
or you can use Framework X (AKA Fx). Which comes with a supper charges cache in build. Fx cache not only caches your data but also updates the cached data in a given duration so that your cache never goes out of new data, checking when the given data was accessed. AND all this with an implementation time of less than a min.
To Know about how to get started with Fx, please follow this link.
Once up and running, you can use the cache as follows.
const { setCache, getCache } = require("@3rdplanet/x-core/cache")
exports.index = async (req, res) => {
let responseData = await getCache(req.url)
if (responseData) {
return res.send(successResponse("cache found...", responseData.response))
}
let someCalculationAnswer = someCalculations(1, 1, 1)
setCache(req.url, someCalculationAnswer, {
function: someCalculations,
params: [1, 1, 1]
}).then(() => {})
return res.send(successResponse("cache in progress...", someCalculationAnswer))
}
Also, you will need to add the following keys in your .env file.
- CACHE_UPDATE_INTERVAL - The interval in seconds to update the cache. The default is 10 seconds.
- CACHE_EXPIRE_TIME - The time in seconds to expire the cache. The default is 60 seconds.
You can learn more about Fx cache here.
Feel free to ask questions in the comments if you have any sort of doubts or queries.
Top comments (0)