Circuit Breaker Pattern in Typescript/Javascript Microservices: A Guide with code example

Ankit Kumar
Webtips
Published in
4 min readJan 4, 2023

--

To understand “How to create Decorators in Typescript for Circuit Breakers”, we need to understand

  1. What are decorators in typescript?
  2. What are circuit breakers in software systems?

Let's first read a bit about decorators

Decorators are a way to decorate functions, members of a class, or a class itself, with extra functionality.

When you apply a decorator to a function, a class, or a class member, you are actually calling a function that is going to receive details of what is being decorated, and the decorator implementation will then be able to transform the code dynamically, adding extra functionality, and reducing boilerplate code.

They are a way to have metaprogramming in TypeScript, which is a programming technique that enables the programmer to create code that uses other code from the application itself as data.

class Greeter {
@format("Hello, %s")
greeting: string;
constructor(message: string) {
this.greeting = message;
}
greet() {
let formatString = getFormat(this, "greeting");
return formatString.replace("%s", this.greeting);
}
}

Read more about Typescript Decorators.

Let’s now see what are circuit breakers

A circuit breaker is an electrical safety device designed to protect an electrical circuit from damage caused by an overcurrent or short circuit. Its basic function is to interrupt current flow to protect equipment and to prevent the risk of fire. Unlike a fuse, which operates once and then must be replaced, a circuit breaker can be reset (either manually or automatically) to resume normal operation.

It’s common for software systems to make remote calls to software running in different processes, probably on different machines across a network. One of the big differences between in-memory calls and remote calls is that remote calls can fail, or hang without a response until some timeout limit is reached. What’s worse if you have many callers on an unresponsive supplier, then you can run out of critical resources leading to cascading failures across multiple systems.

The basic idea behind the circuit breaker is very simple. You wrap a protected function call in a circuit breaker object, which monitors for failures. Once the failures reach a certain threshold, the circuit breaker trips, and all further calls to the circuit breaker return with an error, without the protected call being made at all. Usually, you’ll also want some kind of monitor alert if the circuit breaker trips.

This above example is taken from CircuitBreaker.

Enabling Circuit Breaker (or other) Decorators Support in TypeScript

To enable decorators' support when using the TypeScript Compiler CLI (tsc) the only extra step needed is to pass an additional flag --experimentalDecorators:

tsc --experimentalDecorators

tsconfig.json

When working on a project that has a tsconfig.json file, to enable experimental decorators you must add the experimentalDecorators property to the compilerOptions object:

{
"compilerOptions": {
"experimentalDecorators": true
}
}

Since we are focusing on creating circuit breaker decorators particularly, we will not go into detail about creating all approaches or creating different decorators, hence we will create only Method Decator for this blog and skip other decorators, but you can read more about other decorators from the official documentation of decorators

Dependency

Since we are using CircuitBrekaer from opossum.

npm i opossum

CircuitBreakable — Custom Decorator using CircuitBreaker

Example how we created Custom Decorator using CircuitBreaker from opposum.

And How we used it as a Method Decorator in class with the method.

Further enhancement of custom CircuitBreakable

We were able to customize CircuitBreakable further on

  1. Passing the default result as what method will return as a response — different methods might need different timeouts, let’s say.
  2. Passing custom configs from the different methods — different methods might need different timeouts, let's say.

Let's see the updated code for CircuitBreakable and its example below

Often they (circuit breakers) will protect against a range of errors that protected calls could raise, such as network connection failures. Not all errors should trip the circuit, some should reflect normal failures and be dealt with as part of regular logic.

Also, to be notified about my new articles and stories:

Subscribe to my YouTube Channel for educational content on similar topics

Follow me on Medium, Github, and Twitter for connecting quickly

You can find me on LinkedIn as it's a professional network for people like me and you.

I am quite active on Dev Community as well and write small topics over there.

Cheers !!!!!

--

--

Ankit Kumar
Webtips
Writer for

Engineering Manager | Solution Architect | Engineering Mentor | Navodayan