I'm developing a new REST API and I've seen some projects place the circuit breaker in the Controller. I used to place it in the DAO.

First difference I can say is that placing it in the DAO is that every service which consume this third party will be open in the error scenario. And placing it in the Controller, would EVENTUALLY open every route that consumes this third party; so it won't be immediately. But the second choice (in the Controller) seems easier to mantain.

Any recommendation about where should it go?

有帮助吗?

解决方案

There are two parts in this answer. The first part was already addressed by Robert Harvey in his comment:

  • According to Chris Richardson's catalogue of microservices patterns, the circuit breaker should be in a proxy for the remote service. The API Gateway is a good place for it.
  • Another alternative it the server-side discovery, especially if the recovery strategy implies finding other running instances of the same service.

But there is a second part. The goal of the circuit breaker is to fail fast if service is detected to be unavailable, instead of accumulating steps that will fail later creating a lot of frustration. So the circuit-breaker gets its full sense only if the consuming service is ready to react to the break:

  • Maybe the remote service is essential, and the consuming service could decide to put itself on hold (i.e. internal circuit breaker).
  • May be the remote service is not essential, and the consuming service could decide to continue to serve, but in a degraded mode.
  • (service discovery based breakers will probably not fail but find another working service and the consumers will not notice).

From the general point of view, this kind of choices in the behavior is a controller responsibility: the controller coordinates between the elements of the service, and is able to adapt the processing based on the "fail" information.

However, if in your case, it is only about getting data from elsewhere and if your error processing strategy is always the same (no difference between essential and non-essential; for example try to use a cached value if available and fail otherwhise) you could perfectly well decide to put it in the dao imho.

许可以下: CC-BY-SA归因
scroll top