Circuit Breaker + Retry – Repository or Application Layer

  softwareengineering

I currently have a Web App using ASP.NET Core 2.2, Domain Driven Design, Clean Architecture, and CQRS. I’m using MongoDB as persistence.

I have developed a Repository pattern to abstract the MongoDB implementation. But I’ve been doing some research on how to prepare the application against outages, timeouts, and discrepancies in the network (such as latency). I’ve found the circuit breaker and retry patterns to work well for this scenario. I’m planning on using the Polly library to abstract the implementation details and implement an exponential back-off strategy.

My question is: where should I implement the patterns (Circuit Breaker+ Retry using Polly): at the application layer (Command and Query stack) or at the Repository directly?

I’ve been thinking on the Repository because:
1) The application becomes cleaner and my command/query stack isn’t polluted by the library.
In case of exceptions, I can just catch it and rethrow it (in case of a MongoException)

2) The Repository is in fact the one that makes the connectiom to the Database and not the application layer (command/query stack). Again, I would just need to handle the exception and not the implementation details

You should implement the circuit breaker at the Repository layer in order to protect your upstream layers. Which in this case would be the application.

ie, the application won’t queue up loads of save requests, it will just error each one quickly.

However, you can also bubble this up the layers. Rather than have your application error, albeit quickly, also add a circuit breaker at this layer. So when it detects that the repositories circuit breaker has cut in, it can prevent the attempted saves completely with its own circuit breaker logic.

1

LEAVE A COMMENT