Criando Aplicações Resilientes com o padrão Retry

(Versão em Inglês)

No artigo anterior, vimos que algumas das falhas possíveis em nossa aplicação são as falhas transientes. Estas falhas são automaticamente corrigidas após um curto período de tempo.

O padrão (ou política) Retry torna nossa aplicação resiliente ao fazer novas tentativas (automaticamenteem caso de falha.

A animação abaixo mostra o princípio de funcionamento do Retry. Neste cenário configuramos o mecanismo para fazer até 5 novas tentativas em caso de falha (se você preferir um gif, clique aqui):

Um ponto importante neste exemplo é que ao tornar nossa aplicação resiliente, o usuário final talvez não percebeu que houve falhas nas tentativas de comunicação. Ele fez uma requisição e teve seu resultado. Com isso, podemos dizer que melhoramos a experiência do usuário.

Algumas outras configurações possíveis desse padrão são:

  • RetryForever: fazer tentativas (eternamente) até que se tenha sucesso;
  • Retry(N): fazer N tentativas, e só após às N tentativas a falha é apresentada; e
  • WaitAndRetry(N, T): fará até no máximo N tentativas e esperará por T tempo entre cada tentativas (essa foi a forma utilizada na animação);

Retry Exponencial (Backoff)

Na configuração de Wait and Retry, uma das formas usais de configurar os intervalos entre tentativas é o chamado Retry Exponencial, na qual o intervalo cresce de forma exponencial.

Se você é usuário do Gmail®, por exemplo, já deve ter percebido essa situação. Veja na animação (acelerada) abaixo das tentativas de reconexão realizadas pelo Gmail quando ficamos sem conexão com a internet:

Ao plotar os intervalos entre as tentativas, fica claro que se trata de uma distribuição exponencial:

Distribuição Exponencial dos intervalos entre tentativas do Gmail

Implementando o Padrão Retry

Se você é desenvolvedor já deve estar imaginando como implementar esse padrão usando algumas estruturas como condicionais, laços de repetição, tratamentos de erros…

Não será necessário quebrar muito a cabeça, pois existem frameworks prontos e que irão facilitar muito nossa vida. Entre eles está o Polly Framework para aplicações .NET.

Polly é uma biblioteca que implementa uma gama de padrões de resiliência e tolerância a falhas para .Net e faz parte da .Net Foundation.

Outras features importantes, dessa biblioteca é a linguagem fluente de escrita de padrões de resiliência através de políticas, facilitar a reusabilidade, tratamentos nativos para Thread Safe e suporte Async. Muito Bom!!!

Implementando Retry com Polly

Veja como é simples:


  • Policy indica que iniciaremos uma nova política de resiliência;
  • A função Handle indica que a politica só será ativada se ocorrer a exceção SomeException;
  • A função WaitAndRetry indica a política que queremos e o argumento 5 indica que fará até 5 tentativas com um intervalo exponencial; e
  • colocamos na função Execute o código que será executado pela política, seja ele um procedimento (void) ou função.

Observe que a Polly tornou nossa política de retry explícita e legível, sem que precisássemos interpretar os codicionais e laços de repetição, etc.

A biblioteca Polly permite que você crie as políticas de diversas formas e configurações. O código acima é simple e usual para vários cenários.

O site oficial da biblioteca Polly é bem rico em conteúdo e pode ser melhor explorado.

Espero que tenham gostado e esquecem de deixar seus feedbacks.

No próximo post falaremos sobre o Circuit Breaker, até lá!!

69 respostas para “Criando Aplicações Resilientes com o padrão Retry”

  1. With almost everything that seems to be building inside this subject matter, your viewpoints are fairly exciting. Nonetheless, I appologize, but I can not subscribe to your entire strategy, all be it exhilarating none the less. It seems to everybody that your comments are actually not completely rationalized and in actuality you are generally yourself not totally convinced of your argument. In any event I did appreciate looking at it.

  2. Hey very cool site!! Man .. Beautiful .. Amazing .. I’ll bookmark your site and take the feeds also…I am happy to find a lot of useful info here in the post, we need work out more strategies in this regard, thanks for sharing. . . . . .

  3. I must voice my respect for your kind-heartedness supporting folks who should have help on this area of interest. Your real commitment to passing the message around had become wonderfully effective and has usually encouraged people much like me to realize their targets. Your amazing informative instruction implies much to me and extremely more to my fellow workers. Regards; from each one of us.

  4. Thank you so much for giving everyone such a marvellous chance to read in detail from here. It’s always very brilliant and as well , stuffed with amusement for me and my office colleagues to visit your web site not less than thrice every week to find out the fresh things you will have. Of course, I am just actually fascinated with the terrific pointers served by you. Some 4 facts on this page are essentially the most beneficial we have all ever had.

  5. I simply needed to say thanks once again. I’m not certain the things that I could possibly have implemented without the type of ideas shared by you directly on this problem. This has been the horrifying matter for me, but noticing the very well-written way you resolved it forced me to jump with fulfillment. Now i am thankful for the support and as well , wish you know what an amazing job you are always providing teaching others thru a site. Probably you’ve never met all of us.

  6. I in addition to my guys were actually checking out the great tricks found on your web site while then developed a horrible suspicion I had not expressed respect to the website owner for them. Most of the ladies were definitely for this reason warmed to read all of them and now have unquestionably been tapping into them. Appreciate your actually being indeed accommodating and for figuring out this form of marvelous topics millions of individuals are really wanting to know about. My very own honest regret for not saying thanks to sooner.

  7. I must express appreciation to you just for bailing me out of this difficulty. Right after looking through the internet and finding solutions that were not beneficial, I assumed my life was over. Being alive without the answers to the problems you’ve fixed by means of the posting is a crucial case, as well as the kind which could have badly affected my entire career if I hadn’t come across the website. That skills and kindness in maneuvering all the pieces was priceless. I am not sure what I would’ve done if I had not encountered such a point like this. I can also at this time look forward to my future. Thank you very much for the impressive and effective guide. I will not hesitate to recommend the website to any individual who ought to have assistance on this subject.

  8. I wish to get across my gratitude for your kindness in support of people that require help with this important study. Your real commitment to getting the message all over was really useful and have all the time enabled employees like me to arrive at their dreams. Your useful recommendations means a lot to me and a whole lot more to my office colleagues. Many thanks; from all of us.

  9. I precisely wished to say thanks yet again. I do not know what I would’ve used without these opinions contributed by you about this field. It has been a terrifying matter for me personally, however , encountering the very skilled form you resolved the issue made me to weep over delight. I’m happy for the support and as well , hope that you comprehend what a powerful job you were getting into training most people by way of your webblog. Probably you have never encountered all of us.

  10. My spouse and i were now fulfilled when Jordan managed to conclude his reports through your ideas he came across out of your web page. It’s not at all simplistic to just possibly be giving away techniques which some other people have been trying to sell. And we remember we now have the website owner to appreciate because of that. All the illustrations you have made, the straightforward web site navigation, the friendships your site make it easier to create – it is most fantastic, and it’s really letting our son in addition to the family know that the topic is satisfying, which is truly indispensable. Thank you for all the pieces!

  11. Thank you a lot for giving everyone an extraordinarily brilliant opportunity to discover important secrets from this website. It’s usually very ideal and jam-packed with a good time for me personally and my office fellow workers to visit your blog not less than 3 times weekly to study the newest tips you have got. And lastly, I am always contented with all the cool suggestions you serve. Some two areas on this page are in truth the most efficient I have had.

  12. I’m commenting to make you understand what a wonderful experience our daughter gained going through your web page. She realized some pieces, with the inclusion of what it is like to have an amazing teaching mindset to make a number of people just understand several very confusing issues. You undoubtedly did more than visitors’ desires. Thank you for showing those invaluable, trustworthy, informative and also fun thoughts on your topic to Janet.

  13. Thank you a lot for giving everyone such a breathtaking chance to read critical reviews from this website. It is usually very amazing and also full of fun for me personally and my office peers to visit your blog no less than thrice in 7 days to find out the fresh issues you have. And lastly, I’m always motivated with your eye-popping guidelines you serve. Selected 2 tips in this post are surely the very best we’ve ever had.

  14. Thank you a lot for giving everyone remarkably nice chance to read critical reviews from this blog. It is usually very lovely and also jam-packed with a good time for me and my office co-workers to search your blog at the very least 3 times weekly to read through the latest guides you have. And of course, I am just actually contented considering the eye-popping points you serve. Some 1 facts in this post are completely the most effective we have ever had.

  15. I precisely desired to thank you so much once more. I’m not certain the things I could possibly have tried without the type of ways documented by you concerning my industry. It has been a distressing setting for me, but finding out the very skilled mode you solved that took me to cry with happiness. I am just happy for the work and in addition expect you really know what an amazing job you are putting in instructing people by way of your web site. More than likely you have never got to know all of us.

  16. I am also commenting to make you be aware of what a fine encounter my cousin’s daughter undergone viewing the blog. She picked up too many things, including how it is like to possess a great giving mindset to get the rest clearly know a variety of problematic matters. You truly exceeded our expectations. Thank you for delivering such precious, trusted, informative as well as easy tips on your topic to Sandra.

  17. My wife and i got very contented when Emmanuel could finish up his homework with the precious recommendations he obtained out of your weblog. It is now and again perplexing to simply find yourself releasing tactics people today have been selling. And we also fully grasp we’ve got the website owner to thank for that. Those explanations you made, the straightforward website navigation, the friendships your site make it easier to promote – it’s got everything unbelievable, and it is facilitating our son and our family reckon that that concept is entertaining, and that is extraordinarily mandatory. Thanks for all the pieces!

  18. I enjoy you because of every one of your hard work on this blog. Kate takes pleasure in conducting internet research and it’s really easy to understand why. A number of us know all about the lively tactic you deliver efficient things by means of your website and even inspire response from some others about this concern so our own simple princess is in fact understanding a lot of things. Enjoy the rest of the year. You’re the one carrying out a tremendous job.

  19. I wish to express my respect for your kind-heartedness giving support to individuals that require assistance with that area of interest. Your personal commitment to getting the solution around was surprisingly practical and has in most cases permitted workers much like me to attain their desired goals. Your new important guide means a whole lot a person like me and additionally to my office colleagues. Thanks a lot; from everyone of us.

  20. Thanks so much for giving everyone a very marvellous chance to read articles and blog posts from this site. It really is so pleasurable and packed with a lot of fun for me and my office mates to search your blog minimum thrice in 7 days to find out the new tips you have. And lastly, I’m also actually fascinated considering the dazzling techniques you give. Some 2 areas in this post are really the best we have had.

Deixe uma resposta

O seu endereço de e-mail não será publicado.