Summary
Introduction
Initially, when we are building distributed systems, applications often rely on external services such as APIs, databases, and third-party integrations. However, these dependencies can fail, causing cascading failures in your system. The Circuit Breaker pattern helps prevent such failures from bringing down your entire application.
In this post, I will explain about Opossum, a Node.js library that implements the Circuit Breaker pattern, and see how it can improve the resilience of your applications.
What is the Circuit Breaker Pattern?
The Circuit Breaker pattern is a fault-tolerance mechanism that prevents an application from repeatedly trying to execute an operation that is likely to fail. It works similarly to an electrical circuit breaker:
- Closed State: Requests are allowed to pass through normally.
- Open State: If failures exceed a defined threshold, the circuit "opens," preventing further requests.
- Half-Open State: After a timeout, a few requests are allowed to test if the dependency has recovered.
This helps prevent overwhelming failing services and allows the system to recover gracefully.
What is Opossum?
Opossum is a lightweight implementation of the Circuit Breaker pattern for Node.js. It helps monitor failures and fallback mechanisms, ensuring better resilience in applications.
Hands on
Step 1: Install
You can install Opossum using npm:
npm install opossum
Step 2: Creating a Function to Wrap
We will use Node.js and Axios to make an API request.
const axios = require('axios');
async function fetchData() {
console.log('Requesting...');
const response = await axios.get('$URL');
return response.data;
}
Step 3: Implementing Opossum
Now, let's wrap fetchData
with Opossum.
const CircuitBreaker = require('opossum');
const options = {
timeout: 3000, // 3 seconds timeout
errorThresholdPercentage: 50, // Open circuit if 50% of requests fail
resetTimeout: 5000 // Attempt recovery after 5 seconds
};
const breaker = new CircuitBreaker(fetchData, options);
breaker.fallback(() => ({ message: 'Fallback: Service unavailable' }));
breaker.on('open', () => console.log('Circuit is open!'));
breaker.on('close', () => console.log('Circuit is closed!'));
breaker.on('halfOpen', () => console.log('Circuit is half-open!'));
Step 4: Create the request method
Create a method to perform the request:
function performRequest(breaker) {
breaker.fire()
.then(data => console.log('Data:', data))
.catch(err => console.error('Error:', err));
}
Step 5: Calling the Circuit Breaker
Now, execute the function in a defined interval:
setInterval(() => performRequest(breaker), 1000);
If the API fails repeatedly, Opossum will open the circuit, preventing further requests until recovery.
Step 6: Check information about the Circuit Breaker
To check the stats about the requests performed:
function showStats(breaker) {
console.log(breaker.stats)
}
Step 7: Calling the Circuit Breaker Stats
Execute the function in a defined interval:
setInterval(() => showStats(breaker), 5000);
Conclusion
Opossum is a powerful library that helps Node.js applications become more fault-tolerant by implementing the Circuit Breaker pattern. This technique prevents cascading failures and improves system stability, especially when working with unreliable external services.