Skip to content

Instantly share code, notes, and snippets.

@ryanhs
Last active October 25, 2019 15:00
Show Gist options
  • Save ryanhs/faccd191c02c99b83efbf984cc7e0182 to your computer and use it in GitHub Desktop.
Save ryanhs/faccd191c02c99b83efbf984cc7e0182 to your computer and use it in GitHub Desktop.
circuit breaker example using opossum js
const Promise = require('bluebird');
const CircuitBreaker = require('opossum');
// need a logger
const log = require('bunyan').createLogger({ name: 'example' });
// mock sla
const mockService = sla => () => (Math.random() > (1 - sla) ? Promise.resolve('foo bar') : Promise.delay(3000));
// create circuit breaker
const getFooBreaker = new CircuitBreaker(mockService(0.95), {
timeout: 1000, //mockService will can timeout when got delay
errorThresholdPercentage: 10, // When 10% of requests fail, trip the circuit
resetTimeout: 3000, // After 3s, try again.
});
// fallback?
// getFooBreaker.fallback(() => Promise.resolve('We always prevail!'));
// getFooBreaker.on('fallback', () => log.info('fallback hit!'))
// healthcheck always on!
getFooBreaker.healthCheck(() => Promise.delay(500).tap(() => log.info('health check!')));
// counter for sla
let counter = 0, counter_error = 0;
setInterval(() => {
counter++;
if (counter % 100 === 0) {
let sla = (100 - (counter_error / counter * 100)).toFixed(2) + '%'
log.info({counter, counter_error, sla});
}
// fire request
getFooBreaker
.fire()
.then(() => null)
.catch(() => ++counter_error)
}, 20); // every .2s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment