Making My Node.js API Super Fast

Rate this content
Bookmark

Node.js servers need to process a large number of requests concurrently as the scale grows.  A Node.js micro service which receives an API request needs to do multiple actions, like parsing JWTs, use caching, work with the databases and more. In this talk, Tamar will show strategies to improve your REST API performance - starting from new Node.js frameworks that can work faster, better parsing of request parts, efficient work with caching and DB , better parallelism and more strategies. The talk will include demos, benchmarks and profiling of code to see the improvements. At the end of this talk, developers will have practical knowledge on how to improve API performance in various Node.js platforms.

This talk has been presented at Node Congress 2024, check out the latest edition of this Tech Conference.

FAQ

The speaker's name is Tamar. They are passionate about JavaScript and Node.js, which started from founding their own startup and writing the entire backend in Node.js.

The key areas to focus on include database optimization, efficient serialization and deserialization of JSON, logging, web framework selection, and caching.

Optimizing database queries is crucial because efficient queries and indexes enable fast data fetching and operations, which significantly improve the overall performance of the API.

Using the Native Mongo Driver generally results in better performance compared to Mongoose. Benchmarks showed that the Native Mongo Driver handled more requests per second and had lower latency, while Mongoose added overhead due to serialization and abstraction.

Connection pooling improves database performance by maintaining a pool of connections that can be reused for multiple requests. This reduces the overhead of establishing connections repeatedly and leads to better throughput and lower latency.

JSON serialization and deserialization are synchronous operations that can block the event loop, leading to performance bottlenecks. Using more efficient libraries like FastJSONStringify can improve performance by reducing the time spent in these operations.

Logging can cause performance degradation, as it adds overhead to the application. It's important to use performance-efficient log libraries like PinoJS and avoid unnecessary string concatenation in logging statements.

Fastify is recommended for better performance compared to older frameworks like Express. Benchmarks showed that Fastify handles more requests per second with lower latency.

Caching improves performance by reducing the need for repeated computations or database queries. It can be particularly effective for tasks like JWT authentication. Using distributed caching solutions like Redis is recommended over in-memory caching.

Common performance optimization tips include using asynchronous operations, running tasks in parallel, optimizing connection pools, choosing efficient web frameworks, and using caching for frequently accessed data.

Tamar Twena-Stern
Tamar Twena-Stern
34 min
04 Apr, 2024

Comments

Sign in or register to post your comment.

Video Summary and Transcription

This talk focuses on improving performance in Node.js API development. It covers various areas such as optimizing database work, connection pool, JSON parsing, logging, and web framework selection. Key highlights include the use of Native Mongo Driver for better database performance, optimizing connection pool for improved throughput, replacing Express serializer for faster serialization and deserialization, and choosing Festify as an efficient web framework. Caching and authentication's impact on performance is discussed, along with recommendations for caching types. The talk also emphasizes considering environmental factors and human impact on performance. Fastify is highlighted as a recommended tool for Node.js performance optimization.

1. Introduction to Performance Optimization

Short description:

Hi everyone, welcome to my session about improving performance in your Node.js API. I'm passionate about JavaScript and Node.js. Today we'll discuss improving performance in your API layer, covering areas such as database, serialization, deserialization, logging, web frameworks, and caching. Let's start with database work. Optimize DB queries, use efficient indexes, denormalize data, and consider solutions like read-write replicas and sharding.

Hi everyone, happy to be here and welcome to my session about how to improve performance in your Node.js API and make it really fast. So before starting to talk about technical stuff, let me introduce myself. My name is Tamar. You can follow me on those links and contact me on those links. I'm really passionate about JavaScript and Node.js and my interest in those technologies started when I founded a startup of my own and I wrote the entire backend in Node.js and from there the rest is history.

And enough talking about myself, let's start talking about performance, which is one of my favorite things that I like to talk about. And today we are going to talk about how we're going to improve performance in your API layer. And we're going to revise, we're going to look at those areas, we're going to look at database. We're going to look at serialization and deserialization of your Jasons. We're going to talk about logging. It looks trivial to you, but that can impact your performance. The web framework that you choose and caching.

So let's start with database work. First of all, before we go into JavaScript related stuff, there are some things that you need to keep in mind for every technology that you work with, for every programming language. First of all, of course your DB queries have to be optimized. All of the indexes have to be very efficient and enable really fast fetching and efficient operations. And then you need to denormalize your data. What does it mean? If you have a table of 50 columns and you only need three, don't fetch the entire 50. Fetch only what you need, for example. And save the data in a way which is efficient. Don't save inefficient things. And then you need to think about solutions in the DB layer. That can be read-write replicas that can improve your performance. Working with a replica set, matching the DBs that support that, and sharding.

2. Improving Node.js Application Database Work

Short description:

Let's discuss improving Node.js application-related database work by comparing Mongoose and Native Mongo Driver. Key measurements for performance benchmarking include latency (looking at the 99th percentile), and throughput (average requests per second and total requests). In the benchmark, both Mongoose and Native Mongo Driver were used to post a person object to the database. The results showed that Native Mongo Driver performed significantly better than Mongoose, with an increase in average requests per second and a much smaller 99th percentile.

