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.

  • Awesome! Instead of adding a circuit breaker logic, will it be ok for me if I just throw an exception at the Repository and catch it at the application layer? I would then handle the error gracefully and return it to the client without problems. I'm thinking on creating some sort of middleware inside the repository so it completely ditches future attempts if it's closed (There is some Mongo logic done before inserting or retrieving objects).... Or am I going too complex? (I want this KISS) – Jose A Feb 6 '19 at 22:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.