npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

nodejs-circuit-breaker

v1.0.2

Published

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.

Downloads

169

Readme

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.

🔗 Links

Github

twitter