Problem Statement
When a microservice call fails due to network issues, timeouts, or downstream service errors, the entire user request can fail, causing poor user experience and cascading failures across the system.
Jump into concepts and practice - no test required
This diagram shows a client calling Service A, which calls Service B. If Service B fails, the fallback handler provides an alternative response to Service A, preventing failure propagation.
### Before applying fallback pattern def get_user_profile(user_id): # Direct call without fallback response = call_profile_service(user_id) return response ### After applying fallback pattern class FallbackException(Exception): pass def get_user_profile(user_id): try: response = call_profile_service(user_id) if response.status_code != 200: raise FallbackException() return response except (TimeoutError, FallbackException): # Return cached or default profile as fallback return get_cached_profile(user_id)
fallback pattern in microservices?response = callMainService()
if response.failed:
response = fallbackResponse()
print(response)
What will be printed if callMainService() fails?callMainService() fails, the code assigns fallbackResponse() to response.def get_data():
try:
return call_service()
except:
call_fallback()
What is the bug here?