Created
February 24, 2025 13:50
-
-
Save NithinBiliya/5b96e8710faa574ef54e19cdc3742359 to your computer and use it in GitHub Desktop.
retryWithCircuitBreaker.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const CircuitBreaker = require('opossum'); | |
const fetch = require('node-fetch'); | |
// Function to fetch data from an API | |
async function fetchData(url) { | |
const response = await fetch(url); | |
if (!response.ok) throw new Error('Request failed'); | |
return await response.json(); | |
} | |
// Circuit Breaker Configuration | |
const breakerOptions = { | |
timeout: 3000, // Fail request if it takes longer than 3s | |
errorThresholdPercentage: 50, // Open circuit if 50% of requests fail | |
resetTimeout: 10000, // Wait 10s before allowing requests after circuit opens | |
}; | |
// Wrap the function inside the circuit breaker | |
const breaker = new CircuitBreaker(fetchData, breakerOptions); | |
// Handle circuit breaker events | |
breaker.on('open', () => console.log('Circuit breaker OPENED! No further retries.')); | |
breaker.on('close', () => console.log('Circuit breaker CLOSED! Requests are allowed again.')); | |
breaker.on('halfOpen', () => console.log('Circuit breaker HALF-OPEN! Testing service availability.')); | |
// Function to retry with exponential backoff, using circuit breaker per request | |
async function retryWithCircuitBreaker(url, retries = 5, baseDelay = 500) { | |
for (let i = 0; i < retries; i++) { | |
try { | |
console.log(`Attempt ${i + 1}/${retries}`); | |
const data = await breaker.fire(url); // Each retry attempt is counted separately | |
return data; // Success, return data | |
} catch (error) { | |
console.log(`Retry ${i + 1} failed: ${error.message}`); | |
if (breaker.opened) { | |
console.log('Circuit breaker is OPEN! Stopping further retries.'); | |
throw new Error('Service unavailable, circuit breaker is open.'); | |
} | |
const delay = baseDelay * Math.pow(2, i); | |
console.log(`Waiting ${delay}ms before next retry...`); | |
await new Promise(res => setTimeout(res, delay)); | |
} | |
} | |
throw new Error('All retries failed'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment