Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 5 · Concept · 20 min · revision 3

When the Database or an Upstream API Fails

Handle failing dependencies and network blips using client timeouts, exponential backoff with full jitter, circuit breakers, and degraded fallbacks, so that one failing dependency does not take the rest of the system down with it.

Contentsand lesson path

What you will learn

  • Handle failing dependencies with timeouts, bounded retries with backoff and jitter, and an explicit fallback or error.

Prerequisites: FastAPI Fundamentals

01. Why it matters

In modern distributed microservices and cloud backends, failure is routine rather than exceptional. In this lesson a dependency is any service your code calls: a database, another microservice, a payment API (some teams call it the upstream service). Dependencies crash, database connection pools exhaust under sudden load, cloud network switches drop packets, and third-party payment gateways experience transient latency spikes.

When a dependency slows down or becomes unavailable, a naive backend can turn the problem into a much wider outage:

  • Missing timeouts exhaust server resources: If an HTTP client or database driver lacks explicit timeouts, worker threads or asynchronous event-loop tasks wait indefinitely for responses. New requests pile up behind them, memory use grows, and the API can stop answering health checks.
  • Synchronised retries create thundering herds: If a thousand clients retry a failing database query immediately and at the same moment, the database gets a burst of extra load just when it is trying to recover. This is called a retry storm or thundering herd.
  • Cascading failure across services: When service A waits for service B, and service B waits for service C, a slowdown in C can spread back up to A, because every caller in the chain holds resources while it waits.

The defences in this lesson are explicit timeouts, exponential backoff with random jitter, circuit breakers and fallback paths.

02. Configuring two timeouts: connect and read

The first rule of outbound network communication is that every remote call must have an explicit timeout. Relying on default client timeouts is dangerous: in many programming environments and libraries, the default timeout is infinite or tens of minutes.

Furthermore, production clients must distinguish between two distinct timeout phases:

  • The connect timeout is the longest time allowed to establish the initial TCP handshake and TLS session with the target server. Because this is purely network routing and socket establishment, it should be short (typically 500 milliseconds to 2 seconds).
  • The read (response) timeout is the longest time allowed to wait for the remote server to compute the result and stream back response bytes once the connection is established. This depends on workload complexity (typically 2 to 5 seconds for web APIs).

Here is how to configure explicit timeouts using Python's httpx asynchronous client. Create the client once, in the FastAPI lifespan, and reuse it: a new AsyncClient per call opens a new connection pool, so every request pays a fresh TCP and TLS handshake and the pool timeout means nothing. The two dependency errors are AppError subclasses from the exception handlers lesson; register handlers that map them to 503 and 504. Note the order of the except clauses: ReadTimeout first, then httpx.TransportError, the base class of every other network failure (refused or dropped connections, connect, write and pool timeouts), and finally upstream 5xx answers. A 4xx from the payment service means your request was wrong, so it is left to surface as a bug:

Python · app/payments.py (one shared client with explicit timeouts)
from contextlib import asynccontextmanager

import httpx
from fastapi import FastAPI

from app.exceptions import AppError


class UpstreamUnavailableError(AppError):
    """The dependency could not be reached; a handler maps it to 503."""


class UpstreamTimeoutError(AppError):
    """The dependency accepted the call but did not answer in time: 504."""


# Configure explicit granular timeouts for outbound dependencies
client_timeouts = httpx.Timeout(
    connect=1.0,   # Max 1.0s to establish TCP/TLS connection
    read=4.0,      # Max 4.0s to wait for response byte chunks
    write=2.0,     # Max 2.0s to send request payload bytes
    pool=5.0,      # Max 5.0s to acquire an idle socket from pool
)


@asynccontextmanager
async def lifespan(app: FastAPI):
    # One client and one connection pool, reused by every request
    app.state.payments = httpx.AsyncClient(
        base_url="https://payments.internal", timeout=client_timeouts)
    yield
    await app.state.payments.aclose()


async def fetch_payment_status(client: httpx.AsyncClient, charge_id: str) -> dict:
    try:
        resp = await client.get(f"/v1/charges/{charge_id}")
        resp.raise_for_status()
        return resp.json()
    except httpx.ReadTimeout:
        # Connected, but payment service failed to respond in time
        raise UpstreamTimeoutError("Payment gateway timed out processing")
    except httpx.TransportError:
        # Every other network failure: refused, DNS, connect/write/pool
        # timeouts, a connection dropped mid-response
        raise UpstreamUnavailableError("Payment gateway unreachable")
    except httpx.HTTPStatusError as exc:
        if exc.response.status_code >= 500:  # their failure, not our request's
            raise UpstreamUnavailableError("Payment gateway returned an error")
        raise  # a 4xx means our request was wrong: a bug to fix, not to hide

03. Exponential backoff and randomised jitter

When a transient network glitch occurs, retrying the operation often succeeds. However, retrying immediately or at static intervals creates synchronised waves of network traffic that can overwhelm a recovering dependency.

