Lessons from open-source: CPU profiling in NodeJs.
Tags: javascript, opensource, nextjs, react
Published: 2024-03-27 21:35:15

This lesson is picked from [Nextjs Source code](https://github.com/vercel/next.js/blob/canary/packages/next/src/server/lib/cpu-profile.ts). In this article, you will learn what CPU profiling means, how Next.js source code uses it.

CPU profiling:
--------------

CPU profiling in Node.js refers to the process of analysing the usage of the CPU by the application code. It involves identifying which parts of the code are consuming the most CPU resources, how often they are being executed, and how long they take to execute.

Node.js provides built-in tools for CPU profiling, such as the — prof command-line option, which allows you to generate a CPU profile file. This file contains information about the execution of JavaScript functions, including how much time each function takes to execute and how many times it is called.

> [_Practice the exercises based on documentation_](https://tthroo.com/) _to become an expert in Next.js._

### Further reading resources related to CPU profiling:

*   [https://netflixtechblog.com/node-js-in-flames-ddd073803aa4](https://netflixtechblog.com/node-js-in-flames-ddd073803aa4)
*   [https://medium.com/voodoo-engineering/node-js-and-cpu-profiling-on-production-in-real-time-without-downtime-d6e62af173e2](https://medium.com/voodoo-engineering/node-js-and-cpu-profiling-on-production-in-real-time-without-downtime-d6e62af173e2)
*   [https://nodejs.org/api/inspector.html](https://nodejs.org/api/inspector.html)
*   [https://nodejs.org/en/learn/getting-started/profiling](https://nodejs.org/en/learn/getting-started/profiling)

How Next.js uses CPU profiling?
-------------------------------

You can find the code related to CPU profiling used in Next.js source code [at cpu-profile.ts](https://github.com/vercel/next.js/blob/canary/packages/next/src/server/lib/cpu-profile.ts). The code inside reveals that this profiling is saved to a local file depending on an env variable as shown below.

```
const privateCpuProfileName = process.env.\_\_NEXT\_PRIVATE\_CPU\_PROFILE
const isCpuProfileEnabled = process.env.NEXT\_CPU\_PROF || privateCpuProfileName

if (isCpuProfileEnabled) {
  const { Session } = require('inspector') as typeof import('inspector')
  const fs = require('fs')

  const session = new Session()
  session.connect()

  session.post('Profiler.enable')
  session.post('Profiler.start')

  function saveProfile() {
    session.post('Profiler.stop', (error, param) => {
      if (error) {
        console.error('Cannot generate CPU profiling:', error)
        return
      }

      // Write profile to disk
      const filename = \`${
        privateCpuProfileName || 'CPU.main'
      }.${Date.now()}.cpuprofile\`
      fs.writeFileSync(\`./${filename}\`, JSON.stringify(param.profile))
      process.exit(0)
    })
  }
  process.on('SIGINT', saveProfile)
  process.on('SIGTERM', saveProfile)
  process.on('exit', saveProfile)
}
```

This file is imported in 3 other files related to CLI.

![CPU-Profile used in files](https://media.licdn.com/dms/image/D4E12AQH5kFgXlLfhOA/article-inline_image-shrink_1500_2232/0/1711574957374?e=1717027200&v=beta&t=gL2VZVgCeLSvgdYEg7RjasObV1z6AF0vpe_Odt_hZQc)

Conclusion:
-----------

As I keep reading more and more open source code, I find myself spiralling around the concepts such as observability, instrumentation, memory leaks, performance, using the right data structure/algorithm.

In this article, I have written about CPU profiling for performance monitoring in NodeJs and how Nextjs uses CPU profiling in the CLI related files.