Exercise — Timeouts, Retries, and Backoff: wrap a flaky call safely.
Topic: microservices, Resilience. Level: Intermediate.
Answer
Only retry idempotent calls, cap attempts and per-attempt time, back off exponentially with jitter, and give up to a fallback. Below combines a timeout with a bounded, jittered retry.
```java
TimeLimiter limiter = TimeLimiter.of(Duration.ofSeconds(3));
Retry retry = Retry.of("inventory", RetryConfig.custom()
.maxAttempts(3)
.intervalFunction(IntervalFunction.ofExponentialRandomBackoff(
Duration.ofMillis(200), 2.0, 0.5))
.build());
Supplier<Integer> guarded = Retry.decorateSupplier(retry,
() -> {
try { return limiter.executeFutureSupplier(
() -> CompletableFuture.supplyAsync(() -> client.stock(sku))); }
catch (Exception e) { throw new RuntimeException(e); }
});
int stock = Try.ofSupplier(guarded).recover(ex -> 0).get(); // fallback: 0
```