Sub topic 10
Making degraded behavior visible to operators and users
A fallback that works silently is only half finished. The service keeps answering, but nobody learns that a dependency is down, that responses are stale, or that a feature is missing. This chapter covers how to report degraded behavior to three audiences: the operators who run the service, the client code that calls it, and the people who use it.
This chapter assumes you can read Python, know what HTTP headers and status codes are, and have seen timeouts, retries, circuit breakers, and fallbacks from earlier chapters. It reuses the get_recommendations fallback pattern, which returns cached data or an empty default and flags the response as degraded.
Why silent degradation is a problem
Degradation hides failure by design. The user gets a page and the load balancer gets a 200. Three things go wrong when nothing makes the degradation visible:
- Outages go unnoticed. If the recommendations service is down for six hours and every request still succeeds, no error-rate alert fires. You find out when a product manager asks why click-through fell.
- Fallbacks rot. A cache that is served for six hours instead of six seconds is no longer a fallback in the sense you designed. Nobody decided that staleness was acceptable.
- Decisions are made on wrong data. A client that treats an empty default list as "this user has no recommendations" may store that conclusion or act on it.
The goal is to make every fallback leave evidence, and to make that evidence reach the right audience in a useful form.
Signals for operators
Operators need to answer three questions quickly. Is the service degraded right now? Which dependency caused it? How much traffic is affected? Metrics, logs, and traces each answer part of this.
Metrics
Metrics are cheap to aggregate and good for alerting. For each fallback-protected call, record at least these:
- A counter of outcomes, labeled by dependency and outcome (
success,fallback_cache,fallback_default,rejected_by_breaker). - A gauge for circuit breaker state per dependency (closed, open, half-open), so you can see when a breaker opened and how long it stayed open.
- A latency histogram for the dependency call, so you can see slowness building before timeouts begin.
- The age of served cached data, as a histogram or a maximum, so you can tell whether stale data is minutes or days old.
Keep label values to small, fixed sets. A user_id label creates one time series per user and can overwhelm your metrics system. Use dependency, source, and a short reason such as timeout or connection_error.
The most useful derived number is the fallback ratio: fallbacks divided by all calls to that dependency over a window. It rises while the user-facing error rate stays flat, which is the signal you are missing without it.
Logs
Logs carry the detail that metrics drop. Write one structured line per fallback event with the dependency, the reason, the fallback source, and the elapsed time. Keep two cautions in mind:
- Do not log every fallback at full volume during an outage. If a dependency is down and you serve 5,000 requests per second, you write 5,000 identical warnings per second. Log the first event, then sample, or log breaker state changes (opened, half-open, closed) instead of each rejected call.
- Include a request or trace ID so you can connect a fallback log line to the request that triggered it.
Traces
If you use distributed tracing, add attributes to the span for the dependency call, such as fallback.used=true and fallback.source=cache. A trace then shows the slow timeout, the failed retry, and the fallback in one view, which is the quickest way to explain why one particular request was slow or incomplete.
Instrumenting a fallback
The version below extends the earlier cache-and-default fallback. It counts outcomes, logs the fallback reason, and reports how old the cached data is. It uses only the standard library, and a plain Counter stands in for a real metrics client.
import logging
import time
from collections import Counter
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
logger = logging.getLogger("recommendations")
metrics = Counter()
_cache = {}
def get_recommendations(user_id, fetch, timeout=0.5):
"""Return recommendations plus data describing any degradation."""
try:
items = fetch(user_id, timeout=timeout)
except (TimeoutError, ConnectionError) as exc:
reason = type(exc).__name__
if user_id in _cache:
items, stored_at = _cache[user_id]
source = "cache"
age = round(time.monotonic() - stored_at, 1)
else:
items, source, age = [], "default", None
metrics[("recommendations", "fallback_" + source, reason)] += 1
logger.warning(
"fallback dependency=recommendations source=%s reason=%s age_s=%s",
source, reason, age,
)
return {
"items": items,
"degraded": True,
"feature": "recommendations",
"source": source,
"age_seconds": age,
}
_cache[user_id] = (items, time.monotonic())
metrics[("recommendations", "success", "")] += 1
return {"items": items, "degraded": False, "feature": "recommendations"}
def flaky_fetch(user_id, timeout):
if user_id == "bob":
raise TimeoutError("recommendations timed out")
return ["book", "lamp"]
print(get_recommendations("alice", flaky_fetch))
print(get_recommendations("bob", flaky_fetch))
print(dict(metrics))Running this prints a normal response for alice, then a degraded response for bob with source set to default and age_seconds set to None. It also emits one warning line and ends with the counter values. The source field matters because a cache fallback and a default fallback have different consequences for users, so they should be counted separately.
Signals for callers
A service that degrades is often called by other services or by a front end. Those callers need a machine-readable signal, or they cannot adapt. There are three common places to put it.
- A field in the response body, such as
"degraded": true. This is easy to add and easy for a front end to read. - A response header, such as
X-Degraded: recommendations. Proxies, gateways, and logging tools can read headers without parsing bodies. - A status code, used with care. Returning 200 for a response that is missing a whole optional section is normal. Reserve 503 for cases where a critical dependency failed and you have no useful answer.
For cached fallbacks, HTTP already has the Age header, which states how many seconds a response has been held in a cache. Reusing it for stale fallbacks keeps you close to existing conventions.
def build_headers(result):
"""Translate a degradation result into HTTP response headers."""
headers = {}
if result["degraded"]:
headers["X-Degraded"] = result["feature"]
headers["X-Degraded-Source"] = result["source"]
if result.get("age_seconds") is not None:
headers["Age"] = str(int(result["age_seconds"]))
return headers
print(build_headers({
"degraded": True,
"feature": "recommendations",
"source": "cache",
"age_seconds": 42.7,
}))This prints {'X-Degraded': 'recommendations', 'X-Degraded-Source': 'cache', 'Age': '42'}. A gateway or front end can now decide to hide the recommendations panel, show a notice, or skip storing the response.
Write down in your API documentation what each degraded signal means. A flag that clients do not understand gets ignored.
Messages for users
People using the product do not need to know that a circuit breaker opened. They need to know what they are not getting and what they can do about it. A good degraded-state message:
- Names the affected feature, not the cause. "Recommendations are unavailable right now" is useful. "Upstream service timeout" is not.
- Says what still works. "You can still search and check out."
- Offers a next step when one exists, such as a retry button, but not for something that will fail again immediately.
- Does not alarm. A missing optional panel is not an emergency. A banner for it should be calm and unobtrusive.
- Marks stale data as stale. If you show cached prices or inventory, show when they were last updated, such as "Prices as of 10:42." This matters most when the data drives a decision or a payment.
Sometimes the right choice is to show nothing. A recommendations carousel that quietly disappears is often better than a banner that draws attention to a minor loss. Decide per feature, using the critical-versus-optional classification you made earlier. Critical features that cannot be provided deserve a clear message. Optional ones usually do not.
Connecting the signals
One fallback event should produce several outputs at once. The diagram shows how a single event feeds each audience.
Generate all of these from one place, so that adding a new fallback does not mean remembering four separate changes. A small wrapper or decorator around fallback calls is a common way to do this.
Alerting on degradation
Choose alert conditions that match what you want a person to do:
| Signal | What it tells you | Typical response |
|---|---|---|
| Fallback ratio above a threshold for several minutes | A dependency is failing for a meaningful share of requests | Page for critical features, ticket for optional ones |
| Breaker open longer than its normal cool-down cycle | Trial calls are failing, so the dependency is not recovering | Investigate the dependency |
| Age of served cache data beyond its limit | The fallback is stale beyond what you accepted | Fix the dependency, or stop serving that cache |
| Fallback used while the dependency reports healthy | The timeout or breaker settings are wrong | Review thresholds |
| Default fallback rising versus cache fallback | The cache is cold or expired | Check cache warm-up and time-to-live settings |
Link severity to the feature's importance. Paging someone at night because an optional carousel shows defaults is a poor use of attention. A ticket that opens during working hours is usually enough. A critical dependency with a degraded fallback is different, and may justify a page.
Health checks and readiness
Health endpoints need the same care. A service that has lost an optional dependency is usually still healthy enough to receive traffic, so a readiness check that fails on any dependency error can remove every instance from the load balancer and turn a partial outage into a full one. A better design:
- Keep readiness tied to what the instance needs to serve its critical function.
- Report optional dependency status in a separate field or endpoint for dashboards, such as
"recommendations": "degraded", without failing readiness.
Common mistakes
- Treating the
degradedflag as optional. If one code path forgets to set it, that path is silently misleading. Build the response through one function. - High-cardinality labels. User IDs, URLs with IDs in them, or free-text error messages as metric labels grow without bound. Use fixed categories and put the detail in logs.
- Logging only on failure. If you log only fallbacks, you cannot tell whether a quiet log means health or a broken logger. Counting successes lets you compute a ratio.
- No recovery signal. Record the transition back to normal as well, such as the breaker closing. Without it, nobody knows when an incident ended.
- Showing stale data as fresh. A cached fallback with no timestamp invites users to act on information that may be wrong.
- Leaking internals to users. Hostnames, stack traces, and dependency names in user-facing messages help attackers and confuse everyone else.
Summary
Visible degradation has three parts. Operators get metrics, logs, and traces that show fallback ratio, breaker state, and data staleness. Calling services get a body flag and headers they can act on. Users get short, honest messages about what is affected, shown only where the loss matters. Alerts should be based on the fallback ratio and breaker behavior, and availability numbers should treat fallback responses as a separate outcome.
Exercise
A checkout service calls a loyalty-points service, which is optional, and a payment service, which is critical. The loyalty service has been down for two hours. Error-rate dashboards are flat and no alerts have fired. Name two signals you would add so the team notices, and say what severity of alert each should raise.
Show answer
Add a counter of loyalty fallbacks (labeled with dependency, fallback source, and reason) and alert on its ratio to total loyalty calls over several minutes. Because loyalty is optional, this should open a ticket or send a low-urgency notification, not a page. Also export circuit breaker state for the loyalty dependency and alert if the breaker stays open for longer than a few cool-down cycles, which indicates the dependency is not recovering. This is also a ticket-level alert. The same signals for the payment service would justify a page, since it is critical.
Exercise
Your recommendations fallback serves cached data. A teammate proposes labeling the metric with user_id so you can see which users got stale data. What is wrong with this, and what should you do instead?
Show answer
A user_id label creates one time series per user, which grows without bound and can overload the metrics system. Keep metric labels to small fixed sets such as dependency, fallback source, and reason. Put the user_id in structured log lines or trace attributes, where per-request detail belongs, so you can still look up which users were affected.