DEV Community

Srinivas Kandukuri
Srinivas Kandukuri

Posted on

Node, Express - REST API Performance test With & without Redis cache

As per the official Redis site

"Redis is an open source (BSD licensed), in-memory data structure store, used as a database, cache and message broker".

For more info please go through link Redis

Now we are building sample REST API, testing with and without Redis integration.

CODE BASE GITHUB LINK redisCache_nodejs_express_API

Files/Folder Structure.

Redis

We are using Some external data-source(API) for testing purpose.

Snippet


function cacheMid(req,res,next){
    var api = req.path;
    client.get(api, function(err, data){
        if (data != null) {
            console.log("from Cache");
            res.send(JSON.parse(data));
        } else {
            next();
        }
    })
}

function getAPI(req,res){
   axios.get('http://datasource.kapsarc.org/api/datasets/1.0/search/?rows=500')
    .then(function (response) {
        var api = req.path;
        var dataset = response.data;
        client.setex(api, 50, JSON.stringify(dataset));
        console.log("from API");
        res.send(response.data);
    })
    .catch(function (error) {
      console.log(error);
    });
}

// Router
app.get('/getAPI',cacheMid, getAPI);

Enter fullscreen mode Exit fullscreen mode

When we call /getAPI in postman then cacheMid middleware get called and check for mapped key, here it is 'req.path' is the key
if the there is any data with key in redis database then it will return data, otherwise it will got to else block & call the external API, get the json data, then we are setting into redis database.

Performance API TEST

localhost:4000/getAPI

image

Top comments (3)

Collapse
 
aigoncharov profile image
Andrey Goncharov

Good idea to benchmark Redis as a cache for NodeJS! However, the results of this one might be a little off. As you can see, the second call returned 304 status, which means you hit a browser cache. That's why size is that small.

developer.mozilla.org/en-US/docs/W...

Collapse
 
c4r4x35 profile image
Srinivas Kandukuri

Good catch, i did't observe the response code, but while testing i was trying to hit same API in diff scenarios. I observed lot of time diff.

Collapse
 
devatsrs profile image
Deven Sitapara

What happened when any of data updates in db?