Is Node using 100% CPU? Is Node using 100% CPU? docker docker

Is Node using 100% CPU?


Different tops

What you're seeing is (likely) due to a difference in flavors of top.

I'm going to take a wild guess and say that your Docker image is perhaps based on Alpine? The top command in Alpine is busybox. It reports the per-process CPU usage as a percentage of the TOTAL number of CPUs available (nCPUs * 100%).

This differs from most other flavors of top, which report the per-process CPU usage as a percentage of a SINGLE CPU.

Both tops show same thing: ~50% usage on each CPU

The two top screenshots are actually showing the same thing: node process is using about 50% of each of the 2 CPUs.

Testing theory

We can test this with the following:

# This will max out 1 cpu of the systemdocker run --name stress --rm -d alpine sh -c 'apk add stress-ng && stress-ng --cpu 1'# This shows the busybox top with usage as ratio of total CPUs# press 'c' in top to see the per-CPU info at the topdocker exec -it stress top# This will install and run procps top, with usage as a ratio of single CPUdocker exec -it stress sh -c 'apk add procps && /usr/bin/top'

screenshot of cpu usage in two different cpu usage monitors

In the screenshot above, we can see two different flavors of top. They are reporting the same CPU usage, but the upper one reports this as "100% CPU" (as a percentage of a single core), while lower one reports this as 6% (1/16 cores = 6.25%).

What does this tell us about node's CPU usage?

Node is single-threaded, and cannot use more than 100% of a CPU. ...sort of. Under the hood, Node uses libuv, which does run threads in silos. This is how Node receives asynchronous events for IO operations, for example. These threads do use CPU and can push your CPU usage over 100%. Some packages are also written as add-ons to Node, and these also use threads.

The environment variable UV_THREADPOOL_SIZE limits the maximum number of libuv-controlled threads which may run simultaneously. Setting this to a larger number (default is 4) before running node may remove a bottleneck.

If you are doing some CPU-intensive operations, consider using cluster, Worker Threads, writing your own add-on or spawning separate processes to do the computation.