Ordem dos decoradores de resiliência
Aprenda por que a ordem em que você empilha os padrões de resiliência (repetição, disjuntor, bulkhead, tempo limite, limitador de taxa) altera o comportamento e como escolher a ordem correta.
Ordem dos decoradores de resiliência é uma aula grátis de Microservices Communication Patterns (Saga, Circuit Breaker) no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Microservices Communication Patterns (Saga, Circuit Breaker), e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Microservices Communication Patterns (Saga, Circuit Breaker) inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
Stacking Patterns
Resilience libraries let you wrap a call in multiple patterns at once: retry, circuit breaker, bulkhead, time limiter, rate limiter. The patterns form a chain, and order matters.
The same set of patterns produces different behavior depending on how they are nested.
Decorators as Layers
Think of each pattern as a layer wrapping the next. The outermost layer sees the call first; the innermost actually invokes the dependency.
layers = ['Retry', 'CircuitBreaker', 'Bulkhead', 'TimeLimiter', 'ServiceCall']
for i, l in enumerate(layers):
print(' ' * i + l)Retry Outside the Breaker
The recommended Resilience4j order puts Retry outside the Circuit Breaker.
This means each retry attempt is itself evaluated by the breaker. After enough failed attempts, the breaker opens and stops further retries entirely.
What If Retry Were Inside?
If Retry were inside the breaker, the breaker would only see one outcome per full retry cycle. A burst of internal retries could hammer a failing service before the breaker ever notices.
That is why retry usually wraps the breaker, not the other way around.
Bulkhead Placement
Place the Bulkhead inside the breaker so it limits concurrency on the actual calls. The breaker can then short-circuit before a thread is even acquired, keeping the bulkhead from filling with doomed calls.
breaker_open = True
def call(breaker_open):
if breaker_open:
return 'short-circuited; no bulkhead slot used'
return 'acquire bulkhead slot then call'
print(call(breaker_open))Time Limiter Placement
The TimeLimiter sits close to the call so each individual attempt is bounded. A slow call times out, counts as a failure for the breaker, and can trigger a retry from the outer layer.
Rate Limiter Placement
Put the RateLimiter on the outside if you want to cap total request rate including retries, or inside if you only want to cap actual dependency calls. Decide based on what you are protecting.
Recommended Default Order
A widely used default, from outermost to innermost:
- Retry
- Circuit Breaker
- Rate Limiter
- Time Limiter
- Bulkhead
Adjust to your goals, but understand each move's effect.
Fallback Goes Outermost
The fallback should wrap everything so it can catch failures from any inner layer, including a retry that exhausted attempts or a breaker that is open.
def with_fallback(inner):
try:
return inner()
except Exception:
return 'fallback value'
print(with_fallback(lambda: (_ for _ in ()).throw(Exception('all layers failed'))))Interactions to Watch
Watch for surprising combos:
- Retry plus a rate limiter can amplify load if not bounded.
- A short time limiter inside aggressive retry can storm a slow service.
- Bulkhead rejections may count as breaker failures.
Validate by Testing
Because ordering effects are subtle, validate your chain with integration tests that inject failures and slowness, then assert the observed behavior matches your intent.
Quick Check
Why is Retry typically placed OUTSIDE the Circuit Breaker rather than inside it?
Recap
You learned why decorator order matters:
- Patterns nest as layers; outermost runs first.
- Retry outside the breaker lets the breaker stop retry storms.
- Bulkhead and time limiter sit close to the call.
- Fallback wraps everything.
Choose order by intent, then verify it with failure-injection tests.
Aprenda Microservices Communication Patterns (Saga, Circuit Breaker) com um tutor de IA — grátis
Escreva e execute código real no seu navegador, obtenha ajuda instantânea de um tutor de IA 24/7 e continue de onde parou na web ou no app.
- Cursos
- 12
- Aulas
- 48
Perguntas Frequentes
A aula “Ordem dos decoradores de resiliência” é grátis?
Sim — o texto completo de “Ordem dos decoradores de resiliência” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Microservices Communication Patterns (Saga, Circuit Breaker), atualize para CoddyKit PRO. O curso de Microservices Communication Patterns (Saga, Circuit Breaker) inclui 4 aulas no total.
O que vou aprender em “Ordem dos decoradores de resiliência”?
Aprenda por que a ordem em que você empilha os padrões de resiliência (repetição, disjuntor, bulkhead, tempo limite, limitador de taxa) altera o comportamento e como escolher a ordem correta. Você pratica Microservices Communication Patterns (Saga, Circuit Breaker) com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Microservices Communication Patterns (Saga, Circuit Breaker)?
Nenhuma experiência prévia é necessária. Microservices Communication Patterns (Saga, Circuit Breaker) no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.
Quanto tempo leva a aula “Ordem dos decoradores de resiliência”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Microservices Communication Patterns (Saga, Circuit Breaker)?
Sim. Cada aula de Microservices Communication Patterns (Saga, Circuit Breaker) inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Disjuntor e padrão de antepara
- Disjuntor com lógica de novas tentativas
- Integração da limitação de frequência
- Ordem dos decoradores de resiliência