Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login

You must be logged to download. Click here to login


MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation


MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Optimizing Performance in Express.js

In this tutorial, we shall learn about how one can better the performance of Express.js by optimizing certain areas. While many regular users might be well acquainted with a majority of them, it can still be helpful to know the ones that you mig

When one goes by frameworks for Node.js, it is undoubtedly true that Express.js is surely among the best of frameworks to work with. In fact, one of the biggest advantages of Node.js is that of its highly minimalistic nature and the availability of many plugins. Besides, it also has a fairly simple API, coupled with a large community of developers constantly working on its improvement.

So, when it comes to optimizing Express.js performance, we have tried to approach it in a not so technical way, but rather, in a simple manner that makes it easy to comprehend for most people. Also, if you are a very dedicated Express.js user, you might be familiar with many of the tips that are going to be highlighted here. However, the point is to familiarize yourself with the ones you are not aware of.

Also, before we delve into the tips, we would also take a look at what Express.js actually is.

What is Express.js?

Basically, Express.js is a server framework for Node.js web applications. It belongs to the open source community and is ideally designed to build single/multi-page or hybrid Web-based applications.

It is pretty lightweight and can help you in organizing your application into the MVC architecture on the server-side.

Now, we shall learn some of the tips that can aid in the optimization of Express.js performance. We shall broadly divide this category in to two different aspects as well. One will be the optimization changes that you can make in terms of your code. At the same time, the other set of changes shall deal with changes to be implemented with respect to the environment or setup.

Following image is showing the performance of Express.JS compared to other servers.

Figure 1: Showing performance comparison

To begin, we shall start with techniques that can be applied to the code.

Making use of gZip for compression

The gZip surely happens to be one of those Express.js features that one tends to overlook, despite that fact that it is a really important feature when utilized. This is largely since gZip carries out most of the work in the background, but needs to be set up at first.

What gZip does is compress files that are being transferred from the client to the server, or the other way round. Considering that this really speeds up download and communications times, it is a really handy feature that doesn’t even require your involvement and monitoring.

Also, while Express.js has introduced many new features that are capable of pulling of the same thing as gZip, the latter is still the more popular option because it is supported by more browsers at present. Implementing gZip is also fairly simple in the sense that it only requires the coder to insert the right code at the start of a function, which then applies the features to the gZip function, whenever there is a request from the server or client to download the specific file.

Listing 1: Showing compression

var compression = require('compression');
var express = require('express');
var application = express();

Do not make use of synchronous functions

Functions and methods that are synchronous in nature tend to tie up the entire process that is in execution, until they return. A single call made to a synchronous function usually returns within a few milliseconds or even microseconds. However, the problem lies with the bigger picture.

When we take high-traffic websites into consideration, these calls add up on the whole, taking up a chunk of time, thereby leading to a reduction in the performance of the application. Thus, it is good to avoid their usage in production. While Node.js and many other modules offer both, synchronous and asynchronous versions for all their functions, make sure you are always using asynchronous functions in production. One occasion where the use of synchronous functions may be justified is at the initial startup alone.

Increase the maximum sockets

The HTTP server of Express.js, by default, is known to have an upper limit on the number of sockets, which stands at five. And, this is considered to be pretty restrained approach, as servers are capable of handling plenty more. In fact, the number of sockets depends on the hardware that is in play, and in certain cases, they can even be kept as infinite. But, as usual, you might also want to keep a certain check on this and not overburden the server.

Correct usage of logging

Usually, there are basically two reasons developers tend to log their applications. One of them is debugging and the other is to monitor activity. In development, the common practice is to make use of console.log () or the console.err () functions. However, these functions are synchronous in nature when the destination happens to be a file or a terminal, so they are not really good for production, unless the output is piped to another program.

  • For debugging

If the reason why you log is debugging, then rather than opting for the use of console.log (), you could do with a special module like debug. This module specifically allows you to DEBUG environment variable in order to control the debug messages that are sent to console.err (). Also, to keep your application completely asynchronous, you will need to pipe the console.err () into another program.

  • For application activity

If you are logging so that you can monitor application activity, such as API calls or traffic, you can utilize a logging library such as Winston or Bunyan. This can be a viable alternative to using console.log ().

Handling exceptions properly

Node.js apps are known to crash whenever they encounter an exception that has remained uncaught. Thus, not handling your exceptions and then not taking proper steps to counter them will crash your Express.js applications and make them go offline. Fortunately, Express.js allows for ways that can ensure the automatic restart of your application after a crash. Also, the startup time often tends to be relatively short as well. However, it is still advisable to prevent it from crashing in the first place, for which, you will need to handle exceptions properly. And, in order to do so correctly, make use of –

  • Try-catch
  • Promises.

Following example is showing the use of try-catch block

Listing 2: Showing try-catch example

