Sobes.tech
Senior

How were situations handled when a service was unavailable?

sobes.tech AI

Answer from AI

To handle situations where a service is unavailable, the following approaches are commonly used in Java:

  • Retry: using libraries like Resilience4j or Spring Retry to implement repeated attempts with exponential backoff.
  • Timeouts: setting timeouts on network requests to avoid waiting indefinitely.
  • Circuit Breaker: temporarily disabling a service after multiple failures to prevent system overload and allow recovery.
  • Fallback: returning a pre-prepared response or invoking alternative logic if the service is unavailable.

Example using Resilience4j CircuitBreaker:

CircuitBreaker circuitBreaker = CircuitBreaker.ofDefaults("myService");
Supplier<String> decoratedSupplier = CircuitBreaker
    .decorateSupplier(circuitBreaker, () -> callRemoteService());

Try<String> result = Try.ofSupplier(decoratedSupplier)
    .recover(throwable -> "Fallback response");

System.out.println(result.get());

Thus, the system becomes resilient to temporary failures and does not block when external services are unavailable.