UNPKG

39.4 kBMarkdownView Raw
1# bottleneck
2
3[![Downloads][npm-downloads]][npm-url]
4[![version][npm-version]][npm-url]
5[![License][npm-license]][license-url]
6
7
8Bottleneck is a lightweight and zero-dependency Task Scheduler and Rate Limiter for Node.js and the browser.
9
10Bottleneck is an easy solution as it adds very little complexity to your code. It is battle-hardened, reliable and production-ready and used on a large scale in private companies and open source software.
11
12It supports **Clustering**: it can rate limit jobs across multiple Node.js instances. It uses Redis and strictly atomic operations to stay reliable in the presence of unreliable clients and networks. It also supports *Redis Cluster* and *Redis Sentinel*.
13
14**[Upgrading from version 1?](#upgrading-to-v2)**
15
16<!-- toc -->
17
18- [Install](#install)
19- [Quick Start](#quick-start)
20 * [Gotchas](#gotchas)
21- [Constructor](#constructor)
22- [`submit()`](#submit)
23- [`schedule()`](#schedule)
24- [`wrap()`](#wrap)
25- [Job Options](#job-options)
26- [Jobs Lifecycle](#jobs-lifecycle)
27- [Events](#events)
28- [Retries](#retries)
29- [`updateSettings()`](#updatesettings)
30- [`incrementReservoir()`](#incrementreservoir)
31- [`currentReservoir()`](#currentreservoir)
32- [`stop()`](#stop)
33- [`chain()`](#chain)
34- [Group](#group)
35- [Batching](#batching)
36- [Clustering](#clustering)
37- [Debugging Your Application](#debugging-your-application)
38- [Upgrading To v2](#upgrading-to-v2)
39- [Contributing](#contributing)
40
41<!-- tocstop -->
42
43## Install
44
45```
46npm install --save bottleneck
47```
48
49```js
50import Bottleneck from "bottleneck";
51
52// Note: To support older browsers and Node <6.0, you must import the ES5 bundle instead.
53var Bottleneck = require("bottleneck/es5");
54```
55
56## Quick Start
57
58### Step 1 of 3
59
60Most APIs have a rate limit. For example, to execute 3 requests per second:
61```js
62const limiter = new Bottleneck({
63 minTime: 333
64});
65```
66
67If there's a chance some requests might take longer than 333ms and you want to prevent more than 1 request from running at a time, add `maxConcurrent: 1`:
68```js
69const limiter = new Bottleneck({
70 maxConcurrent: 1,
71 minTime: 333
72});
73```
74
75Sometimes, a quota resets on an interval. In this example, we throttle to 100 requests every 60 seconds:
76```js
77const limiter = new Bottleneck({
78 reservoir: 100, // initial value
79 reservoirRefreshAmount: 100,
80 reservoirRefreshInterval: 60 * 1000, // must be divisible by 250
81
82 // also use maxConcurrent and/or minTime for safety
83 maxConcurrent: 1,
84 minTime: 333
85});
86```
87`reservoir` is a counter decremented every time a job is launched, we set its initial value to 100. Then, every `reservoirRefreshInterval` (60000 ms), `reservoir` is automatically reset to `reservoirRefreshAmount` (100).
88
89**IMPORTANT: refresh intervals are not a replacement for minTime/maxConcurrent!** It's strongly recommended to also use `minTime` and/or `maxConcurrent` to spread out the load. For example, suppose a lot of jobs are queued up because the `reservoir` is 0. As soon as the reservoir refresh is triggered, 100 jobs will automatically be launched, all at the same time! To prevent that and keep your application running smoothly, use `minTime` and `maxConcurrent` to *stagger* the jobs.
90
91**IMPORTANT: refresh intervals prevent a limiter from being garbage collected.** Call `limiter.disconnect()` to clear the interval and allow the memory to be freed.
92
93### Step 2 of 3
94
95#### ➤ Using callbacks?
96
97Instead of this:
98```js
99someAsyncCall(arg1, arg2, callback);
100```
101Do this:
102```js
103limiter.submit(someAsyncCall, arg1, arg2, callback);
104```
105
106#### ➤ Using promises?
107
108Instead of this:
109```js
110myFunction(arg1, arg2)
111.then((result) => {
112 /* handle result */
113});
114```
115Do this:
116```js
117limiter.schedule(() => myFunction(arg1, arg2))
118.then((result) => {
119 /* handle result */
120});
121```
122Or this:
123```js
124const wrapped = limiter.wrap(myFunction);
125
126wrapped(arg1, arg2)
127.then((result) => {
128 /* handle result */
129});
130```
131
132#### ➤ Using async/await?
133
134Instead of this:
135```js
136const result = await myFunction(arg1, arg2);
137```
138Do this:
139```js
140const result = await limiter.schedule(() => myFunction(arg1, arg2));
141```
142Or this:
143```js
144const wrapped = limiter.wrap(myFunction);
145
146const result = await wrapped(arg1, arg2);
147```
148
149### Step 3 of 3
150
151Remember...
152
153Bottleneck builds a queue of jobs and executes them as soon as possible. By default, the jobs will be executed in the order they were received.
154
155**Read the 'Gotchas' and you're good to go**. Or keep reading to learn about all the fine tuning and advanced options available. If your rate limits need to be enforced across a cluster of computers, read the [Clustering](#clustering) docs.
156
157[Need help debugging your application?](#debugging-your-application)
158
159Instead of throttling maybe [you want to batch up requests](#batching) into fewer calls?
160
161#### Gotchas
162
163* If you're passing an object's method as a job, you'll probably need to `bind()` the object:
164```js
165// instead of this:
166limiter.schedule(object.doSomething);
167// do this:
168limiter.schedule(object.doSomething.bind(object));
169// or, wrap it in an arrow function instead:
170limiter.schedule(() => object.doSomething());
171```
172
173* Bottleneck requires Node 6+ to function. However, an ES5 build is included: `var Bottleneck = require("bottleneck/es5");`.
174
175* Make sure you're catching `"error"` events emitted by your limiters!
176
177* Consider setting a `maxConcurrent` value instead of leaving it `null`. This can help your application's performance, especially if you think the limiter's queue might become very long.
178
179* **When using `submit()`**, if a callback isn't necessary, you must pass `null` or an empty function instead. It will not work otherwise.
180
181* **When using `submit()`**, make sure all the jobs will eventually complete by calling their callback, or set an [`expiration`](#job-options). Even if you submitted your job with a `null` callback , it still needs to call its callback. This is particularly important if you are using a `maxConcurrent` value that isn't `null` (unlimited), otherwise those not completed jobs will be clogging up the limiter and no new jobs will be allowed to run. It's safe to call the callback more than once, subsequent calls are ignored.
182
183## Docs
184
185### Constructor
186
187```js
188const limiter = new Bottleneck({/* options */});
189```
190
191Basic options:
192
193| Option | Default | Description |
194|--------|---------|-------------|
195| `maxConcurrent` | `null` (unlimited) | How many jobs can be executing at the same time. Consider setting a value instead of leaving it `null`, it can help your application's performance, especially if you think the limiter's queue might get very long. |
196| `minTime` | `0` ms | How long to wait after launching a job before launching another one. |
197| `highWater` | `null` (unlimited) | How long can the queue be? When the queue length exceeds that value, the selected `strategy` is executed to shed the load. |
198| `strategy` | `Bottleneck.strategy.LEAK` | Which strategy to use when the queue gets longer than the high water mark. [Read about strategies](#strategies). Strategies are never executed if `highWater` is `null`. |
199| `penalty` | `15 * minTime`, or `5000` when `minTime` is `0` | The `penalty` value used by the `BLOCK` strategy. |
200| `reservoir` | `null` (unlimited) | How many jobs can be executed before the limiter stops executing jobs. If `reservoir` reaches `0`, no jobs will be executed until it is no longer `0`. New jobs will still be queued up. |
201| `reservoirRefreshInterval` | `null` (disabled) | Every `reservoirRefreshInterval` milliseconds, the `reservoir` value will be automatically reset to `reservoirRefreshAmount`. The `reservoirRefreshInterval` value should be a [multiple of 250 (5000 for Clustering)](https://github.com/SGrondin/bottleneck/issues/88). |
202| `reservoirRefreshAmount` | `null` (disabled) | The value to reset `reservoir` to when `reservoirRefreshInterval` is in use. |
203| `Promise` | `Promise` (built-in) | This lets you override the Promise library used by Bottleneck. |
204
205
206### submit()
207
208Adds a job to the queue. This is the callback version of `schedule()`.
209```js
210limiter.submit(someAsyncCall, arg1, arg2, callback);
211```
212You can pass `null` instead of an empty function if there is no callback, but `someAsyncCall` still needs to call **its** callback to let the limiter know it has completed its work.
213
214`submit()` can also accept [advanced options](#job-options).
215
216### schedule()
217
218Adds a job to the queue. This is the Promise and async/await version of `submit()`.
219```js
220const fn = function(arg1, arg2) {
221 return httpGet(arg1, arg2); // Here httpGet() returns a promise
222};
223
224limiter.schedule(fn, arg1, arg2)
225.then((result) => {
226 /* ... */
227});
228```
229In other words, `schedule()` takes a function **fn** and a list of arguments. `schedule()` returns a promise that will be executed according to the rate limits.
230
231`schedule()` can also accept [advanced options](#job-options).
232
233Here's another example:
234```js
235// suppose that `client.get(url)` returns a promise
236
237const url = "https://wikipedia.org";
238
239limiter.schedule(() => client.get(url))
240.then(response => console.log(response.body));
241```
242
243### wrap()
244
245Takes a function that returns a promise. Returns a function identical to the original, but rate limited.
246```js
247const wrapped = limiter.wrap(fn);
248
249wrapped()
250.then(function (result) {
251 /* ... */
252})
253.catch(function (error) {
254 // Bottleneck might need to fail the job even if the original function can never fail.
255 // For example, your job is taking longer than the `expiration` time you've set.
256});
257```
258
259### Job Options
260
261`submit()`, `schedule()`, and `wrap()` all accept advanced options.
262```js
263// Submit
264limiter.submit({/* options */}, someAsyncCall, arg1, arg2, callback);
265
266// Schedule
267limiter.schedule({/* options */}, fn, arg1, arg2);
268
269// Wrap
270const wrapped = limiter.wrap(fn);
271wrapped.withOptions({/* options */}, arg1, arg2);
272```
273
274| Option | Default | Description |
275|--------|---------|-------------|
276| `priority` | `5` | A priority between `0` and `9`. A job with a priority of `4` will be queued ahead of a job with a priority of `5`. **Important:** You must set a low `maxConcurrent` value for priorities to work, otherwise there is nothing to queue because jobs will be be scheduled immediately! |
277| `weight` | `1` | Must be an integer equal to or higher than `0`. The `weight` is what increases the number of running jobs (up to `maxConcurrent`) and decreases the `reservoir` value. |
278| `expiration` | `null` (unlimited) | The number of milliseconds a job is given to complete. Jobs that execute for longer than `expiration` ms will be failed with a `BottleneckError`. |
279| `id` | `<no-id>` | You should give an ID to your jobs, it helps with [debugging](#debugging-your-application). |
280
281### Strategies
282
283A strategy is a simple algorithm that is executed every time adding a job would cause the number of queued jobs to exceed `highWater`. Strategies are never executed if `highWater` is `null`.
284
285#### Bottleneck.strategy.LEAK
286When adding a new job to a limiter, if the queue length reaches `highWater`, drop the oldest job with the lowest priority. This is useful when jobs that have been waiting for too long are not important anymore. If all the queued jobs are more important (based on their `priority` value) than the one being added, it will not be added.
287
288#### Bottleneck.strategy.OVERFLOW_PRIORITY
289Same as `LEAK`, except it will only drop jobs that are *less important* than the one being added. If all the queued jobs are as or more important than the new one, it will not be added.
290
291#### Bottleneck.strategy.OVERFLOW
292When adding a new job to a limiter, if the queue length reaches `highWater`, do not add the new job. This strategy totally ignores priority levels.
293
294#### Bottleneck.strategy.BLOCK
295When adding a new job to a limiter, if the queue length reaches `highWater`, the limiter falls into "blocked mode". All queued jobs are dropped and no new jobs will be accepted until the limiter unblocks. It will unblock after `penalty` milliseconds have passed without receiving a new job. `penalty` is equal to `15 * minTime` (or `5000` if `minTime` is `0`) by default. This strategy is ideal when bruteforce attacks are to be expected. This strategy totally ignores priority levels.
296
297
298### Jobs lifecycle
299
3001. **Received**. You new job has been added to your limiter. Bottleneck needs to check whether if can be accepted into the queue.
3012. **Queued**. Bottleneck has accepted your job, but it can not tell at what exact timestamp it will run yet, because it is dependent on previous jobs.
3023. **Running**. Your job is not in the queue anymore, it will be executed after a delay that was computed according to your `minTime` setting.
3034. **Executing**. Your job is executing its code.
3045. **Done**. Your job has completed.
305
306**Note:** By default, Bottleneck does not keep track of DONE jobs, to save memory. You can enable this feature by passing `trackDoneStatus: true` as an option when creating a limiter.
307
308#### counts()
309
310```js
311const counts = limiter.counts();
312
313console.log(counts);
314/*
315{
316 RECEIVED: 0,
317 QUEUED: 0,
318 RUNNING: 0,
319 EXECUTING: 0,
320 DONE: 0
321}
322*/
323```
324
325Returns an object with the current number of jobs per status in the limiter.
326
327#### jobStatus()
328
329```js
330console.log(limiter.jobStatus("some-job-id"));
331// Example: QUEUED
332```
333
334Returns the status of the job with the provided job id **in the limiter**. Returns `null` if no job with that id exist.
335
336#### jobs()
337
338```js
339console.log(limiter.jobs("RUNNING"));
340// Example: ['id1', 'id2']
341```
342
343Returns an array of all the job ids with the specified status **in the limiter**. Not passing a status string returns all the known ids.
344
345#### queued()
346
347```js
348const count = limiter.queued(priority);
349
350console.log(count);
351```
352
353`priority` is optional. Returns the number of `QUEUED` jobs with the given `priority` level. Omitting the `priority` argument returns the total number of queued jobs **in the limiter**.
354
355#### clusterQueued()
356
357```js
358const count = await limiter.clusterQueued();
359
360console.log(count);
361```
362
363Returns the number of `QUEUED` jobs **in the Cluster**.
364
365#### empty()
366
367```js
368if (limiter.empty()) {
369 // do something...
370}
371```
372
373Returns a boolean which indicates whether there are any `RECEIVED` or `QUEUED` jobs **in the limiter**.
374
375#### running()
376
377```js
378limiter.running()
379.then((count) => console.log(count));
380```
381
382Returns a promise that returns the **total weight** of the `RUNNING` and `EXECUTING` jobs **in the Cluster**.
383
384#### done()
385
386```js
387limiter.done()
388.then((count) => console.log(count));
389```
390
391Returns a promise that returns the **total weight** of `DONE` jobs **in the Cluster**. Does not require passing the `trackDoneStatus: true` option.
392
393#### check()
394
395```js
396limiter.check()
397.then((wouldRunNow) => console.log(wouldRunNow));
398```
399Checks if a new job would be executed immediately if it was submitted now. Returns a promise that returns a boolean.
400
401
402### Events
403
404Event names: `"error"`, `"empty"`, `"idle"`, `"dropped"`, `"depleted"` and `"debug"`.
405
406__'error'__
407```js
408limiter.on("error", function (error) {
409 /* handle errors here */
410});
411```
412
413The two main causes of error events are: uncaught exceptions in your event handlers, and network errors when Clustering is enabled.
414
415__'failed'__
416```js
417limiter.on("failed", function (error, jobInfo) {
418 // This will be called every time a job fails.
419});
420```
421
422__'retry'__
423
424See [Retries](#retries) to learn how to automatically retry jobs.
425```js
426limiter.on("retry", function (error, jobInfo) {
427 // This will be called every time a job is retried.
428});
429```
430
431__'empty'__
432```js
433limiter.on("empty", function () {
434 // This will be called when `limiter.empty()` becomes true.
435});
436```
437
438__'idle'__
439```js
440limiter.on("idle", function () {
441 // This will be called when `limiter.empty()` is `true` and `limiter.running()` is `0`.
442});
443```
444
445__'dropped'__
446```js
447limiter.on("dropped", function (dropped) {
448 // This will be called when a strategy was triggered.
449 // The dropped request is passed to this event listener.
450});
451```
452
453__'depleted'__
454```js
455limiter.on("depleted", function (empty) {
456 // This will be called every time the reservoir drops to 0.
457 // The `empty` (boolean) argument indicates whether `limiter.empty()` is currently true.
458});
459```
460
461__'debug'__
462```js
463limiter.on("debug", function (message, data) {
464 // Useful to figure out what the limiter is doing in real time
465 // and to help debug your application
466});
467```
468
469Use `removeAllListeners()` with an optional event name as first argument to remove listeners.
470
471Use `.once()` instead of `.on()` to only receive a single event.
472
473
474### Retries
475
476The following example:
477```js
478const limiter = new Bottleneck();
479
480// Listen to the "failed" event
481limiter.on("failed", async (error, jobInfo) => {
482 const id = jobInfo.options.id;
483 console.warn(`Job ${id} failed: ${error}`);
484
485 if (jobInfo.retryCount === 0) { // Here we only retry once
486 console.log(`Retrying job ${id} in 25ms!`);
487 return 25;
488 }
489});
490
491// Listen to the "retry" event
492limiter.on("retry", (error, jobInfo) => console.log(`Now retrying ${jobInfo.options.id}`));
493
494const main = async function () {
495 let executions = 0;
496
497 // Schedule one job
498 const result = await limiter.schedule({ id: 'ABC123' }, async () => {
499 executions++;
500 if (executions === 1) {
501 throw new Error("Boom!");
502 } else {
503 return "Success!";
504 }
505 });
506
507 console.log(`Result: ${result}`);
508}
509
510main();
511```
512will output
513```
514Job ABC123 failed: Error: Boom!
515Retrying job ABC123 in 25ms!
516Now retrying ABC123
517Result: Success!
518```
519To re-run your job, simply return an integer from the `'failed'` event handler. The number returned is how many milliseconds to wait before retrying it. Return `0` to retry it immediately.
520
521**IMPORTANT:** When you ask the limiter to retry a job it will not send it back into the queue. It will stay in the `EXECUTING` [state](#jobs-lifecycle) until it succeeds or until you stop retrying it. **This means that it counts as a concurrent job for `maxConcurrent` even while it's just waiting to be retried.** The number of milliseconds to wait ignores your `minTime` settings.
522
523
524### updateSettings()
525
526```js
527limiter.updateSettings(options);
528```
529The options are the same as the [limiter constructor](#constructor).
530
531**Note:** Changes don't affect `SCHEDULED` jobs.
532
533### incrementReservoir()
534
535```js
536limiter.incrementReservoir(incrementBy);
537```
538Returns a promise that returns the new reservoir value.
539
540### currentReservoir()
541
542```js
543limiter.currentReservoir()
544.then((reservoir) => console.log(reservoir));
545```
546Returns a promise that returns the current reservoir value.
547
548### stop()
549
550The `stop()` method is used to safely shutdown a limiter. It prevents any new jobs from being added to the limiter and waits for all `EXECUTING` jobs to complete.
551
552```js
553limiter.stop(options)
554.then(() => {
555 console.log("Shutdown completed!")
556});
557```
558
559`stop()` returns a promise that resolves once all the `EXECUTING` jobs have completed and, if desired, once all non-`EXECUTING` jobs have been dropped.
560
561| Option | Default | Description |
562|--------|---------|-------------|
563| `dropWaitingJobs` | `true` | When `true`, drop all the `RECEIVED`, `QUEUED` and `RUNNING` jobs. When `false`, allow those jobs to complete before resolving the Promise returned by this method. |
564| `dropErrorMessage` | `This limiter has been stopped.` | The error message used to drop jobs when `dropWaitingJobs` is `true`. |
565| `enqueueErrorMessage` | `This limiter has been stopped and cannot accept new jobs.` | The error message used to reject a job added to the limiter after `stop()` has been called. |
566
567### chain()
568
569Tasks that are ready to be executed will be added to that other limiter. Suppose you have 2 types of tasks, A and B. They both have their own limiter with their own settings, but both must also follow a global limiter G:
570```js
571const limiterA = new Bottleneck( /* some settings */ );
572const limiterB = new Bottleneck( /* some different settings */ );
573const limiterG = new Bottleneck( /* some global settings */ );
574
575limiterA.chain(limiterG);
576limiterB.chain(limiterG);
577
578// Requests added to limiterA must follow the A and G rate limits.
579// Requests added to limiterB must follow the B and G rate limits.
580// Requests added to limiterG must follow the G rate limits.
581```
582
583To unchain, call `limiter.chain(null);`.
584
585## Group
586
587The `Group` feature of Bottleneck manages many limiters automatically for you. It creates limiters dynamically and transparently.
588
589Let's take a DNS server as an example of how Bottleneck can be used. It's a service that sees a lot of abuse and where incoming DNS requests need to be rate limited. Bottleneck is so tiny, it's acceptable to create one limiter for each origin IP, even if it means creating thousands of limiters. The `Group` feature is perfect for this use case. Create one Group and use the origin IP to rate limit each IP independently. Each call with the same key (IP) will be routed to the same underlying limiter. A Group is created like a limiter:
590
591
592```js
593const group = new Bottleneck.Group(options);
594```
595
596The `options` object will be used for every limiter created by the Group.
597
598The Group is then used with the `.key(str)` method:
599
600```js
601// In this example, the key is an IP
602group.key("77.66.54.32").schedule(() => {
603 /* process the request */
604});
605```
606
607#### key()
608
609* `str` : The key to use. All jobs added with the same key will use the same underlying limiter. *Default: `""`*
610
611The return value of `.key(str)` is a limiter. If it doesn't already exist, it is generated for you. Calling `key()` is how limiters are created inside a Group.
612
613Limiters that have been idle for longer than 5 minutes are deleted to avoid memory leaks, this value can be changed by passing a different `timeout` option, in milliseconds.
614
615#### on("created")
616
617```js
618group.on("created", (limiter, key) => {
619 console.log("A new limiter was created for key: " + key)
620
621 // Prepare the limiter, for example we'll want to listen to its "error" events!
622 limiter.on("error", (err) => {
623 // Handle errors here
624 })
625});
626```
627
628Listening for the `"created"` event is the recommended way to set up a new limiter. Your event handler is executed before `key()` returns the newly created limiter.
629
630#### updateSettings()
631
632```js
633const group = new Bottleneck.Group({ maxConcurrent: 2, minTime: 250 });
634group.updateSettings({ minTime: 500 });
635```
636After executing the above commands, **new limiters** will be created with `{ maxConcurrent: 2, minTime: 500 }`.
637
638
639#### deleteKey()
640
641* `str`: The key for the limiter to delete.
642
643Manually deletes the limiter at the specified key. When using Clustering, the Redis data is immediately deleted and the other Groups in the Cluster will eventually delete their local key automatically, unless it is still being used.
644
645#### keys()
646
647Returns an array containing all the keys in the Group.
648
649#### clusterKeys()
650
651Same as `group.keys()`, but returns all keys in this Group ID across the Cluster.
652
653#### limiters()
654
655```js
656const limiters = group.limiters();
657
658console.log(limiters);
659// [ { key: "some key", limiter: <limiter> }, { key: "some other key", limiter: <some other limiter> } ]
660```
661
662## Batching
663
664Some APIs can accept multiple operations in a single call. Bottleneck's Batching feature helps you take advantage of those APIs:
665```js
666const batcher = new Bottleneck.Batcher({
667 maxTime: 1000,
668 maxSize: 10
669});
670
671batcher.on("batch", (batch) => {
672 console.log(batch); // ["some-data", "some-other-data"]
673
674 // Handle batch here
675});
676
677batcher.add("some-data");
678batcher.add("some-other-data");
679```
680
681`batcher.add()` returns a Promise that resolves once the request has been flushed to a `"batch"` event.
682
683| Option | Default | Description |
684|--------|---------|-------------|
685| `maxTime` | `null` (unlimited) | Maximum acceptable time (in milliseconds) a request can have to wait before being flushed to the `"batch"` event. |
686| `maxSize` | `null` (unlimited) | Maximum number of requests in a batch. |
687
688Batching doesn't throttle requests, it only groups them up optimally according to your `maxTime` and `maxSize` settings.
689
690## Clustering
691
692Clustering lets many limiters access the same shared state, stored in Redis. Changes to the state are Atomic, Consistent and Isolated (and fully [ACID](https://en.wikipedia.org/wiki/ACID) with the right [Durability](https://redis.io/topics/persistence) configuration), to eliminate any chances of race conditions or state corruption. Your settings, such as `maxConcurrent`, `minTime`, etc., are shared across the whole cluster, which means —for example— that `{ maxConcurrent: 5 }` guarantees no more than 5 jobs can ever run at a time in the entire cluster of limiters. 100% of Bottleneck's features are supported in Clustering mode. Enabling Clustering is as simple as changing a few settings. It's also a convenient way to store or export state for later use.
693
694Bottleneck will attempt to spread load evenly across limiters.
695
696### Enabling Clustering
697
698First, add `redis` or `ioredis` to your application's dependencies:
699```bash
700# NodeRedis (https://github.com/NodeRedis/node_redis)
701npm install --save redis
702
703# or ioredis (https://github.com/luin/ioredis)
704npm install --save ioredis
705```
706Then create a limiter or a Group:
707```js
708const limiter = new Bottleneck({
709 /* Some basic options */
710 maxConcurrent: 5,
711 minTime: 500
712 id: "my-super-app" // All limiters with the same id will be clustered together
713
714 /* Clustering options */
715 datastore: "redis", // or "ioredis"
716 clearDatastore: false,
717 clientOptions: {
718 host: "127.0.0.1",
719 port: 6379
720
721 // Redis client options
722 // Using NodeRedis? See https://github.com/NodeRedis/node_redis#options-object-properties
723 // Using ioredis? See https://github.com/luin/ioredis/blob/master/API.md#new-redisport-host-options
724 }
725});
726```
727
728| Option | Default | Description |
729|--------|---------|-------------|
730| `datastore` | `"local"` | Where the limiter stores its internal state. The default (`"local"`) keeps the state in the limiter itself. Set it to `"redis"` or `"ioredis"` to enable Clustering. |
731| `clearDatastore` | `false` | When set to `true`, on initial startup, the limiter will wipe any existing Bottleneck state data on the Redis db. |
732| `clientOptions` | `{}` | This object is passed directly to the redis client library you've selected. |
733| `clusterNodes` | `null` | **ioredis only.** When `clusterNodes` is not null, the client will be instantiated by calling `new Redis.Cluster(clusterNodes, clientOptions)` instead of `new Redis(clientOptions)`. |
734| `timeout` | `null` (no TTL) | The Redis TTL in milliseconds ([TTL](https://redis.io/commands/ttl)) for the keys created by the limiter. When `timeout` is set, the limiter's state will be automatically removed from Redis after `timeout` milliseconds of inactivity. |
735
736**Note: When using Groups**, the `timeout` option has a default of `300000` milliseconds and the generated limiters automatically receive an `id` with the pattern `${group.id}-${KEY}`.
737
738### Important considerations when Clustering
739
740The first limiter connecting to Redis will store its [constructor options](#constructor) on Redis and all subsequent limiters will be using those settings. You can alter the constructor options used by all the connected limiters by calling `updateSettings()`. The `clearDatastore` option instructs a new limiter to wipe any previous Bottleneck data (for that `id`), including previously stored settings.
741
742Queued jobs are **NOT** stored on Redis. They are local to each limiter. Exiting the Node.js process will lose those jobs. This is because Bottleneck has no way to propagate the JS code to run a job across a different Node.js process than the one it originated on. Bottleneck doesn't keep track of the queue contents of the limiters on a cluster for performance and reliability reasons. You can use something like [`BeeQueue`](https://github.com/bee-queue/bee-queue) in addition to Bottleneck to get around this limitation.
743
744Due to the above, functionality relying on the queue length happens purely locally:
745- Priorities are local. A higher priority job will run before a lower priority job **on the same limiter**. Another limiter on the cluster might run a lower priority job before our higher priority one.
746- Assuming constant priority levels, Bottleneck guarantees that jobs will be run in the order they were received **on the same limiter**. Another limiter on the cluster might run a job received later before ours runs.
747- `highWater` and load shedding ([strategies](#strategies)) are per limiter. However, one limiter entering Blocked mode will put the entire cluster in Blocked mode until `penalty` milliseconds have passed. See [Strategies](#strategies).
748- The `"empty"` event is triggered when the (local) queue is empty.
749- The `"idle"` event is triggered when the (local) queue is empty *and* no jobs are currently running anywhere in the cluster.
750
751You must work around these limitations in your application code if they are an issue to you. The `publish()` method could be useful here.
752
753The current design guarantees reliability, is highly performant and lets limiters come and go. Your application can scale up or down, and clients can be disconnected at any time without issues.
754
755It is **strongly recommended** that you give an `id` to every limiter and Group since it is used to build the name of your limiter's Redis keys! Limiters with the same `id` inside the same Redis db will be sharing the same datastore.
756
757It is **strongly recommended** that you set an `expiration` (See [Job Options](#job-options)) *on every job*, since that lets the cluster recover from crashed or disconnected clients. Otherwise, a client crashing while executing a job would not be able to tell the cluster to decrease its number of "running" jobs. By using expirations, those lost jobs are automatically cleared after the specified time has passed. Using expirations is essential to keeping a cluster reliable in the face of unpredictable application bugs, network hiccups, and so on.
758
759Network latency between Node.js and Redis is not taken into account when calculating timings (such as `minTime`). To minimize the impact of latency, Bottleneck performs the absolute minimum number of state accesses. Keeping the Redis server close to your limiters will help you get a more consistent experience. Keeping the system time consistent across all clients will also help.
760
761It is **strongly recommended** to [set up an `"error"` listener](#events) on all your limiters and on your Groups.
762
763### Clustering Methods
764
765The `ready()`, `publish()` and `clients()` methods also exist when using the `local` datastore, for code compatibility reasons: code written for `redis`/`ioredis` won't break with `local`.
766
767#### ready()
768
769This method returns a promise that resolves once the limiter is connected to Redis.
770
771As of v2.9.0, it's no longer necessary to wait for `.ready()` to resolve before issuing commands to a limiter. The commands will be queued until the limiter successfully connects. Make sure to listen to the `"error"` event to handle connection errors.
772
773```js
774const limiter = new Bottleneck({/* options */});
775
776limiter.on("error", (err) => {
777 // handle network errors
778});
779
780limiter.ready()
781.then(() => {
782 // The limiter is ready
783});
784```
785
786#### publish(message)
787
788This method broadcasts the `message` string to every limiter in the Cluster. It returns a promise.
789```js
790const limiter = new Bottleneck({/* options */});
791
792limiter.on("message", (msg) => {
793 console.log(msg); // prints "this is a string"
794});
795
796limiter.publish("this is a string");
797```
798
799To send objects, stringify them first:
800```js
801limiter.on("message", (msg) => {
802 console.log(JSON.parse(msg).hello) // prints "world"
803});
804
805limiter.publish(JSON.stringify({ hello: "world" }));
806```
807
808#### clients()
809
810If you need direct access to the redis clients, use `.clients()`:
811```js
812console.log(limiter.clients());
813// { client: <Redis Client>, subscriber: <Redis Client> }
814```
815
816### Additional Clustering information
817
818- Bottleneck is compatible with [Redis Clusters](https://redis.io/topics/cluster-tutorial), but you must use the `ioredis` datastore and the `clusterNodes` option.
819- Bottleneck is compatible with Redis Sentinel, but you must use the `ioredis` datastore.
820- Bottleneck's data is stored in Redis keys starting with `b_`. It also uses pubsub channels starting with `b_` It will not interfere with any other data stored on the server.
821- Bottleneck loads a few Lua scripts on the Redis server using the `SCRIPT LOAD` command. These scripts only take up a few Kb of memory. Running the `SCRIPT FLUSH` command will cause any connected limiters to experience critical errors until a new limiter connects to Redis and loads the scripts again.
822- The Lua scripts are highly optimized and designed to use as few resources as possible.
823
824### Managing Redis Connections
825
826Bottleneck needs to create 2 Redis Clients to function, one for normal operations and one for pubsub subscriptions. These 2 clients are kept in a `Bottleneck.RedisConnection` (NodeRedis) or a `Bottleneck.IORedisConnection` (ioredis) object, referred to as the Connection object.
827
828By default, every Group and every standalone limiter (a limiter not created by a Group) will create their own Connection object, but it is possible to manually control this behavior. In this example, every Group and limiter is sharing the same Connection object and therefore the same 2 clients:
829```js
830const connection = new Bottleneck.RedisConnection({
831 clientOptions: {/* NodeRedis/ioredis options */}
832 // ioredis also accepts `clusterNodes` here
833});
834
835
836const limiter = new Bottleneck({ connection: connection });
837const group = new Bottleneck.Group({ connection: connection });
838```
839You can access and reuse the Connection object of any Group or limiter:
840```js
841const group = new Bottleneck.Group({ connection: limiter.connection });
842```
843When a Connection object is created manually, the connectivity `"error"` events are emitted on the Connection itself.
844```js
845connection.on("error", (err) => { /* handle connectivity errors here */ });
846```
847If you already have a NodeRedis/ioredis client, you can ask Bottleneck to reuse it, although currently the Connection object will still create a second client for pubsub operations:
848```js
849import Redis from "redis";
850const client = new Redis.createClient({/* options */});
851
852const connection = new Bottleneck.RedisConnection({
853 // `clientOptions` and `clusterNodes` will be ignored since we're passing a raw client
854 client: client
855});
856
857const limiter = new Bottleneck({ connection: connection });
858const group = new Bottleneck.Group({ connection: connection });
859```
860Depending on your application, using more clients can improve performance.
861
862Use the `disconnect(flush)` method to close the Redis clients.
863```js
864limiter.disconnect();
865group.disconnect();
866```
867If you created the Connection object manually, you need to call `connection.disconnect()` instead, for safety reasons.
868
869## Debugging your application
870
871Debugging complex scheduling logic can be difficult, especially when priorities, weights, and network latency all interact with one another.
872
873If your application is not behaving as expected, start by making sure you're catching `"error"` [events emitted](#events) by your limiters and your Groups. Those errors are most likely uncaught exceptions from your application code.
874
875Make sure you've read the ['Gotchas'](#gotchas) section.
876
877To see exactly what a limiter is doing in real time, listen to the `"debug"` event. It contains detailed information about how the limiter is executing your code. Adding [job IDs](#job-options) to all your jobs makes the debug output more readable.
878
879When Bottleneck has to fail one of your jobs, it does so by using `BottleneckError` objects. This lets you tell those errors apart from your own code's errors:
880```js
881limiter.schedule(fn)
882.then((result) => { /* ... */ } )
883.catch((error) => {
884 if (error instanceof Bottleneck.BottleneckError) {
885 /* ... */
886 }
887});
888```
889
890## Upgrading to v2
891
892The internal algorithms essentially haven't changed from v1, but many small changes to the interface were made to introduce new features.
893
894All the breaking changes:
895- Bottleneck v2 requires Node 6+ or a modern browser. Use `require("bottleneck/es5")` if you need ES5 support in v2. Bottleneck v1 will continue to use ES5 only.
896- The Bottleneck constructor now takes an options object. See [Constructor](#constructor).
897- The `Cluster` feature is now called `Group`. This is to distinguish it from the new v2 [Clustering](#clustering) feature.
898- The `Group` constructor takes an options object to match the limiter constructor.
899- Jobs take an optional options object. See [Job options](#job-options).
900- Removed `submitPriority()`, use `submit()` with an options object instead.
901- Removed `schedulePriority()`, use `schedule()` with an options object instead.
902- The `rejectOnDrop` option is now `true` by default. It can be set to `false` if you wish to retain v1 behavior. However this option is left undocumented as enabling it is considered to be a poor practice.
903- Use `null` instead of `0` to indicate an unlimited `maxConcurrent` value.
904- Use `null` instead of `-1` to indicate an unlimited `highWater` value.
905- Renamed `changeSettings()` to `updateSettings()`, it now returns a promise to indicate completion. It takes the same options object as the constructor.
906- Renamed `nbQueued()` to `queued()`.
907- Renamed `nbRunning` to `running()`, it now returns its result using a promise.
908- Removed `isBlocked()`.
909- Changing the Promise library is now done through the options object like any other limiter setting.
910- Removed `changePenalty()`, it is now done through the options object like any other limiter setting.
911- Removed `changeReservoir()`, it is now done through the options object like any other limiter setting.
912- Removed `stopAll()`. Use the new `stop()` method.
913- `check()` now accepts an optional `weight` argument, and returns its result using a promise.
914- Removed the `Group` `changeTimeout()` method. Instead, pass a `timeout` option when creating a Group.
915
916Version 2 is more user-friendly and powerful.
917
918After upgrading your code, please take a minute to read the [Debugging your application](#debugging-your-application) chapter.
919
920
921## Contributing
922
923This README is always in need of improvements. If wording can be clearer and simpler, please consider forking this repo and submitting a Pull Request, or simply opening an issue.
924
925Suggestions and bug reports are also welcome.
926
927To work on the Bottleneck code, simply clone the repo, makes your changes to the files located in `src/` only, then run `./scripts/build.sh && npm test` to ensure that everything is set up correctly.
928
929To speed up compilation time during development, run `./scripts/build.sh dev` instead. Make sure to build and test without `dev` before submitting a PR.
930
931The tests must also pass in Clustering mode and using the ES5 bundle. You'll need a Redis server running locally (latency needs to be minimal to run the tests). If the server isn't using the default hostname and port, you can set those in the `.env` file. Then run `./scripts/build.sh && npm run test-all`.
932
933All contributions are appreciated and will be considered.
934
935[license-url]: https://github.com/SGrondin/bottleneck/blob/master/LICENSE
936
937[npm-url]: https://www.npmjs.com/package/bottleneck
938[npm-license]: https://img.shields.io/npm/l/bottleneck.svg?style=flat
939[npm-version]: https://img.shields.io/npm/v/bottleneck.svg?style=flat
940[npm-downloads]: https://img.shields.io/npm/dm/bottleneck.svg?style=flat