Wouter Van Respaille

Freelance Fullstack Javascript Developer


Optimise your node.js api with these tips.
  • Written by Wouter Van Respaille
  • February 10th, 2015
  • About Javascript

Optimise your node.js api with these tips.

While building your API in node.js there are possibilities that somehow you API is running slow. There are some ways to make it faster.

  1. Compress your resource endpoints. This is something very important you should definitely consider using.

    In Express 3.0 you can use:

    app.use(express.compress());

    In Express 4.0 you can install this compression module which makes use of gzip and deflate. So, what is gzip? Whenever a browser requests a file from a server and this browser supports gzip it can send “Accept-Encoding: gzip” in the header. If your server does not have any compression enabled it will just send the full size file. But when your server uses compression, like the example above, it will send a compressed file back to the browser which the browser can decompress and use. This will reduce the size of your data packages by more than 70%:

    var compression = require(‘compression’); var app = express(); app.use(compression());

    There are a lot more options you can explore in the compression module. The bigger the compression, the slower the response. Try to find the best options for your use case.

  2. Use paging when requesting a lot of data. You can add params and make sure there’s a maximum page size.

    GET /users?page=1&limit=10

  3. Avoid blocking. Blocking only slows the process down. You should only use synchronous calls for one time requests like when you start your server.

  4. Use CDN’s for static assets serving like cloudflare’s amazon.

  5. Load balance your load across multiple CPU’s. If your server has multiple CPU’s it would be best to spread the load across all of them. You can use node’s cluster module for this or you can use a process manager like pm2 where you can enable clustering with one simple command.

    pm2 start app.js -i max

  6. If you’re uploading huge files you should stream these processes, so the user agents can start processing it as soon as possible.

  7. Index any keys that are used often. Like for filtering and search.

There are still hundred of ways to optimise your web server. Each of the ones I mentioned you can explore and optimise.

Freelance Javascript Product Developer
Hey There!
What is This?

Got a project or just want to talk? hi@woutervanrespaille.be

Copyright Wouter Van Respaille. All Rights Reserved.