But we are in a Node.js conference, and after talking a little bit about generic tips, let's go into Node.js stuff. How can I improve my Node.js application-related database work? When we are starting to work with Node.js, we are starting to work with the first tutorial that we are all doing, Node.js, express and Mongoose. Let's start with that, and let's take a benchmark and see how that is going to perform. When we are going to do a benchmark, we have to keep in mind the following things. First of all, the measurements that are the most important is the latency. You need to look at the 99th percentile, not the average. Because when you are telling you have a contract with a third party, and you are telling them all of my requests are faster than this, you need to give them the 99th percentile in the latency. Not the median, not the average. That is really important. Second, measuring throughput. For measuring throughput, we have two important things that we need to look at. First is the average request per second, and then the total request. Those measurements will give you a good idea about how your throughput is improving.

Now we are going to compare Mongoose and Native Mongo Driver. I wrote a server that works with Mongoose, and that server exposed one post request, that is posting a person object, something really simple. The code is not something really interesting. We are building a server with Express and Mongoose, building a Mongoose schema of several parameters, and then that is the function that we are going to measure. Post, and then we are creating a new person object, and saving it as you can see here. The Native Mongo Driver code is going to do exactly the same. A post request, which also is posting a person object, and that is because we want to compare apples to apples. When we are doing performance benchmark, we want to compare things that are doing the same. Here is the code that is running with the Native Mongo Driver. As you can see, this is also doing insert1 into the database.

Cool. Those are the results that we have with Mongoose. You can see if we are going to look at average requests per second, we are around 5700 requests, and the total request is around 64,000, and the 99th percentile is 4 millisecond, but as we are using Mongo Driver, we can see that things improved hugely. We can see that the average requests per second went up to 9500, which is a lot. It's more than 30%, I think. The 99th percentile is much smaller, by 50%, and we were able to serve, in the time of the benchmark, around 30,000% more requests. As you can see, if we are going to see it in a graph, Native Mongo Driver performs much better than Mongoose.

QnA

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

It's a Jungle Out There: What's Really Going on Inside Your Node_Modules Folder
Node Congress 2022Node Congress 2022
26 min
It's a Jungle Out There: What's Really Going on Inside Your Node_Modules Folder
Top Content
The talk discusses the importance of supply chain security in the open source ecosystem, highlighting the risks of relying on open source code without proper code review. It explores the trend of supply chain attacks and the need for a new approach to detect and block malicious dependencies. The talk also introduces Socket, a tool that assesses the security of packages and provides automation and analysis to protect against malware and supply chain attacks. It emphasizes the need to prioritize security in software development and offers insights into potential solutions such as realms and Deno's command line flags.
Towards a Standard Library for JavaScript Runtimes
Node Congress 2022Node Congress 2022
34 min
Towards a Standard Library for JavaScript Runtimes
Top Content
There is a need for a standard library of APIs for JavaScript runtimes, as there are currently multiple ways to perform fundamental tasks like base64 encoding. JavaScript runtimes have historically lacked a standard library, causing friction and difficulty for developers. The idea of a small core has both benefits and drawbacks, with some runtimes abusing it to limit innovation. There is a misalignment between Node and web browsers in terms of functionality and API standards. The proposal is to involve browser developers in conversations about API standardization and to create a common standard library for JavaScript runtimes.
Get rid of your API schemas with tRPC
React Day Berlin 2022React Day Berlin 2022
29 min
Get rid of your API schemas with tRPC
Today's Talk introduces TRPC, a library that eliminates the need for code generation and provides type safety and better collaboration between front-end and back-end. TRPC is demonstrated in a Next JS application integrated with Prisma, allowing for easy implementation and interaction with the database. The library allows for seamless usage in the client, with automatic procedure renaming and the ability to call methods without generating types. TRPC's client-server interaction is based on HTTP requests and allows for easy debugging and tracing. The library also provides runtime type check and validation using Zod.
ESM Loaders: Enhancing Module Loading in Node.js
JSNation 2023JSNation 2023
22 min
ESM Loaders: Enhancing Module Loading in Node.js
ESM Loaders enhance module loading in Node.js by resolving URLs and reading files from the disk. Module loaders can override modules and change how they are found. Enhancing the loading phase involves loading directly from HTTP and loading TypeScript code without building it. The loader in the module URL handles URL resolution and uses fetch to fetch the source code. Loaders can be chained together to load from different sources, transform source code, and resolve URLs differently. The future of module loading enhancements is promising and simple to use.
Out of the Box Node.js Diagnostics
Node Congress 2022Node Congress 2022
34 min
Out of the Box Node.js Diagnostics
This talk covers various techniques for getting diagnostics information out of Node.js, including debugging with environment variables, handling warnings and deprecations, tracing uncaught exceptions and process exit, using the v8 inspector and dev tools, and generating diagnostic reports. The speaker also mentions areas for improvement in Node.js diagnostics and provides resources for learning and contributing. Additionally, the responsibilities of the Technical Steering Committee in the TS community are discussed.
Step aside resolvers: a new approach to GraphQL execution
GraphQL Galaxy 2022GraphQL Galaxy 2022
16 min
Step aside resolvers: a new approach to GraphQL execution
GraphQL has made a huge impact in the way we build client applications, websites, and mobile apps. Despite the dominance of resolvers, the GraphQL specification does not mandate their use. Introducing Graphast, a new project that compiles GraphQL operations into execution and output plans, providing advanced optimizations. In GraphFast, instead of resolvers, we have plan resolvers that deal with future data. Graphfast plan resolvers are short and efficient, supporting all features of modern GraphQL.

