Cache — A Cost-Effective Way to Consider When You Implement APIs!
Use cache to lower your cost when you use third-party APIs.
Do you want to pay for SaaS service whenever a user requests an API call (think of how many users you will be expected on a daily basis)? The answer is NO!!! Not only it will increase your bill, but also it may slow the product when users have to make API calls.
The solution is simple — cache! Store the response to your database, and check your database before you make the API call, if the result is already stored in the database, then you can just return the result from your database instead of making the API call; but if the result is not yet stored in the database, we can just store the response to the database in order to use when a user needs to get the data next time.
There are popular caching services like Redis, Memcached, etc.
Below, I am using MongoDB as a database example to store the cache.
const collection = client.db("database").collection("collection");
const result = await collection.findOne({ id: ID });if (result) {
// console.log("Cache found, return from cache, no needs for API");
return res.json(result);
} else {
// console.log("Cache not found, we are making the API call");
const result = await axios(config).then(function (response) {
return response.data.result;
}).catch(function (error) {
console.log(error);
});
if (result) {
// console.log("Creating new cache");
collection.insertOne({
result: result ? result : {},
});
// console.log("return the result from API");
res.json({
result: result ? result : {},
});
}
}
At the end of the day, how much you spend is an important factor in the revenue of the product you are building.
Happy coding^^