DEV Community

Cover image for How To Improve the Performance of a Node Js Application Server Side by using simple techniques
Peter Kelvin Torver
Peter Kelvin Torver

Posted on • Updated on • Originally published at codesermon.com

How To Improve the Performance of a Node Js Application Server Side by using simple techniques

You have worked on that awesome looking node.js app but maybe your app experiencing slow performance and you have been thinking of ways to improve the performance of your application. Luckily for you, in this tutorial we’re going to see how we can improve the performance of a node js application by using these ubiquitous techniques.
There are many ways you can improve the performance of your node.js application but in this tutorial, we will be focusing on compression and cache-manager.

Compression

Compression helps by reducing amount of response data from Nodejs application before sending it down to client application for consumption. This greatly improves the performance of application and as a result it takes a shorter time for a client application to receive the response as the amount of the response payload is drastically reduced.
In our Nodejs application, we can easily make use of compression by installing it from npm

npm install compression
Enter fullscreen mode Exit fullscreen mode

and passing it as a middleware to our express app. The compression library supports different compression formats like Gzip, deflate with Gzip being the default.
Example of using compression in our Node.js express app is shown below;

const compression = require("compression");
const express = require("express");
const app = express();
// this will compress all responses
app.use(compression())

Enter fullscreen mode Exit fullscreen mode

Caching

Caching is the process of storing frequently accessed data in a temporary storage. Caching is a great way to improve the performance of an application as temporary cached data can be retrieved quicker which reduces bandwidth and database reads. If an application has higher number of users, there is need to cache data that can be frequently accessed by your users. Caching can be done server side and client side but, in this article, we will be focusing on server-side caching only.
There are many libraries available when it comes to caching under node js such as cache-manager, redis cache, memcacahed, node-cache e.t.c but we will be using cache-manager to implement the server-side caching.

Benefits of using cache-manager

Cache-manager comes with a lot of benefits which include;

  • It includes a wrap function that lets you wrap any function in cache.

  • It features a built-in memory cache (using node-lru-cache), with the standard functions you'd expect in most caches; set, get, mset, mget, del

  • It lets you set up a tiered cache strategy. This may be of limited use in most cases, but imagine a scenario where you expect tons of traffic, and don't want to hit your primary cache (like Redis) for every request. You decide to store the most commonly-requested data in an in-memory cache, perhaps with a very short timeout and/or a small data size limit.

  • It allows you to get and set multiple keys at once for caching store that support it. This means that when getting muliple keys it will go through the different caches starting from the highest priority one (see multi store below) and merge the values it finds at each level.
    Read more about cache-manager here

Basic implementation of cache-manager

In order to implement cache manager, you have to install the package from npm using the command

npm install cache-manager
Enter fullscreen mode Exit fullscreen mode
const cacheManager = require('cache-manager');
const memoryCache = cacheManager.caching({store: 'memory', max: 100, ttl: 10/*seconds*/});
var ttl = 5;
// Note: callback is optional in set() and del().
// Note: memory cache clones values before setting them unless
// shouldCloneBeforeSet is set to false

memoryCache.set('foo', 'bar', {ttl: ttl}, function(err) {
    if (err) { throw err; }

    memoryCache.get('foo', function(err, result) {
        console.log(result);
        // >> 'bar'
        memoryCache.del('foo', function(err) {});
    });
});

function getUser(id, cb) {
    setTimeout(function () {
        console.log("Returning user from slow database.");
        cb(null, {id: id, name: 'Bob'});
    }, 100);
}

var userId = 123;
var key = 'user_' + userId;

// Note: ttl is optional in wrap()
memoryCache.wrap(key, function (cb) {
    getUser(userId, cb);
}, {ttl: ttl}, function (err, user) {
    console.log(user);

    // Second time fetches user from memoryCache
    memoryCache.wrap(key, function (cb) {
        getUser(userId, cb);
    }, function (err, user) {
        console.log(user);
    });
});

// Outputs:
// Returning user from slow database.
// { id: 123, name: 'Bob' }
// { id: 123, name: 'Bob' }
Enter fullscreen mode Exit fullscreen mode

In order to implement our full node.js express API caching system using cache-manager, you can watch the video tutorial below.

In the video below(see at the bottom), I talked about compression and the full implementation of our cache system.

What you will learn;

  • Why it is important to compress our server response
  • How to efficiently implement a cache-system to improving your node.js application performance.
  • How to improve the performance of your node.js application without the need for redis db.

Conclusion

Performance of our software applications greatly determine the user retention of our application as slow performing apps will tend to drive users away. When designing a software application, extra measures like performance optimization should be put in place in order to ensure our applications perform up to expectation.
In this article, you’ve learned how to improve the performance of your node.js application without necessarily paying for high costly services redis db.
Although performance optimization is a broad topic and even on the node.js server-side performance optimization, there are still other factors to take into consideration as this article focused more on compression and caching. So, you can do your research on how to efficiently optimize your node.js application besides these techniques we have demonstrated here.

I run this youtube channel known as TechFortified where I publish amazing tech content. Please don't forget to like, comment, subscribe and turn on notification for more awesome videos like this. Thank you.

Top comments (0)