Sub topic 2
What Graceful Degradation Means
This chapter defines graceful degradation and separates it from two other outcomes: failing completely and failing fast. It assumes you have built a service that calls other services or databases over a network, that you know how exceptions work in your language, and that you understand HTTP status codes, latency, and availability. Later chapters cover the mechanisms (timeouts, retries, circuit breakers) in detail. Here the goal is a working model of the idea itself.
The core idea
Graceful degradation is a design approach in which a service keeps doing its most important work, with reduced quality or reduced scope, when something it depends on stops working properly.
The alternative is the default behavior of most code. A request handler calls a dependency. The dependency fails or hangs. The exception propagates up. The user gets an error page, even though 90% of what they wanted had nothing to do with the broken part.
Graceful degradation breaks that link. A failure in one part of the system reduces what the service can offer. It does not stop the service from working.
Some everyday examples:
- A product page loads without the "customers also bought" section because the recommendation service is down.
- A search box returns results ordered by a simple default ranking because the personalization service timed out.
- A video player drops from HD to standard quality when bandwidth falls.
- A checkout page accepts an order and says "your confirmation email will arrive shortly" because the email provider is unreachable.
In each case the user can still do the main thing they came to do.
Three ways a service can respond to failure
It helps to name the possible outcomes when a dependency fails. There are three.
| Outcome | What the service does | What the user sees |
|---|---|---|
| Fail completely | Waits, retries without limit, or crashes. The failure spreads. | Hangs, timeouts, or a generic error. Often unrelated features break too. |
| Fail fast | Detects the problem quickly and returns a clear error. | A quick, honest error for the affected request. |
| Degrade gracefully | Detects the problem quickly and returns a reduced but useful response. | The page or API works, with some missing or approximate content. |
Failing completely
A complete failure is usually not a deliberate choice. It happens when no one decided what should occur when a dependency misbehaves. A typical chain looks like this:
- A dependency becomes slow, not dead.
- Each request to your service waits on it with no time limit.
- Worker threads or connections pile up, all blocked on the slow call.
- The worker pool is exhausted. Requests that never touch the dependency are now queued behind blocked ones.
- The whole service stops responding.
This is a cascading failure. One slow optional component takes down the whole service. Slowness is often worse than an outright error, because an error returns immediately and frees the worker, while a hang holds on to it.
Failing fast
Failing fast means returning an error quickly instead of waiting. It is a large improvement over failing completely. It frees resources, gives callers prompt feedback, and keeps the service responsive for other requests.
Failing fast is still a failure for that request, though. If the recommendation call fails fast and your handler lets the exception through, the user sees an error page. Fast, but still an error page.
Degrading gracefully
Graceful degradation includes failing fast as a building block, because you have to detect problems quickly before you can substitute something else. It then adds a decision: what useful response can we give instead?
The relationship looks like this:
Both the degraded response and the fast error are deliberate outcomes. The only unacceptable outcome is the one with no decision behind it.
A worked example
Consider an e-commerce product page. To build it, the service calls four things:
- The product database, for name, price, and description.
- The inventory service, for stock status.
- The recommendation service, for "you might also like".
- The review service, for star ratings and comments.
Without any degradation design, the handler might look like this:
def product_page(product_id, user_id, clients):
product = clients["catalog"].get(product_id)
stock = clients["inventory"].get(product_id)
recs = clients["recommendations"].get(user_id)
reviews = clients["reviews"].get(product_id)
return {
"product": product,
"stock": stock,
"recommendations": recs,
"reviews": reviews,
}If any of the four calls raises an exception, the whole page fails. If any of them hangs, the page hangs. The availability of the page is the product of the availability of all four dependencies. Four dependencies that are each up 99.9% of the time give a page that is up about 99.6% of the time (0.999^4 ≈ 0.996). Each new dependency lowers the total.
A degraded version treats the dependencies differently:
def product_page(product_id, user_id, clients):
# Essential: without these there is no page to show.
product = clients["catalog"].get(product_id)
page = {"product": product, "degraded": []}
# Important but substitutable: show "check availability" if unknown.
try:
page["stock"] = clients["inventory"].get(product_id, timeout=0.3)
except (TimeoutError, ConnectionError):
page["stock"] = "unknown"
page["degraded"].append("inventory")
# Optional: omit the section if unavailable.
try:
page["recommendations"] = clients["recommendations"].get(user_id, timeout=0.5)
except (TimeoutError, ConnectionError):
page["recommendations"] = []
page["degraded"].append("recommendations")
try:
page["reviews"] = clients["reviews"].get(product_id, timeout=0.5)
except (TimeoutError, ConnectionError):
page["reviews"] = []
page["degraded"].append("reviews")
return pageFour things changed:
- The catalog call is still allowed to raise. A product page with no product is not useful, so a fast error is the right outcome.
- The other three calls have time limits and catch the specific failures that signal "dependency unavailable".
- Each catch block substitutes a defined value:
"unknown"for stock, an empty list for the optional sections. - The response records which parts are degraded, so callers and operators can tell.
The page now depends fully on one dependency and loosely on three others. Deciding which is which is the subject of the next chapter.
Degradation is a spectrum
Degradation is not one on/off switch. A service can have several levels, each giving up more:
| Level | Condition | Behavior |
|---|---|---|
| Full service | All dependencies healthy | Everything works. |
| Mild degradation | An optional dependency fails | Optional content is missing or stale. |
| Heavy degradation | An important dependency fails | Core flow works with reduced accuracy, such as "stock unknown". |
| Minimal service | Many dependencies fail or load is extreme | Only the essential function, such as read-only browsing, remains. |
| Unavailable | The essential dependency fails | A clear error. |
Designing these levels in advance lets you reason about what the service promises at each step. It also lets you put the cutoff for "unavailable" at the right place instead of letting it fall wherever the code happens to break.
What graceful degradation is not
Several things are easy to confuse with it.
- It is not hiding errors. If you catch an exception and return an empty list with no signal, you have turned a visible problem into an invisible one. Degraded responses should be marked, counted, and logged. A later chapter covers this.
- It is not retrying forever. Retries can help with brief faults, but unlimited retries against a struggling dependency make the failure worse.
- It is not high availability. Redundancy (extra servers, replicas, multiple zones) reduces the chance that a component fails. Degradation decides what happens after a component fails anyway. The two work together.
- It is not always the right answer. Some operations must fail rather than approximate. A payment service that cannot reach its ledger should not guess that the charge succeeded.
Properties of a good degraded response
A degraded response is only useful if it meets a few conditions.
- It is honest. It does not claim to be full-fidelity. Stale data is labeled as stale, and unknown values are shown as unknown.
- It is bounded in time. The service decides quickly. A fallback that arrives after 30 seconds is not a fallback.
- It is safe. The substitute value cannot cause a harmful action, such as charging the wrong amount or leaking another user's data.
- It is cheap. The fallback path must not depend on the same failing resource. A fallback that calls a second instance of the same broken service fails the same way.
- It is tested. Fallback code runs rarely, so it tends to rot. Untested fallbacks often fail at the exact moment they are needed.
The fourth property catches many real designs. If a cache lives in the same database that just went down, the cache is not a fallback.
Where degradation sits in the larger toolkit
Graceful degradation is the goal. The techniques in the rest of this tutorial are the means.
| Technique | Role in degradation |
|---|---|
| Timeouts | Bound how long the service waits, so slowness becomes a detectable failure. |
| Retries with backoff and jitter | Recover from brief faults without overloading the dependency. |
| Circuit breakers | Stop calling a dependency that is known to be failing, and switch to the fallback immediately. |
| Fallback strategies | Provide the substitute value or behavior. |
| Bulkheads | Keep a failure in one area from consuming resources used by others. |
| Load shedding | Drop low-priority work when demand exceeds capacity. |
| Signals and testing | Make degraded behavior visible and prove it works. |
None of these works alone. A fallback without a timeout never runs, because the code is still waiting. A timeout without a fallback just produces a faster error.
A minimal pattern
The smallest useful degradation pattern is a function that wraps a call, bounds it, and substitutes a default. You can reuse it for optional dependencies:
def optional(fetch, default, expected_errors=(TimeoutError, ConnectionError)):
"""Call fetch(). On an expected failure, return (default, True)."""
try:
return fetch(), False
except expected_errors:
return default, True
# Usage
recs, degraded = optional(lambda: [1, 2, 3], default=[])
print(recs, degraded) # [1, 2, 3] False
def failing():
raise TimeoutError("recommendation service timed out")
recs, degraded = optional(failing, default=[])
print(recs, degraded) # [] TrueTwo details matter. First, the function catches only the listed exceptions. Catching Exception would also swallow bugs such as a KeyError from bad code, and those should surface. Second, it returns a flag with the value, so the caller can pass the degraded state on to the response.
Note that this sketch does not enforce a time limit itself. It relies on fetch raising TimeoutError when its own timeout expires. The next chapters show how to set that limit.
Common mistakes
- Treating all dependencies the same. Wrapping everything in try/except, or nothing at all, ignores that dependencies differ in importance.
- Catching too broadly.
except Exceptionhides programming errors behind a fallback. - Fallbacks that share the failure. A fallback reading from the failed database, or calling the failed service through another route.
- Silent degradation. Nobody learns that recommendations have been empty for three days.
- No time limit. The fallback never triggers because the call never returns.
- Designing only the happy path in tests. The degraded paths ship untested.
Summary
Graceful degradation means a failing dependency lowers what the service offers instead of ending it. It builds on failing fast, since you need quick detection, and adds a deliberate choice of a useful substitute. Good degraded responses are honest, quick, safe, independent of the failed resource, and tested. The next chapter covers how to decide which parts of your service are essential and which can be dropped.
Exercise
A news site's article page calls an article database (title and body), a comment service, and an ad service. The comment service starts responding in 20 seconds instead of 50 ms. With no timeouts, the whole site becomes unresponsive, including pages that do not show comments. (a) Explain why slowness in one service affects unrelated pages. (b) Describe a degraded behavior for the comment service and for the ad service, and say which dependency should cause a fast error if it fails.
Show answer
(a) Each request that calls the comment service holds a worker thread or connection for up to 20 seconds. As these requests accumulate, the worker pool fills with blocked requests. Requests for pages that do not use comments then wait in the queue behind them, so the whole service stops responding. This is a cascading failure caused by missing time limits. (b) Comments: set a short timeout (for example 500 ms) and, on failure, show the article without the comment section, or show a message such as "Comments are temporarily unavailable". Ads: on failure, render the page with no ad or a house ad, because the page is still fully readable. The article database should cause a fast error, because an article page without a title and body has no useful content to show.
Exercise
A developer writes this fallback for a function that checks whether a user is allowed to view a document: except Exception: return True. The authorization service is sometimes unreachable. Explain what is wrong with this approach, and what outcome would be safer.
Show answer
Returning True when the authorization service is down grants access to everyone during an outage, which is a security failure. Catching Exception also hides unrelated bugs. Authorization is a critical dependency whose failure must not be approximated with a permissive default. The safer outcome is to fail fast with a clear error (or deny access), catching only the specific connection and timeout errors, and logging the event so operators see it.