Sub topic 1
How dependencies fail: errors, slowness, and partial outages
Every service you build calls something else: a database, a payment API, a search index, a feature flag service, an internal microservice. Each of these calls can fail, and the way it fails decides which defenses will work. This chapter describes the main failure modes and how each one spreads into your service. The rest of the tutorial builds the defenses on this base.
Prerequisites
This chapter assumes you can:
- Build a service that calls other services or databases over a network.
- Read and write exception handling in a language such as Python, Java, or Go.
- Describe an HTTP request and response, including status codes.
- Explain latency (how long a call takes) and availability (the fraction of calls that succeed).
The code examples use Python 3.8 or later and only the standard library.
Why failure modes matter
A dependency is any component your service needs in order to answer a request but does not control. Your code does not fail the same way every time it calls one. The call might return an error at once, hang for thirty seconds, or succeed for 90% of users and fail for the rest. Each pattern needs a different response.
Teams often treat all failures as one thing: "the dependency is down." That model leads to retry loops that make outages worse, and to timeouts that are too long to help. A better model sorts failures into a few categories and asks what each one costs your service.
The main failure modes
| Failure mode | What the caller sees | Typical cause | Main risk to the caller |
|---|---|---|---|
| Hard failure | Immediate error (connection refused, DNS failure, HTTP 503) | Process crashed, host unreachable, deploy gone wrong | Errors surface to users unless handled |
| Slowness | Success, but late | Overload, garbage collection pauses, lock contention, cold caches | Callers pile up waiting and run out of threads or connections |
| Timeout or hang | No answer at all | Network partition, dropped packets, deadlocked server | Resources held until the timeout fires, if one is set at all |
| Partial outage | Some requests fail, others succeed | One bad node, one shard, one region, one feature path | Failures look random and are hard to reproduce |
| Wrong or stale data | A success response with bad content | Replication lag, bad deploy, schema drift | No error signal, so wrong answers spread silently |
| Throttling | Rejections such as HTTP 429 | You exceeded a quota, or the dependency is shedding load | Aggressive retries make it worse |
The next sections look at each one.
Hard failures
A hard failure is the easiest to handle. The call fails quickly with a clear signal: a refused connection, an unresolvable hostname, or a 5xx status. The caller learns the answer in milliseconds and can move on.
Hard failures still need handling. If you let the exception propagate, one dead optional dependency turns every request into an error page. They are also cheap to detect, so hard failures are where fallbacks pay off first.
Slowness is usually worse than errors
A dependency that is slow but not down is more dangerous than one that is down. A failing call returns fast and frees its resources. A slow call holds a thread, a connection, and memory for the whole wait, and your service has only a fixed number of each.
You can see the mechanism with arithmetic. Suppose your service has 50 worker threads, receives 100 requests per second, and each request calls the dependency once. When the dependency answers in 20 ms, each request occupies a thread for about 20 ms. Average concurrency is 100 × 0.02 = 2 threads in use. If the dependency slows to 2 seconds, concurrency becomes 100 × 2 = 200 threads wanted, and you only have 50. The pool saturates within about half a second. Every new request now queues, including requests that never touch the slow dependency.
This relationship is Little's Law: concurrency equals arrival rate times time spent in the system. Slowness raises the time term, and capacity runs out quickly.
The following script shows the effect with a small thread pool. It compares a dependency that fails at once with one that succeeds slowly.
import time
from concurrent.futures import ThreadPoolExecutor
def fast_error():
raise ConnectionError("connection refused")
def slow_ok():
time.sleep(1.0)
return "ok"
def run(dependency, requests=8, workers=4):
start = time.monotonic()
outcomes = []
with ThreadPoolExecutor(max_workers=workers) as pool:
futures = [pool.submit(dependency) for _ in range(requests)]
for future in futures:
try:
outcomes.append(future.result())
except ConnectionError as exc:
outcomes.append(f"error: {exc}")
elapsed = time.monotonic() - start
return elapsed, outcomes
if __name__ == "__main__":
for name, dep in [("fast error", fast_error), ("slow success", slow_ok)]:
elapsed, outcomes = run(dep)
print(f"{name}: {len(outcomes)} requests finished in {elapsed:.2f}s")On a typical machine the output looks like this:
fast error: 8 requests finished in 0.00s
slow success: 8 requests finished in 2.00sAll eight requests failed in the first case, yet the service stayed responsive. In the second case every call "worked," but with 4 workers and 1 second per call, 8 requests take 2 seconds. Extend this to a service that also handles unrelated requests on the same pool, and those requests wait behind the slow ones.
Timeouts and hangs
A hang is the extreme case of slowness: the answer never arrives. This happens when a packet is dropped and the connection stays half open, when a server process deadlocks, or when a load balancer accepts the connection but has no healthy backend.
Many client libraries have no default timeout, or a very long one. Python's requests library, for example, waits indefinitely unless you pass a timeout argument. A hang with no timeout holds a resource forever. Chapter 4 covers how to choose timeout values. The point here is that a missing timeout turns any network problem into a resource leak.
There are also several stages where waiting can happen: connecting, sending the request, and waiting for the response. They fail differently. A connect timeout points to an unreachable host. A read timeout points to a host that accepted the work but did not answer.
Partial outages
Real dependencies are rarely fully up or fully down. Common partial patterns include:
- One of five instances is unhealthy, so about 20% of calls fail.
- One database shard is down, so only users whose data lives there are affected.
- One endpoint of the dependency is broken, such as
/searchwhile/lookupworks. - One availability zone has a network problem, so only calls that cross it fail.
- The dependency works for small requests but times out on large ones.
Partial outages are hard to diagnose because the average hides them. A dashboard that shows a 98% success rate looks healthy, while a specific group of users sees a 100% failure rate. They also defeat simple health checks. A health endpoint may return 200 while the real code path is broken.
Partial failure also makes retries useful. If one instance in five is bad, a retry has a good chance of reaching a healthy one. That same property makes retries tempting in cases where they cause harm, as the next section shows.
Wrong or stale data
Some failures return a success status with bad content. Examples include a cache that serves data from before an update, a read replica that lags by minutes, a deploy that changes a field name, or a pricing service that returns zero for unknown products.
These failures bypass error handling because there is no error. Treat the dependency's output as input you must validate at the boundary: check required fields, sane ranges, and freshness timestamps where they are available.
Throttling
A throttled call is rejected on purpose, often with HTTP 429 or 503 and sometimes a Retry-After header. The dependency is protecting itself. Throttling means the system works as designed, but the effect on your service is the same as an outage for those requests. If your response is to retry immediately, you add load to something already shedding load.
How a failure spreads
A failure in one dependency does not stay there. It moves upstream through the resources your service shares. The usual sequence is:
- The dependency slows down or starts hanging.
- Calls to it hold threads, connections, or memory longer.
- A shared pool fills up.
- Requests that do not need the dependency now wait for a free thread.
- Your service's own latency rises, and its callers hit their timeouts.
- Those callers retry, which adds load and repeats the pattern one level up.
The result is a cascading failure, where an outage in a minor component takes down a service that was otherwise healthy.
The loop from G back to C is what makes the failure self-reinforcing. Once it starts, the system often stays broken even after the original dependency recovers, because the backlog and retry traffic keep the pool full.
Classifying a failure when it arrives
You cannot choose a response until you know what kind of failure you have. A small classification step at the call site helps. The function below maps outcomes to categories that later chapters will use to decide between retrying, falling back, and giving up.
from enum import Enum
class Failure(Enum):
RETRYABLE = "retryable" # may succeed if tried again soon
THROTTLED = "throttled" # back off; do not hammer
PERMANENT = "permanent" # retrying will not help
UNKNOWN = "unknown"
def classify_status(status_code):
if status_code in (408, 502, 503, 504):
return Failure.RETRYABLE
if status_code == 429:
return Failure.THROTTLED
if 400 <= status_code < 500:
return Failure.PERMANENT
if status_code >= 500:
return Failure.UNKNOWN
return None # not a failure
def classify_exception(exc):
if isinstance(exc, (TimeoutError, ConnectionError)):
return Failure.RETRYABLE
return Failure.UNKNOWN
if __name__ == "__main__":
for code in (200, 404, 429, 503, 500):
print(code, classify_status(code))The reasoning behind these categories:
- A 404 or 400 means your request was wrong. Sending it again produces the same answer.
- A 503 or a connection reset often means a momentary condition, so another attempt may work.
- A 500 is ambiguous. It may be a bug triggered by this input, or a transient fault. Treating it as unknown pushes you to make a deliberate choice.
- Whether a retry is safe also depends on whether the operation is idempotent, meaning repeating it has the same effect as doing it once. A repeated
GETis harmless. A repeated "charge this card" is not, unless you pass an idempotency key.
Common mistakes
- Assuming "down" is the only failure. Tests that only simulate a refused connection miss slowness, which is the more damaging case.
- No timeout, or a default timeout. A library default of "wait forever" or 60 seconds is rarely what you want.
- Sharing one pool for everything. One slow call path then drains capacity for all paths.
- Trusting the average. Look at percentiles (p95, p99) and at success rate per user segment or per shard. A mean latency of 80 ms can hide a p99 of 8 seconds.
- Treating success status as correctness. A 200 with stale or empty data is still a failure for the user.
- Retrying everything. Retrying permanent errors wastes capacity, and retrying non-idempotent operations can duplicate side effects.
Where the rest of the tutorial goes
The failure modes above map to specific defenses:
| Failure mode | Primary defense | Chapter topic |
|---|---|---|
| Slowness and hangs | Timeouts | Bounding the cost of waiting |
| Brief hard failures | Retries with backoff and jitter | Retrying without a storm |
| Sustained failures | Circuit breakers | Stop calling a failing dependency |
| Any failure of an optional feature | Fallbacks | Cache, defaults, alternatives |
| Failures that spread through shared resources | Bulkheads | Containing failure |
| Overload | Load shedding | Protecting core functions |
Each defense handles only part of the problem, so they are used together. The next chapter defines graceful degradation as the goal that ties them together.
Exercise
Your service has 40 worker threads and receives 200 requests per second. Each request makes one call to a dependency. Normally the call takes 25 ms. During an incident, the dependency still returns success but now takes 1.5 seconds per call. Using concurrency = arrival rate × time in system, estimate how many threads you need before and during the incident, and say what happens to requests that do not call the dependency if all requests share the same 40 threads.
Show answer
Before: 200 × 0.025 = 5 threads in use, well under 40. During the incident: 200 × 1.5 = 300 threads wanted, but only 40 exist, so the pool saturates in a fraction of a second. Requests that never call the dependency still need a worker thread, so they queue behind the slow calls and see higher latency or time out. The dependency is not returning errors, yet the whole service becomes unresponsive. Separate pools (bulkheads) and timeouts on the dependency call would limit the damage.
Exercise
A dashboard shows 99% overall success for a service that reads from a database split into 100 shards. One shard is completely down. What does this tell you about averages, and what would you add to the monitoring to detect the problem?
Show answer
One failed shard out of 100 gives about 1% overall failures, which looks healthy on an aggregate success rate, but every user whose data lives on that shard fails 100% of the time. Averages hide partial outages. Add success rate and latency broken down by shard (or by user segment, region, or instance), and alert on the worst segment instead of only the overall figure.