How to use cache in NodeJs API
In this tutorial, we will do an introduction to how we can use cache in our NodeJs API. We will use node-cache in this example.
Why cache?
Caching is great when you have e.g a third party API integration that you are calling from your endpoint, or doing some heavy calculation of some sort. When you know that you get multiple requests that should get the same response for the same input, caching is great to speed up the process. Or if you for example know that your data source is updated, like, one time every 5th hour, you might as well just cache the result the first time and let the cache serve the result back instead of calling your data source again and again.
Set up our cache
In this guide, we will set up a simple API, that will serve results from Algobook currency API from the cache if it exists, otherwise, we will call a the API and then store it in the cache so the next request will get the cached result.
Install dependencies
npm i express node-cache axios
Our server.js
Create a file called server.js and add following code
// Import our dependencies const { default: axios } = require("axios"); const express = require("express"); const NodeCache = require("node-cache"); const myCache = new NodeCache({ stdTTL: 3600, checkperiod: 120 }); const app = express(); const getCacheKey = (from, to) => `currency_${from}_${to}`; app.get("/currencyRate", async (req, res) => { const { from, to } = req.query; const cachedRate = myCache.get(getCacheKey(from, to)); // If we found the rate in our cache, we will use the cached value if (cachedRate) { console.log("Serving data from cache"); res.send(cachedRate); } else { // Not in cache, let's go to the source and get it console.log("Serving from the source"); const rate = await axios.get( "https://stocks.algobook.info/api/v1/exchange/rate?from=USD&to=SEK" ); // Setting the value in the cache myCache.set(getCacheKey(from, to), rate.data); res.send(rate.data); } }); app.listen(3500, function () { console.log("Web server listening on port 3500"); });
Notes about the code
- We are setting up a cache that will last 1 hour (3600 seconds) and it will be checked every 120 second by the library
- getCacheKey() function will generate our key that we use in the cache
- We will check if we have the value in our cache, if so, we will serve it from the cache. Otherwise, we will call our API to get the value.
Testing
Let's fire some requests to see what will happen
node server.js
GET localhost:3500/currencyRate?from=USD&to=EUR // Serving from the source 800 ms GET localhost:3500/currencyRate?from=USD&to=EUR // Serving data from cache 3 ms GET localhost:3500/currencyRate?from=USD&to=SEK // Serving from the source 700 ms GET localhost:3500/currencyRate?from=USD&to=SEK // Serving from the cache 5 ms
So, as we can see, our response time is significantly lower when we get it from the source. This can be very effective in a production API, especially when it is used by many consumers.
Outro
That's it for this guide. I hope you found this guide interesting, and that it brung some value to you. Caching is really effective and should be used as much as we can, especially for stale(ish) data.
NOTE if you are using for example a cloud provider that are using multiple instances, the cache will not be shared between them. If your usecase requires a shared cache, consider something like Redis for that. Link to our intro guide for Redis in NodeJs.
All the best,