feat: add version to pool information
[poolifier.git] / README.md
CommitLineData
f2b5671a 1<div align="center">
0feeec4a 2 <img src="./images/logo.png" width="340px" height="266px"/>
ddaa3a76 3</div>
4
063f8c5b 5<h2 align="center">Node Thread Pool and Cluster Pool :arrow_double_up: :on:</h2>
1d4f79e7
APA
6
7<p align="center">
8 <a href="https://www.npmjs.com/package/poolifier">
9 <img alt="Weekly Downloads" src="https://img.shields.io/npm/dw/poolifier"></a>
d7757502 10 <a href="https://github.com/poolifier/poolifier/actions/workflows/ci.yml">
86f8562e 11 <img alt="Actions Status" src="https://github.com/poolifier/poolifier/actions/workflows/ci.yml/badge.svg"></a>
1d4f79e7
APA
12 <a href="https://sonarcloud.io/dashboard?id=pioardi_poolifier">
13 <img alt="Quality Gate Status" src="https://sonarcloud.io/api/project_badges/measure?project=pioardi_poolifier&metric=alert_status"></a>
609edfec 14 <a href="https://sonarcloud.io/dashboard?id=pioardi_poolifier">
22147b67 15 <img alt="Code Coverage" src="https://sonarcloud.io/api/project_badges/measure?project=pioardi_poolifier&metric=coverage"></a>
1d4f79e7
APA
16 <a href="https://standardjs.com">
17 <img alt="Javascript Standard Style Guide" src="https://img.shields.io/badge/code_style-standard-brightgreen.svg"></a>
18 <a href="https://gitter.im/poolifier/community?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge">
19 <img alt="Gitter chat" src="https://badges.gitter.im/poolifier/community.svg"></a>
e8a862ca
JB
20 <a href="https://opencollective.com/poolifier">
21 <img alt="Open Collective" src="https://opencollective.com/poolifier/tiers/badge.svg"></a>
8f8dc0e0
JB
22 <a href="https://badgen.net/badge/Dependabot/enabled/green?icon=dependabot">
23 <img alt="Dependabot" src="https://badgen.net/badge/Dependabot/enabled/green?icon=dependabot"></a>
1d4f79e7
APA
24 <a href="http://makeapullrequest.com">
25 <img alt="PR Welcome" src="https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square"></a>
26 <a href="https://img.shields.io/static/v1?label=dependencies&message=no%20dependencies&color=brightgreen">
27 <img alt="No dependencies" src="https://img.shields.io/static/v1?label=dependencies&message=no%20dependencies&color=brightgreen"></a>
1d4f79e7
APA
28</p>
29
74750c7f 30## Why Poolifier?
e76f5485 31
4dce520e 32Poolifier is used to perform CPU intensive and I/O intensive tasks on nodejs servers, it implements worker pools using [worker-threads](https://nodejs.org/api/worker_threads.html#worker_threads_worker_threads) and cluster pools using [Node.js cluster](https://nodejs.org/api/cluster.html) modules.
50aa7901 33With poolifier you can improve your **performance** and resolve problems related to the event loop.
063f8c5b 34Moreover you can execute your tasks using an API designed to improve the **developer experience**.
0feeec4a 35Please consult our [general guidelines](#general-guidance).
e76f5485 36
bd2ff6e0
JB
37- Easy to use :white_check_mark:
38- Performance [benchmarks](./benchmarks/README.md) :white_check_mark:
82be29c0 39- Dynamic pool size :white_check_mark:
e42a859c 40- Easy switch from a pool to another :white_check_mark:
82be29c0
JB
41- No runtime dependencies :white_check_mark:
42- Proper async integration with node async hooks :white_check_mark:
bd2ff6e0
JB
43- Support CommonJS, ESM, and TypeScript :white_check_mark:
44- Support for worker-threads and cluster node modules :white_check_mark:
82be29c0 45- Support sync and async tasks :white_check_mark:
89a4abfd 46- Tasks distribution strategies :white_check_mark:
bd2ff6e0 47- General guidance on pool choice :white_check_mark:
82be29c0
JB
48- Widely tested :white_check_mark:
49- Error handling out of the box :white_check_mark:
50- Active community :white_check_mark:
bd2ff6e0 51- Code quality [![Bugs](https://sonarcloud.io/api/project_badges/measure?project=pioardi_poolifier&metric=bugs)](https://sonarcloud.io/dashboard?id=pioardi_poolifier)
d28c7996
JB
52 [![Code Smells](https://sonarcloud.io/api/project_badges/measure?project=pioardi_poolifier&metric=code_smells)](https://sonarcloud.io/dashboard?id=pioardi_poolifier)
53 [![Duplicated Lines (%)](https://sonarcloud.io/api/project_badges/measure?project=pioardi_poolifier&metric=duplicated_lines_density)](https://sonarcloud.io/dashboard?id=pioardi_poolifier)
54 [![Maintainability Rating](https://sonarcloud.io/api/project_badges/measure?project=pioardi_poolifier&metric=sqale_rating)](https://sonarcloud.io/dashboard?id=pioardi_poolifier)
55 [![Reliability Rating](https://sonarcloud.io/api/project_badges/measure?project=pioardi_poolifier&metric=reliability_rating)](https://sonarcloud.io/dashboard?id=pioardi_poolifier)
56 [![Technical Debt](https://sonarcloud.io/api/project_badges/measure?project=pioardi_poolifier&metric=sqale_index)](https://sonarcloud.io/dashboard?id=pioardi_poolifier)
bd2ff6e0 57- Code security [![Security Rating](https://sonarcloud.io/api/project_badges/measure?project=pioardi_poolifier&metric=security_rating)](https://sonarcloud.io/dashboard?id=pioardi_poolifier) [![Vulnerabilities](https://sonarcloud.io/api/project_badges/measure?project=pioardi_poolifier&metric=vulnerabilities)](https://sonarcloud.io/dashboard?id=pioardi_poolifier)
ddaa3a76 58
50aa7901 59## Contents
e76f5485 60
34a572eb 61<h3 align="center">
50aa7901
S
62 <a href="#overview">Overview</a>
63 <span> · </span>
34a572eb 64 <a href="#installation">Installation</a>
65 <span> · </span>
66 <a href="#usage">Usage</a>
67 <span> · </span>
4f4ae1cb 68 <a href="#node-versions">Node versions</a>
50aa7901 69 <span> · </span>
34a572eb 70 <a href="#api">API</a>
71 <span> · </span>
e36cfb13 72 <a href="#general-guidance">General guidance</a>
48211d04 73 <span> · </span>
34a572eb 74 <a href="#contribute">Contribute</a>
75 <span> · </span>
50aa7901 76 <a href="#team">Team</a>
34a572eb 77 <span> · </span>
78 <a href="#license">License</a>
79</h3>
80
50aa7901 81## Overview
13031992 82
31b90205
JB
83Node pool contains two [worker-threads](https://nodejs.org/api/worker_threads.html#worker_threads_worker_threads)/[cluster worker](https://nodejs.org/api/cluster.html#cluster_class_worker) pool implementations, you don't have to deal with worker-threads/cluster worker complexity.
84The first implementation is a static worker pool, with a defined number of workers that are started at creation time and will be reused.
85The second implementation is a dynamic worker pool with a number of worker started at creation time (these workers will be always active and reused) and other workers created when the load will increase (with an upper limit, these workers will be reused when active), the new created workers will be stopped after a configurable period of inactivity.
77492f2e 86You have to implement your worker by extending the ThreadWorker or ClusterWorker class.
50aa7901
S
87
88## Installation
89
90```shell
27c5fb75 91npm install poolifier --save
1a4ec243 92```
1a4ec243 93
50aa7901
S
94## Usage
95
31b90205 96You can implement a worker-threads worker in a simple way by extending the class ThreadWorker:
1a4ec243
APA
97
98```js
99'use strict'
d2eb4964 100const { ThreadWorker } = require('poolifier')
1a4ec243 101
78cea37e 102function yourFunction(data) {
106744f7 103 // this will be executed in the worker thread,
104 // the data will be received by using the execute method
105 return { ok: 1 }
106}
107
50aa7901 108module.exports = new ThreadWorker(yourFunction, {
124119cf 109 maxInactiveTime: 60000
50aa7901 110})
1a4ec243
APA
111```
112
0feeec4a 113Instantiate your pool based on your needs :
1a4ec243
APA
114
115```js
116'use strict'
6961ca9a 117const { DynamicThreadPool, FixedThreadPool, PoolEvents, availableParallelism } = require('poolifier')
1a4ec243 118
31b90205 119// a fixed worker-threads pool
6961ca9a 120const pool = new FixedThreadPool(availableParallelism(), './yourWorker.js', {
53795b86
JB
121 errorHandler: e => console.error(e),
122 onlineHandler: () => console.info('worker is online')
123})
1a4ec243 124
53795b86 125pool.emitter.on(PoolEvents.busy, () => console.info('Pool is busy'))
164d950a 126
31b90205 127// or a dynamic worker-threads pool
6961ca9a 128const pool = new DynamicThreadPool(availableParallelism() / 2, availableParallelism(), './yourWorker.js', {
53795b86
JB
129 errorHandler: e => console.error(e),
130 onlineHandler: () => console.info('worker is online')
131})
106744f7 132
53795b86
JB
133pool.emitter.on(PoolEvents.full, () => console.info('Pool is full'))
134pool.emitter.on(PoolEvents.busy, () => console.info('Pool is busy'))
1a4ec243
APA
135
136// the execute method signature is the same for both implementations,
137// so you can easy switch from one to another
8351c9af
JB
138pool
139 .execute({})
140 .then(res => {
141 console.info(res)
142 })
143 .catch(err => {
144 console.error(err)
145 })
1a4ec243
APA
146```
147
17a9a094 148You can do the same with the classes ClusterWorker, FixedClusterPool and DynamicClusterPool.
31b90205 149
f997872c 150**See [examples](./examples/) folder for more details (in particular if you want to use a pool with [multiple worker functions](./examples/multiFunctionExample.js))**.
1a4ec243 151
6677a3d3 152Remember that workers can only send and receive structured-cloneable data.
deb85c12 153
50aa7901 154## Node versions
34a572eb 155
9e45c2c4 156Node versions >= 16.14.x are supported.
1a4ec243 157
059ea823 158## [API](https://poolifier.github.io/poolifier/)
4680c1b2 159
5e5ea237 160### `PoolOptions`
50aa7901 161
70e9dd65 162An object with these properties:
50aa7901 163
46e857ca 164- `messageHandler` (optional) - A function that will listen for message event on each worker
f42ca86f
JB
165- `errorHandler` (optional) - A function that will listen for error event on each worker
166- `onlineHandler` (optional) - A function that will listen for online event on each worker
167- `exitHandler` (optional) - A function that will listen for exit event on each worker
46e857ca 168- `workerChoiceStrategy` (optional) - The worker choice strategy to use in this pool:
5519f8f3 169
b4db5969 170 - `WorkerChoiceStrategies.ROUND_ROBIN`: Submit tasks to worker in a round robin fashion
1c6fe997
JB
171 - `WorkerChoiceStrategies.LEAST_USED`: Submit tasks to the worker with the minimum number of executed, executing and queued tasks
172 - `WorkerChoiceStrategies.LEAST_BUSY`: Submit tasks to the worker with the minimum tasks total execution and wait time
a7bbf44a 173 - `WorkerChoiceStrategies.LEAST_ELU`: Submit tasks to the worker with the minimum event loop utilization (ELU) (experimental)
9e2ab226 174 - `WorkerChoiceStrategies.WEIGHTED_ROUND_ROBIN`: Submit tasks to worker by using a [weighted round robin scheduling algorithm](./src/pools/selection-strategies/README.md#weighted-round-robin) based on tasks execution time
129ab848
JB
175 - `WorkerChoiceStrategies.INTERLEAVED_WEIGHTED_ROUND_ROBIN`: Submit tasks to worker by using an [interleaved weighted round robin scheduling algorithm](./src/pools/selection-strategies/README.md#interleaved-weighted-round-robin) based on tasks execution time(experimental)
176 - `WorkerChoiceStrategies.FAIR_SHARE`: Submit tasks to worker by using a [fair share scheduling algorithm](./src/pools/selection-strategies/README.md#fair-share) based on tasks execution time (the default) or ELU active time
5519f8f3 177
9b2bdf94 178 `WorkerChoiceStrategies.WEIGHTED_ROUND_ROBIN`, `WorkerChoiceStrategies.INTERLEAVED_WEIGHTED_ROUND_ROBIN` and `WorkerChoiceStrategies.FAIR_SHARE` strategies are targeted to heavy and long tasks.
f42ca86f 179 Default: `WorkerChoiceStrategies.ROUND_ROBIN`
5519f8f3 180
da309861
JB
181- `workerChoiceStrategyOptions` (optional) - The worker choice strategy options object to use in this pool.
182 Properties:
183
9adcefab 184 - `measurement` (optional) - The measurement to use in worker choice strategies: `runTime`, `waitTime` or `elu`.
9e2ab226
JB
185 - `runTime` (optional) - Use the tasks [median](./src/pools/selection-strategies/README.md#median) runtime instead of the tasks average runtime in worker choice strategies.
186 - `waitTime` (optional) - Use the tasks [median](./src/pools/selection-strategies/README.md#median) wait time instead of the tasks average wait time in worker choice strategies.
187 - `elu` (optional) - Use the tasks [median](./src/pools/selection-strategies/README.md#median) ELU instead of the tasks average ELU in worker choice strategies.
129ab848 188 - `weights` (optional) - The worker weights to use in weighted round robin worker choice strategies: `{ 0: 200, 1: 300, ..., n: 100 }`.
7171d33f 189
9adcefab 190 Default: `{ runTime: { median: false }, waitTime: { median: false }, elu: { median: false } }`
da309861 191
1f68cede 192- `restartWorkerOnError` (optional) - Restart worker on uncaught error in this pool.
609154c5 193 Default: `true`
dfd00839 194- `enableEvents` (optional) - Events emission enablement in this pool.
609154c5 195 Default: `true`
dfd00839 196- `enableTasksQueue` (optional) - Tasks queue per worker enablement in this pool.
609154c5 197 Default: `false`
34a572eb 198
83d127b9 199- `tasksQueueOptions` (optional) - The worker tasks queue options object to use in this pool.
7171d33f
JB
200 Properties:
201
202 - `concurrency` (optional) - The maximum number of tasks that can be executed concurrently on a worker.
203
dfd00839 204 Default: `{ concurrency: 1 }`
7171d33f 205
92e7183f 206#### `ThreadPoolOptions extends PoolOptions`
70e9dd65 207
129ab848 208- `workerOptions` (optional) - An object with the worker options to pass to worker. See [worker_threads](https://nodejs.org/api/worker_threads.html#worker_threads_new_worker_filename_options) for more details.
70e9dd65 209
92e7183f 210#### `ClusterPoolOptions extends PoolOptions`
70e9dd65 211
129ab848 212- `env` (optional) - An object with the environment variables to pass to worker. See [cluster](https://nodejs.org/api/cluster.html#cluster_cluster_fork_env) for more details.
70e9dd65 213
430745c9 214- `settings` (optional) - An object with the cluster settings. See [cluster](https://nodejs.org/api/cluster.html#cluster_cluster_settings) for more details.
70e9dd65
JB
215
216### `pool = new FixedThreadPool/FixedClusterPool(numberOfThreads/numberOfWorkers, filePath, opts)`
217
218`numberOfThreads/numberOfWorkers` (mandatory) Number of workers for this pool
219`filePath` (mandatory) Path to a file with a worker implementation
220`opts` (optional) An object with the pool options properties described above
221
31b90205 222### `pool = new DynamicThreadPool/DynamicClusterPool(min, max, filePath, opts)`
50aa7901 223
31b90205
JB
224`min` (mandatory) Same as FixedThreadPool/FixedClusterPool numberOfThreads/numberOfWorkers, this number of workers will be always active
225`max` (mandatory) Max number of workers that this pool can contain, the new created workers will die after a threshold (default is 1 minute, you can override it in your worker implementation).
70e9dd65
JB
226`filePath` (mandatory) Path to a file with a worker implementation
227`opts` (optional) An object with the pool options properties described above
34a572eb 228
70e9dd65 229### `pool.execute(data, name)`
50aa7901 230
0feeec4a 231`data` (optional) An object that you want to pass to your worker implementation
609154c5 232`name` (optional) A string with the task function name that you want to execute on the worker. Default: `'default'`
0feeec4a 233This method is available on both pool implementations and returns a promise.
34a572eb 234
235### `pool.destroy()`
34a572eb 236
50aa7901
S
237Destroy method is available on both pool implementations.
238This method will call the terminate method on each worker.
34a572eb 239
31b90205 240### `class YourWorker extends ThreadWorker/ClusterWorker`
50aa7901 241
70e9dd65 242`taskFunctions` (mandatory) The task function or task functions object that you want to execute on the worker
50aa7901
S
243`opts` (optional) An object with these properties:
244
dfd00839 245- `maxInactiveTime` (optional) - Max time to wait tasks to work on in milliseconds, after this period the new worker will die.
3832ad95 246 The last active time of your worker unit will be updated when a task is submitted to a worker or when a worker terminate a task.
920278a2 247 If `killBehavior` is set to `KillBehaviors.HARD` this value represents also the timeout for the tasks that you submit to the pool, when this timeout expires your tasks is interrupted before completion and removed. The worker is killed if is not part of the minimum size of the pool.
3832ad95 248 If `killBehavior` is set to `KillBehaviors.SOFT` your tasks have no timeout and your workers will not be terminated until your task is completed.
609154c5 249 Default: `60000`
15eacd5d 250
dfd00839 251- `killBehavior` (optional) - Dictates if your async unit (worker/process) will be deleted in case that a task is active on it.
a6a2dc4c
JB
252 **KillBehaviors.SOFT**: If `currentTime - lastActiveTime` is greater than `maxInactiveTime` but a task is still executing or queued, then the worker **won't** be deleted.
253 **KillBehaviors.HARD**: If `currentTime - lastActiveTime` is greater than `maxInactiveTime` but a task is still executing or queued, then the worker will be deleted.
3832ad95 254 This option only apply to the newly created workers.
f42ca86f 255 Default: `KillBehaviors.SOFT`
50aa7901 256
e36cfb13 257## General guidance
34a572eb 258
31b90205 259Performance is one of the main target of these worker pool implementations, we want to have a strong focus on this.
e36cfb13
APA
260We already have a bench folder where you can find some comparisons.
261
262### Internal Node.js thread pool
263
264Before to jump into each poolifier pool type, let highlight that **Node.js comes with a thread pool already**, the libuv thread pool where some particular tasks already run by default.
265Please take a look at [which tasks run on the libuv thread pool](https://nodejs.org/en/docs/guides/dont-block-the-event-loop/#what-code-runs-on-the-worker-pool).
266
e843b904 267**If your task runs on libuv thread pool**, you can try to:
e36cfb13 268
0feeec4a 269- Tune the libuv thread pool size setting the [UV_THREADPOOL_SIZE](https://nodejs.org/api/cli.html#cli_uv_threadpool_size_size).
e36cfb13
APA
270
271and/or
272
0feeec4a 273- Use poolifier cluster pool that spawning child processes will also increase the number of libuv threads since that any new child process comes with a separated libuv thread pool. **More threads does not mean more fast, so please tune your application**.
e36cfb13
APA
274
275### Cluster vs Threads worker pools
276
277**If your task does not run into libuv thread pool** and is CPU intensive then poolifier **thread pools** (FixedThreadPool and DynamicThreadPool) are suggested to run CPU intensive tasks, you can still run I/O intensive tasks into thread pools, but performance enhancement is expected to be minimal.
063f8c5b 278Thread pools are built on top of Node.js [worker-threads](https://nodejs.org/api/worker_threads.html#worker_threads_worker_threads) module.
279
e36cfb13
APA
280**If your task does not run into libuv thread pool** and is I/O intensive then poolifier **cluster pools** (FixedClusterPool and DynamicClusterPool) are suggested to run I/O intensive tasks, again you can still run CPU intensive tasks into cluster pools, but performance enhancement is expected to be minimal.
281Consider that by default Node.js already has great performance for I/O tasks (asynchronous I/O).
4a6952ff 282Cluster pools are built on top of Node.js [cluster](https://nodejs.org/api/cluster.html) module.
75876e4c 283
e36cfb13 284If your task contains code that runs on libuv plus code that is CPU intensive or I/O intensive you either split it either combine more strategies (i.e. tune the number of libuv threads and use cluster/thread pools).
0feeec4a 285But in general, **always profile your application**.
e36cfb13
APA
286
287### Fixed vs Dynamic pools
063f8c5b 288
31b90205 289To choose your pool consider that with a FixedThreadPool/FixedClusterPool or a DynamicThreadPool/DynamicClusterPool (in this case is important the min parameter passed to the constructor) your application memory footprint will increase.
063f8c5b 290Increasing the memory footprint, your application will be ready to accept more tasks, but during idle time your application will consume more memory.
afe102b2 291One good choice from poolifier team point of view is to profile your application using fixed or dynamic worker pool, and to see your application metrics when you increase/decrease the num of workers.
31b90205 292For example you could keep the memory footprint low choosing a DynamicThreadPool/DynamicClusterPool with 5 workers, and allow to create new workers until 50/100 when needed, this is the advantage to use the DynamicThreadPool/DynamicClusterPool.
0feeec4a 293But in general, **always profile your application**.
48211d04 294
50aa7901 295## Contribute
34a572eb 296
91633990 297Choose your task here [2.6.x](https://github.com/orgs/poolifier/projects/1), propose an idea, a fix, an improvement.
1a4ec243 298
0feeec4a
JB
299See [CONTRIBUTING](CONTRIBUTING.md) guidelines.
300
50aa7901 301## Team
1a4ec243 302
39deb558 303**Creator/Owner:**
39deb558 304
50aa7901
S
305- [**Alessandro Pio Ardizio**](https://github.com/pioardi)
306
307**_Contributors_**
308
309- [**Shinigami92**](https://github.com/Shinigami92)
310- [**Jérôme Benoit**](https://github.com/jerome-benoit)
39deb558 311
50aa7901 312## License
1a4ec243 313
9507c1d4 314[MIT](./LICENSE)