#Resilience: Circuit Breaker Pattern
- closed: normal operation
- open: block request (after a failure threshold)
- half: test a few requests
// Using opossum circuit breaker with Next.js API route
import CircuitBreaker from 'opossum';
// pages/api/products.js
export default async function handler(req, res) {
const breaker = new CircuitBreaker(fetchProducts, {
timeout: 3000,// ms
errorThresholdPercentage: 50,
resetTimeout: 30000// ms
});
try {
const data = await breaker.fire();
res.status(200).json(data);
} catch (error) {
// Circuit is open or operation failed
res.status(503).json({ error: 'Service temporarily unavailable' });
}
}