refactor: cleanup enums namespace
[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
64060857 37- Performance :racehorse: [benchmarks](./benchmarks/README.md)
f2b5671a 38- Security :bank: :cop: [![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)
b1b24f66 39- Easy to use :couple:
82be29c0 40- Dynamic pool size :white_check_mark:
e42a859c 41- Easy switch from a pool to another :white_check_mark:
82be29c0
JB
42- No runtime dependencies :white_check_mark:
43- Proper async integration with node async hooks :white_check_mark:
44- Support for worker threads and cluster node modules :white_check_mark:
45- Support sync and async tasks :white_check_mark:
46- General guidance on pools to use :white_check_mark:
47- Widely tested :white_check_mark:
48- Error handling out of the box :white_check_mark:
49- Active community :white_check_mark:
5fd75a2e 50- Code quality :octocat: [![Bugs](https://sonarcloud.io/api/project_badges/measure?project=pioardi_poolifier&metric=bugs)](https://sonarcloud.io/dashboard?id=pioardi_poolifier)
d28c7996
JB
51 [![Code Smells](https://sonarcloud.io/api/project_badges/measure?project=pioardi_poolifier&metric=code_smells)](https://sonarcloud.io/dashboard?id=pioardi_poolifier)
52 [![Duplicated Lines (%)](https://sonarcloud.io/api/project_badges/measure?project=pioardi_poolifier&metric=duplicated_lines_density)](https://sonarcloud.io/dashboard?id=pioardi_poolifier)
53 [![Maintainability Rating](https://sonarcloud.io/api/project_badges/measure?project=pioardi_poolifier&metric=sqale_rating)](https://sonarcloud.io/dashboard?id=pioardi_poolifier)
54 [![Reliability Rating](https://sonarcloud.io/api/project_badges/measure?project=pioardi_poolifier&metric=reliability_rating)](https://sonarcloud.io/dashboard?id=pioardi_poolifier)
55 [![Technical Debt](https://sonarcloud.io/api/project_badges/measure?project=pioardi_poolifier&metric=sqale_index)](https://sonarcloud.io/dashboard?id=pioardi_poolifier)
ddaa3a76 56
50aa7901 57## Contents
e76f5485 58
34a572eb 59<h3 align="center">
50aa7901
S
60 <a href="#overview">Overview</a>
61 <span> · </span>
34a572eb 62 <a href="#installation">Installation</a>
63 <span> · </span>
64 <a href="#usage">Usage</a>
65 <span> · </span>
4f4ae1cb 66 <a href="#node-versions">Node versions</a>
50aa7901 67 <span> · </span>
34a572eb 68 <a href="#api">API</a>
69 <span> · </span>
e36cfb13 70 <a href="#general-guidance">General guidance</a>
48211d04 71 <span> · </span>
34a572eb 72 <a href="#contribute">Contribute</a>
73 <span> · </span>
50aa7901 74 <a href="#team">Team</a>
34a572eb 75 <span> · </span>
76 <a href="#license">License</a>
77</h3>
78
50aa7901 79## Overview
13031992 80
31b90205
JB
81Node 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.
82The first implementation is a static worker pool, with a defined number of workers that are started at creation time and will be reused.
83The 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.
0feeec4a 84You have to implement your worker extending the ThreadWorker or ClusterWorker class.
50aa7901
S
85
86## Installation
87
88```shell
27c5fb75 89npm install poolifier --save
1a4ec243 90```
1a4ec243 91
50aa7901
S
92## Usage
93
31b90205 94You can implement a worker-threads worker in a simple way by extending the class ThreadWorker:
1a4ec243
APA
95
96```js
97'use strict'
d2eb4964 98const { ThreadWorker } = require('poolifier')
1a4ec243 99
78cea37e 100function yourFunction(data) {
106744f7 101 // this will be executed in the worker thread,
102 // the data will be received by using the execute method
103 return { ok: 1 }
104}
105
50aa7901 106module.exports = new ThreadWorker(yourFunction, {
124119cf 107 maxInactiveTime: 60000
50aa7901 108})
1a4ec243
APA
109```
110
0feeec4a 111Instantiate your pool based on your needs :
1a4ec243
APA
112
113```js
114'use strict'
aee46736 115const { DynamicThreadPool, FixedThreadPool, PoolEvents } = require('poolifier')
1a4ec243 116
31b90205 117// a fixed worker-threads pool
1a4ec243 118const pool = new FixedThreadPool(15,
106744f7 119 './yourWorker.js',
120 { errorHandler: (e) => console.error(e), onlineHandler: () => console.log('worker is online') })
1a4ec243 121
aee46736 122pool.emitter.on(PoolEvents.busy, () => console.log('Pool is busy'))
164d950a 123
31b90205 124// or a dynamic worker-threads pool
1a4ec243 125const pool = new DynamicThreadPool(10, 100,
106744f7 126 './yourWorker.js',
127 { errorHandler: (e) => console.error(e), onlineHandler: () => console.log('worker is online') })
128
aee46736
JB
129pool.emitter.on(PoolEvents.full, () => console.log('Pool is full'))
130pool.emitter.on(PoolEvents.busy, () => console.log('Pool is busy'))
1a4ec243
APA
131
132// the execute method signature is the same for both implementations,
133// so you can easy switch from one to another
134pool.execute({}).then(res => {
135 console.log(res)
777b7824 136}).catch ....
1a4ec243
APA
137
138```
139
17a9a094 140You can do the same with the classes ClusterWorker, FixedClusterPool and DynamicClusterPool.
31b90205 141
4abb4f36 142**See examples folder for more details (in particular if you want to use a pool with [multiple worker functions](./examples/multiFunctionExample.js))**.
1a4ec243 143
ec2ccfc8 144Remember that workers can only send and receive serializable data.
deb85c12 145
50aa7901 146## Node versions
34a572eb 147
9e45c2c4 148Node versions >= 16.14.x are supported.
1a4ec243 149
059ea823 150## [API](https://poolifier.github.io/poolifier/)
4680c1b2 151
31b90205 152### `pool = new FixedThreadPool/FixedClusterPool(numberOfThreads/numberOfWorkers, filePath, opts)`
50aa7901 153
f42ca86f 154`numberOfThreads/numberOfWorkers` (mandatory) Number of workers for this pool
50aa7901 155`filePath` (mandatory) Path to a file with a worker implementation
f42ca86f 156`opts` (optional) An object with these properties:
50aa7901 157
46e857ca 158- `messageHandler` (optional) - A function that will listen for message event on each worker
f42ca86f
JB
159- `errorHandler` (optional) - A function that will listen for error event on each worker
160- `onlineHandler` (optional) - A function that will listen for online event on each worker
161- `exitHandler` (optional) - A function that will listen for exit event on each worker
46e857ca 162- `workerChoiceStrategy` (optional) - The worker choice strategy to use in this pool:
5519f8f3 163
46e857ca 164 - `WorkerChoiceStrategies.ROUND_ROBIN`: Submit tasks to worker in a round robbin fashion
e4543b14
JB
165 - `WorkerChoiceStrategies.LEAST_USED`: Submit tasks to the least used worker
166 - `WorkerChoiceStrategies.LEAST_BUSY`: Submit tasks to the least busy worker
cb9eb085 167 - `WorkerChoiceStrategies.WEIGHTED_ROUND_ROBIN`: Submit tasks to worker using a weighted round robin scheduling algorithm based on tasks execution time
71002f09 168 - `WorkerChoiceStrategies.INTERLEAVED_WEIGHTED_ROUND_ROBIN`: Submit tasks to worker using an interleaved weighted round robin scheduling algorithm based on tasks execution time (experimental)
46e857ca 169 - `WorkerChoiceStrategies.FAIR_SHARE`: Submit tasks to worker using a fair share tasks scheduling algorithm based on tasks execution time
5519f8f3 170
dfd00839 171 `WorkerChoiceStrategies.WEIGHTED_ROUND_ROBIN` and `WorkerChoiceStrategies.FAIR_SHARE` strategies are targeted to heavy and long tasks.
f42ca86f 172 Default: `WorkerChoiceStrategies.ROUND_ROBIN`
5519f8f3 173
da309861
JB
174- `workerChoiceStrategyOptions` (optional) - The worker choice strategy options object to use in this pool.
175 Properties:
176
9e45c2c4 177 - `medRunTime` (optional) - Use the tasks median runtime instead of the tasks average runtime in worker choice strategies.
4c0ada52 178 - `weights` (optional) - The worker weights to use in the weighted round robin worker choice strategy: `{ 0: 200, 1: 300, ..., n: 100 }`
7171d33f 179
dfd00839 180 Default: `{ medRunTime: false }`
da309861 181
1f68cede
JB
182- `restartWorkerOnError` (optional) - Restart worker on uncaught error in this pool.
183 Default: true
dfd00839
JB
184- `enableEvents` (optional) - Events emission enablement in this pool.
185 Default: true
186- `enableTasksQueue` (optional) - Tasks queue per worker enablement in this pool.
187 Default: false
34a572eb 188
83d127b9 189- `tasksQueueOptions` (optional) - The worker tasks queue options object to use in this pool.
7171d33f
JB
190 Properties:
191
192 - `concurrency` (optional) - The maximum number of tasks that can be executed concurrently on a worker.
193
dfd00839 194 Default: `{ concurrency: 1 }`
7171d33f 195
31b90205 196### `pool = new DynamicThreadPool/DynamicClusterPool(min, max, filePath, opts)`
50aa7901 197
31b90205
JB
198`min` (mandatory) Same as FixedThreadPool/FixedClusterPool numberOfThreads/numberOfWorkers, this number of workers will be always active
199`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).
200`filePath` (mandatory) Same as FixedThreadPool/FixedClusterPool
201`opts` (optional) Same as FixedThreadPool/FixedClusterPool
34a572eb 202
203### `pool.execute(data)`
50aa7901 204
0feeec4a
JB
205`data` (optional) An object that you want to pass to your worker implementation
206This method is available on both pool implementations and returns a promise.
34a572eb 207
208### `pool.destroy()`
34a572eb 209
50aa7901
S
210Destroy method is available on both pool implementations.
211This method will call the terminate method on each worker.
34a572eb 212
31b90205 213### `class YourWorker extends ThreadWorker/ClusterWorker`
50aa7901 214
a86b6df1 215`taskFunctions` (mandatory) The task function(s) that you want to execute on the worker
50aa7901
S
216`opts` (optional) An object with these properties:
217
dfd00839 218- `maxInactiveTime` (optional) - Max time to wait tasks to work on in milliseconds, after this period the new worker will die.
3832ad95
S
219 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.
220 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 and the worker is killed if is not part of the minimum size of the pool.
221 If `killBehavior` is set to `KillBehaviors.SOFT` your tasks have no timeout and your workers will not be terminated until your task is completed.
dfd00839 222 Default: 60000
15eacd5d 223
dfd00839 224- `killBehavior` (optional) - Dictates if your async unit (worker/process) will be deleted in case that a task is active on it.
f42ca86f 225 **KillBehaviors.SOFT**: If `currentTime - lastActiveTime` is greater than `maxInactiveTime` but a task is still running, then the worker **won't** be deleted.
a9d9ea34 226 **KillBehaviors.HARD**: If `currentTime - lastActiveTime` is greater than `maxInactiveTime` but a task is still running, then the worker will be deleted.
3832ad95 227 This option only apply to the newly created workers.
f42ca86f 228 Default: `KillBehaviors.SOFT`
50aa7901 229
e36cfb13 230## General guidance
34a572eb 231
31b90205 232Performance is one of the main target of these worker pool implementations, we want to have a strong focus on this.
e36cfb13
APA
233We already have a bench folder where you can find some comparisons.
234
235### Internal Node.js thread pool
236
237Before 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.
238Please 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).
239
e843b904 240**If your task runs on libuv thread pool**, you can try to:
e36cfb13 241
0feeec4a 242- Tune the libuv thread pool size setting the [UV_THREADPOOL_SIZE](https://nodejs.org/api/cli.html#cli_uv_threadpool_size_size).
e36cfb13
APA
243
244and/or
245
0feeec4a 246- 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
247
248### Cluster vs Threads worker pools
249
250**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 251Thread pools are built on top of Node.js [worker-threads](https://nodejs.org/api/worker_threads.html#worker_threads_worker_threads) module.
252
e36cfb13
APA
253**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.
254Consider that by default Node.js already has great performance for I/O tasks (asynchronous I/O).
4a6952ff 255Cluster pools are built on top of Node.js [cluster](https://nodejs.org/api/cluster.html) module.
75876e4c 256
e36cfb13 257If 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 258But in general, **always profile your application**.
e36cfb13
APA
259
260### Fixed vs Dynamic pools
063f8c5b 261
31b90205 262To 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 263Increasing the memory footprint, your application will be ready to accept more tasks, but during idle time your application will consume more memory.
31b90205
JB
264One good choose from my point of view is to profile your application using Fixed/Dynamic worker pool, and to see your application metrics when you increase/decrease the num of workers.
265For 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 266But in general, **always profile your application**.
48211d04 267
50aa7901 268## Contribute
34a572eb 269
d1affa4c 270Choose your task here [2.4.x](https://github.com/orgs/poolifier/projects/1), propose an idea, a fix, an improvement.
1a4ec243 271
0feeec4a
JB
272See [CONTRIBUTING](CONTRIBUTING.md) guidelines.
273
50aa7901 274## Team
1a4ec243 275
39deb558 276<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
39deb558 277
278**Creator/Owner:**
39deb558 279
50aa7901
S
280- [**Alessandro Pio Ardizio**](https://github.com/pioardi)
281
282**_Contributors_**
283
284- [**Shinigami92**](https://github.com/Shinigami92)
285- [**Jérôme Benoit**](https://github.com/jerome-benoit)
39deb558 286
50aa7901 287## License
1a4ec243 288
9507c1d4 289[MIT](./LICENSE)