Adicionando alternativas aos disjuntores
Aprenda a combinar um disjuntor com uma lógica de alternativa para que, quando o disjuntor estiver aberto, seu serviço degrade de forma controlada em vez de fazer a solicitação do usuário falhar.
Adicionando alternativas aos disjuntores é 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.
Why Fallbacks Matter
A circuit breaker protects your service by failing fast when a dependency is down. But failing fast still means the user gets an error unless you provide a fallback.
A fallback is the plan B that runs when the breaker is open.
The Fallback Contract
A fallback should return a sensible default quickly and never call the same failing dependency. It is invoked when:
- The breaker is open, or
- The protected call throws or times out.
A Simple Fallback
Here is the core idea: try the real call, and if it fails, return the fallback value.
def get_price(call_remote):
try:
return call_remote()
except Exception:
return 'fallback: last-known price'
print(get_price(lambda: (_ for _ in ()).throw(Exception('down'))))Fallback: Cached Value
A common strategy is to serve the last successful response from a cache. The user sees slightly stale data instead of an error.
cache = {'price': 42}
def get_with_cache(breaker_open):
if breaker_open:
return cache.get('price', 'unavailable')
return 'fresh value'
print(get_with_cache(True))Fallback: Default Value
When no cache exists, return a safe default: an empty list, a neutral recommendation, or a generic message. The key is that the user experience degrades, not breaks.
def recommendations(breaker_open):
if breaker_open:
return ['Popular item A', 'Popular item B']
return ['Personalized 1', 'Personalized 2']
print(recommendations(True))Fallback: Alternate Service
Sometimes plan B is another provider. If the primary payment gateway's breaker is open, route to a secondary gateway. Each provider has its own breaker.
Wiring Fallbacks in Resilience4j
Most libraries let you attach a fallback declaratively. With Resilience4j you decorate the call with a circuit breaker and supply a recover function that runs on failure or open state.
Keep Fallbacks Fast and Safe
A fallback must not introduce new failure modes:
- No call to the broken dependency.
- No blocking I/O that could also hang.
- Bounded, predictable execution time.
Communicating Degradation
Tell the user (and your dashboards) when degraded data is served. A subtle UI note like 'showing cached results' sets expectations, and a metric on fallback rate reveals dependency health.
fallback_count = 0
def record_fallback():
global fallback_count
fallback_count += 1
return fallback_count
print('Fallbacks served:', record_fallback())When NOT to Fall Back
Some operations have no safe default. You cannot 'fall back' on confirming a payment. In those cases, fail clearly and let the caller retry later rather than fabricate a result.
Testing Fallbacks
Write tests that force the breaker open and assert the fallback runs and returns the expected safe value. Fallbacks that are never tested tend to break silently.
Quick Check
Which of these is a valid requirement for a circuit breaker fallback?
Recap
You learned to add fallbacks to circuit breakers:
- Fallbacks run when the breaker is open or the call fails.
- Common strategies: cached value, safe default, alternate service.
- Keep fallbacks fast, safe, and free of the broken dependency.
- Communicate degradation and test fallbacks explicitly.
Fallbacks turn fast failures into graceful degradation.
Perguntas Frequentes
A aula “Adicionando alternativas aos disjuntores” é grátis?
Sim — o texto completo de “Adicionando alternativas aos disjuntores” é 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 “Adicionando alternativas aos disjuntores”?
Aprenda a combinar um disjuntor com uma lógica de alternativa para que, quando o disjuntor estiver aberto, seu serviço degrade de forma controlada em vez de fazer a solicitação do usuário falhar. 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 “Adicionando alternativas aos disjuntores”?
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
- Escolha de uma biblioteca de disjuntores
- Configuração de instâncias de disjuntores
- Integração em chamadas de serviço
- Adicionando alternativas aos disjuntores