What is advantage of circuit breaker design pattern in API architecture?

后端 未结 3 957
别跟我提以往
别跟我提以往 2021-02-10 17:18

So sorry if this question is not fit for SO.

But I tried looking lot for answer.

I was studying Circuit Breaker design pattern, As I understand its used for maki

3条回答
  •  北荒
    北荒 (楼主)
    2021-02-10 17:40

    Our colleagues have already shown the advantages of a circuit breaker, so I'll concentrate on practical examples.

    So, looking at your example, you have a flow that has to call a payment API> Let's assume its an "external" component. Without this call, the whole flow probably can't be considered as "successfully completed" (I understand you have some online process that has a payment as one of its essential steps).

    In this case Circuit Breaker indeed probably won't be that useful unless as a fallback you store the payment command in some kind of intermediate storage and then "re-apply" the payment logic.

    The whole point of a circuit breaker is to provide a reasonable fallback so that the flow won't be considered as failed if the fallback logic gets applied.

    Here is another example where Circuit breaker has much more sense.

    If you build a "netflix-like" portal and in UI there is a widget that shows "recommended" movies. The recommendation engine takes into consideration the movies you've seen / liked before. Technically this is an "external system"/microservice.

    Now, what if the flow that populates the data for the UI, is not able to get the recommendations (for example, if the recommendation service is down), will you "fail" the whole flow? Probably not, maybe its better to show some "generic list" of recommended movies and let the user proceed to work with the application.

    In this case, the Circuit breaker can be a good choice for implementing the call to external recommendation service.

    Now, what's the difference between this flow and exception handling?

    If the reason for the failure of that recommendation system is some temp network outage / Database slowness, probably its the best to give this service some time and not to try to call it over and over again, we should give it a chance to 'recuperate'. When we apply a circuit breaker, during the "open-circuit" period our code won't even try to call the server, directly routing to the fallback method.

    A regular try/catch block, on the other hand, will always call the recommendation service.

    So to wrap up, a circuit breaker is a pattern for fault tolerance as was stated in the question; its a tool which can be applicable in some situations, and irrelevant in other cases.

提交回复
热议问题