Skip to content

Instantly share code, notes, and snippets.

@Samjin
Forked from rjoydip-zz/UV_THREADPOOL_SIZE.md
Created September 2, 2021 22:11
Show Gist options
  • Save Samjin/69b7f31f09cf4e359157418466fdaf6e to your computer and use it in GitHub Desktop.
Save Samjin/69b7f31f09cf4e359157418466fdaf6e to your computer and use it in GitHub Desktop.
How you can set `UV_THREADPOOL_SIZE` value?
const {readdir} = require('fs');
process.env.UV_THREADPOOL_SIZE = 6; // This will work
readdir('.', () => {
process.env.UV_THREADPOOL_SIZE = 20; // This won't
});
[1,2,3].forEach(element => {
process.env.UV_THREADPOOL_SIZE = 7; // This will work because this isn't a async task
});
process.stdout.write("[UV_THREADPOOL_SIZE]", process.env.UV_THREADPOOL_SIZE);
// Note: You cannot change the size of the thread pool once it is created or entered in the event-loop/worker-thread.
// npm-script: cross-env UV_THREADPOOL_SIZE=5 node index
// install "cross-env" as devDependencies

When you need to set value to "UV_THREADPOOL_SIZE"?

  • Libuv has a default thread pool size of 4, and uses a queue to manage access to the thread pool - the upshot is that if you have 5 long-running DB queries all going at the same time, one of them (and any other asynchronous action that relies on the thread pool) will be waiting for those queries to finish before they even get started.

  • Note, however, that tuning UV_THREADPOOL_SIZE may make more sense for a standalone application like a CLI written in Node.js. If you are standing up a bunch of Node.js processes using the cluster module then I would be surprised if tuning UV_THREADPOOL_SIZE was particularly beneficial for you. But if your application resembles the web tooling benchmarks then tuning UV_THREADPOOL_SIZE may help with performance.

@Samjin
Copy link
Author

Samjin commented Sep 2, 2021

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment