Opossum

Circuit breaker that executes asynchronous functions and monitors their exe...

README

opossum


Node.js CI
Coverage Status
Known Vulnerabilities
dependencies Status

Opossum is a Node.js circuit breaker that executes asynchronous functions
and monitors their execution status. When things start failing, opossum
plays dead and fails fast. If you want, you can provide a fallback function
to be executed when in the failure state.

For more about the circuit breaker pattern, there are lots of resources
on the web - search it! Fowler's blog post is one place to

|
---------------
License:
Documentation:
Typings:
Issue
Engines:

Usage


Let's say you've got an API that depends on something that might fail -
a network operation, or disk read, for example. Wrap those functions up in a
CircuitBreaker and you have control over your destiny.

  1. ```javascript
  2. const CircuitBreaker = require('opossum');

  3. function asyncFunctionThatCouldFail(x, y) {
  4.   return new Promise((resolve, reject) => {
  5.     // Do something, maybe on the network or a disk
  6.   });
  7. }

  8. const options = {
  9.   timeout: 3000, // If our function takes longer than 3 seconds, trigger a failure
  10.   errorThresholdPercentage: 50, // When 50% of requests fail, trip the circuit
  11.   resetTimeout: 30000 // After 30 seconds, try again.
  12. };
  13. const breaker = new CircuitBreaker(asyncFunctionThatCouldFail, options);

  14. breaker.fire(x, y)
  15.   .then(console.log)
  16.   .catch(console.error);
  17. ```

AbortController support


