Improve your system using Retry Policy — Part I (Failsafe)

Luiz Gustavo De O. Costa
3 min readJan 29, 2022

--

Unavailable is one of the QOS (Quality of System) items that should be near 100%. We know that sometimes one system or another becomes unavailable and our code should be ready to handle those situations, and in this series I’ll bring some options.

DO NOT DISTURB label

1. Definition

Retry policies express when retries should be performed for an execution.

2. Situation

For this example, let’s think about database communication or even other services to buy/sell a stock. Is a common scenario, since in the process (as I know) you need to send a request via a broker and then the broker sends this to a central, here in Brazil is the B3.

Imagine you using your mobile to try to send/buy a stock and then the request arrives to the broker. The broker can’t do all the steps at once, is required an integration point and where the Retry policy could be applied.

For any POF (point of failure) in my opinion should have the retry policy instead of control by your own code 👨‍💻. Why? Error prone.

3. Model

Class diagram

4. Hands On

4.1 TradeService — sell

From the line 9 until the 18, the Retry Policy is created. The way to create is pretty straight forward, and you can define any kind of Exception, delay etc and then use it on line 24, inside the Failsafe.

To sum up, any IllegalStateException thrown by the repository, will be made more than 3 requests within an interval of 2 seconds, otherwise the client will receive the error.

TradeService.sell

4.2 TradeRepository — sell

Since the target does not access the DB or other layer, the sale is just logging.

TradeRepository.sell

4.3 TradeService — buy

As shown before, first is required to declare the RetryPolicy and then use it. There is small difference, since this method call is async.

Since the async is used we can control the timeout and more.

TradeService.asyncBuy

4.4 TradeRepository — buy

This method has more code, still hard coded, and the intent is to throw an IllegalStateException sometimes, to simulate an interruption.

TradeRepository.buy

5. Tests

In order to test the Retry, we need to cover the success and the failing path.

TradeServiceTest class

6. Next steps

For the next steps I'll bring Spring, Quarkus and Reactive programming using Retry Policy, stay connected!

7. Code

The complete code is available on my GitHub.

8. Tech stack

  • Java 8
  • Lombok
  • JUnit5
  • Mockito
  • Failsafe

9. References

https://pixabay.com

--

--

Luiz Gustavo De O. Costa
Luiz Gustavo De O. Costa

Written by Luiz Gustavo De O. Costa

Hey friend!! I’m Luiz Gustavo, a Java developer and I’m here to learn and write about Java, tests and good practices

No responses yet