Two techniques work together:

  • With exponential backoff, the delay between successive retry attempts doubles with each attempt: delay = base_delay * (2 ** attempt). For example, with a base of 100ms, successive retries wait 100ms, 200ms, 400ms, 800ms, and 1600ms.
  • Full jitter fixes a second problem. If 500 worker instances fail at the exact same millisecond, pure exponential backoff still causes all 500 instances to retry at the exact same synchronised intervals (e.g., all 500 retry together at t=200ms, then t=400ms). Full jitter breaks the synchronisation by picking a uniform random delay between 0 and the exponential maximum: sleep = random.uniform(0, delay). This spreads the retries across the whole window instead of bunching them together.

Choose the exceptions to retry with care. In httpx, a connect timeout raises ConnectTimeout, which is a TimeoutException, not a ConnectError, so catching only ConnectError silently skips the most common transient failure. The helper below lists both, plus read and pool timeouts. Retry like this only for idempotent operations: a read timeout on a POST may mean the server did the work.

Python · app/retry.py (exponential backoff and full jitter)
import asyncio
import random
import logging

import httpx

logger = logging.getLogger("resilience")

# Transport failures worth retrying. Retry only idempotent operations.
RETRYABLE = (httpx.ConnectError, httpx.ConnectTimeout,
             httpx.ReadTimeout, httpx.PoolTimeout)


async def call_with_retry(
    operation,
    max_attempts: int = 4,
    base_delay: float = 0.2,
    max_delay: float = 3.0,
):
    """Execute an async operation with exponential backoff and jitter."""
    for attempt in range(1, max_attempts + 1):
        try:
            return await operation()
        except RETRYABLE as err:
            if attempt == max_attempts:
                logger.error("Exhausted all %d retry attempts: %s", attempt, err)
                raise
            # Compute exponential backoff upper bound
            calculated = min(max_delay, base_delay * (2 ** (attempt - 1)))
            # Apply Full Jitter: random duration between 0 and calculated delay
            sleep_duration = random.uniform(0, calculated)
            logger.warning(
                "Attempt %d failed (%s). Retrying in %.2fs...",
                attempt,
                err,
                sleep_duration,
            )
            await asyncio.sleep(sleep_duration)

04. Circuit breakers and degraded fallbacks

While retries are appropriate for fleeting network hiccups, continuous retries against a dependency in a full outage only cause harm. A circuit breaker acts as an automatic safety switch that protects both your service and the dependency it calls.

A circuit breaker operates in three states:

  • Closed (normal operation): all requests pass through to the dependency. The breaker monitors the error rate.
  • Open (tripped): if the failure rate exceeds a defined threshold (e.g., 50% failures over 20 requests), the circuit trips open. Subsequent requests fail immediately or trigger fallback logic without calling the dependency, giving it time to recover.
  • Half-open (probing): after a cooldown reset timeout (e.g., 30 seconds), the breaker allows a limited number of trial requests through. If the trials succeed, the circuit closes; if they fail, the circuit returns to Open.

When a circuit is open or retries are exhausted, applications should execute graceful fallbacks rather than returning a generic 500 error to users:

  • Stale cache: if the live product catalogue service is unreachable, return the last cached product descriptions from Redis, and say so in the response (for example with a stale: true field), so clients can show that the data may be out of date.
  • Default value: if the personalised recommendation engine fails, fall back to a static list of top-selling products rather than rendering a blank homepage or error page.
  • Asynchronous queue: if an email notification service is down, write the notification to a durable retry queue (or a transactional outbox table) that a worker drains with backoff once the provider recovers. Move messages that still fail after a set number of attempts to a dead-letter queue, which holds failures for a person to inspect; nothing is delivered from it automatically.

05. Check your understanding

Practice check · 3 questions

Resilience, retries, and circuit breakers

Three questions on network failure handling, exponential backoff, and fallbacks.

Q1. Your retry helper catches httpx.ConnectError and httpx.ReadTimeout. The upstream host is unreachable, and every call fails with a 1 s connect timeout. What happens?
Q2. What does a circuit breaker do while it is in the open state?
Q3. With the lesson's client_timeouts, the payment service completes the TCP and TLS handshakes, then sends no HTTP response for 6 seconds. What does fetch_payment_status raise?
Practice only: not graded, not saved, not evidence.

06. Apply it

Inspect your application's outbound HTTP client configurations across all external service integrations. Check that every remote dependency has explicit connect and read timeouts sized for that dependency (the ranges above are a starting point), instead of relying on library defaults. For critical external APIs, wrap remote calls in a resilience helper implementing exponential backoff with full jitter, and establish a fallback strategy returning cached data when dependencies are down.

Circuit breakers and jittered retries limit how far one failing dependency spreads, and keep retries from piling onto a service that is trying to recover. In the next lesson, you will put these principles into practice inside a hands-on lab: implementing structured JSON logging with correlation request IDs.

07. Review prompt

Contrast connection timeouts with read timeouts, explaining the specific failure mode each protects against. Explain why exponential backoff without jitter is insufficient under high load, and describe the three operational states of a circuit breaker.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check