You can provide an AbortController (https://developer.mozilla.org/en-US/docs/Web/API/AbortController, https://nodejs.org/docs/latest/api/globals.html#globals_class_abortcontroller) for aborting on going request upon
reaching Opossum timeout.

  1. ```javascript
  2. const CircuitBreaker = require('opossum');
  3. const http = require('http);

  4. function asyncFunctionThatCouldFail(abortSignal, x, y) {
  5.   return new Promise((resolve, reject) => {
  6.     http.get(
  7.       'http://httpbin.org/delay/10',
  8.       { signal: abortSignal },
  9.       (res) => {
  10.         if(res.statusCode < 300) {
  11.           resolve(res.statusCode);
  12.           return;
  13.         }

  14.         reject(res.statusCode);
  15.       }
  16.     );
  17.   });
  18. }

  19. const abortController = new AbortController();
  20. const options = {
  21.   abortController,
  22.   timeout: 3000, // If our function takes longer than 3 seconds, trigger a failure
  23. };
  24. const breaker = new CircuitBreaker(asyncFunctionThatCouldFail, options);

  25. breaker.fire(abortController.signal)
  26.   .then(console.log)
  27.   .catch(console.error);
  28. ```

Fallback


You can also provide a fallback function that will be executed in the
event of failure. To take some action when the fallback is performed,
listen for the fallback event.

  1. ```javascript
  2. const breaker = new CircuitBreaker(asyncFunctionThatCouldFail, options);
  3. // if asyncFunctionThatCouldFail starts to fail, firing the breaker
  4. // will trigger our fallback function
  5. breaker.fallback(() => 'Sorry, out of service right now');
  6. breaker.on('fallback', (result) => reportFallbackEvent(result));
  7. ```

Once the circuit has opened, a timeout is set based on options.resetTimeout.
When the resetTimeout expires, opossum will enter the halfOpen state.
Once in the halfOpen state, the next time the circuit is fired, the circuit's
action will be executed again. If successful, the circuit will close and emit
the close event. If the action fails or times out, it immediately re-enters
the open state.

When a fallback function is triggered, it's considered a failure, and the
fallback function will continue to be executed until the breaker is closed.

The fallback function accepts the same parameters as the fire function:

  1. ```javascript
  2. const delay = (delay, a, b, c) =>
  3.   new Promise((resolve) => {
  4.     setTimeout(() => {
  5.       resolve();
  6.     }, delay);
  7.   });

  8. const breaker = new CircuitBreaker(delay);
  9. breaker.fire(20000, 1, 2, 3);
  10. breaker.fallback((delay, a, b, c) => `Sorry, out of service right now. But your parameters are: ${delay}, ${a}, ${b} and ${c}`);
  11. ```

Breaker State Initialization


There may be times where you will need to initialize the state of a Circuit Breaker.  Primary use cases for this are in a serverless environment such as Knative or AWS Lambda, or any container based platform, where the container being deployed is ephemeral.

The toJSON method is a helper function to get the current state and status of a breaker:

  1. ```
  2. const breakerState = breaker.toJSON();
  3. ```

This will return an object that might look similar to this:

  1. ```
  2. {
  3.   state: {
  4.     enabled: true,
  5.     name: 'functionName'
  6.     closed: true,
  7.     open: false,
  8.     halfOpen: false,
  9.     warmUp: false,
  10.     shutdown: false
  11.   },
  12.   status: {
  13.     ...
  14.   }
  15. };
  16. ```

A new circuit breaker instance can be created with this state by passing this object in:

  1. ```
  2. const breaker = new CircuitBreaker({state: state});
  3. ```

Status Initialization


There may also be times where you will need to pre-populate the stats of the Circuit Breaker Status Object.  Primary use cases for this are also in a serverless environment such as Knative or AWS Lambda, or any container based platform, where the container being deployed is ephemeral.

Getting the existing cumalative stats for a breaker can be done like this:

  1. ```
  2. const stats = breaker.stats;
  3. ```

stats will be an object that might look similar to this:

  1. ```
  2. {
  3.   failures: 11,
  4.   fallbacks: 0,
  5.   successes: 5,
  6.   rejects: 0,
  7.   fires: 16,
  8.   timeouts: 0,
  9.   cacheHits: 0,
  10.   cacheMisses: 0,
  11.   semaphoreRejections: 0,
  12.   percentiles: {
  13.     '0': 0,
  14.     '1': 0,
  15.     '0.25': 0,
  16.     '0.5': 0,
  17.     '0.75': 0,
  18.     '0.9': 0,
  19.     '0.95': 0,
  20.     '0.99': 0,
  21.     '0.995': 0
  22.   },
  23.   latencyTimes: [ 0 ],
  24.   latencyMean: 0
  25. }
  26. ```

To then re-import those stats, first create a new Status object with the previous stats and then pass that as an option to the CircuitBreaker constructor:

  1. ```
  2. const statusOptions = {
  3.   stats: {....}
  4. };

  5. const newStatus = CircuitBreaker.newStatus(statusOptions);

  6. const breaker = new CircuitBreaker({status: newStatus});
  7. ```

Browser


Opossum really shines in a browser. You can use it to guard against network
failures in your AJAX calls.

We recommend using webpack to bundle your applications,
since it does not have the effect of polluting the window object with a global.
However, if you need it, you can access a circuitBreaker function in the global
namespace by doing something similar to what is shown in the below example.

Here is an example using hapi.js. See the
repository for more detail.

Include opossum.js in your HTML file.

  1. ```html
  2. <html>
  3. <head>
  4.   <title>My Super App</title>
  5.   <script type='text/javascript' src="/jquery.js"></script>
  6.   <script type='text/javascript' src="/opossum.js"></script>
  7.   <script type='text/javascript' src="/app.js"></script>
  8. <body>
  9. ...
  10. </body>
  11. </head>
  12. </html>
  13. ```

In your application, set a route to the file, pointing to
node_modules/opossum/dist/opossum-min.js.

  1. ```js
  2. // server.js
  3. const server = new Hapi.Server();
  4. server.register(require('inert', (err) => possibleError(err)));
  5. server.route({
  6.   method: 'GET',
  7.   path: '/opossum.js',
  8.   handler: {
  9.     file: {
  10.       path: path.join(__dirname, 'node_modules', 'opossum', 'dist', 'opossum-min.js'),
  11.     }
  12.   }
  13. });
  14. ```
In the browser's global scope will be a CircuitBreaker constructor. Use it
to create circuit breakers, guarding against network failures in your REST
API calls.

  1. ```js
  2. // app.js
  3. const route = 'https://example-service.com/rest/route';
  4. const circuitBreakerOptions = {
  5.   timeout: 500,
  6.   errorThresholdPercentage: 50,
  7.   resetTimeout: 5000
  8. };

  9. const breaker = new CircuitBreaker(() => $.get(route), circuitBreakerOptions);
  10. breaker.fallback(() => `${route} unavailable right now. Try later.`));
  11. breaker.on('success', (result) => $(element).append(JSON.stringify(result)}));

  12. $(() => {
  13.   $('#serviceButton').click(() => breaker.fire().catch((e) => console.error(e)));
  14. });

  15. ```

Events


A CircuitBreaker will emit events for important things that occur.
Here are the events you can listen for.

  fire - emitted when the breaker is fired.
  reject - emitted when the breaker is open (or halfOpen).
  timeout - emitted when the breaker action times out.
  success - emitted when the breaker action completes successfully
  failure - emitted when the breaker action fails, called with the error
  open - emitted when the breaker state changes to open
  close - emitted when the breaker state changes to closed
  halfOpen - emitted when the breaker state changes to halfOpen
  fallback - emitted when the breaker has a fallback function and executes it
  semaphoreLocked - emitted when the breaker is at capacity and cannot execute the request
  healthCheckFailed - emitted when a user-supplied health check function returns a rejected promise
  shutdown - emitted when the breaker shuts down

Handling events gives a greater level of control over your application behavior.

  1. ```js
  2. const breaker = new CircuitBreaker(() => $.get(route), circuitBreakerOptions);

  3. breaker.fallback(() => ({ body: `${route} unavailable right now. Try later.` }));

  4. breaker.on('success',
  5.   (result) => $(element).append(
  6.     makeNode(`SUCCESS: ${JSON.stringify(result)}`)));

  7. breaker.on('timeout',
  8.   () => $(element).append(
  9.     makeNode(`TIMEOUT: ${route} is taking too long to respond.`)));

  10. breaker.on('reject',
  11.   () => $(element).append(
  12.     makeNode(`REJECTED: The breaker for ${route} is open. Failing fast.`)));

  13. breaker.on('open',
  14.   () => $(element).append(
  15.     makeNode(`OPEN: The breaker for ${route} just opened.`)));

  16. breaker.on('halfOpen',
  17.   () => $(element).append(
  18.     makeNode(`HALF_OPEN: The breaker for ${route} is half open.`)));

  19. breaker.on('close',
  20.   () => $(element).append(
  21.     makeNode(`CLOSE: The breaker for ${route} has closed. Service OK.`)));

  22. breaker.on('fallback',
  23.   (data) => $(element).append(
  24.     makeNode(`FALLBACK: ${JSON.stringify(data)}`)));
  25. ```


Promises vs. Callbacks

The opossum API returns a Promise from CircuitBreaker.fire().
But your circuit action - the async function that might fail -
doesn't have to return a promise. You can easily turn Node.js style
callback functions into something opossum understands by using the built in
Node core utility function util.promisify() .

  1. ```javascript
  2. const fs = require('fs');
  3. const { promisify } = require('util');
  4. const CircuitBreaker = require('opossum');

  5. const readFile = promisify(fs.readFile);
  6. const breaker = new CircuitBreaker(readFile, options);

  7. breaker.fire('./package.json', 'utf-8')
  8.   .then(console.log)
  9.   .catch(console.error);
  10. ```

And just for fun, your circuit doesn't even really have to be a function.
Not sure when you'd use this - but you could if you wanted to.

  1. ```javascript
  2. const breaker = new CircuitBreaker('foo', options);

  3. breaker.fire()
  4.   .then(console.log) // logs 'foo'
  5.   .catch(console.error);
  6. ```

Calculating errorThresholdPercentage


The errorThresholdPercentage value is compared to the error rate. That rate is determined by dividing the number of failures by the number of times the circuit has been fired. You can see this comparison here:

  1. ```js
  2. // check stats to see if the circuit should be opened
  3.   const stats = circuit.stats;
  4.   if ((stats.fires < circuit.volumeThreshold) && !circuit.halfOpen) return;
  5.   const errorRate = stats.failures / stats.fires * 100;
  6.   if (errorRate > circuit.options.errorThresholdPercentage || circuit.halfOpen) {
  7.     circuit.open();
  8.   }
  9. ```

The numbers for fires and failures come from the stats that are indeed governed by rollingCountTimeout and rollingCountBuckets. The timeout value is the total number of seconds for which the stats are being maintained, and the buckets value is the number of slots in the window. The defaults are 10 seconds and 10 buckets. So, the statistics that are being compared against errorThresholdPercentage are based on 10 samples, one per second over the last 10 seconds.

Example: a circuit is fired 24 times over 10 seconds with a somewhat bursty pattern, failing three times.

  1. ```
  2. | fires: 2 | fires: 1 | fires: 3 | fires: 0 | fires: 9 | fires: 3 | fires: 2 | fires: 0 | fires: 4 | fires: 0 |
  3. | fails: 0 | fails: 0 | fails: 0 | fails: 0 | fails: 0 | fails: 3 | fails: 0 | fails: 0 | fails: 0 | fails: 0 |
  4. ```
The failure rate here is 3/24 or 1/8 or 12.5%. The default error threshold is 50%, so in this case, the circuit would not open. However, if you modified the rollingCountTimeout to 3 seconds, and the rollingCountBuckets to 3  (not recommended), then the stats array might look like these three seconds from above.

  1. ```
  2. | fires: 3 | fires: 2 | fires: 0 |
  3. | fails: 3 | fails: 0 | fails: 0 |
  4. ```
Now, without changing errorThresholdPercentage our circuit will open because our error rate is now 3/5 or 60%. It's tricky to test this stuff because the array of statistics is a rolling count. Every second the oldest bucket is removed and a new one is added, so the totals change constantly in a way that may not be intuitive.

For example, if the first example is shifted right, dropping the first bucket and adding another with fires: 3 the total number of fires now in the stats is not 27 (24+3) but 25 (24-2+3).

The code that is summing the stats samples is here:

  1. ```js
  2.   const totals = this[WINDOW].reduce((acc, val) => {
  3.     if (!val) { return acc; }
  4.     Object.keys(acc).forEach(key => {
  5.       if (key !== 'latencyTimes' && key !== 'percentiles') {
  6.         (acc[key] += val[key] || 0);
  7.       }
  8.     });

  9.     if (this.rollingPercentilesEnabled) {
  10.       acc.latencyTimes.push.apply(acc.latencyTimes, val.latencyTimes || []);
  11.     }
  12.     return acc;
  13.   }, bucket());
  14. ```


Typings


Typings are available here.

If you'd like to add them, run npm install @types/opossum in your project.

Metrics


Prometheus

The [opossum-prometheus](https://github.com/nodeshift/opossum-prometheus) module
can be used to produce metrics that are consumable by Prometheus.
These metrics include information about the circuit itself, for example how many
times it has opened, as well as general Node.js statistics, for example event loop lag.


Hystrix

The [opossum-hystrix](https://github.com/nodeshift/opossum-hystrix) module can
be used to produce metrics that are consumable by the Hystrix Dashboard.

Troubleshooting


You may run into issues related to too many listeners on an EventEmitter like this.

  1. ```sh
  2. (node:25619) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 10 unpipe listeners added. Use emitter.setMaxListeners() to increase limit
  3. (node:25619) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 drain listeners added. Use emitter.setMaxListeners() to increase limit
  4. (node:25619) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 error listeners added. Use emitter.setMaxListeners() to increase limit
  5. (node:25619) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 close listeners added. Use emitter.setMaxListeners() to increase limit
  6. (node:25619) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 finish listeners added. Use emitter.setMaxListeners() to increase limit
  7. ```

In some cases, seeing this error might indicate a bug in client code, where many CircuitBreakers are inadvertently being created. But there are legitimate scenarios where this may not be the case. For example, it could just be that you need more than 10 CircuitBreakers in your app. That's ok.

To get around the error, you can set the number of listeners on the stream.

  1. ```js
  2. breaker.stats.getHystrixStream().setMaxListeners(100);
  3. ```

Or it could be that you have a large test suite which exercises some code that creates CircuitBreakers and does so repeatedly. If the CircuitBreaker being created is only needed for the duration of the test, use breaker.shutdown() when the circuit is no longer in use to clean up all listeners.