Optimizing API Performance with NodeCache in Node.js

 

Introduction : 

Efficient API response time is crucial for any web application. One way to achieve this is by implementing caching. In this blog, we'll explore how NodeCache can be used in a Node.js project to improve performance by reducing redundant API calls

What is Caching?

Caching stores frequently accessed data in memory, allowing for quicker retrieval. Instead of fetching data repeatedly from an external API or database, the system first checks if the required data is already available in cache

Why Use NodeCache?

  • Improves response time by avoiding repeated API calls

  • Reduces API rate limits and dependency on external services

  • Enhances scalability by lowering server load





                                       fig1: CACHING IN NODE.JS
                                                         

How to Implement NodeCache in Node.js

Step 1: Install NodeCache

   npm install node-cache

Step 2: Import and Configure NodeCache

  • const NodeCache = require("node-cache");
  • const cache = new NodeCache({ stdTTL: 60, checkperiod: 120 });
  • stdTTL: Standard time-to-live (TTL) in seconds

  • checkperiod: Interval to remove expired cache data

Node-cache has following major functions


  • .set(key, val, [ ttl ]): Used to set some value corresponding to a particular key in the cache. This same key must be used to retrieve this value.
  • .get(key):Used to get value set to specified key. It returns undefined, if the key is not already present.
  • has(key): Used to check if the cache already has some value set for specified key. Returns true if present otherwise false.

Working of node-cache 

first request 

                                      


Whenever a request (GET/products) is made, it will check whether data is available in the cache to that specified key (products) using has (key) method. If it is not available, it will fetch data from the fake API database and store it in the cache using the set (key, value) method.

Second Request

                     
                                        


From the next request onwards, it will check whether data is available in the cache to that specified key(products) using has (key) method. If it's available, it will get the data from the cache directly using the get (key) method.

Conclusion

Using NodeCache improves performance, reduces API load, and enhances user experience. By integrating caching, we ensure optimal API usage and avoid unnecessary requests.



Recommended Articles 

  1. https://infinijith.com/blog/nodejs/node-cache
  2.    Advantages of using microservices in Nodejs
  3. Optimizing app performance with Nodejs cluster


                                

Comments

Popular posts from this blog

What Is a Proxy? A Simple Explanation for Beginners

How to Implement API Rate Limiting in a NodeJS Express Application