🚀 Big News: Socket Acquires Coana to Bring Reachability Analysis to Every Appsec Team.Learn more
Socket
Sign inDemoInstall
Socket

nodejs-circuit-breaker

Package Overview
Dependencies
Maintainers
0
Versions
3
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

nodejs-circuit-breaker

A robust Node.js Circuit Breaker implementation that monitors API health and handles failures gracefully by temporarily blocking failing URLs and retrying them after a certain timeout. Supports multiple HTTP methods and customizable failure thresholds.

1.0.2
latest
Source
npm
Version published
Maintainers
0
Created
Source

Node Circuit Breaker

A flexible Circuit Breaker implementation for handling network requests. This package helps manage unreliable services, preventing requests to unhealthy services, and automatically retrying when the service is healthy again. It supports HTTP methods, detailed error handling, and tracks the health of services across requests.

Features

  • Multiple HTTP Methods: Supports different HTTP methods like GET, POST, PUT, DELETE.

  • Circuit Breaker States: Manages the CLOSED, OPEN, and HALF-OPEN states autonomously.

  • Error Logging: Stores the last error data for better debugging.

  • Timeout and Retry Mechanism: Implements custom timeouts with exponential backoff.

  • Threshold Configuration: Customizable failure and success thresholds.

  • Persistent State: Tracks URL states and saves failure/success information to a JSON file.

Installation

Install the pacakage with npm

  npm install my-circuit-breaker

Usage/Examples

Here’s a simple example of how to use the node-circuit-breaker module to protect API calls:

const initiateBreaker = require('my-circuit-breaker');

const response = await initiateBreaker('https://api.example.com/data', {
  method: 'GET',            // HTTP method (default: GET)
  failureThreshold: 3,       // Number of failures before opening the circuit
  successThreshold: 5,       // Number of successes before closing the circuit
  timeout: 60000             // Time in ms before trying again after an open circuit
});

console.log(response.message);

In this example:

  • The circuit breaker will open after 3 consecutive failures.
  • It will move to HALF-OPEN state after 60 seconds.
  • If 5 consecutive successes are recorded in HALF-OPEN state, the circuit will close again.
  • Failure counts reset after a successful request.

Customizations

The initiateBreaker function accepts two arguments:

  • Url: (String) The URL to monitor.
  • Options: (Object) Optional parameters.

Options

  • Method: HTTP method to use (default: "GET").
  • Failure Threshold: Number of consecutive failures required to open the circuit (default: 3).
  • Success Threshold: Number of consecutive successes required to close the circuit (default: 5).
  • Timeout: Time (in ms) to wait before moving from OPEN to HALF-OPEN (default: 10000 or 10 seconds).

Example

const initiateBreaker = require('my-circuit-breaker');

const response = await initiateBreaker('https://api.example.com/data', {
  method: 'POST',
  failureThreshold: 4,
  successThreshold: 3,
  timeout: 30000, // 30 seconds
});

if (response.error) {
  console.log(`Request failed: ${response.message}`, response.error);
} else {
  console.log(`Request succeeded: ${response.message}`, response.data);
}

Response structure

The initiateBreaker function returns an object with the following structure:

{
  "error": Object,       // Contains error data from the last failed request (if any)
  "data": Object,        // Contains data from the successful request (if successful)
  "message": String      // Describes the result of the request and circuit state
}

Handling Errors

If a request fails, the last error data is stored and can be accessed in subsequent requests to the same URL.

const response = await initiateBreaker('https://api.example.com/data');
if (response.error) {
  console.log('Last error data:', response.error);
}

Successful Responses

If a request is successful, the request response is accessed in the data object

const response = await initiateBreaker('https://api.example.com/data');
if (response.data) {
  console.log('Sucessfull data:', response.data);
}

Contributing

Feel free to open issues or contribute to this project by submitting pull requests.

  • Fork the repo.
  • Create your feature branch (git checkout -b feature/AmazingFeature).
  • Commit your changes (git commit -m 'Add some AmazingFeature').
  • Push to the branch (git push origin feature/AmazingFeature).
  • Open a Pull Request.

🚀 About Me

This project was build with ❤ by Abdulwahab Abdulwarith.

Github

twitter

Keywords

circuit-breaker

FAQs

Package last updated on 16 Oct 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts