Welcome to circuit-breaker-js: Ensuring Reliable Service Communication
The circuit-breaker-js library is essential for developers looking to build resilient web applications. It implements the circuit breaker pattern, which helps prevent cascading failures in distributed systems by temporarily blocking any interaction with a failing service. In this post, we will dive deep into its functionalities, explain numerous APIs, and illustrate their usage with code snippets.
Installation
npm install circuit-breaker-js
Creating a Circuit Breaker
const CircuitBreaker = require('circuit-breaker-js');
const options = {
timeout: 5000, // If the request takes longer than 5 seconds, trigger the fallback.
errorThreshold: 50, // If 50% of the requests fail, open the circuit.
resetTimeout: 30000 // After 30 seconds, attempt to close the circuit.
};
const breaker = new CircuitBreaker(options);
Using the Circuit Breaker
const serviceRequest = () => {
return new Promise((resolve, reject) => {
// Mock API request
const succeed = Math.random() > 0.5;
setTimeout(() => {
succeed ? resolve('Success!') : reject(new Error('Failed!'));
}, 1000);
});
};
breaker.run(serviceRequest, (error) => {
console.log('Fallback: ', error.message);
}).then(result => {
console.log(result);
}).catch(error => {
console.log(error.message);
});
Advanced API Usage
Fallback Function
const fallback = () => 'Fallback executed';
breaker.fallback(fallback);
breaker.run(serviceRequest, fallback);
Event Listeners
breaker.on('open', () => console.log('Circuit opened'));
breaker.on('close', () => console.log('Circuit closed'));
breaker.on('halfOpen', () => console.log('Circuit half-open'));
Custom Error Handling
breaker.fallback((error) => 'Custom Fallback: ' + error.message);
Wrapping HTTP Requests
const axios = require('axios');
const httpRequest = () => axios.get('https://api.example.com/data');
breaker.run(httpRequest).then(response => {
console.log(response.data);
}).catch(error => {
console.log('HTTP Request failed', error.message);
});
Real-World Application Example
const express = require('express');
const app = express();
app.get('/data', (req, res) => {
breaker.run(httpRequest).then(response => {
res.send(response.data);
}).catch(() => {
res.send('Service unavailable. Please try again later.');
});
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
With circuit-breaker-js, you can build robust applications that gracefully handle service failures. This tool is indispensable for developers aiming to enhance the reliability and performance of their distributed systems.
Hash: 4e3b6d9fbc849e33c5da3682aefa4995123e557747247f38a137e40e149d91c3