Workshops on related topic

Node.js Masterclass
Node Congress 2023Node Congress 2023
109 min
Node.js Masterclass
Top Content
Workshop
Matteo Collina
Matteo Collina
Have you ever struggled with designing and structuring your Node.js applications? Building applications that are well organised, testable and extendable is not always easy. It can often turn out to be a lot more complicated than you expect it to be. In this live event Matteo will show you how he builds Node.js applications from scratch. You’ll learn how he approaches application design, and the philosophies that he applies to create modular, maintainable and effective applications.

Level: intermediate
Hands-on with AG Grid's React Data Grid
React Summit 2022React Summit 2022
147 min
Hands-on with AG Grid's React Data Grid
WorkshopFree
Sean Landsman
Sean Landsman
Get started with AG Grid React Data Grid with a hands-on tutorial from the core team that will take you through the steps of creating your first grid, including how to configure the grid with simple properties and custom components. AG Grid community edition is completely free to use in commercial applications, so you'll learn a powerful tool that you can immediately add to your projects. You'll also discover how to load data into the grid and different ways to add custom rendering to the grid. By the end of the workshop, you will have created an AG Grid React Data Grid and customized with functional React components.- Getting started and installing AG Grid- Configuring sorting, filtering, pagination- Loading data into the grid- The grid API- Using hooks and functional components with AG Grid- Capabilities of the free community edition of AG Grid- Customizing the grid with React Components
Building GraphQL APIs on top of Ethereum with The Graph
GraphQL Galaxy 2021GraphQL Galaxy 2021
48 min
Building GraphQL APIs on top of Ethereum with The Graph
WorkshopFree
Nader Dabit
Nader Dabit
The Graph is an indexing protocol for querying networks like Ethereum, IPFS, and other blockchains. Anyone can build and publish open APIs, called subgraphs, making data easily accessible.

In this workshop you’ll learn how to build a subgraph that indexes NFT blockchain data from the Foundation smart contract. We’ll deploy the API, and learn how to perform queries to retrieve data using various types of data access patterns, implementing filters and sorting.

By the end of the workshop, you should understand how to build and deploy performant APIs to The Graph to index data from any smart contract deployed to Ethereum.
Build and Deploy a Backend With Fastify & Platformatic
JSNation 2023JSNation 2023
104 min
Build and Deploy a Backend With Fastify & Platformatic
WorkshopFree
Matteo Collina
Matteo Collina
Platformatic allows you to rapidly develop GraphQL and REST APIs with minimal effort. The best part is that it also allows you to unleash the full potential of Node.js and Fastify whenever you need to. You can fully customise a Platformatic application by writing your own additional features and plugins. In the workshop, we’ll cover both our Open Source modules and our Cloud offering:- Platformatic OSS (open-source software) — Tools and libraries for rapidly building robust applications with Node.js (https://oss.platformatic.dev/).- Platformatic Cloud (currently in beta) — Our hosting platform that includes features such as preview apps, built-in metrics and integration with your Git flow (https://platformatic.dev/). 
In this workshop you'll learn how to develop APIs with Fastify and deploy them to the Platformatic Cloud.
Building a Hyper Fast Web Server with Deno
JSNation Live 2021JSNation Live 2021
156 min
Building a Hyper Fast Web Server with Deno
WorkshopFree
Matt Landers
Will Johnston
2 authors
Deno 1.9 introduced a new web server API that takes advantage of Hyper, a fast and correct HTTP implementation for Rust. Using this API instead of the std/http implementation increases performance and provides support for HTTP2. In this workshop, learn how to create a web server utilizing Hyper under the hood and boost the performance for your web apps.
0 to Auth in an Hour Using NodeJS SDK
Node Congress 2023Node Congress 2023
63 min
0 to Auth in an Hour Using NodeJS SDK
WorkshopFree
Asaf Shen
Asaf Shen
Passwordless authentication may seem complex, but it is simple to add it to any app using the right tool.
We will enhance a full-stack JS application (Node.JS backend + React frontend) to authenticate users with OAuth (social login) and One Time Passwords (email), including:- User authentication - Managing user interactions, returning session / refresh JWTs- Session management and validation - Storing the session for subsequent client requests, validating / refreshing sessions
At the end of the workshop, we will also touch on another approach to code authentication using frontend Descope Flows (drag-and-drop workflows), while keeping only session validation in the backend. With this, we will also show how easy it is to enable biometrics and other passwordless authentication methods.
Table of contents- A quick intro to core authentication concepts- Coding- Why passwordless matters
Prerequisites- IDE for your choice- Node 18 or higher