Video in progress
If you wrap an external HTTP client with decorators for retry, circuit breaker, timeout and metrics, how does their order matter?
Order changes behavior: if retry is inside the circuit breaker, the breaker counts each attempt separately; if it's outside, retries keep hitting an open breaker. Whether the timeout applies to each attempt or to the total time also comes from the order.
📖 Answer
Think of each layer as a decorator that implements the same interface. From the outside in, I usually build it like this:
metrics -> retry -> circuitBreaker -> bulkhead -> timeout -> http call
Why:
- Metrics goes outermost: it measures the time the user actually waited, retries included. If you also put a separate metric inside, you can see "how many attempts it took".
- Retry sits outside the breaker. Every attempt goes through the breaker; if the breaker opens,
CallNotPermittedExceptionis thrown immediately, and in the retry configuration this exception must be in the list of exceptions that aren't retried. Otherwise you hit an open breaker three times and wait for nothing. - Timeout goes innermost: a separate limit for each attempt. If you put it outside the retry, you get an overall deadline. You may need both.
With Resilience4j annotations, the order is set by aspect order, and the default isn't what everyone expects: Retry ( CircuitBreaker ( RateLimiter ( TimeLimiter ( Bulkhead ( function ) ) ) ) ). You can change it with settings like resilience4j.retry.retryAspectOrder. For important integrations I prefer writing it explicitly in code with Decorators.ofSupplier(...) instead of annotations, so the order is visible.
One more risk is a retry storm. In a three-layer service chain where each layer tries 3 times, the lowest service gets 27 times more requests. Retry in only one layer (usually at the edge), add backoff with jitter, and don't retry non-idempotent operations at all.
Sign up to mark studied questions and save your progress.