Sub topic 2
Timeouts: Bounding the Cost of Waiting
Assume you know how to call network services, handle exceptions, and distinguish latency from availability. This chapter focuses on making dependency failures cheaper and safer.
Timeouts: Bounding the Cost of Waiting
A timeout is a limit on how long your service waits for a dependency. Without one, a stuck connection can consume a worker until the request itself times out. Enough stuck workers can make your service unavailable.
Set deadlines for connection, reading, and the whole operation when your HTTP client supports them. Choose values from your service's latency budget. A timeout should leave time to return a response, not consume the entire incoming request deadline.
Failing fast returns an error immediately. Failing completely makes the whole feature unavailable. Graceful degradation returns a useful reduced response instead.
def get_recommendations(user_id, fetch, timeout=0.5):
try:
items = fetch(user_id, timeout=timeout)
return {"items": items, "degraded": False}
except (TimeoutError, ConnectionError):
return {"items": [], "degraded": True}Retries with Exponential Backoff and Jitter
Retries help with brief transient failures, such as a dropped connection. Exponential backoff increases the wait after each failure. Jitter adds randomness so many clients do not retry simultaneously and create a retry storm.
Retry only operations that are safe to repeat, and cap both the attempt count and total time.
import random
import time
def call_with_retry(fn, attempts=3, base=0.1, cap=2.0):
for attempt in range(attempts):
try:
return fn()
except (TimeoutError, ConnectionError):
if attempt == attempts - 1:
raise
delay = random.uniform(0, min(cap, base * 2 ** attempt))
time.sleep(delay)Circuit Breakers
A circuit breaker tracks failures. After a threshold, it opens and skips dependency calls for a cool-down period. Calls go directly to a fallback. A later trial request checks whether the dependency recovered.
The breaker must be shared at the right scope and made thread-safe in production. Record when it opens, closes, and rejects calls.
Fallback Strategies
Choose the fallback from the feature's importance and data freshness requirements:
| Strategy | Suitable when |
|---|---|
| Cache | Recent data is better than no data |
| Default value | An empty or safe result is acceptable |
| Simplified feature | Core behavior can work without enrichment |
| Alternative provider | Another trusted dependency supplies similar data |
Return a degraded-state signal in the response, metrics, and logs. This lets users understand reduced behavior and lets operators measure its frequency.
Exercise
Why should a retry policy use both exponential backoff and jitter?
Show answer
Backoff reduces pressure after failures, while jitter spreads retries across time and prevents synchronized retry storms.