The before code calls another service without limits, risking long waits or failures spreading. The after code adds a timeout to stop waiting too long and a circuit breaker to stop calling the failing service after repeated errors, returning a fallback response instead.
### Before resilience (naive call without timeout or circuit breaker)
import requests
def call_service_b():
response = requests.get('http://service-b/api/data')
return response.json()
### After applying resilience with timeout and circuit breaker
import requests
from circuitbreaker import circuit
@circuit(failure_threshold=3, recovery_timeout=10)
def call_service_b():
try:
response = requests.get('http://service-b/api/data', timeout=2)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException:
return {'data': 'fallback response'}