Sub topic 3
Deciding what is essential and what can be dropped
This chapter assumes you have built a service that calls other services or databases over a network, you know how exceptions work in your language, and you understand HTTP requests and responses. It also assumes you know what latency and availability mean. The previous chapters described how dependencies fail and what graceful degradation means. This chapter covers the decision that comes before any timeout, retry, or fallback: which dependencies the service cannot live without, and which it can lose.
Why classification comes first
A fallback is only useful if you know what the service should do when a dependency is gone. That answer differs by dependency. Losing the payment provider during checkout should stop the order. Losing the recommendation engine should only mean the page shows fewer suggestions.
If you skip the classification, two failures are common:
- Everything is treated as critical. Any dependency error turns into a 500 response. The service is only as available as its least reliable dependency.
- Everything is treated as optional. The service hides real failures behind defaults, and users get wrong results without knowing it. A checkout that skips the fraud check "because it was down" is an example.
The goal is to decide, per dependency and per feature, what a failure means and what the service will do about it. You make this decision once, in design, and write it down. You should not make it at 3 a.m. during an incident.
Critical and optional dependencies
A critical dependency is one without which the request cannot produce a correct, safe result. An optional dependency is one whose absence makes the result less complete or less polished, but still correct and safe.
Ask these questions about each dependency, for each operation that uses it:
- Can the operation produce a correct result without it? If not, it is critical for that operation.
- Would a wrong or stale result cause harm? Harm includes money lost, data corrupted, security bypassed, or legal obligations broken.
- Can the user complete their main goal without it? The main goal is the reason they came to the service.
- Is the data it supplies decorative, advisory, or authoritative? Decorative and advisory data can often be dropped. Authoritative data usually cannot.
The classification belongs to an operation, not to the dependency alone. One dependency can be critical in one place and optional in another.
| Dependency | Operation | Classification | Reason |
|---|---|---|---|
| Primary database | Place order | Critical | The order must be stored durably |
| Payment provider | Place order | Critical | No payment, no order |
| Recommendation service | Product page | Optional | Page works without suggestions |
| Review service | Product page | Optional | Reviews inform but are not required to buy |
| Inventory service | Product page | Optional (approximate) | A cached stock level is acceptable for display |
| Inventory service | Place order | Critical | Overselling has a real cost |
| Email provider | Order confirmation | Optional (deferred) | The email can be sent later from a queue |
| Auth service | Any authenticated request | Critical | Without identity, access cannot be granted safely |
The inventory service appears twice. For display, a stale count is fine. At the moment of purchase, the same data decides whether the sale is valid. Classifying by service name alone would get one of these two wrong.
A third category: degradable
The critical/optional split is a useful start, but many dependencies fit neither label cleanly. Three working categories are more accurate:
- Critical: the operation fails, or is rejected with a clear error, when the dependency is unavailable.
- Degradable: the operation succeeds with reduced quality. It might use older data, an approximation, or a simpler method.
- Optional: the operation succeeds and the feature is simply omitted.
In the table above, inventory on a product page is degradable. Recommendations are optional. The difference matters because degradable dependencies need a fallback that produces something plausible, while optional ones only need the code to skip the feature.
Failing closed and failing open
When a dependency that makes a safety or security decision is unavailable, you must choose a default direction.
- Fail closed means deny the action when the check cannot be performed. A permission service that is down should cause access to be denied.
- Fail open means allow the action when the check cannot be performed. A rate limiter that is down might allow traffic through, because blocking all users would be worse than allowing some excess.
The right choice depends on the cost of being wrong in each direction.
| Check | Typical choice | Reasoning |
|---|---|---|
| Authentication | Fail closed | Allowing unknown users is a security breach |
| Authorization | Fail closed | Same reason |
| Fraud scoring | Depends on the business | Closed blocks all sales; open accepts some fraud. Some teams fail open only below a purchase amount |
| Rate limiting | Usually fail open | Blocking everyone is a bigger outage than allowing excess requests briefly |
| Feature flags | Fail to a known default | Use the last known value or a compiled-in safe default |
Fail-open decisions deserve extra care. If you choose to fail open, make sure it is limited in scope (for example, only for low-value transactions) and visible in logs and metrics, so you can review what was let through.
Mapping dependencies for one request
The most reliable way to classify is to trace a single request and list every call it makes. The following diagram shows a product page request and how each call is treated.
Once you have this map, each branch becomes a small design decision with three parts: the failure behavior, the fallback, and who is told.
Writing the degradation contract
For each dependency and operation, record a short degradation contract. A contract is a statement of what the service promises when the dependency fails. A useful contract answers these questions:
- What class is the dependency for this operation (critical, degradable, optional)?
- What does the service return when it fails?
- How stale or approximate may the fallback result be?
- How long may the service run in this state?
- Who is told, and how (user message, metric, log, alert)?
A contract for the recommendation service might read:
- Class: optional on the product page.
- Behavior: omit the "You may also like" section. Return a 200 response.
- Staleness: a cached result up to 24 hours old is acceptable. Past that, omit the section.
- Duration: no limit, but alert if the failure lasts more than 15 minutes.
- Signaling: increment a degraded-response metric. Do not show an error message to the user.
A contract for the payment provider is shorter:
- Class: critical on checkout.
- Behavior: return a clear error, such as 503 with a retry hint. Do not create the order.
- Staleness: not applicable.
- Signaling: page the on-call engineer when the failure rate passes a threshold.
Writing this down gives the team something to review, and it gives tests something to check against. The final chapter of this tutorial uses these contracts as the source of fault-injection test cases.
Encoding the classification in code
Classification is easy to lose if it only lives in a document. A small amount of structure keeps it visible in the code. The sketch below declares each dependency's class in one place and has a single helper that applies the rule.
from enum import Enum
class Criticality(Enum):
CRITICAL = "critical"
DEGRADABLE = "degradable"
OPTIONAL = "optional"
class DependencyUnavailable(Exception):
"""Raised when a critical dependency fails."""
def call_dependency(name, criticality, fn, fallback=None):
"""Call fn. Apply the failure policy for the dependency's class."""
try:
return fn(), False
except (TimeoutError, ConnectionError) as exc:
if criticality is Criticality.CRITICAL:
raise DependencyUnavailable(name) from exc
if criticality is Criticality.DEGRADABLE and fallback is not None:
return fallback(), True
if criticality is Criticality.OPTIONAL:
return None, True
raise DependencyUnavailable(name) from exc
def build_product_page(product_id, services):
product, _ = call_dependency(
"product_db", Criticality.CRITICAL,
lambda: services["product_db"](product_id),
)
stock, stock_degraded = call_dependency(
"inventory", Criticality.DEGRADABLE,
lambda: services["inventory"](product_id),
fallback=lambda: services["stock_cache"](product_id),
)
recs, recs_degraded = call_dependency(
"recommendations", Criticality.OPTIONAL,
lambda: services["recommendations"](product_id),
)
return {
"product": product,
"stock": stock,
"recommendations": recs or [],
"degraded": stock_degraded or recs_degraded,
}Three details in this sketch are worth noting:
- Only specific exceptions are caught. A programming error such as
KeyErrorstill surfaces, so a bug is not mistaken for an outage. - A degradable dependency with no fallback available is treated as critical. That is the safe direction.
- The function returns a flag alongside the result. The caller can then set a
degradedfield in the response, which later chapters use for metrics and user messages.
The critical call fails the whole page by raising an exception. The HTTP layer decides how to turn DependencyUnavailable into a 503 response.
Edge cases that change the classification
Classifications are not permanent. Watch for these situations.
Dependencies that look optional but are not
Some dependencies seem decorative until you trace what depends on their output. A "pricing hints" service that supplies discount data may look optional on a product page. If the checkout later trusts the price shown on the page, dropping the discount data can charge customers the wrong amount. Follow the data forward: if a later step consumes the result, the dependency may be more important than it looks.
Optional dependencies that are slow
An optional dependency can still take down a service if it is slow. A call with no timeout that blocks a worker thread for 30 seconds consumes the same resources as a critical call. Classification decides what to do after a failure. Timeouts decide how long you wait before you reach that point. Optional dependencies usually need shorter timeouts than critical ones, since you are less willing to pay for them.
Fallbacks that depend on other failing things
A cache fallback is only a fallback if the cache is independent of the failing dependency. If the cache is populated by the same service that is down, a long outage empties it and the fallback disappears. Check that each fallback has a failure mode different from the thing it replaces.
Compound degradation
Several optional features can fail at once. Each failure alone is harmless, but a page with no recommendations, no reviews, and stale stock may no longer meet the user's goal. Define a floor: a minimum set of features below which the service reports itself as unavailable instead of returning an empty shell. Some teams express this as a count of failed optional dependencies. Others name the features that must be present together.
Business rules change
Whether stale prices are acceptable during a sale differs from a normal day. Review classifications when the business context changes, and when new dependencies are added. A new call added to a request path should arrive with a classification and a contract.
Common mistakes
- Classifying by team or service name rather than by operation. The inventory example above shows why.
- Making the classification implicit. If it exists only as scattered
try/exceptblocks, no one can review it. - Treating "optional" as "ignorable". An optional dependency that fails for days still needs an alert, since users are getting a worse product.
- Skipping the user's view. The people who decide what is essential should include product owners, not only engineers. Engineers can say what is technically possible, but the business decides what a user can do without.
- Failing open on security checks because it was easier to code.
Summary of the decision process
- List every dependency call on each important request path.
- For each call, ask whether a correct and safe result is possible without it.
- Label it critical, degradable, or optional for that operation.
- For security and safety checks, decide whether to fail closed or open, and limit any open behavior.
- Write a degradation contract covering behavior, staleness, duration, and signaling.
- Encode the classification in code, in one place.
- Revisit it when the business or the architecture changes.
Exercise
A checkout service calls four dependencies: the payment provider, a tax calculation service, a "customers also bought" recommendation service, and a loyalty-points service that shows the user's point balance on the order summary. Classify each as critical, degradable, or optional for the "place order" operation, and give a one-sentence reason for each. Then state what the service should do if the loyalty-points service fails, and name one signal you would emit.
Show answer
Payment provider: critical, because an order cannot be completed without taking payment. Tax calculation: critical, because charging the wrong tax is a legal and financial problem (a cached rate table could make it degradable only if the business accepts that risk). Recommendations: optional, because the order does not depend on them. Loyalty points: optional or degradable, because the balance is informational. If it fails, the service should still place the order, omit the balance (or show the last cached balance labeled as possibly out of date), and not show an error. It should also make sure points earned on this order are recorded for later, for example by queuing the update. Signals: increment a degraded-response counter tagged with the dependency name "loyalty", and log a warning that includes the order ID so the points can be reconciled.
Exercise
A rate limiter service is unavailable. The API gateway can either fail open (allow all requests) or fail closed (reject all requests). Which would you choose for a public read-only product search API, and which for an endpoint that sends SMS messages that cost money? Explain how you could limit the risk of the fail-open choice.
Show answer
For product search, fail open. Rejecting every request turns a limiter outage into a full outage, and extra read traffic is cheap. For the SMS endpoint, fail closed, or fail open only with a strict local fallback, because uncontrolled traffic has a direct financial cost and can be abused. To limit the risk of failing open, apply a coarse in-process limit on each gateway instance that works without the limiter service, set a short time limit on the open state, log and count every request admitted while the limiter was down, and alert so someone can review the traffic.