Skip to content

Instantly share code, notes, and snippets.

@parthghiya
Created November 5, 2017 17:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save parthghiya/777c2b423c9c8faf0d427fd7a3eeb95b to your computer and use it in GitHub Desktop.
Save parthghiya/777c2b423c9c8faf0d427fd7a3eeb95b to your computer and use it in GitHub Desktop.
Circuit breaker in Node JS
/*
Sample Implementation of Circuit Breaker using hystrixjs in NodeJS
It uses reactive principles
Link : https://www.npmjs.com/package/hystrixjs
*/
var CommandsFactory = require('hystrixjs').commandFactory;
var serviceCommand = CommandsFactory.getOrCreate("Service on port :" + service.port + ":" + port)
.circuitBreakerErrorThresholdPercentage(service.errorThreshold)
.timeout(service.timeout)
.run(makeRequest)
.circuitBreakerRequestVolumeThreshold(service.concurrency)
.circuitBreakerSleepWindowInMilliseconds(service.timeout)
.statisticalWindowLength(10000)
.statisticalWindowNumberOfBuckets(10)
.errorHandler(isErrorHandler)
.build();
/*
Explanation
-circuitBreakerSleepWindowInMilliseconds - how long the circuit breaker should stay opened, before allowing a single request to test the health of the service
-errorHandler - function to validate if the error response from the service is an actual error. If this function returns an error object (default implementation), this request call will be marked as failure, which will influence the error percentage. If it returns null or false, the call will not be marked as failure. An example could be a 404 error, if the customer is not found.
timeout for request
-circuitBreakerRequestVolumeThreshold - minimum number of requests in a rolling window that needs to be exceeded, before the circuit breaker will bother at all to calculate the health
-circuitBreakerForceOpened - force this circuit breaker to be always opened
-circuitBreakerForceClosed - force this circuit breaker to be always closed
-circuitBreakerErrorThresholdPercentage - error percentage threshold to trip the circuit
-statisticalWindowLength - length of the window to keep track of execution counts metrics (success, failure)
-statisticalWindowNumberOfBuckets - number of buckets within the statistical window
-percentileWindowNumberOfBuckets - number of buckets within the percentile window
-percentileWindowLength - length of the window to keep track of execution times
-requestVolumeRejectionThreshold - maximum number of concurrent requests, which can be executed. Defaults to 0, i.e. no limitation
-fallbackTo - function, which will be executed if the request fails. The function will be called with the error as the 1st argument and an array of the original args as the 2nd argument
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment