Circuitbreaker Pattern (Typescript)
JS
S
JavaScriptTo run the example, use the following command: node index.js You can then access the route at http://localhost:3000/data. The circuit breaker will manage the microservice call, and you can observe the state changes based on the service's availability. This example provides a clear and simple demonstration of using a circuit breaker to protect a microservice call, making it suitable for a blog post.
1// index.js
2
3const express = require('express');
4const CircuitBreaker = require('opossum');
5const axios = require('axios');
6
7const app = express();
8const port = 3000;
9
10// Define the microservice call
11const callMicroservice = async () => {
12 const response = await axios.get('https://api.example.com/data');
13 return response.data;
14};
15
16// Configure circuit breaker options
17const options = {
18 timeout: 3000, // 3 seconds
19 errorThresholdPercentage: 50,
20 resetTimeout: 5000 // 5 seconds
21};
22
23// Create a circuit breaker instance
24const breaker = new CircuitBreaker(callMicroservice, options);
25
26// Event listeners for circuit breaker
27breaker.on('open', () => console.log('Circuit breaker opened'));
28breaker.on('halfOpen', () => console.log('Circuit breaker half-open: testing service'));
29breaker.on('close', () => console.log('Circuit breaker closed: service is healthy'));
30
31// Define a route that uses the circuit breaker
32app.get('/data', async (req, res) => {
33 try {
34 const result = await breaker.fire();
35 res.send(result);
36 } catch (error) {
37 res.status(503).send('Service is currently unavailable. Please try again later.');
38 }
39});
40
41app.listen(port, () => {
42 console.log(`Server running at http://localhost:${port}`);
43});Created on 5/28/2024