TL;DR
- A circuit breaker protects a caller from repeated slow or failing dependency calls. It tracks recent outcomes for one dependency and fails fast when another attempt is unlikely to succeed.
- The familiar states are closed (allow traffic), open (reject immediately), and half-open (allow a bounded probe to test recovery).
- Use explicit HTTP timeouts first. Classify dependency failures separately from caller errors, and retry only transient, safe-to-repeat operations within the request’s total deadline.
- Keep breaker state per dependency and operation boundary. A local breaker is usually process-scoped, so each worker can probe independently; a distributed breaker changes the coordination and failure model.
- Fallbacks must preserve business meaning. A stale read may be acceptable; a failed payment authorization must not be reported as a success.
Why one slow dependency can affect unrelated requests
A FastAPI route calls a shipping, payment, identity, or messaging provider. The remote endpoint becomes slow, while inbound traffic continues. Each handler waits for its HTTP timeout and holds request memory, a client connection, a task slot, or another scarce resource. New work queues behind the stalled calls. If several dependencies share a connection pool or request deadline, one provider’s incident can consume capacity needed by healthy routes.
A timeout limits how long one attempt waits. It does not reduce the number of requests that will make the same failing call over and over. A circuit breaker observes recent outcomes and temporarily refuses calls when the dependency is unhealthy. The application can return a deliberate degraded response or queue work for later, depending on the operation.
The circuit breaker pattern is a resilience control, not a way to make a remote service reliable. It does not repair the provider, guarantee a successful fallback, or prove whether a timed-out write took effect. Microsoft’s pattern guidance separates retries for transient faults from circuit breaking for repeated failures and describes the closed, open, and half-open states. Microsoft Azure Circuit Breaker pattern · AWS Prescriptive Guidance: circuit breaker
Define the dependency boundary
Create a separate breaker around each independently failing provider boundary, such as a shipping quote API or a specific payment processor. If two providers have unrelated health, a single combined counter can open both when only one is failing. If a provider has regions or materially separate endpoints, consider whether those are separate dependencies in your system’s failure model.
Do not automatically make one circuit per customer. That can create high-cardinality state and still leave the provider-wide rate limit unprotected. Use tenant-level quotas for isolation, and a dependency-level circuit for provider health. Add a narrower circuit only when there is a technical boundary whose failure is independent, and define a bounded state lifecycle.
Decide which calls count as failures. Timeouts, connection errors, and selected server errors are common signals. A validation error caused by a malformed request is not evidence that the provider is unhealthy. A 401 may mean your credential was revoked, while a 429 may indicate rate limiting that needs backoff or admission control. Classify each response using the provider’s documented semantics.
Breaker keys and metrics should be low-cardinality. Record dependency name, operation, region, state, and failure category. Do not use raw URL paths, customer IDs, request IDs, or credentials as metric labels. Put request-specific details in controlled traces with sensitive attributes removed.
Use timeouts and bounded retries before opening the circuit
Set connect, read, write, and pool timeouts for outbound HTTP. HTTPX applies a default network-inactivity timeout and lets the caller configure each timeout dimension. A pool timeout indicates local connection saturation, not necessarily provider unavailability, so do not count every pool wait as a remote failure. HTTPX timeout configuration · HTTPX exception hierarchy
Choose the request budget from the inbound endpoint deadline and service objectives. If an API must respond within a second, three sequential retries with one-second timeouts violate that promise even if each setting looks reasonable. Include connection acquisition, backoff, response parsing, and any downstream work in the total budget.
Retries help with transient failures, but can amplify load. Use a finite attempt limit, exponential backoff with jitter, and a retry budget. Only retry operations that are idempotent or protected by an idempotency key. A read timeout after sending a payment request does not prove the provider did not authorize the payment. The safe response may be to query by idempotency key or reconcile later rather than to send an unrelated second charge attempt. AWS retry with backoff guidance
Place retries and the breaker deliberately. If every retry is a separate breaker sample, a short burst can trip the breaker quickly. If the breaker only sees the final result, it reacts more slowly but corresponds to one logical operation. Choose and document the unit of measurement. Never allow a retry loop to retry a circuit-open rejection.
Model the three states and their transitions
Closed: allow calls and observe outcomes
In the closed state, calls reach the dependency. Track outcomes in a rolling time window or a bounded consecutive-failure counter. A time window should require enough samples before a failure percentage becomes meaningful. A tiny number of calls can produce an alarming error percentage by chance, while a minimum-call threshold prevents a single request from deciding that the entire provider is down.
Failure thresholds are workload-specific. Select them from observed success rates, call volume, timeout budgets, and the cost of continuing to call a broken service. A payment endpoint may need a different policy from an optional recommendation feed. Keep the initial setting conservative, replay representative failure data, and tune from incident evidence rather than adopting a magic percentage.
Open: fail fast without contacting the provider
Once the configured failure condition is met, the circuit opens. Calls return an application-level dependency-unavailable result immediately. This protects local capacity and reduces avoidable pressure on the recovering service. The response should tell the route whether to use a permitted fallback, return a retriable error, or enqueue work.
Do not return success-shaped data for an operation that did not succeed. A failed payment call cannot become “paid” because the circuit opened. A stale shipping estimate may be acceptable if the interface labels it as stale. A notification can often be placed into a durable outbox or queue, provided it has a stable operation ID and delivery policy.
Half-open: test recovery with a limited probe
After a cool-down period, move to half-open and allow a small number of probe calls. If they succeed according to the dependency contract, close the circuit and resume normal traffic. If they fail, reopen it and wait before probing again. Limiting probes prevents a recovering service from immediately receiving the entire accumulated demand.
Use jitter on the reset interval across many application instances so every process does not probe at the same instant. If your provider supplies a Retry-After value for throttling, incorporate that signal in an explicit policy. Keep the probe timeout bounded and ensure cancellation of the inbound request does not leave a probe semaphore stuck.
Integrate shared async clients with FastAPI lifespan
Use a shared async HTTP client per application process so connections can be reused and closed cleanly. FastAPI lifespan is designed for resources created before serving requests and released during shutdown. Each Uvicorn worker is a separate process with its own client and in-memory breaker state. FastAPI lifespan events · HTTPX async clients
from contextlib import asynccontextmanager
from fastapi import FastAPI, Request
import httpx
@asynccontextmanager
async def lifespan(app: FastAPI):
timeout = httpx.Timeout(
connect=0.4, read=1.2, write=0.8, pool=0.2
)
app.state.carrier_client = httpx.AsyncClient(
base_url="https://carrier.example",
timeout=timeout,
limits=httpx.Limits(
max_connections=40,
max_keepalive_connections=20,
),
)
app.state.carrier_breaker = CircuitBreaker(
name="carrier.quote",
failure_threshold=5, # illustrative; tune from observed traffic
reset_after=10.0, # illustrative; tune from recovery behavior
half_open_probes=1,
)
try:
yield
finally:
await app.state.carrier_client.aclose()
app = FastAPI(lifespan=lifespan)
@app.post("/quotes")
async def create_quote(request: Request, payload: QuoteInput):
breaker = request.app.state.carrier_breaker
client = request.app.state.carrier_client
try:
return await breaker.call(
lambda: fetch_quote(client, payload)
)
except CircuitOpen:
return await quote_fallback_or_unavailable(payload)
CircuitBreaker and fetch_quote are intentionally interface-level names here, not imports from a specific library. A real implementation must define concurrency safety, failure classification, rolling-window behavior, cancellation, state-change events, and metrics. Avoid synchronous network calls or blocking sleeps inside an async route because they stall the event loop.
A process-local breaker is often simpler than a shared Redis record. It reacts to the process’s observed failures and avoids a network dependency in the control path. In a scaled deployment, each worker can have a different state and half-open probes can multiply with process count. If a hard fleet-wide call cap is required, use a deliberate shared limiter or service-mesh control and account for its availability and consistency behavior. Do not make an in-memory lock appear distributed.
Choose useful fallback behavior per operation
Fallbacks should be specified in the product contract. For an optional read, return a cached value with its age or omit the optional section. For a write, persist an intent to a durable queue only if the operation can be replayed safely and the user receives a pending status. For a real-time payment authorization, return a clear retriable error and reconcile uncertain outcomes with the provider’s idempotency mechanism.
Cache fallback data with an explicit staleness limit. An outage can turn a cache into a second source of misleading truth if the application serves old permissions, prices, balances, or inventory without a bound. Never use cached authorization to grant access beyond the documented policy.
Make the fallback observable. Count open-circuit rejections separately from provider failures. Record breaker state transitions and fallback selection with a dependency name and sanitized reason. Avoid logging the entire HTTP request or provider response, which may include authorization headers, personal data, or payment metadata.
For queued work, expose pending state and retry outcomes. The queue needs bounded retries, dead-letter handling, idempotency, and an operator path. See our transactional outbox guide and our worker quota guide for durable delivery and fair capacity.
Instrument the breaker as part of the dependency contract
Track request count and latency by dependency and operation, failure classes, current state, open duration, half-open probe result, retry attempts, fallback count, and local pool timeouts. A breaker opening is an important incident signal, but it is not sufficient to identify whether the cause is a provider outage, a bad credential, a client bug, or local saturation.
Alert on state transitions and sustained open duration with context such as region and operation. If the provider is global but one region is failing, a global circuit can deny healthy regions unnecessarily. Conversely, a separate breaker per process can miss a provider-wide rate limit. Choose the key based on the fault domain you intend to isolate.
Use trace spans around dependency calls, but avoid recording authorization headers, secret query parameters, or raw request bodies. Link a failure to the sanitized provider request ID when the vendor supplies one. Keep metric labels bounded and place user identifiers in access-controlled logs only when incident response requires them.
Test thresholds, races, and recovery
Test a successful call, a timeout, a connection failure, a provider 5xx, a caller 4xx, a provider 429, an open rejection, a failed half-open probe, and successful recovery. Verify the exact errors that count toward the breaker. A bad payload should not open the circuit for every caller.
Run concurrent requests around the threshold boundary. Confirm only the intended number of half-open probes reach the dependency, state transitions cannot corrupt counters, and cancellation releases locks or permits. Test two worker processes to demonstrate the documented local-state behavior. If state is shared, inject a Redis or service-mesh outage and verify the application’s failure policy.
Simulate a provider that times out after accepting a write. Verify retries use a stable idempotency key or are suppressed until the operation is reconciled. Test that the fallback preserves business meaning, stale data has a visible age, and queued operations do not duplicate side effects.
Finally, test a gradual recovery. A breaker that reopens after one successful probe may flap under noisy latency. A breaker that waits too long may continue rejecting requests after the provider is healthy. Tune the probe policy with representative latency and error data, then review it during incidents.
Frequently asked questions
Should every FastAPI dependency have its own circuit breaker?
Use a breaker for remote dependencies where repeated slow or failing calls can consume local capacity or worsen an outage. Keep independent fault domains separate, but do not create unbounded per-user breakers. Some queues, caches, or service meshes may already provide sufficient isolation for a particular path.
Should HTTP 4xx responses trip the circuit?
Usually not by default. A caller-specific validation error does not show that the dependency is unhealthy. Classify responses using provider semantics: authentication failures may indicate a credential problem, and 429 may indicate throttling that needs admission control or backoff. Make the policy explicit and observable.
Can I use a local in-memory breaker across multiple Uvicorn workers?
No. Each worker process has its own memory and breaker state, so they observe failures independently and may each send half-open probes. This is often acceptable. Use a shared limiter or service-mesh mechanism if you need a fleet-wide call cap, and account for its own failure mode.
Is a circuit breaker a replacement for HTTP timeouts or retries?
No. Timeouts bound how long an attempt can wait. Retries can recover from transient failures when bounded and safe to repeat. A circuit breaker stops calls likely to keep failing. Combine them only with a total deadline, retry budget, correct failure classification, and idempotency for side effects.
Make failure behavior a documented part of each integration
For every provider, document the timeout budget, retryable failures, idempotency behavior, breaker threshold, reset policy, fallback, and incident owner. Keep the breaker narrow enough to isolate one dependency but simple enough to operate. A circuit that fails fast without safe business behavior can still damage the user experience.
Start with explicit timeouts and telemetry, then add a breaker where failure testing shows that repeated calls threaten unrelated capacity. If your team is hardening integrations against a slow third-party API, talk with our engineering team about failure domains, retries, and recovery tests.
