UNPKG

41 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 & Common Mistakes](#gotchas--common-mistakes)
21- [Constructor](#constructor)
22- [Refresh Intervals](#refresh-intervals)
23- [`submit()`](#submit)
24- [`schedule()`](#schedule)
25- [`wrap()`](#wrap)
26- [Job Options](#job-options)
27- [Jobs Lifecycle](#jobs-lifecycle)
28- [Events](#events)
29- [Retries](#retries)
30- [`updateSettings()`](#updatesettings)
31- [`incrementReservoir()`](#incrementreservoir)
32- [`currentReservoir()`](#currentreservoir)
33- [`stop()`](#stop)
34- [`chain()`](#chain)
35- [Group](#group)
36- [Batching](#batching)
37- [Clustering](#clustering)
38- [Debugging Your Application](#debugging-your-application)
39- [Upgrading To v2](#upgrading-to-v2)
40- [Contributing](#contributing)
41
42<!-- tocstop -->
43
44## Install
45
46```
47npm install --save bottleneck
48```
49
50```js
51import Bottleneck from "bottleneck";
52
53// Note: To support older browsers and Node <6.0, you must import the ES5 bundle instead.
54var Bottleneck = require("bottleneck/es5");
55```
56
57## Quick Start
58
59### Step 1 of 3
60
61Most APIs have a rate limit. For example, to execute 3 requests per second:
62```js
63const limiter = new Bottleneck({
64 minTime: 333
65});
66```
67
68If 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`:
69```js
70const limiter = new Bottleneck({
71 maxConcurrent: 1,
72 minTime: 333
73});
74```
75
76`minTime` and `maxConcurrent` are enough for the majority of use cases. They work well together to ensure a smooth rate of requests. If your use case requires executing requests in **bursts** or every time a quota resets, look into [Refresh Intervals](#refresh-intervals).
77
78### Step 2 of 3
79
80#### ➤ Using promises?
81
82Instead of this:
83```js
84myFunction(arg1, arg2)
85.then((result) => {
86 /* handle result */
87});
88```
89Do this:
90```js
91limiter.schedule(() => myFunction(arg1, arg2))
92.then((result) => {
93 /* handle result */
94});
95```
96Or this:
97```js
98const wrapped = limiter.wrap(myFunction);
99
100wrapped(arg1, arg2)
101.then((result) => {
102 /* handle result */
103});
104```
105
106#### ➤ Using async/await?
107
108Instead of this:
109```js
110const result = await myFunction(arg1, arg2);
111```
112Do this:
113```js
114const result = await limiter.schedule(() => myFunction(arg1, arg2));
115```
116Or this:
117```js
118const wrapped = limiter.wrap(myFunction);
119
120const result = await wrapped(arg1, arg2);
121```
122
123#### ➤ Using callbacks?
124
125Instead of this:
126```js
127someAsyncCall(arg1, arg2, callback);
128```
129Do this:
130```js
131limiter.submit(someAsyncCall, arg1, arg2, callback);
132```
133
134### Step 3 of 3
135
136Remember...
137
138Bottleneck 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.
139
140**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.
141
142[Need help debugging your application?](#debugging-your-application)
143
144Instead of throttling maybe [you want to batch up requests](#batching) into fewer calls?
145
146### Gotchas & Common Mistakes
147
148* Make sure the function you pass to `schedule()` or `wrap()` only returns once **all the work it does** has completed.
149
150Instead of this:
151```js
152limiter.schedule(() => {
153 tasksArray.forEach(x => processTask(x));
154 // BAD, we return before our processTask() functions are finished processing!
155});
156```
157Do this:
158```js
159limiter.schedule(() => {
160 const allTasks = tasksArray.map(x => processTask(x));
161 // GOOD, we wait until all tasks are done.
162 return Promise.all(allTasks);
163});
164```
165
166* If you're passing an object's method as a job, you'll probably need to `bind()` the object:
167```js
168// instead of this:
169limiter.schedule(object.doSomething);
170// do this:
171limiter.schedule(object.doSomething.bind(object));
172// or, wrap it in an arrow function instead:
173limiter.schedule(() => object.doSomething());
174```
175
176* Bottleneck requires Node 6+ to function. However, an ES5 build is included: `var Bottleneck = require("bottleneck/es5");`.
177
178* Make sure you're catching `"error"` events emitted by your limiters!
179
180* 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.
181
182* If you plan on using `priorities`, make sure to set a `maxConcurrent` value.
183
184* **When using `submit()`**, if a callback isn't necessary, you must pass `null` or an empty function instead. It will not work otherwise.
185
186* **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.
187
188## Docs
189
190### Constructor
191
192```js
193const limiter = new Bottleneck({/* options */});
194```
195
196Basic options:
197
198| Option | Default | Description |
199|--------|---------|-------------|
200| `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. |
201| `minTime` | `0` ms | How long to wait after launching a job before launching another one. |
202| `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. |
203| `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`. |
204| `penalty` | `15 * minTime`, or `5000` when `minTime` is `0` | The `penalty` value used by the `BLOCK` strategy. |
205| `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. |
206| `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). |
207| `reservoirRefreshAmount` | `null` (disabled) | The value to reset `reservoir` to when `reservoirRefreshInterval` is in use. |
208| `Promise` | `Promise` (built-in) | This lets you override the Promise library used by Bottleneck. |
209
210
211### Refresh Intervals
212
213Refresh Intervals let you execute requests in bursts, by resetting a quota on an interval. In this example, we throttle to 100 requests every 60 seconds:
214```js
215const limiter = new Bottleneck({
216 reservoir: 100, // initial value
217 reservoirRefreshAmount: 100,
218 reservoirRefreshInterval: 60 * 1000, // must be divisible by 250
219
220 // also use maxConcurrent and/or minTime for safety
221 maxConcurrent: 1,
222 minTime: 333
223});
224```
225`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).
226
227Refresh Intervals are an advanced feature, please take the time to read and understand the following warnings.
228
229- **Refresh Intervals are not a replacement for `minTime` and `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 this flooding effect and keep your application running smoothly, use `minTime` and `maxConcurrent` to *stagger* the jobs.
230
231- **The Refresh Interval starts from the moment the limiter is created**. Let's suppose we're using `reservoirRefreshAmount: 5`. If you happen to add 10 jobs just 1ms before the refresh is triggered, the first 5 will run immediately, then 1ms later it will refresh the reservoir value and that will make the last 5 also run right away. It will have run 10 jobs in just over 1ms no matter what your refresh interval was!
232
233- **Refresh Intervals prevent a limiter from being garbage collected.** Call `limiter.disconnect()` to clear the interval and allow the memory to be freed. However, it's not necessary to call `.disconnect()` to allow the application to exit.
234
235### submit()
236
237Adds a job to the queue. This is the callback version of `schedule()`.
238```js
239limiter.submit(someAsyncCall, arg1, arg2, callback);
240```
241You 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.
242
243`submit()` can also accept [advanced options](#job-options).
244
245### schedule()
246
247Adds a job to the queue. This is the Promise and async/await version of `submit()`.
248```js
249const fn = function(arg1, arg2) {
250 return httpGet(arg1, arg2); // Here httpGet() returns a promise
251};
252
253limiter.schedule(fn, arg1, arg2)
254.then((result) => {
255 /* ... */
256});
257```
258In 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.
259
260`schedule()` can also accept [advanced options](#job-options).
261
262Here's another example:
263```js
264// suppose that `client.get(url)` returns a promise
265
266const url = "https://wikipedia.org";
267
268limiter.schedule(() => client.get(url))
269.then(response => console.log(response.body));
270```
271
272### wrap()
273
274Takes a function that returns a promise. Returns a function identical to the original, but rate limited.
275```js
276const wrapped = limiter.wrap(fn);
277
278wrapped()
279.then(function (result) {
280 /* ... */
281})
282.catch(function (error) {
283 // Bottleneck might need to fail the job even if the original function can never fail.
284 // For example, your job is taking longer than the `expiration` time you've set.
285});
286```
287
288### Job Options
289
290`submit()`, `schedule()`, and `wrap()` all accept advanced options.
291```js
292// Submit
293limiter.submit({/* options */}, someAsyncCall, arg1, arg2, callback);
294
295// Schedule
296limiter.schedule({/* options */}, fn, arg1, arg2);
297
298// Wrap
299const wrapped = limiter.wrap(fn);
300wrapped.withOptions({/* options */}, arg1, arg2);
301```
302
303| Option | Default | Description |
304|--------|---------|-------------|
305| `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! |
306| `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. |
307| `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`. |
308| `id` | `<no-id>` | You should give an ID to your jobs, it helps with [debugging](#debugging-your-application). |
309
310### Strategies
311
312A 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`.
313
314#### Bottleneck.strategy.LEAK
315When 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.
316
317#### Bottleneck.strategy.OVERFLOW_PRIORITY
318Same 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.
319
320#### Bottleneck.strategy.OVERFLOW
321When 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.
322
323#### Bottleneck.strategy.BLOCK
324When 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.
325
326
327### Jobs lifecycle
328
3291. **Received**. You new job has been added to your limiter. Bottleneck needs to check whether it can be accepted into the queue.
3302. **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.
3313. **Running**. Your job is not in the queue anymore, it will be executed after a delay that was computed according to your `minTime` setting.
3324. **Executing**. Your job is executing its code.
3335. **Done**. Your job has completed.
334
335**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.
336
337#### counts()
338
339```js
340const counts = limiter.counts();
341
342console.log(counts);
343/*
344{
345 RECEIVED: 0,
346 QUEUED: 0,
347 RUNNING: 0,
348 EXECUTING: 0,
349 DONE: 0
350}
351*/
352```
353
354Returns an object with the current number of jobs per status in the limiter.
355
356#### jobStatus()
357
358```js
359console.log(limiter.jobStatus("some-job-id"));
360// Example: QUEUED
361```
362
363Returns the status of the job with the provided job id **in the limiter**. Returns `null` if no job with that id exist.
364
365#### jobs()
366
367```js
368console.log(limiter.jobs("RUNNING"));
369// Example: ['id1', 'id2']
370```
371
372Returns an array of all the job ids with the specified status **in the limiter**. Not passing a status string returns all the known ids.
373
374#### queued()
375
376```js
377const count = limiter.queued(priority);
378
379console.log(count);
380```
381
382`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**.
383
384#### clusterQueued()
385
386```js
387const count = await limiter.clusterQueued();
388
389console.log(count);
390```
391
392Returns the number of `QUEUED` jobs **in the Cluster**.
393
394#### empty()
395
396```js
397if (limiter.empty()) {
398 // do something...
399}
400```
401
402Returns a boolean which indicates whether there are any `RECEIVED` or `QUEUED` jobs **in the limiter**.
403
404#### running()
405
406```js
407limiter.running()
408.then((count) => console.log(count));
409```
410
411Returns a promise that returns the **total weight** of the `RUNNING` and `EXECUTING` jobs **in the Cluster**.
412
413#### done()
414
415```js
416limiter.done()
417.then((count) => console.log(count));
418```
419
420Returns a promise that returns the **total weight** of `DONE` jobs **in the Cluster**. Does not require passing the `trackDoneStatus: true` option.
421
422#### check()
423
424```js
425limiter.check()
426.then((wouldRunNow) => console.log(wouldRunNow));
427```
428Checks if a new job would be executed immediately if it was submitted now. Returns a promise that returns a boolean.
429
430
431### Events
432
433Event names: `"error"`, `"empty"`, `"idle"`, `"dropped"`, `"depleted"` and `"debug"`.
434
435__'error'__
436```js
437limiter.on("error", function (error) {
438 /* handle errors here */
439});
440```
441
442The two main causes of error events are: uncaught exceptions in your event handlers, and network errors when Clustering is enabled.
443
444__'failed'__
445```js
446limiter.on("failed", function (error, jobInfo) {
447 // This will be called every time a job fails.
448});
449```
450
451__'retry'__
452
453See [Retries](#retries) to learn how to automatically retry jobs.
454```js
455limiter.on("retry", function (error, jobInfo) {
456 // This will be called every time a job is retried.
457});
458```
459
460__'empty'__
461```js
462limiter.on("empty", function () {
463 // This will be called when `limiter.empty()` becomes true.
464});
465```
466
467__'idle'__
468```js
469limiter.on("idle", function () {
470 // This will be called when `limiter.empty()` is `true` and `limiter.running()` is `0`.
471});
472```
473
474__'dropped'__
475```js
476limiter.on("dropped", function (dropped) {
477 // This will be called when a strategy was triggered.
478 // The dropped request is passed to this event listener.
479});
480```
481
482__'depleted'__
483```js
484limiter.on("depleted", function (empty) {
485 // This will be called every time the reservoir drops to 0.
486 // The `empty` (boolean) argument indicates whether `limiter.empty()` is currently true.
487});
488```
489
490__'debug'__
491```js
492limiter.on("debug", function (message, data) {
493 // Useful to figure out what the limiter is doing in real time
494 // and to help debug your application
495});
496```
497
498Use `removeAllListeners()` with an optional event name as first argument to remove listeners.
499
500Use `.once()` instead of `.on()` to only receive a single event.
501
502
503### Retries
504
505The following example:
506```js
507const limiter = new Bottleneck();
508
509// Listen to the "failed" event
510limiter.on("failed", async (error, jobInfo) => {
511 const id = jobInfo.options.id;
512 console.warn(`Job ${id} failed: ${error}`);
513
514 if (jobInfo.retryCount === 0) { // Here we only retry once
515 console.log(`Retrying job ${id} in 25ms!`);
516 return 25;
517 }
518});
519
520// Listen to the "retry" event
521limiter.on("retry", (error, jobInfo) => console.log(`Now retrying ${jobInfo.options.id}`));
522
523const main = async function () {
524 let executions = 0;
525
526 // Schedule one job
527 const result = await limiter.schedule({ id: 'ABC123' }, async () => {
528 executions++;
529 if (executions === 1) {
530 throw new Error("Boom!");
531 } else {
532 return "Success!";
533 }
534 });
535
536 console.log(`Result: ${result}`);
537}
538
539main();
540```
541will output
542```
543Job ABC123 failed: Error: Boom!
544Retrying job ABC123 in 25ms!
545Now retrying ABC123
546Result: Success!
547```
548To 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.
549
550**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.
551
552
553### updateSettings()
554
555```js
556limiter.updateSettings(options);
557```
558The options are the same as the [limiter constructor](#constructor).
559
560**Note:** Changes don't affect `SCHEDULED` jobs.
561
562### incrementReservoir()
563
564```js
565limiter.incrementReservoir(incrementBy);
566```
567Returns a promise that returns the new reservoir value.
568
569### currentReservoir()
570
571```js
572limiter.currentReservoir()
573.then((reservoir) => console.log(reservoir));
574```
575Returns a promise that returns the current reservoir value.
576
577### stop()
578
579The `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.
580
581```js
582limiter.stop(options)
583.then(() => {
584 console.log("Shutdown completed!")
585});
586```
587
588`stop()` returns a promise that resolves once all the `EXECUTING` jobs have completed and, if desired, once all non-`EXECUTING` jobs have been dropped.
589
590| Option | Default | Description |
591|--------|---------|-------------|
592| `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. |
593| `dropErrorMessage` | `This limiter has been stopped.` | The error message used to drop jobs when `dropWaitingJobs` is `true`. |
594| `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. |
595
596### chain()
597
598Tasks 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:
599```js
600const limiterA = new Bottleneck( /* some settings */ );
601const limiterB = new Bottleneck( /* some different settings */ );
602const limiterG = new Bottleneck( /* some global settings */ );
603
604limiterA.chain(limiterG);
605limiterB.chain(limiterG);
606
607// Requests added to limiterA must follow the A and G rate limits.
608// Requests added to limiterB must follow the B and G rate limits.
609// Requests added to limiterG must follow the G rate limits.
610```
611
612To unchain, call `limiter.chain(null);`.
613
614## Group
615
616The `Group` feature of Bottleneck manages many limiters automatically for you. It creates limiters dynamically and transparently.
617
618Let'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:
619
620
621```js
622const group = new Bottleneck.Group(options);
623```
624
625The `options` object will be used for every limiter created by the Group.
626
627The Group is then used with the `.key(str)` method:
628
629```js
630// In this example, the key is an IP
631group.key("77.66.54.32").schedule(() => {
632 /* process the request */
633});
634```
635
636#### key()
637
638* `str` : The key to use. All jobs added with the same key will use the same underlying limiter. *Default: `""`*
639
640The 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.
641
642Limiters 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.
643
644#### on("created")
645
646```js
647group.on("created", (limiter, key) => {
648 console.log("A new limiter was created for key: " + key)
649
650 // Prepare the limiter, for example we'll want to listen to its "error" events!
651 limiter.on("error", (err) => {
652 // Handle errors here
653 })
654});
655```
656
657Listening 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.
658
659#### updateSettings()
660
661```js
662const group = new Bottleneck.Group({ maxConcurrent: 2, minTime: 250 });
663group.updateSettings({ minTime: 500 });
664```
665After executing the above commands, **new limiters** will be created with `{ maxConcurrent: 2, minTime: 500 }`.
666
667
668#### deleteKey()
669
670* `str`: The key for the limiter to delete.
671
672Manually 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.
673
674#### keys()
675
676Returns an array containing all the keys in the Group.
677
678#### clusterKeys()
679
680Same as `group.keys()`, but returns all keys in this Group ID across the Cluster.
681
682#### limiters()
683
684```js
685const limiters = group.limiters();
686
687console.log(limiters);
688// [ { key: "some key", limiter: <limiter> }, { key: "some other key", limiter: <some other limiter> } ]
689```
690
691## Batching
692
693Some APIs can accept multiple operations in a single call. Bottleneck's Batching feature helps you take advantage of those APIs:
694```js
695const batcher = new Bottleneck.Batcher({
696 maxTime: 1000,
697 maxSize: 10
698});
699
700batcher.on("batch", (batch) => {
701 console.log(batch); // ["some-data", "some-other-data"]
702
703 // Handle batch here
704});
705
706batcher.add("some-data");
707batcher.add("some-other-data");
708```
709
710`batcher.add()` returns a Promise that resolves once the request has been flushed to a `"batch"` event.
711
712| Option | Default | Description |
713|--------|---------|-------------|
714| `maxTime` | `null` (unlimited) | Maximum acceptable time (in milliseconds) a request can have to wait before being flushed to the `"batch"` event. |
715| `maxSize` | `null` (unlimited) | Maximum number of requests in a batch. |
716
717Batching doesn't throttle requests, it only groups them up optimally according to your `maxTime` and `maxSize` settings.
718
719## Clustering
720
721Clustering 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.
722
723Bottleneck will attempt to spread load evenly across limiters.
724
725### Enabling Clustering
726
727First, add `redis` or `ioredis` to your application's dependencies:
728```bash
729# NodeRedis (https://github.com/NodeRedis/node_redis)
730npm install --save redis
731
732# or ioredis (https://github.com/luin/ioredis)
733npm install --save ioredis
734```
735Then create a limiter or a Group:
736```js
737const limiter = new Bottleneck({
738 /* Some basic options */
739 maxConcurrent: 5,
740 minTime: 500
741 id: "my-super-app" // All limiters with the same id will be clustered together
742
743 /* Clustering options */
744 datastore: "redis", // or "ioredis"
745 clearDatastore: false,
746 clientOptions: {
747 host: "127.0.0.1",
748 port: 6379
749
750 // Redis client options
751 // Using NodeRedis? See https://github.com/NodeRedis/node_redis#options-object-properties
752 // Using ioredis? See https://github.com/luin/ioredis/blob/master/API.md#new-redisport-host-options
753 }
754});
755```
756
757| Option | Default | Description |
758|--------|---------|-------------|
759| `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. |
760| `clearDatastore` | `false` | When set to `true`, on initial startup, the limiter will wipe any existing Bottleneck state data on the Redis db. |
761| `clientOptions` | `{}` | This object is passed directly to the redis client library you've selected. |
762| `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)`. |
763| `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. |
764
765**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}`.
766
767### Important considerations when Clustering
768
769The 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.
770
771Queued 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.
772
773Due to the above, functionality relying on the queue length happens purely locally:
774- 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.
775- 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.
776- `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).
777- The `"empty"` event is triggered when the (local) queue is empty.
778- The `"idle"` event is triggered when the (local) queue is empty *and* no jobs are currently running anywhere in the cluster.
779
780You must work around these limitations in your application code if they are an issue to you. The `publish()` method could be useful here.
781
782The 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.
783
784It 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.
785
786It 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.
787
788Network 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.
789
790It is **strongly recommended** to [set up an `"error"` listener](#events) on all your limiters and on your Groups.
791
792### Clustering Methods
793
794The `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`.
795
796#### ready()
797
798This method returns a promise that resolves once the limiter is connected to Redis.
799
800As 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.
801
802```js
803const limiter = new Bottleneck({/* options */});
804
805limiter.on("error", (err) => {
806 // handle network errors
807});
808
809limiter.ready()
810.then(() => {
811 // The limiter is ready
812});
813```
814
815#### publish(message)
816
817This method broadcasts the `message` string to every limiter in the Cluster. It returns a promise.
818```js
819const limiter = new Bottleneck({/* options */});
820
821limiter.on("message", (msg) => {
822 console.log(msg); // prints "this is a string"
823});
824
825limiter.publish("this is a string");
826```
827
828To send objects, stringify them first:
829```js
830limiter.on("message", (msg) => {
831 console.log(JSON.parse(msg).hello) // prints "world"
832});
833
834limiter.publish(JSON.stringify({ hello: "world" }));
835```
836
837#### clients()
838
839If you need direct access to the redis clients, use `.clients()`:
840```js
841console.log(limiter.clients());
842// { client: <Redis Client>, subscriber: <Redis Client> }
843```
844
845### Additional Clustering information
846
847- Bottleneck is compatible with [Redis Clusters](https://redis.io/topics/cluster-tutorial), but you must use the `ioredis` datastore and the `clusterNodes` option.
848- Bottleneck is compatible with Redis Sentinel, but you must use the `ioredis` datastore.
849- 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.
850- 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.
851- The Lua scripts are highly optimized and designed to use as few resources as possible.
852
853### Managing Redis Connections
854
855Bottleneck 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.
856
857By 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:
858```js
859const connection = new Bottleneck.RedisConnection({
860 clientOptions: {/* NodeRedis/ioredis options */}
861 // ioredis also accepts `clusterNodes` here
862});
863
864
865const limiter = new Bottleneck({ connection: connection });
866const group = new Bottleneck.Group({ connection: connection });
867```
868You can access and reuse the Connection object of any Group or limiter:
869```js
870const group = new Bottleneck.Group({ connection: limiter.connection });
871```
872When a Connection object is created manually, the connectivity `"error"` events are emitted on the Connection itself.
873```js
874connection.on("error", (err) => { /* handle connectivity errors here */ });
875```
876If 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:
877```js
878import Redis from "redis";
879const client = new Redis.createClient({/* options */});
880
881const connection = new Bottleneck.RedisConnection({
882 // `clientOptions` and `clusterNodes` will be ignored since we're passing a raw client
883 client: client
884});
885
886const limiter = new Bottleneck({ connection: connection });
887const group = new Bottleneck.Group({ connection: connection });
888```
889Depending on your application, using more clients can improve performance.
890
891Use the `disconnect(flush)` method to close the Redis clients.
892```js
893limiter.disconnect();
894group.disconnect();
895```
896If you created the Connection object manually, you need to call `connection.disconnect()` instead, for safety reasons.
897
898## Debugging your application
899
900Debugging complex scheduling logic can be difficult, especially when priorities, weights, and network latency all interact with one another.
901
902If 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.
903
904Make sure you've read the ['Gotchas'](#gotchas) section.
905
906To 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.
907
908When 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:
909```js
910limiter.schedule(fn)
911.then((result) => { /* ... */ } )
912.catch((error) => {
913 if (error instanceof Bottleneck.BottleneckError) {
914 /* ... */
915 }
916});
917```
918
919## Upgrading to v2
920
921The internal algorithms essentially haven't changed from v1, but many small changes to the interface were made to introduce new features.
922
923All the breaking changes:
924- 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.
925- The Bottleneck constructor now takes an options object. See [Constructor](#constructor).
926- The `Cluster` feature is now called `Group`. This is to distinguish it from the new v2 [Clustering](#clustering) feature.
927- The `Group` constructor takes an options object to match the limiter constructor.
928- Jobs take an optional options object. See [Job options](#job-options).
929- Removed `submitPriority()`, use `submit()` with an options object instead.
930- Removed `schedulePriority()`, use `schedule()` with an options object instead.
931- 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.
932- Use `null` instead of `0` to indicate an unlimited `maxConcurrent` value.
933- Use `null` instead of `-1` to indicate an unlimited `highWater` value.
934- Renamed `changeSettings()` to `updateSettings()`, it now returns a promise to indicate completion. It takes the same options object as the constructor.
935- Renamed `nbQueued()` to `queued()`.
936- Renamed `nbRunning` to `running()`, it now returns its result using a promise.
937- Removed `isBlocked()`.
938- Changing the Promise library is now done through the options object like any other limiter setting.
939- Removed `changePenalty()`, it is now done through the options object like any other limiter setting.
940- Removed `changeReservoir()`, it is now done through the options object like any other limiter setting.
941- Removed `stopAll()`. Use the new `stop()` method.
942- `check()` now accepts an optional `weight` argument, and returns its result using a promise.
943- Removed the `Group` `changeTimeout()` method. Instead, pass a `timeout` option when creating a Group.
944
945Version 2 is more user-friendly and powerful.
946
947After upgrading your code, please take a minute to read the [Debugging your application](#debugging-your-application) chapter.
948
949
950## Contributing
951
952This 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.
953
954Suggestions and bug reports are also welcome.
955
956To 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.
957
958To speed up compilation time during development, run `./scripts/build.sh dev` instead. Make sure to build and test without `dev` before submitting a PR.
959
960The 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`.
961
962All contributions are appreciated and will be considered.
963
964[license-url]: https://github.com/SGrondin/bottleneck/blob/master/LICENSE
965
966[npm-url]: https://www.npmjs.com/package/bottleneck
967[npm-license]: https://img.shields.io/npm/l/bottleneck.svg?style=flat
968[npm-version]: https://img.shields.io/npm/v/bottleneck.svg?style=flat
969[npm-downloads]: https://img.shields.io/npm/dm/bottleneck.svg?style=flat