Circuit Breaker/Exponential Backoff Pattern (C#)

Electric circuit breaker device image

This device pictured above, part of all electrical systems(you hope so😀) has a feature to  put a break in electricity supply if something goes wrong.

WHY: Wherever there is overcurrent or short circuit, this prevents further damage to the whole system.

In software the current flowing through the network is the data. If one of the service your app depends on is down or slow, retrying it could cause more damage than solve the problem.

As part of making your application resilient and keeping the relevant services healthy, usually two patterns of retry are clubbed together. Circuit Breaker and Exponential Backoff.  In case of failure in service calls, following diagram explains how retry, exponential backoff and eventual circuit break looks like on a timeline.

Here it is re-trying a failing request four times, increasing the delay in calls each time, eventually giving up(break)

Alright, show me the code already…

An example in C# with Polly and Flurl

Don’t worry, you can copy or tinker the code here

Doing this just helped me wrap my head around it a bit better, production quality implementation will always look more detailed.

Understanding ASP.net core dependency injection types

When adding dependencies in asp.net core project you will see three options

  • Transient
  • Scoped
  • Singleton

Just for my mental note, trying to document it with images

The scenario is very simple, maybe not a true real-world one but whatever gets the point across. There is only one endpoint in a controller, which then calls a service which eventually calls a repository. All these rely on ILogger

In each of these, the change in color indicates a new instance

Hope these images make it easier to remember.

GraphQL vs REST vs gRPC Pizza Analogy

This is not to provide you with any technical internals or implementation details, maybe just to establish a mental model. It might come handy when deciding what to use.

Imagine you are craving Pizza. You have three options…

Order from a pizza place that has preset pizza menu. No customization of size or toppings, that’s REST.

A pizza place that allows you complete customization of size and toppings, that’s GraphQL. Probably will be slower than REST.

The third option is a frozen pizza you have it in your fridge. You already bought the kind you like, that’s gRPC. This is the fastest way you will get your pizza.

And just like Pizza relies on dough, they all rely on HTTP