Failsafe policies overview

September 14, 2020 No comments Failsafe Policies Library

1. Introduction

In this article, we will cover failsafe policies responsible for determining which execution results or failures to handle. By default, all thrown exceptions will be handled. Failsafe is a flexible API that allows us to handle also more specific errors under specified conditions.

In case you want to read more about failsafe, check getting started with Failsafe library post.

2. Failsafe policies

Failsafe supports four kinds of policies:

  • Retry - express when retries should be performed for an execution,
  • Timeout - allows failing an execution with TimeoutExceededException if it takes too long to complete,
  • Fallback - allows providing an alternative result for a failed execution,
  • Circuit Breaker - allows creating systems that fail fast by temporarily disabling execution as a way of preventing system overload.

3. Policies composition

Failsafe policies can be composed in many different ways. We can also create multiple policies of the same type.

The following code shows the use of typical policies composition:

Failsafe.with(fallback, retry, circuitBreaker, timeout).get(supplier);

In this example supplier is evaluated first, then it’s result is handled by the Timeout, then the CircuitBreaker, the RetryPolicy, and the Fallback.

Each policy makes its own determination as to whether the result represents a failure. This allows different policies to be used for handling different types of failures.

4. Handling specific failures or conditions

Policies can also be configured to handle more specific failures or conditions:

policy.handle(ConnectException.class, SocketException.class)
       .handleIf(failure -> failure instanceof ConnectException);

They can also be configured to handle specific results or result conditions:

policy.handleResult(null)
      .handleResultIf(result -> result == null);

5. Conclusion

In this short article, we presented failsafe policies that determine which execution results or failures to handle and how to handle them. We showed that policies could be handled conditionally and can be composed in many ways.

{{ message }}

{{ 'Comments are closed.' | trans }}