Añadir fallbacks a los circuit breakers
Aprenda a combinar un circuit breaker con lógica de fallback para que, cuando el circuito esté abierto, el servicio se degrade correctamente en lugar de que falle la solicitud del usuario.
Añadir fallbacks a los circuit breakers es una lección gratuita de Microservices Communication Patterns (Saga, Circuit Breaker) en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Microservices Communication Patterns (Saga, Circuit Breaker), y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Microservices Communication Patterns (Saga, Circuit Breaker) incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en 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.
Preguntas frecuentes
¿La lección «Añadir fallbacks a los circuit breakers» es gratis?
Sí — el texto completo de «Añadir fallbacks a los circuit breakers» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Microservices Communication Patterns (Saga, Circuit Breaker), actualiza a CoddyKit PRO. El curso de Microservices Communication Patterns (Saga, Circuit Breaker) incluye 4 lecciones en total.
¿Qué aprenderé en «Añadir fallbacks a los circuit breakers»?
Aprenda a combinar un circuit breaker con lógica de fallback para que, cuando el circuito esté abierto, el servicio se degrade correctamente en lugar de que falle la solicitud del usuario. Practicas Microservices Communication Patterns (Saga, Circuit Breaker) con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Microservices Communication Patterns (Saga, Circuit Breaker)?
No se requiere experiencia previa. Microservices Communication Patterns (Saga, Circuit Breaker) en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.
¿Cuánto tiempo toma la lección «Añadir fallbacks a los circuit breakers»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Microservices Communication Patterns (Saga, Circuit Breaker)?
Sí. Cada lección de Microservices Communication Patterns (Saga, Circuit Breaker) incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Elección de una biblioteca de circuit breaker
- Configuración de instancias de circuit breaker
- Integración en llamadas a servicios
- Añadir fallbacks a los circuit breakers