Cache — A Cost-Effective Way to Consider When You Implement APIs!

Hanwen Zhang
2 min readAug 17, 2022

--

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 expect 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.

Photo by Tobias Fischer on Unsplash

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.

Dynamic Programming (Caching)

  • Cache stores the function for reusability
  • Cache-Control: instruction of request and response cache;
  • Redis: in-memory data structure store (server), used as a NoSQL key–value persistent database, cache, and message broker.
function memoize(cb) {   //saving data and use it later on
const cache = new Map()
return (...args) => {
const key = JSON.stringify(args)
if (cache.has(key)) return cache.get(key) //check if the cache has the data, if so, return it

const result = cb(...args)
cache.set(key, result)
return result
}
}

Happy coding^^

--

--

Hanwen Zhang

Full-Stack Software Engineer at a Healthcare Tech Company | Document My Coding Journey | Improve My Knowledge | Share Coding Concepts in a Simple Way