Additional details on benchmarks
[poolifier.git] / README.md
1 <div align="center">
2 <img src="./docs/logo.png" width="340px" height="266px"/>
3 </div>
4
5 <h2 align="center">Node Thread Pool :arrow_double_up: :on:</h2>
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>
10 <a href="https://github.com/pioardi/node-pool/actions">
11 <img alt="Actions Status" src="https://github.com/pioardi/node-pool/workflows/NodeCI/badge.svg"></a>
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>
14 <a href="https://sonarcloud.io/component_measures/metric/coverage/list?id=pioardi_poolifier">
15 <img alt="Code coverage" src="https://sonarcloud.io/api/project_badges/measure?project=pioardi_poolifier&metric=coverage"></a>
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>
20 <a href="https://badgen.net/dependabot/dependabot/dependabot-core/?icon=dependabot">
21 <img alt="Dependabot" src="https://badgen.net/dependabot/dependabot/dependabot-core/?icon=dependabot"></a>
22 <a href="http://makeapullrequest.com">
23 <img alt="PR Welcome" src="https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square"></a>
24 <a href="https://img.shields.io/static/v1?label=dependencies&message=no%20dependencies&color=brightgreen">
25 <img alt="No dependencies" src="https://img.shields.io/static/v1?label=dependencies&message=no%20dependencies&color=brightgreen"></a>
26 </p>
27
28 ## Why Poolifier?
29
30 Poolifier is used to perform heavy CPU bound tasks on nodejs servers, it implements worker pools (yes, more worker pool implementations, so you can choose which one fit better for you) using [worker-threads](https://nodejs.org/api/worker_threads.html#worker_threads_worker_threads).
31 With poolifier you can improve your **performance** and resolve problems related to the event loop.
32 Moreover you can execute your CPU tasks using an API designed to improve the **developer experience**.
33
34 - Performance :racehorse:
35 - 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)
36 - Easy to use :couple:
37 - Easy switch from a pool to another, easy to tune :heavy_check_mark:
38 - Dynamic pool size :heavy_check_mark:
39 - No runtime dependencies :heavy_check_mark:
40 - Proper async integration with node async hooks :heavy_check_mark:
41 - Support for worker threads and cluster node modules :heavy_check_mark:
42 - Support sync and async tasks :heavy_check_mark:
43 - General guidance on pools to use :heavy_check_mark:
44 - Widely tested :heavy_check_mark:
45 - Error handling out of the box :heavy_check_mark:
46 - Active community :heavy_check_mark:
47 - Code quality :octocat: [![Bugs](https://sonarcloud.io/api/project_badges/measure?project=pioardi_poolifier&metric=bugs)](https://sonarcloud.io/dashboard?id=pioardi_poolifier)
48 [![Code Smells](https://sonarcloud.io/api/project_badges/measure?project=pioardi_poolifier&metric=code_smells)](https://sonarcloud.io/dashboard?id=pioardi_poolifier)
49 [![Duplicated Lines (%)](https://sonarcloud.io/api/project_badges/measure?project=pioardi_poolifier&metric=duplicated_lines_density)](https://sonarcloud.io/dashboard?id=pioardi_poolifier)
50 [![Maintainability Rating](https://sonarcloud.io/api/project_badges/measure?project=pioardi_poolifier&metric=sqale_rating)](https://sonarcloud.io/dashboard?id=pioardi_poolifier)
51 [![Reliability Rating](https://sonarcloud.io/api/project_badges/measure?project=pioardi_poolifier&metric=reliability_rating)](https://sonarcloud.io/dashboard?id=pioardi_poolifier)
52 [![Technical Debt](https://sonarcloud.io/api/project_badges/measure?project=pioardi_poolifier&metric=sqale_index)](https://sonarcloud.io/dashboard?id=pioardi_poolifier)
53
54 ## Contents
55
56 <h3 align="center">
57 <a href="#overview">Overview</a>
58 <span> · </span>
59 <a href="#installation">Installation</a>
60 <span> · </span>
61 <a href="#usage">Usage</a>
62 <span> · </span>
63 <a href="#node-versions"> Node versions</a>
64 <span> · </span>
65 <a href="#api">API</a>
66 <span> · </span>
67 <a href="#choose-your-pool">Choose your pool</a>
68 <span> · </span>
69 <a href="#contribute">Contribute</a>
70 <span> · </span>
71 <a href="#team">Team</a>
72 <span> · </span>
73 <a href="#license">License</a>
74 </h3>
75
76 ## Overview
77
78 Node 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.
79 The first implementation is a static worker pool, with a defined number of workers that are started at creation time and will be reused.
80 The 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.
81 You have to implement your worker extending the ThreadWorker or ClusterWorker class
82
83 ## Installation
84
85 ```shell
86 npm install poolifier --save
87 ```
88
89 ## Usage
90
91 You can implement a worker-threads worker in a simple way by extending the class ThreadWorker:
92
93 ```js
94 'use strict'
95 const { ThreadWorker } = require('poolifier')
96
97 function yourFunction (data) {
98 // this will be executed in the worker thread,
99 // the data will be received by using the execute method
100 return { ok: 1 }
101 }
102
103 module.exports = new ThreadWorker(yourFunction, {
104 maxInactiveTime: 60000,
105 async: false
106 })
107 ```
108
109 Instantiate your pool based on your needed :
110
111 ```js
112 'use strict'
113 const { FixedThreadPool, DynamicThreadPool } = require('poolifier')
114
115 // a fixed worker-threads pool
116 const pool = new FixedThreadPool(15,
117 './yourWorker.js',
118 { errorHandler: (e) => console.error(e), onlineHandler: () => console.log('worker is online') })
119
120 // or a dynamic worker-threads pool
121 const pool = new DynamicThreadPool(10, 100,
122 './yourWorker.js',
123 { errorHandler: (e) => console.error(e), onlineHandler: () => console.log('worker is online') })
124
125 pool.emitter.on('FullPool', () => console.log('Pool is full'))
126
127 // the execute method signature is the same for both implementations,
128 // so you can easy switch from one to another
129 pool.execute({}).then(res => {
130 console.log(res)
131 }).catch ....
132
133 ```
134
135 You can do the same with the classes ClusterWorker, FixedClusterPool and DynamicClusterPool.
136
137 **See examples folder for more details (in particular if you want to use a pool for [multiple functions](./examples/multiFunctionExample.js)).**
138 **Now TypeScript is also supported, find how to use it into the example folder**.
139
140 Remember that workers can only send and receive serializable data.
141
142 ## Node versions
143
144 You can use node versions 12.x, 13.x, 14.x
145
146 ## API
147
148 ### `pool = new FixedThreadPool/FixedClusterPool(numberOfThreads/numberOfWorkers, filePath, opts)`
149
150 `numberOfThreads/numberOfWorkers` (mandatory) Num of workers for this worker pool
151 `filePath` (mandatory) Path to a file with a worker implementation
152 `opts` (optional) An object with these properties :
153
154 - `errorHandler` - A function that will listen for error event on each worker
155 - `onlineHandler` - A function that will listen for online event on each worker
156 - `exitHandler` - A function that will listen for exit event on each worker
157 - `maxTasks` - This is just to avoid not useful warnings message, is used to set [maxListeners](https://nodejs.org/dist/latest-v12.x/docs/api/events.html#events_emitter_setmaxlisteners_n) on event emitters (workers are event emitters)
158
159 ### `pool = new DynamicThreadPool/DynamicClusterPool(min, max, filePath, opts)`
160
161 `min` (mandatory) Same as FixedThreadPool/FixedClusterPool numberOfThreads/numberOfWorkers, this number of workers will be always active
162 `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).
163 `filePath` (mandatory) Same as FixedThreadPool/FixedClusterPool
164 `opts` (optional) Same as FixedThreadPool/FixedClusterPool
165
166 ### `pool.execute(data)`
167
168 Execute method is available on both pool implementations (return type : Promise):
169 `data` (mandatory) An object that you want to pass to your worker implementation
170
171 ### `pool.destroy()`
172
173 Destroy method is available on both pool implementations.
174 This method will call the terminate method on each worker.
175
176 ### `class YourWorker extends ThreadWorker/ClusterWorker`
177
178 `fn` (mandatory) The function that you want to execute on the worker
179 `opts` (optional) An object with these properties:
180
181 - `maxInactiveTime` - Max time to wait tasks to work on (in ms), after this period the new worker will die.
182 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.
183 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.
184 If `killBehavior` is set to `KillBehaviors.SOFT` your tasks have no timeout and your workers will not be terminated until your task is completed.
185 Default: 60.000 ms
186
187 - `async` - true/false, true if your function contains async pieces else false
188 - `killBehavior` - Dictates if your async unit (worker/process) will be deleted in case that a task is active on it.
189 **SOFT**: If `currentTime - lastActiveTime` is greater than `maxInactiveTime` but a task is still running, then the worker **won't** be deleted.
190 **HARD**: If `lastActiveTime` is greater than `maxInactiveTime` but a task is still running, then the worker will be deleted.
191 This option only apply to the newly created workers.
192 Default: `SOFT`
193
194 ## Choose your pool
195
196 Performance is one of the main target of these worker pool implementations, we want to have a strong focus on this.
197 We already have a bench folder where you can find some comparisons.
198 To 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.
199 Increasing the memory footprint, your application will be ready to accept more CPU bound tasks, but during idle time your application will consume more memory.
200 One 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.
201 For 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.
202 But in general, **always profile your application**
203
204 ## Contribute
205
206 See guidelines [CONTRIBUTING](CONTRIBUTING.md)
207 Choose your task here [2.0.0](https://github.com/pioardi/poolifier/projects/1), propose an idea, a fix, an improvement.
208
209 ## Team
210
211 <!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
212 <!-- prettier-ignore-start -->
213 <!-- markdownlint-disable -->
214
215 **Creator/Owner:**
216
217 - [**Alessandro Pio Ardizio**](https://github.com/pioardi)
218
219 **_Contributors_**
220
221 - [**Shinigami92**](https://github.com/Shinigami92)
222 - [**Jérôme Benoit**](https://github.com/jerome-benoit)
223
224 ## License
225
226 [MIT](./LICENSE)