Explain Timeouts, Retries, and Exponential Backoff.
Topic: microservices, Resilience. Level: Intermediate.
Answer
- **Timeout**: cap how long you wait for a dependency so a slow call fails fast instead of pinning a thread.
- **Retry**: re-attempt transient failures — but only **idempotent** operations, or you risk double side-effects.
- **Exponential backoff**: increase the delay between retries (1s, 2s, 4s…) to avoid hammering a struggling service.
- **Jitter**: add randomness so many clients don't retry in lockstep (the "thundering herd").
Always bound total attempts and total time; combine with a circuit breaker so retries don't prolong an outage.
```java
// Resilience4j: retry with exponential backoff + jitter
RetryConfig cfg = RetryConfig.custom()
.maxAttempts(4)
.intervalFunction(IntervalFunction.ofExponentialRandomBackoff(
Duration.ofSeconds(1), 2.0, 0.5)) // 1s,2s,4s (+/-50% jitter)
.retryOnException(ex -> ex instanceof IOException)
.build();
Retry retry = Retry.of("payment", cfg);
Supplier<Reply> call = Retry.decorateSupplier(retry, () -> paymentClient.charge(req));
```