app.get('/search', function (req, res) {
  setImmediate(function () {
    var jsonString = req.query.params;
    try {
      var jsonObject = JSON.parse(jsonString);
    } catch (e) {
      res.status(400).send('JSON string not valid');

Listing 3: Showing example of promises

 app.get('/', function (req, res, next) {
    .then(function (data_input) {
      // manage data
      return makeCsvFile(data_input)
    .then(function (csv) {
      // manage csv
app.use(function (err, req, res, next) {
  // manage error

Using Uglify

When it comes to web design topics, there is often a lot of stress between static design elements that look particularly good and also require quite the processing power to host them. Especially, when you are dealing with websites that make use of plenty of stylistic elements, it is often understood that such a website likely looks good at the cost of overall performance.

However, this need not be true all the same. There are several services, such as Uglify (not literally!), that can help tackle the issue. What Uglify tends to do is speed up sites that by minifying elements that aren’t in use, like say elements that aren’t on the screen at an instant. This can largely improve the performance aspects of several websites, especially ones that are rather dense.

Reduction in middleware

Middleware is often a part of several programs. Keeping in tandem, Express.js also makes use of several superstructures of client-server hierarchies in order to communicate. As such, it is often pretty easy to start using and relying on middleware, even in situation when you really don’t require them. And, as has already been mentioned with plenty of these optimization tips already, overusing anything can lead to a decline in performance in memory.

However, the process to disable to middleware packages is rather easy. So, if you find yourself as someone who is into using such kind of packages more often than not, you can always do back and curb the habit.

Now, there are also some changes that can be implemented in terms of the environment, as already mentioned above, that can aid in the optimization process of an Express.js application. We shall now take a look at some of these techniques.

Cache control

The entire idea behind caching is that it saves the user a whole lot of time whenever they tend to use objects that are used very frequently. Cached objects can be downloaded and stored from beforehand, so that they happen to be easily accessible when someone needs to use them. Also, when an object needs to be downloaded pretty much every time, caching can be a viable alternative solution as it not only saves bandwidth, but also increases the processing power.

However, there is also a certain something that you need to be wary of when caching. It is not always right to cache too many things, as caching is all about occupying memory. Therefore, it is up to you to decide what you cache and what you cannot. A number of analytic services available out there can help you decide on that, by providing statics on the objects that are most used.

Production mode

This is probably one of those aspects that are more often overlooked than not. Express.js, by default, is known to run on development mode, which happens to be the standard view when running the framework. However, it also does have a production mode that can bear usefulness in plenty of situations.

In general, the difference between production and development modes has much to do with caching. In the latter option, everything is loaded from request to request and file to file. However, in the production mode, loaded files are cached so that reusing them later becomes a whole lot easier. This further means that making any kind of changes to the server is easier, as a server reboot or anything about the likes of it, is not required. Also, overusing production mode by caching too many files is something you would like to avoid, as it eats away a large chunk of your memory.

Ensuring automatic restart of applications

When in production, you would not like your application to ever be offline. And, in order to do that, you will also need to make sure that your application restarts, whether it is an app crash or a server crash. Although, you will always hope that such an occurrence does not take place, you will still need to be prepared for handling such a situation. To do so, you need to –

Use a process manager that can restart the application or Node.js when it crashes. Some of the most popular process managers to use are PM2, Forever, and StrongLoop Process Manager.

Making use of the init system that is provided by your OS, in order to restart the process manager on the crashing of the OS. You can also use just the init system without making use of the process manager.

Node.js applications crash on encountering uncaught exceptions, so the first step is to test you application well and ensure that it is capable of handling all exceptions. But still, putting a mechanism that automatically restarts the application is something of a good practice.

Running the application in a cluster

You can increase the performance of your Express.js application in a multi-core system by launching a cluster of processes. A cluster basically runs several instances of one single application, usually one instance in each core of the CPU, which distributes the overall task among many instances and sharing the load.

Using a load balancer

A single instance can only handle a limited amount of traffic and load, despite all the optimization techniques that may have been implemented. Using a load balancer allows you to scale an app and run multiple instances of it. This leads to an overall increase in performance and speed.

Following is a typical Express.JS server architecture. The database and clients can be different based on the application requirement.

Figure 2: Showing server architecture


Considering that Express.js offers numerous apps and tools that can help you in the optimization process of your app, one of the key things to remember is to stick to two basic principles – moderation and temperance. The first always is to finding out exactly what your application and server requires. This can then help you in creating Express.js applications that not only boast of having good looks, but also function very well.

Hopefully, this article has equipped you with tips and tricks that can help you the implementation of optimization techniques in your future development work.

Website: Have 16 years of experience as a technical architect and software consultant in enterprise application and product development. Have interest in new technology and innovation area along with technical...

What did you think of this post?
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!

> More info about MrBool Credits
You must be logged to download.

Click here to login