Distributed applications often use the retry pattern described in the previous lesson. As soon as an application scales over several nodes across a network, it needs to handle failure scenarios that might occur. For example, as soon as an application sends some request over HTTP, there is a possibility that the demand fails: the server might be down, the network might be unreachable, or the remote application might have a temporary overload. The requester needs to retry and handle all those different conditions correctly in order to be robust.

Since this is a very typical usage, a library called tenacity has been created for Python, and it can easily be used to implement this strategy on any function using a decoratorA decorator takes in a function, adds some functionality and returns it..

tenacity.Retrying()

The following example implements the algorithm shown in the following example in a few lines using tenacity. This will make the function do_something be called over and over again until it succeeds by not raising any kind of exception.

To run the application below, click Run and run the command python tenacity-simple.py.

If you want to update the source code in coding playgrounds, you need to press the Run button again after changing the code and repeat the instructions to run the application.

Get hands-on with 1200+ tech skills courses.