Skip to content

Circuit Breaker Configuration

A circuit breaker is used to protect resources (remote, local, or otherwise) from being overloaded when in a failure state. For example, a remote website may be unavailable and calling that web site in a message consumer takes 30-60 seconds to time out. By continuing to call the failing service, the service may be unable to recover. A circuit breaker detects the repeated failures and trips, preventing further calls to the service and giving it time to recover. Once the reset interval expires, calls are slowly allowed back to the service. If it is still failing, the breaker remains open, and the timeout interval resets. Once the service returns to healthy, calls flow normally as the breaker closes.

Read Martin Fowler’s description of the pattern here.

To add the circuit breaker to a receive endpoint:

e.UseCircuitBreaker(cb =>
{
cb.TrackingPeriod = TimeSpan.FromMinutes(1);
cb.TripThreshold = 15;
cb.ActiveThreshold = 10;
cb.ResetInterval = TimeSpan.FromMinutes(5);
});

To configure on all receive endpoints:

services.AddMassTransit(x =>
{
x.UsingRabbitMq((context, cfg) =>
{
cfg.UseCircuitBreaker(cb =>
{
cb.TripThreshold = 15;
cb.ActiveThreshold = 10;
cb.ResetInterval = TimeSpan.FromMinutes(5);
});
cfg.ConfigureEndpoints(context);
});
});

There are four options that can be adjusted on a circuit breaker.

OptionDescription
TrackingPeriodThe time window for tracking exceptions
TripThresholdThis is a percentage, and is based on the ratio of successful to failed attempts. When set to 15, if the ratio exceeds 15%, the circuit breaker opens and remains open until the ResetInterval expires.
ActiveThresholdThe number of messages that must reach the circuit breaker in a tracking period before the circuit breaker can trip. If set to 10, the trip threshold is not evaluated until at least 10 messages have been received.
ResetIntervalThe period of time between the circuit breaker trip and the first attempt to close the circuit breaker. Messages that reach the circuit breaker during the open period will immediately fail with the same exception that tripped the circuit breaker.

By default, all exceptions are tracked. An exception filter can be configured to only track specific exceptions:

cfg.UseCircuitBreaker(cb =>
{
cb.TripThreshold = 15;
cb.ActiveThreshold = 10;
cb.ResetInterval = TimeSpan.FromMinutes(5);
cb.Handle<TransientException>();
});

Only handle exceptions that are likely to be transient. If you handle exceptions that are not transient (such as ArgumentNullException), the circuit breaker may never close.