Skip to content

Background Tasks, Caching & External APIs: BackgroundTasks, httpx, Retries, In-Memory & Redis Caching ​

"You can define background tasks to be run after returning a response." — FastAPI documentation, "Background Tasks", fastapi.tiangolo.com/tutorial/background-tasks/

Summary: A FastAPI endpoint rarely works alone: it sends an e-mail, calls a payment provider, reads exchange rates from someone else's API, caches the answer and receives webhooks back. This chapter covers the mechanics of all five. BackgroundTasks.add_task() runs a function in the same process after the response has gone out: response first, then the task. That makes it cheap, but anything it holds is lost on crash, so durable work goes to a queue (Celery, RQ, arq, Dramatiq, TaskIQ) or into an outbox table. Outbound calls go through one httpx.AsyncClient per app. The lifespan creates it, with explicit connect, read, write and pool timeouts and pool limits, and it is wrapped in tenacity retries. Those retries fire only for idempotent requests, follow Retry-After, use exponential backoff with jitter and stay inside a retry budget. Around them sit a circuit breaker and an outbound rate limiter. Caching starts in-process (functools.lru_cache, cachetools.TTLCache, an async single-flight cache) and moves to Redis with redis.asyncio. The Redis layer uses cache-aside with JSON values, TTLs with jitter, versioned keys, negative caching, invalidation on write and stampede protection with a SET NX PX lock. Webhooks are verified with HMAC over the raw body and processed idempotently by event id. Every number on this page comes from a real run of the snippet project: a real Uvicorn, a local stub server for the external APIs, and fakeredis standing in for Redis. Focus: BackgroundTasks and add_task, response first then task, lost on crash, when to use a queue; httpx.Client vs httpx.AsyncClient, connect timeout, read timeout, write and pool timeouts, pool limits, keep-alive, base_url, one client per app (the lifespan client), raise_for_status; retries with tenacity and backoff, exponential backoff, jitter, retry budget, idempotency key, retry only idempotent requests, Retry-After; circuit breaker and half-open; bulkhead and outbound rate limiting (aiolimiter, semaphore); lru_cache, cachetools TTLCache, async cache, per-process cache; cache-aside, read-through, write-through; redis.asyncio, connection pool, serialization (pickle vs JSON), TTL, cache key design, namespacing keys, invalidation; stampede (dogpile), lock-based recompute, early recompute, probabilistic early expiration, negative caching; fastapi-cache2 and aiocache; Celery, RQ, arq, Dramatiq and TaskIQ (at-least-once, visibility timeout, result backend, scheduled tasks, beat); the outbox pattern; webhooks (webhook signature, HMAC, idempotent webhook processing, webhook retries); respx; observability of retries with structured logging; the Laravel and Go equivalents. Learning goal: Decide for any side effect whether it belongs in the request, in BackgroundTasks, in an outbox or in a queue. Call any external API with a shared, bounded, timed-out client and a retry policy that can never double-charge. Add an in-memory or Redis cache that survives a stampede and can be invalidated. Accept webhooks safely. Prove each of those with a test that runs.

This page owns the FastAPI-side mechanics of side effects, outbound HTTP and application caching. Its neighbours are linked, not re-taught:

Versions. Facts below were checked against these sources, saved on 2026-11-29:

  • FastAPI docs (background tasks, lifespan events, dependencies with yield, release notes) and the Starlette background docs.
  • Starlette 0.49.3 source (background.py, responses.py), the httpx docs (clients, timeouts, resource limits, async, transports, exceptions) and the tenacity docs, API page and 9.1.2 source.
  • The backoff README, the aiolimiter docs, Python's functools, hmac and pickle pages, the cachetools docs, the redis-py docs (asyncio examples, connections, lock, retry) and the redis.io pages for SET, EXPIRE, client-side caching and distributed locks.
  • The fastapi-cache2 README, the aiocache docs, and the Celery docs (introduction, calling, tasks, periodic tasks, Redis broker), plus the RQ, arq, Dramatiq and TaskIQ docs.
  • Stripe's webhook, signature and idempotent-request pages and GitHub's webhook validation and best-practice pages.
  • The respx guide, the Laravel 13 docs (queues, Horizon, HTTP client, cache, rate limiting), Go's net/http/client.go, errgroup and singleflight sources, the AWS Builders' Library article on timeouts, retries and jitter and the AWS "Exponential Backoff And Jitter" post.
  • RFC 9110 and the Vattani, Chierichetti and Lowenstein paper "Optimal Probabilistic Cache Stampede Prevention".

The page is written for Python 3.12+. The snippets ran on the only interpreter on the build machine, CPython 3.9.6, so the project pins the newest releases that install there: FastAPI 0.128.8, Starlette 0.49.3, Pydantic 2.13.5, httpx 0.28.1, Uvicorn 0.39.0, tenacity 9.1.2, backoff 2.2.1, aiolimiter 1.2.1, cachetools 6.2.6, redis 7.0.1, SQLAlchemy 2.0.58, and fakeredis 2.41.0 with lupa for Lua, respx 0.23.1, pytest 8.4.2 and pytest-asyncio 1.2.0 for the tests. PyPI on 2026-11-29 listed FastAPI 0.165.0, tenacity 9.2.1, redis 8.2.0 and cachetools 8.0.3 as latest, all needing Python 3.10 or newer. No Redis server exists on the build machine: every Redis behaviour shown as "real" ran against fakeredis, which implements the commands in memory (including Lua through lupa), and the redis-cli lines are marked "expected, not run". SQLAlchemy and SQLModel appear only for the outbox and webhook tables (SQLite in memory); Alembic owns their migrations (Alembic chapter).

Page map ​

If you are looking forGo to
The tables you can memorise in one minuteEverything in one minute
Why side effects and outbound calls need their own chapterWhy it exists
Celery 2009 to TaskIQ 2022, lifespan 0.93.0Where it comes from
The shop app before and after, with numbersPython
BackgroundTasks, add_task, what runs whenBackgroundTasks
SIGKILL vs SIGTERM, when a queue is neededLost on crash
Celery, RQ, arq, Dramatiq, TaskIQTask queues
httpx.Client vs httpx.AsyncClientSync vs async client
connect, read, write, pool timeoutsTimeouts
Limits, keep-alive, one client per appPool limits and the lifespan client
raise_for_status, the exception treeErrors
tenacity, backoff, jitterRetries
Idempotency-Key, double chargesRetry only idempotent requests
Retry-After, retry budgetRetry-After and the retry budget
closed / open / half-openCircuit breaker
aiolimiter, Semaphore, bulkheadOutbound rate limiting
lru_cache, TTLCache, async cachesIn-memory caching
cache-aside, read-through, write-throughCache patterns
redis.asyncio, pool, pickle vs JSON, TTLRedis caching
shop:v1:rate:EUR, invalidationKey design and invalidation
stampede, dogpile, XFetch, negative cachingStampede protection
fastapi-cache2, aiocache, ETagCache libraries and HTTP caching
transactional outboxOutbox
HMAC signatures, duplicate deliveriesWebhooks
respx, stub servers, fakeredisTesting external calls
logs and metrics for retriesObservability
Starlette's send-then-run, tenacity's order, exact errors, SQLMechanics
The classic bugs and their fixesSolving the classic problems
BackgroundTasks or queue, which cacheChoosing
Monolith to distributed systemIn architecture
Reproduce every numberLab
Queues, Horizon, Http::retry, Cache::rememberFor PHP/Laravel developers
http.Client Timeout, errgroup, singleflightThe Go angle

Everything in one minute ​

The vocabulary in one table. Each row is unpacked in the concept catalogue.

TermWhat it isPlain wordsPython API
Background taskFunction run after the response, same process"Do it after you hang up"tasks.add_task(fn, *args)
Task queueDurable list of jobs consumed by worker processes"A ticket on the kitchen rail"Celery, RQ, arq, Dramatiq, TaskIQ
OutboxTable row written in the business transaction, published later"A letter in the out-tray"INSERT INTO outbox ...
Shared clientOne connection pool per process"One phone line, kept open"httpx.AsyncClient(...) in the lifespan
TimeoutUpper bound per phase of a call"Hang up after 2 s of silence"httpx.Timeout(connect=1, read=2, ...)
Pool limitsMax connections, max idle keep-alive"At most 20 lines"httpx.Limits(max_connections=20)
Retry policyWhich errors repeat, how often, how long to wait"Call back, but not forever"tenacity.AsyncRetrying(...)
Idempotency keyClient-chosen id that makes a POST safe to repeat"Order number on the cheque"Idempotency-Key: <uuid> header
Circuit breakerStops calling a failing upstream for a while"Fuse box"hand-rolled, purgatory, aiobreaker
BulkheadCap on concurrent calls to one dependency"Only 10 seats for this guest"asyncio.Semaphore(10)
Rate limiterCap on calls per time window"5 calls a second"aiolimiter.AsyncLimiter(5, 1)
In-process cacheDict-like cache inside one worker"Sticky note on my desk"lru_cache, cachetools.TTLCache
Shared cacheCache every worker reads"Whiteboard in the hall"redis.asyncio.Redis
StampedeMany concurrent misses recompute the same key"Everyone runs to the kitchen at once"lock, single-flight, XFetch
WebhookAn HTTP call from a provider to you"They phone you back"POST /webhooks/payments

Where each side effect belongs. Numbers are from the Lab (CPython 3.9.6, macOS).

Side effectExamplePut it inWhyMeasured
Must be in the answerprice, stock, payment resultthe request, with timeout + retriesthe client needs the resultReadTimeout after 0.103 s with read=0.1
Small, losing it is acceptablewelcome e-mail, audit log line, cache warm-upBackgroundTasksno infrastructure; runs after the responseclient had the 201 after 0.006 s, mail at 0.304 s
Must happen if the transaction committed"order placed" event, invoiceoutbox row + relayatomic with the data; survives crashesrelay crash: published twice, applied once
Slow, heavy, scheduled or must be retried for hoursPDF, export, nightly synctask queue (Celery / RQ / arq / Dramatiq / TaskIQ)separate workers, acks, retries, beatnot run (no broker here)
Reaction to someone else's eventStripe payment.succeededwebhook route: verify, dedupe, 2xx fastprovider retries until 2xxduplicate delivery answered duplicate

httpx timeouts and limits. Defaults from the httpx docs, behaviour from the real run.

SettingBoundshttpx defaultThis projectWhat you see when it fires
connectTCP (+ TLS) handshake5 s1 shttpx.ConnectTimeout
readgap waiting for response bytes5 s2 shttpx.ReadTimeout (0.103 s with read=0.1)
writesending the request body5 s2 shttpx.WriteTimeout
poolwaiting for a free pooled connection5 s0.5 shttpx.PoolTimeout (real)
max_connectionsopen connections per client10020calls queue for the pool
max_keepalive_connectionsidle connections kept2010extra connections closed when idle
keepalive_expiryhow long an idle connection lives5 s30 sreconnect after idling

Retry rules. What the snippet's call() does; each rule has a test.

SituationRetry?WaitMeasured
GET, 503yesfull jitter, base 0.05 s2 retries logged, attempt 3 succeeded
GET, 429 + Retry-After: 1yesthe header (capped at 5 s)success after 1.004 s
POST, no Idempotency-Key, 500non/a1 attempt, 1 charge
POST + Idempotency-Key, 500yesbackoff2 attempts, 1 charge, Idempotent-Replayed: true
any, 404 / 400 / 422non/a1 attempt
upstream down, 20 calls, 3 attempts eachbudgetedn/a60 requests without a budget, 24 with
breaker openno call at alln/a503 in 0.6 ms

Cache layers.

LayerScopeSurvives restartShared by workersTypical TTLStampede toolMeasured
functools.lru_cacheprocessnononone (size only)n/aCacheInfo(hits=2, misses=3, maxsize=128, currsize=3)
cachetools.TTLCacheprocessnonoseconds to minutessingle-flight Future50 misses → 1 load
Redis cache-asideall workersyes (if persisted)yesseconds to hoursSET NX PX lock, XFetch50 misses → 1 recompute (no lock: 50)
HTTP caching (ETag, Cache-Control)client / CDNn/an/aheader-drivenCDN request collapsingsee Exception Handling & Responses

What prints when something is wrong. Real output from the snippet run.

MistakeWhat you seeWhere
Background task raisedERROR: Exception in ASGI application (client already got 201)Uvicorn log
No timeout reached the upstream's slownesshttpx.ReadTimeoutexception
All pooled connections busyhttpx.PoolTimeoutexception
Upstream port closedhttpx.ConnectError: All connection attempts failedexception
Treated a 404 as successnothing; httpx does not raise until raise_for_status(): Client error '404 Not Found' for url '...'exception text
lru_cache on async defRuntimeError: cannot reuse already awaited coroutinesecond await
Webhook body re-serialised before verifying400 {"detail": "signature mismatch"}response
Local test traffic through a system proxy503 from 127.0.0.1:1082 instead of your stubhttpx trust_env

Why it exists ​

A request handler is the worst place to do slow or unreliable work. The client is waiting, the worker is busy, and every second of an e-mail provider's latency becomes a second of your p99. But the handler is also the only place where you know the work must happen. That tension produces three questions this chapter answers:

  • When does a side effect run? Inline, after the response, in the same transaction or in another process.
  • How do you talk to services you do not control? Bounded, timed out, retried only when safe, cut off when they are down.
  • How do you stop paying for the same answer twice? Cache it at the right layer, expire it, and make sure that a popular key expiring does not send fifty workers to the database at once.

The AWS Builders' Library sums up the risk of the middle question: "Retries are 'selfish.' In other words, when a client retries, it spends more of the server's time to get a higher chance of success." It also gives the arithmetic of layered retries: "a five-deep stack of service calls … three retries at each layer … the load on the database will increase 243x".

Naive version (the Before app)Production version (the After app)
E-mail sent inside the handlerBackgroundTasks for the e-mail, outbox for events that must not be lost
httpx.Client() per request, default timeoutsone httpx.AsyncClient per process from the lifespan, explicit Timeout and Limits
Sync client inside async defasync client; sync only in def routes and workers
for _ in range(3) around a POSTtenacity, retry only idempotent requests, Idempotency-Key, Retry-After, jitter, budget
Keeps calling a dead upstreamcircuit breaker: fail fast, half-open probe
Unbounded concurrent callsbulkhead + AsyncLimiter
Global dict as cacheTTL, size bound, Redis for shared state, versioned keys, invalidation
Every miss recomputeslock-based recompute, single-flight, early recompute
Trusts webhook JSONHMAC over the raw body, timestamp window, dedup by event id

An everyday picture. A restaurant takes phone orders.

  • Writing the receipt while the customer is still on the line is the inline call. Saying "thank you, goodbye" and then writing the receipt is a background task. If the restaurant burns down before you write it, the receipt is lost.
  • Pinning the order on the kitchen rail, where the night shift will find it even if you go home, is a queue. Writing it into the order book at the same moment you take the money is the outbox.
  • Calling the supplier is an external API. You give up after a while (timeout), you call back later rather than redialling every second (backoff with jitter), and you never re-send a bank transfer just because the line dropped (idempotency key). After five dead calls in a row you stop trying until the morning (circuit breaker), and you keep at most two lines busy with them (bulkhead).
  • The price list on the wall is the cache. When it is wiped at closing time, the first waiter rewrites it while the others wait a moment instead of all phoning the supplier (stampede lock).

Three common misunderstandings, up front ​

  1. "BackgroundTasks is a job queue." It is a list of functions attached to one response, run by the same worker on the same event loop. Measured: SIGKILL one second after the 202 lost the job (marker written: False); there is no retry, no record and no dashboard.
  2. "Retrying makes calls more reliable." It makes idempotent calls more reliable. Measured with the Before app: a provider that commits and then answers 500 twice produced 3 charges for one payment under a naive retry loop.
  3. "A cache with a TTL is safe." Not when the key is hot. Measured: 50 concurrent misses for one key ran the 100 ms recompute 50 times; with a SET NX PX lock, once.

Where it comes from ​

The pieces are older than FastAPI:

  • Task queues. Celery's first release on PyPI (0.1.2) was uploaded on 2009-04-27. RQ (Redis Queue) followed on 2013-12-16, arq (asyncio + Redis) on 2016-07-30, Dramatiq on 2017-06-02 and TaskIQ ("Distributed task queue with full async support") on 2022-08-08.
  • Retry libraries. backoff 1.0 was uploaded on 2014-05-13 and tenacity 2.0.0 on 2016-08-25.
  • Caches. cachetools 0.0.0 was uploaded on 2014-03-22, and functools.lru_cache is in the standard library. aiocache arrived on 2016-10-02 and fastapi-cache2 on 2020-08-26.
  • Redis clients. redis-py's first PyPI file is 2.7.0 (2012-10-08). The separate aioredis package (2014-06-12, last release 2.0.1 on 2021-12-27) now says "Aioredis is now in redis-py 4.2.0rc1+"; redis-py 4.2.0 was uploaded on 2022-03-23 and ships redis.asyncio.
  • HTTP and frameworks. httpx 0.6.7 is its first PyPI file (2019-07-19) and 0.28.1 is from 2024-12-06; 1.0 exists only as dev releases. Starlette 0.1.0 dates from 2018-06-25 and FastAPI 0.1.0 from 2018-12-08. FastAPI 0.93.0 (2023-03-07) added "support for lifespan async context managers (superseding startup and shutdown events)". That lifespan is the place where this chapter creates its one client per app.
  • Mocking, limiting, breaking. respx 0.3.1 is from 2019-11-16, aiolimiter 1.0.0b0 from 2019-11-30, aiobreaker 1.0.0 from 2018-08-12 and purgatory 1.0.0 from 2022-02-27.
  • Standards and research. RFC 9110 (June 2022) is the current definition of Retry-After ("either an HTTP-date or a number of seconds"). The probabilistic early expiration used here comes from the Vattani, Chierichetti and Lowenstein paper, which calls the problem "cache stampede … (also called dog-piling, cache miss storm, or cache choking)".
1  2009-04-27  Celery 0.1.2 on PyPI: the first mainstream Python task queue
2  2012-10-08  redis-py 2.7.0 (first PyPI file); 2012-03-14 fakeredis 0.1
3  2013-12-16  RQ 0.1.0: Redis-backed jobs, one function call per job
4  2014        backoff 1.0 (05-13), cachetools 0.0.0 (03-22), aioredis 0.0.2 (06-12)
5  2016        tenacity 2.0.0 (08-25), arq 0.0.1 (07-30), aiocache 0.0.1 (10-02)
6  2017-06-02  Dramatiq 0.0.1
7  2018        Starlette 0.1.0 (06-25), aiobreaker 1.0.0 (08-12), FastAPI 0.1.0 (12-08)
8  2019        httpx 0.6.7 (07-19), respx 0.3.1 (11-16), aiolimiter 1.0.0b0 (11-30)
9  2020-08-26  fastapi-cache2 0.1.0
10 2021-12-27  aioredis 2.0.1, its last release; 2022-03-23 redis-py 4.2.0 ("Aioredis is now in redis-py 4.2.0rc1+")
11 2022        purgatory 1.0.0 (02-27), RFC 9110 (June), TaskIQ 0.0.1 (08-08)
12 2023-03-07  FastAPI 0.93.0: lifespan async context managers
13 2024-12-06  httpx 0.28.1, the version pinned here (0.29.0 on 2026-11-26 needs Python 3.10+)
14 2026-11     FastAPI 0.165.0, redis 8.2.0, tenacity 9.2.1, purgatory 3.0.2: all require Python >= 3.10/3.11

Python ​

Before ​

The shop's first version, which works on a laptop:

  • The welcome e-mail is sent inline with a sync client inside async def.
  • Every request opens a new httpx.Client with default timeouts.
  • Rates are "cached" in a module-level dict that never expires.
  • Payments are retried three times in a loop, POST included, without an idempotency key.
py
"""The "before" app: every mistake this chapter fixes, in one file.

- the welcome e-mail is sent inline, so the user waits for the mail provider;
- a new httpx.Client per request, no explicit timeout, sync calls inside `async def`;
- a retry loop that retries everything, POST included, with no backoff and no idempotency key;
- a process-global dict as the "cache": no TTL, no size bound, one copy per worker.
"""
from typing import Any, Dict

import httpx
from fastapi import FastAPI
from pydantic import BaseModel

UPSTREAM = {"url": "http://127.0.0.1:9"}   # set by the test
CACHE: Dict[str, Any] = {}

app = FastAPI(title="shop-before")


class SignupIn(BaseModel):
    email: str


class PaymentIn(BaseModel):
    amount: int


@app.post("/signup", status_code=201)
async def signup(body: SignupIn) -> Dict[str, str]:
    with httpx.Client(base_url=UPSTREAM["url"]) as client:          # blocks the event loop
        client.post("/email?delay_ms=0", json={"to": body.email, "template": "welcome"})
    return {"status": "created"}


@app.get("/rates/{currency}")
async def get_rate(currency: str) -> Any:
    if currency in CACHE:
        return CACHE[currency]
    with httpx.Client(base_url=UPSTREAM["url"]) as client:          # new TCP connection every time
        response = client.get(f"/rates/{currency}")
    CACHE[currency] = response.json()
    return CACHE[currency]


@app.post("/payments", status_code=201)
async def create_payment(body: PaymentIn, fail: int = 0) -> Any:
    last = None
    for _ in range(3):                                               # retries a non-idempotent POST
        with httpx.Client(base_url=UPSTREAM["url"]) as client:
            last = client.post(f"/charges?commit_then_fail={fail}", json={"amount": body.amount})
        if last.status_code < 500:
            return last.json()
    return {"error": last.status_code if last else None}

Its tests run against the same stub server as the After app. Real results:

  • A provider that commits the charge and then answers 500 twice gets 3 charges for one payment (['ch_1', 'ch_2', 'ch_3']).
  • Five rate lookups open 5 TCP connections.
  • The dict cache answers the second lookup without a call, and it will keep answering it forever.
py
"""The Before app's mistakes, measured against the same stub."""
import httpx
import pytest
import pytest_asyncio

from app import before
from app.stub_server import STATE


@pytest_asyncio.fixture
async def before_client(upstream):
    before.UPSTREAM["url"] = upstream
    before.CACHE.clear()
    async with httpx.AsyncClient(transport=httpx.ASGITransport(app=before.app), base_url="http://b") as c:
        yield c


@pytest.mark.asyncio
async def test_naive_retry_double_charges(before_client):
    r = await before_client.post("/payments?fail=2", json={"amount": 500})
    print(f"\nBefore: provider committed then 500 twice -> {len(STATE.charges)} charges for one payment "
          f"({[c['id'] for c in STATE.charges]}), response {r.json()}")
    assert len(STATE.charges) == 3


@pytest.mark.asyncio
async def test_client_per_request_opens_a_connection_each_time(before_client):
    for cur in ["EUR", "USD", "GBP", "JPY", "CHF"]:
        await before_client.get(f"/rates/{cur}")
    assert len(STATE.client_ports) == 5


@pytest.mark.asyncio
async def test_global_dict_cache_never_expires(before_client):
    await before_client.get("/rates/EUR")
    await before_client.get("/rates/EUR")
    assert STATE.hits["/rates/EUR"] == 1 and "EUR" in before.CACHE   # no TTL, no bound, no invalidation

After ​

The same shop built properly. The lifespan owns everything that binds to the event loop:

  • one httpx.AsyncClient with Timeout and Limits;
  • a redis.asyncio client, with fakeredis in tests;
  • the RedisCache, a CircuitBreaker, an OutboundGuard (rate limit plus bulkhead) and a RetryBudget;
  • the SQLAlchemy engine for the outbox.

The routes:

  • POST /signup adds the welcome e-mail with add_task.
  • GET /rates/{currency} is cache-aside over a guarded, retried, breaker-protected call.
  • POST /payments requires and forwards an Idempotency-Key.
  • POST /orders writes the order and its outbox event in one transaction.
  • POST /webhooks/payments verifies an HMAC signature over the raw body and processes each event id once.
py
"""The "after" app: BackgroundTasks for a small side effect, one httpx.AsyncClient per app from the
lifespan, retries + circuit breaker + outbound rate limit around the exchange-rate API, a Redis
cache-aside layer with stampede protection, idempotent payments, an outbox and a signed webhook
receiver. No `from __future__ import annotations` here: FastAPI 0.128.8 must see real annotations."""
import asyncio
import json
import logging
import time
from contextlib import asynccontextmanager
from typing import Any, Callable, Dict, List, Optional

import httpx
from fastapi import BackgroundTasks, Depends, FastAPI, Header, HTTPException, Request
from pydantic import BaseModel
from redis.asyncio import Redis
from sqlalchemy import update
from starlette.concurrency import run_in_threadpool
from sqlalchemy.engine import Engine
from typing_extensions import Annotated

from .breaker import CircuitBreaker, CircuitOpenError
from .cache_redis import RedisCache
from .external import RetryableStatus, RetryBudget, call, make_client
from .outbox import make_engine, mark_webhook_processed, orders, place_order
from .ratelimit import OutboundGuard
from .webhooks import SignatureError, verify

log = logging.getLogger("app")


class SignupIn(BaseModel):
    email: str


class RateOut(BaseModel):
    currency: str
    rate: float


class PaymentIn(BaseModel):
    amount: int


class OrderIn(BaseModel):
    email: str
    total_cents: int


async def send_welcome_email(client: httpx.AsyncClient, email: str, events: List[Any]) -> None:
    """Runs AFTER the response has been sent, in the same process and event loop."""
    events.append(("task_start", time.perf_counter()))
    try:
        await call(client, "POST", "/email", json={"to": email, "template": "welcome"}, attempts=1)
    except Exception as exc:                # nobody else will see this error: log it
        log.error(json.dumps({"event": "background_task_failed", "task": "welcome_email",
                              "error": type(exc).__name__}))
        raise
    finally:
        events.append(("task_end", time.perf_counter()))


def create_app(upstream_url: str, redis_factory: Callable[[], Redis], *,
               engine: Optional[Engine] = None, webhook_secret: str = "whsec_test",
               transport: Optional[httpx.AsyncBaseTransport] = None,
               rate: float = 50, period: float = 1.0, max_concurrent: int = 10,
               email_delay_s: float = 0.0) -> FastAPI:

    @asynccontextmanager
    async def lifespan(app: FastAPI):
        # Everything loop-bound is created here, inside the running loop, once per process.
        app.state.http = make_client(upstream_url, transport=transport)
        app.state.redis = redis_factory()
        app.state.cache = RedisCache(app.state.redis, namespace="shop", version=1, default_ttl=300)
        app.state.breaker = CircuitBreaker("rates", failure_threshold=3, reset_timeout=5.0)
        app.state.guard = OutboundGuard(rate, period, max_concurrent)
        app.state.budget = RetryBudget(ratio=0.2, min_per_window=3)
        app.state.engine = engine or make_engine()
        app.state.events = []
        try:
            yield
        finally:
            await app.state.http.aclose()
            await app.state.redis.aclose()

    app = FastAPI(title="shop", lifespan=lifespan)

    def state(request: Request) -> Any:
        return request.app.state

    State = Annotated[Any, Depends(state)]

    @app.post("/signup", status_code=201)
    async def signup(body: SignupIn, tasks: BackgroundTasks, st: State) -> Dict[str, str]:
        st.events.append(("handler", time.perf_counter()))
        if email_delay_s:
            async def slow_send(client: httpx.AsyncClient, email: str, events: List[Any]) -> None:
                await asyncio.sleep(email_delay_s)
                await send_welcome_email(client, email, events)
            tasks.add_task(slow_send, st.http, body.email, st.events)
        else:
            tasks.add_task(send_welcome_email, st.http, body.email, st.events)
        return {"status": "created"}

    async def fetch_rate(st: Any, currency: str) -> Optional[Dict[str, Any]]:
        async def one_call() -> Optional[Dict[str, Any]]:
            try:
                response = await call(st.http, "GET", f"/rates/{currency}", budget=st.budget, attempts=3)
            except httpx.HTTPStatusError as exc:
                if exc.response.status_code == 404:
                    return None              # a business answer, not an outage: the breaker stays closed
                raise
            return response.json()

        return await st.guard.run(st.breaker.call, one_call)   # None is cached as a negative entry

    @app.get("/rates/{currency}", response_model=RateOut)
    async def get_rate(currency: str, st: State) -> Any:
        key = st.cache.key("rate", currency.upper())
        try:
            value = await st.cache.get_or_set(key, lambda: fetch_rate(st, currency.upper()), ttl=60)
        except CircuitOpenError:
            raise HTTPException(503, "rates provider unavailable", headers={"Retry-After": "5"})
        except httpx.TimeoutException:
            raise HTTPException(504, "rates provider timed out")
        except (RetryableStatus, httpx.HTTPStatusError, httpx.TransportError):
            raise HTTPException(502, "rates provider error")
        if value is None:
            raise HTTPException(404, "unknown currency")
        return value

    @app.delete("/rates/{currency}/cache", status_code=204)
    async def invalidate_rate(currency: str, st: State) -> None:
        await st.cache.invalidate(st.cache.key("rate", currency.upper()))

    @app.post("/payments", status_code=201)
    async def create_payment(body: PaymentIn, st: State,
                             idempotency_key: Annotated[str, Header(min_length=8)]) -> Any:
        # The client's key is forwarded, so OUR retries (and the client's) cannot double-charge.
        response = await call(st.http, "POST", "/charges", json={"amount": body.amount},
                              headers={"Idempotency-Key": idempotency_key}, attempts=3)
        return response.json()

    @app.post("/orders", status_code=201)
    def create_order(body: OrderIn, st: State) -> Dict[str, int]:
        # `def` route: runs in the thread pool, so the sync SQLAlchemy engine does not block the loop.
        return {"order_id": place_order(st.engine, body.email, body.total_cents)}

    @app.post("/webhooks/payments")
    async def payment_webhook(request: Request, st: State,
                              x_signature: Annotated[Optional[str], Header()] = None) -> Dict[str, str]:
        raw = await request.body()           # verify the exact bytes, before JSON parsing
        try:
            verify(webhook_secret, x_signature, raw)
        except SignatureError as exc:
            raise HTTPException(400, str(exc))
        event = json.loads(raw)

        def apply(conn: Any) -> None:
            conn.execute(update(orders).where(orders.c.id == event["data"]["order_id"])
                         .values(status="paid"))

        # Sync SQLAlchemy inside `async def`: run it in the thread pool so the loop stays free.
        fresh = await run_in_threadpool(mark_webhook_processed, st.engine, event["id"], apply)
        return {"status": "processed" if fresh else "duplicate"}

    return app

The outbound layer (client factory, retry predicate, Retry-After wait, retry budget, structured log lines, plus the same policy written with backoff):

py
"""Calling external APIs with httpx: one client per app, explicit timeouts and pool limits,
tenacity retries that only fire for idempotent requests, Retry-After, a retry budget, and
structured log lines for every retry."""
import email.utils
import json
import logging
import time
from typing import Any, Optional

import backoff
import httpx
from tenacity import (
    AsyncRetrying,
    RetryCallState,
    retry_if_exception,
    stop_after_attempt,
    stop_after_delay,
    wait_random_exponential,
)

log = logging.getLogger("outbound")

# connect: TCP + TLS handshake; read: gap between bytes; write: sending the body;
# pool: waiting for a free connection from the pool.
DEFAULT_TIMEOUT = httpx.Timeout(connect=1.0, read=2.0, write=2.0, pool=0.5)
DEFAULT_LIMITS = httpx.Limits(max_connections=20, max_keepalive_connections=10, keepalive_expiry=30.0)

IDEMPOTENT_METHODS = frozenset({"GET", "HEAD", "OPTIONS", "PUT", "DELETE"})
RETRYABLE_STATUS = frozenset({408, 429, 500, 502, 503, 504})


def make_client(base_url: str, *, timeout: httpx.Timeout = DEFAULT_TIMEOUT,
                limits: httpx.Limits = DEFAULT_LIMITS,
                transport: Optional[httpx.AsyncBaseTransport] = None) -> httpx.AsyncClient:
    """Build the one AsyncClient the app shares (created in the lifespan, closed on shutdown)."""
    return httpx.AsyncClient(base_url=base_url, timeout=timeout, limits=limits, transport=transport,
                             headers={"User-Agent": "shop-backend/1.0"})


class RetryableStatus(Exception):
    """Raised for a response whose status says "try again" (429, 503, ...)."""

    def __init__(self, response: httpx.Response) -> None:
        super().__init__(f"HTTP {response.status_code}")
        self.response = response


def request_is_idempotent(request: httpx.Request) -> bool:
    """Safe to repeat: an idempotent method, or a POST that carries an Idempotency-Key."""
    return request.method in IDEMPOTENT_METHODS or "Idempotency-Key" in request.headers


class RetryBudget:
    """Retries may add at most `ratio` extra load (plus a small floor), counted per process.

    Without a budget, 3 retries per call turn an outage into 4x the traffic on the failing service.
    """

    def __init__(self, ratio: float = 0.2, min_per_window: int = 3, window_s: float = 10.0,
                 clock: Any = time.monotonic) -> None:
        self.ratio, self.min, self.window, self.clock = ratio, min_per_window, window_s, clock
        self._start = clock()
        self.requests = 0
        self.retries = 0
        self.denied = 0

    def _roll(self) -> None:
        if self.clock() - self._start >= self.window:
            self._start, self.requests, self.retries = self.clock(), 0, 0

    def record_request(self) -> None:
        self._roll()
        self.requests += 1

    def try_spend(self) -> bool:
        self._roll()
        if self.retries < max(self.min, self.ratio * self.requests):
            self.retries += 1
            return True
        self.denied += 1
        return False


def _request_of(exc: BaseException) -> Optional[httpx.Request]:
    if isinstance(exc, RetryableStatus):
        return exc.response.request
    if isinstance(exc, httpx.RequestError):
        return exc.request
    return None


def should_retry(exc: BaseException) -> bool:
    request = _request_of(exc)
    if request is None:
        return False                          # programming errors: never
    if not request_is_idempotent(request):
        return False                          # retry only idempotent requests
    return isinstance(exc, (httpx.TransportError, RetryableStatus))   # 4xx (HTTPStatusError): never


class stop_when_budget_exhausted:
    """A tenacity stop condition. Placed LAST in `stop_a | stop_b | this` so a token is spent only
    when the attempt and deadline limits would really allow another try (stop_any short-circuits)."""

    def __init__(self, budget: RetryBudget) -> None:
        self.budget = budget

    def __call__(self, state: RetryCallState) -> bool:
        return not self.budget.try_spend()


def parse_retry_after(value: Optional[str], now: Optional[float] = None) -> Optional[float]:
    """Retry-After is either delay-seconds or an HTTP-date (RFC 9110, section 10.2.3)."""
    if not value:
        return None
    if value.strip().isdigit():
        return float(value)
    parsed = email.utils.parsedate_to_datetime(value)
    return max(0.0, parsed.timestamp() - (now if now is not None else time.time()))


class WaitRetryAfterOrJitter:
    """Honour the server's Retry-After (capped), else full-jitter exponential backoff."""

    def __init__(self, multiplier: float = 0.05, max_wait: float = 2.0, cap: float = 5.0) -> None:
        self.backoff = wait_random_exponential(multiplier=multiplier, max=max_wait)
        self.cap = cap

    def __call__(self, state: RetryCallState) -> float:
        exc = state.outcome.exception() if state.outcome else None
        if isinstance(exc, RetryableStatus):
            ra = parse_retry_after(exc.response.headers.get("Retry-After"))
            if ra is not None:
                return min(ra, self.cap)
        return self.backoff(state)


def _log_before_sleep(state: RetryCallState) -> None:
    exc = state.outcome.exception() if state.outcome else None
    request = _request_of(exc) if exc else None
    log.warning(json.dumps({
        "event": "outbound_retry",
        "attempt": state.attempt_number,
        "wait_s": round(state.next_action.sleep, 3) if state.next_action else None,
        "method": request.method if request else None,
        "url": str(request.url) if request else None,
        "reason": type(exc).__name__ + (f" {exc}" if isinstance(exc, RetryableStatus) else ""),
    }))


async def call(client: httpx.AsyncClient, method: str, url: str, *, attempts: int = 4,
               deadline_s: float = 5.0, budget: Optional[RetryBudget] = None,
               wait: Any = None, **kwargs: Any) -> httpx.Response:
    """One outbound call with retries; raises the last error when the policy gives up."""
    if budget:
        budget.record_request()
    stop = stop_after_attempt(attempts) | stop_after_delay(deadline_s)
    if budget:
        stop = stop | stop_when_budget_exhausted(budget)
    retrying = AsyncRetrying(
        stop=stop,
        wait=wait or WaitRetryAfterOrJitter(),
        retry=retry_if_exception(should_retry),
        before_sleep=_log_before_sleep,
        reraise=True,
    )
    async for attempt in retrying:
        with attempt:
            started = time.perf_counter()
            response = await client.request(method, url, **kwargs)
            log.info(json.dumps({"event": "outbound_call", "method": method, "url": str(response.url),
                                 "status": response.status_code,
                                 "ms": round((time.perf_counter() - started) * 1000, 1),
                                 "attempt": attempt.retry_state.attempt_number}))
            if response.status_code in RETRYABLE_STATUS:
                raise RetryableStatus(response)
            response.raise_for_status()      # 4xx: a bug or a business answer, never retried
            return response
    raise AssertionError("unreachable")      # pragma: no cover


# The same policy with the `backoff` library (decorator style), for comparison.
@backoff.on_exception(backoff.expo, httpx.TransportError, max_tries=3, factor=0.05,
                      jitter=backoff.full_jitter)
async def get_with_backoff(client: httpx.AsyncClient, url: str) -> httpx.Response:
    response = await client.get(url)
    response.raise_for_status()
    return response

The external APIs are a real HTTP/1.1 server: Starlette under Uvicorn on an ephemeral port, in its own thread. It records each request's source port, so the tests can count TCP connections:

py
"""A local stand-in for the external APIs this chapter calls (exchange rates, payments, e-mail, webhooks).

It is a real HTTP/1.1 server (Starlette under Uvicorn, ephemeral port, own thread), so timeouts,
keep-alive and connection pools behave as they do against a remote service. Each request records
the client's source port: one distinct port = one TCP connection, which is how the tests count
connections opened by "client per request" vs "one client per app".
"""
import asyncio
import threading
import time
from collections import Counter, defaultdict
from contextlib import contextmanager
from typing import Any, Dict, Iterator, List

import uvicorn
from starlette.applications import Starlette
from starlette.requests import Request
from starlette.responses import JSONResponse, Response
from starlette.routing import Route


class StubState:
    def __init__(self) -> None:
        self.reset()

    def reset(self) -> None:
        self.hits: Counter = Counter()             # path -> number of requests
        self.client_ports: set = set()              # distinct source ports = TCP connections
        self.flaky_seen: Dict[str, int] = defaultdict(int)
        self.charges: List[Dict[str, Any]] = []     # every charge actually created
        self.idempotency: Dict[str, Dict[str, Any]] = {}   # Idempotency-Key -> stored response
        self.emails: List[Dict[str, Any]] = []
        self.hooks: List[Dict[str, Any]] = []
        self.hook_failures_left = 0
        self.in_flight = 0
        self.peak_in_flight = 0


STATE = StubState()


async def _track(request: Request) -> None:
    STATE.hits[request.url.path] += 1
    if request.client:
        STATE.client_ports.add(request.client.port)


async def rates(request: Request) -> Response:
    """GET /rates/{currency}?delay_ms=: a slow read endpoint (idempotent)."""
    await _track(request)
    delay = int(request.query_params.get("delay_ms", "0")) / 1000
    STATE.in_flight += 1
    STATE.peak_in_flight = max(STATE.peak_in_flight, STATE.in_flight)
    try:
        await asyncio.sleep(delay)
    finally:
        STATE.in_flight -= 1
    cur = request.path_params["currency"].upper()
    if cur.startswith("X"):                    # XXX, XAA, ...: unknown currencies
        return JSONResponse({"detail": "unknown currency"}, status_code=404)
    return JSONResponse({"currency": cur, "rate": 1.08 if cur == "EUR" else 1.0})


async def flaky(request: Request) -> Response:
    """GET /flaky/{key}?fail=N&status=503&retry_after=S: fails N times per key, then succeeds."""
    await _track(request)
    key = request.path_params["key"]
    fail = int(request.query_params.get("fail", "0"))
    status = int(request.query_params.get("status", "503"))
    STATE.flaky_seen[key] += 1
    if STATE.flaky_seen[key] <= fail:
        headers = {}
        if "retry_after" in request.query_params:
            headers["Retry-After"] = request.query_params["retry_after"]
        return JSONResponse({"detail": "try again"}, status_code=status, headers=headers)
    return JSONResponse({"key": key, "attempt": STATE.flaky_seen[key]})


async def charges(request: Request) -> Response:
    """POST /charges: creates a charge. Honours Idempotency-Key like a payment provider.

    `?commit_then_fail=N`: the first N calls create the charge and THEN answer 500, the case where
    the client cannot tell whether the side effect happened.
    """
    await _track(request)
    body = await request.json()
    key = request.headers.get("Idempotency-Key")
    if key and key in STATE.idempotency:
        return JSONResponse(STATE.idempotency[key], headers={"Idempotent-Replayed": "true"})
    charge = {"id": f"ch_{len(STATE.charges) + 1}", "amount": body["amount"]}
    STATE.charges.append(charge)
    if key:
        STATE.idempotency[key] = charge
    fail = int(request.query_params.get("commit_then_fail", "0"))
    if STATE.hits[request.url.path] <= fail:
        return JSONResponse({"detail": "internal error"}, status_code=500)
    return JSONResponse(charge, status_code=201)


async def email(request: Request) -> Response:
    await _track(request)
    STATE.emails.append(await request.json())
    return JSONResponse({"queued": True}, status_code=202)


async def hooks(request: Request) -> Response:
    """POST /hooks: a webhook receiver on the other side, failing the first N deliveries."""
    await _track(request)
    if STATE.hook_failures_left > 0:
        STATE.hook_failures_left -= 1
        return JSONResponse({"detail": "down"}, status_code=503)
    STATE.hooks.append({"body": (await request.body()).decode(), "signature": request.headers.get("X-Signature")})
    return Response(status_code=204)


stub_app = Starlette(routes=[
    Route("/rates/{currency}", rates),
    Route("/flaky/{key}", flaky),
    Route("/charges", charges, methods=["POST"]),
    Route("/email", email, methods=["POST"]),
    Route("/hooks", hooks, methods=["POST"]),
])


@contextmanager
def serve_in_thread(app: Any = stub_app, lifespan: str = "off") -> Iterator[str]:
    """Run `app` under Uvicorn on 127.0.0.1:<ephemeral> in a daemon thread; yield its base URL."""
    config = uvicorn.Config(app, host="127.0.0.1", port=0, log_level="warning", lifespan=lifespan)
    server = uvicorn.Server(config)
    thread = threading.Thread(target=server.run, daemon=True)
    thread.start()
    deadline = time.monotonic() + 10
    while not server.started:
        if time.monotonic() > deadline:
            raise RuntimeError("stub server did not start")
        time.sleep(0.01)
    port = server.servers[0].sockets[0].getsockname()[1]
    try:
        yield f"http://127.0.0.1:{port}"
    finally:
        server.should_exit = True
        thread.join(timeout=5)

The fixtures run the After app's lifespan explicitly (httpx.ASGITransport does not) and give each test a fresh fakeredis server. The project file pins the stack:

py
import os
from typing import Any, AsyncIterator, Iterator, Tuple

import fakeredis
import httpx
import pytest
import pytest_asyncio

from app.main import create_app
from app.stub_server import STATE, serve_in_thread

# httpx honours proxy settings (trust_env=True). On the build machine macOS reports a system proxy
# (127.0.0.1:1082) and urllib does not bypass it for 127.0.0.1, so local test traffic went through
# it. An explicit NO_PROXY makes httpx use the environment only (subprocesses inherit it).
os.environ.setdefault("NO_PROXY", "127.0.0.1,localhost")


@pytest.fixture(scope="session")
def upstream() -> Iterator[str]:
    """The local external-API stub (real HTTP on an ephemeral port), shared by the session."""
    with serve_in_thread() as base:
        yield base


@pytest.fixture(autouse=True)
def reset_stub() -> Iterator[None]:
    STATE.reset()
    yield


@pytest.fixture
def redis_server() -> fakeredis.FakeServer:
    """One in-memory "Redis server"; every FakeAsyncRedis(server=...) is a separate client of it."""
    return fakeredis.FakeServer()


@pytest_asyncio.fixture
async def shop(upstream: str, redis_server: fakeredis.FakeServer) -> AsyncIterator[Tuple[Any, httpx.AsyncClient]]:
    """The After app with its lifespan running, driven in-process through httpx.ASGITransport."""
    app = create_app(upstream, lambda: fakeredis.FakeAsyncRedis(server=redis_server))
    async with app.router.lifespan_context(app):      # ASGITransport alone does not run the lifespan
        transport = httpx.ASGITransport(app=app)
        async with httpx.AsyncClient(transport=transport, base_url="http://shop") as client:
            yield app, client
toml
[project]
name = "background-tasks-caching-external-apis"
version = "0.1.0"
description = "Snippets for the Background Tasks, Caching & External APIs chapter: BackgroundTasks, httpx, tenacity retries, circuit breaker, outbound rate limiting, in-memory and Redis caching, webhooks, outbox"
# The page targets Python 3.12+; the pins below are the newest releases that still install on 3.9,
# the only interpreter on the build machine (FastAPI 0.129.0 dropped 3.9).
requires-python = ">=3.9"
dependencies = [
    "fastapi==0.128.8",
    "starlette==0.49.3",
    "pydantic==2.13.5",
    "sqlalchemy==2.0.58",
    "httpx==0.28.1",
    "uvicorn==0.39.0",
    "tenacity==9.1.2",
    "backoff==2.2.1",
    "aiolimiter==1.2.1",
    "cachetools==6.2.6",
    "redis==7.0.1",
    # Lets Pydantic evaluate `X | None` annotations on Python 3.9; not needed on 3.10+.
    "eval-type-backport==0.4.0; python_version < '3.10'",
]

[project.optional-dependencies]
test = [
    "pytest==8.4.2",
    "pytest-asyncio==1.2.0",       # last release for Python 3.9
    "anyio==4.12.1",
    "respx==0.23.1",
    "fakeredis[lua]==2.41.0",      # in-memory Redis; [lua] adds lupa so EVAL/register_script work
]

[build-system]
requires = ["setuptools>=61"]
build-backend = "setuptools.build_meta"

[tool.setuptools]
packages = ["app"]

[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "-q -p no:cacheprovider"
pythonpath = ["."]
asyncio_mode = "strict"
asyncio_default_fixture_loop_scope = "function"

The Python angle ​

Python has no built-in job runner, HTTP client pool or shared cache, so each piece is a library:

  • Starlette provides BackgroundTask(s), and FastAPI injects them.
  • httpx provides the pooled client. It is built on httpcore, and the async side runs on AnyIO.
  • tenacity and backoff provide retries.
  • cachetools and the standard library provide in-process caches.
  • redis-py provides redis.asyncio.

Three language facts shape the code:

  • The event loop is single-threaded, so asyncio.Lock, Semaphore, AsyncLimiter and per-key Futures are cheap and need no thread safety. They are also per process, and on Python 3.9 they bind to the loop that is running when they are created. That is why the lifespan creates them, never module import.
  • functools.lru_cache knows nothing about coroutines. On an async def it caches the coroutine object, and the second await fails.
  • FastAPI reads type hints at runtime. The DI chapter's warning still applies: no from __future__ import annotations in a module that declares class dependencies on FastAPI 0.128.8. main.py here has none.

The concept catalogue ​

BackgroundTasks vs a task queue: where the job livesBackgroundTasks (in-process)POST /signuphandler runs201 sent firstclient done: 0.006 stask runs: same process,same loop (e-mail at 0.304 s)SIGKILL / OOM / deploy:job lost, no retry, no recordSIGTERM: Uvicorn waits for it ("Waiting for background tasks to complete.")Task queue (Celery, RQ, arq, Dramatiq, TaskIQ)POST /ordershandler runsjob / outbox rowstored durably, 202broker: Redis / RabbitMQ /SQS (message reserved)worker process runs it,ack AFTER successworker crashes before ack(no ack within the timeout)visible again after thevisibility timeout: redeliveredResult: at-least-once delivery, retries, scheduling (beat / cron), result backend; the task must be idempotent.Timings on the top lane are from the real run (tests/test_background.py, tests/test_lost_on_crash.py).

BackgroundTasks and add_task: response first, then task Must-know ​

In plain words: You hand FastAPI a function and its arguments. It sends the response to the client, and then, in the same worker, it calls your function. The client never waits for it and never hears whether it worked.

Common misunderstanding: "My test shows the endpoint takes 300 ms, so the task runs before the response." In-process test clients (TestClient, httpx.ASGITransport) return only when the whole ASGI call has finished, tasks included. Measured with the same app: under real Uvicorn the client had the 201 after 0.006 s and the e-mail went out 0.304 s after the handler ran; through ASGITransport the client waited 0.305 s.

Definition:

  • Declare a parameter of type BackgroundTasks and call tasks.add_task(func, *args, **kwargs). A dependency can declare one too, and FastAPI merges them into one object per request.
  • Starlette's docs say a background task "will run only once the response has been sent". In Starlette 0.49.3's Response.__call__, the response sends http.response.start, then http.response.body, then await self.background().
  • BackgroundTasks runs its tasks in order, one after another. An async def task is awaited on the event loop, and a plain def task goes to the thread pool (run_in_threadpool).
  • If a task raises, the response is long gone. Uvicorn logs Exception in ASGI application and the remaining tasks of that response do not run.
1  client  POST /signup ─▶ handler: validate, insert user, tasks.add_task(send_welcome_email, ...)
2  server  send http.response.start (201) + http.response.body   -> client has the answer (0.006 s)
3  server  await background(): send_welcome_email runs on the same event loop (0.304 s later)
4  server  task raises?  -> "Exception in ASGI application" in the log, nobody else is told
5  server  SIGTERM now?  -> Uvicorn: "Waiting for background tasks to complete." (it finishes)
6  server  SIGKILL now?  -> the task is gone; nothing persisted that it existed
py
"""BackgroundTasks: the response goes out first, then the task runs in the same process."""
import logging
import time

import fakeredis
import httpx
import pytest

from app.main import create_app
from app.stub_server import STATE, serve_in_thread


def test_response_first_then_task_under_real_uvicorn(upstream):
    app = create_app(upstream, lambda: fakeredis.FakeAsyncRedis(), email_delay_s=0.3)
    with serve_in_thread(app, lifespan="on") as base:
        t0 = time.perf_counter()
        r = httpx.post(f"{base}/signup", json={"email": "ana@example.com"})
        client_got_response = time.perf_counter() - t0
        assert r.status_code == 201
        assert STATE.emails == []                    # the mail has not been sent yet
        deadline = time.monotonic() + 5
        while not STATE.emails and time.monotonic() < deadline:
            time.sleep(0.01)
        events = dict(app.state.events)
    task_done_after = events["task_end"] - events["handler"]
    print(f"\nuvicorn: client had the 201 after {client_got_response:.3f}s; "
          f"e-mail sent {task_done_after:.3f}s after the handler ran")
    assert client_got_response < 0.2
    assert task_done_after >= 0.3
    assert STATE.emails == [{"to": "ana@example.com", "template": "welcome"}]


@pytest.mark.asyncio
async def test_asgi_transport_waits_for_background_tasks(upstream):
    """In-process test clients return only when the whole ASGI call (tasks included) is done."""
    app = create_app(upstream, lambda: fakeredis.FakeAsyncRedis(), email_delay_s=0.3)
    async with app.router.lifespan_context(app):
        async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://t") as c:
            t0 = time.perf_counter()
            r = await c.post("/signup", json={"email": "bo@example.com"})
            elapsed = time.perf_counter() - t0
    print(f"\nASGITransport: client had the 201 after {elapsed:.3f}s (task already finished)")
    assert r.status_code == 201 and elapsed >= 0.3
    assert len(STATE.emails) == 1


def test_failing_task_does_not_change_the_response(caplog):
    """The provider is down (closed port). The client still got 201; only the log knows."""
    app = create_app("http://127.0.0.1:1", lambda: fakeredis.FakeAsyncRedis())
    caplog.set_level(logging.ERROR)
    with serve_in_thread(app, lifespan="on") as base:
        r = httpx.post(f"{base}/signup", json={"email": "cy@example.com"})
        time.sleep(0.3)
    print("\n" + "\n".join(f"{rec.name}: {rec.getMessage().splitlines()[0]}" for rec in caplog.records))
    assert r.status_code == 201
    messages = [rec.getMessage() for rec in caplog.records]
    assert any("background_task_failed" in m for m in messages)

Lost on crash: when to use a queue Must-know ​

In plain words: A background task exists only in the memory of one process. If the process dies, the task dies with it, and nobody knows it was ever there.

Common misunderstanding: "Graceful shutdown makes BackgroundTasks safe." It covers deploys (SIGTERM). It does not cover OOM kills, segfaults, kill -9, node loss or a task that takes longer than the platform's grace period.

Definition: The snippet starts a real Uvicorn in a subprocess, posts an order receipt job that takes 1 s and signals the process 0.2 s later. Real results:

  • SIGKILL: exit code -9, marker file not written. The job is lost.
  • SIGTERM: exit code -15, marker written. Uvicorn logged Waiting for background tasks to complete. (CTRL+C to force quit); its --timeout-graceful-shutdown is the "maximum number of seconds to wait for graceful shutdown".

Use a queue (or an outbox) as soon as any of these is true:

  • the work must happen even if the web process dies;
  • it must be retried for longer than a request lifetime;
  • it takes seconds of CPU;
  • it is scheduled;
  • it needs a result someone polls;
  • it must be rate limited across the fleet;
  • you need to see it (a dashboard or a failed-jobs table).

FastAPI's own docs point the same way: for "heavy background computation" that does not need the same process, "you might benefit from using other bigger tools like Celery".

py
"""BackgroundTasks live in the web process: SIGKILL loses an accepted job; SIGTERM lets Uvicorn
finish it (graceful shutdown). A queue with acknowledgements survives both."""
import os
import signal
import socket
import subprocess
import sys
import time
from pathlib import Path

import httpx
import pytest

ROOT = Path(__file__).resolve().parents[1]


def _free_port() -> int:
    with socket.socket() as s:
        s.bind(("127.0.0.1", 0))
        return s.getsockname()[1]


def _start(marker: Path):
    port = _free_port()
    env = {**os.environ, "MARKER_FILE": str(marker), "PYTHONDONTWRITEBYTECODE": "1"}
    proc = subprocess.Popen([sys.executable, "-m", "app.crash_demo", str(port)], cwd=ROOT, env=env,
                            stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
    base = f"http://127.0.0.1:{port}"
    for _ in range(200):
        try:
            httpx.get(f"{base}/docs", timeout=0.2)
            return proc, base
        except httpx.HTTPError:
            time.sleep(0.05)
    proc.kill()
    raise RuntimeError("server did not start")


@pytest.mark.parametrize("sig", [signal.SIGKILL, signal.SIGTERM], ids=["SIGKILL", "SIGTERM"])
def test_accepted_job_and_process_death(tmp_path, sig):
    marker = tmp_path / "marker.txt"
    proc, base = _start(marker)
    r = httpx.post(f"{base}/orders/42/receipt")
    assert r.status_code == 202                      # the client was told "accepted"
    time.sleep(0.2)
    proc.send_signal(sig)
    out, _ = proc.communicate(timeout=10)
    print(f"\n{sig.name}: 202 received, exit code {proc.returncode}, marker written: {marker.exists()}")
    if sig == signal.SIGTERM:
        print("\n".join(line for line in out.splitlines() if "shutdown" in line.lower() or "Waiting" in line))
    if sig == signal.SIGKILL:
        assert not marker.exists()                  # lost on crash
    else:
        assert marker.read_text() == "receipt for order 42 sent\n"
py
"""Run by tests/test_lost_on_crash.py in a SUBPROCESS: a BackgroundTasks job that takes 1 s and
then writes a marker file. SIGKILL during that second loses it; SIGTERM lets Uvicorn finish it."""
import asyncio
import os
import sys

import uvicorn
from fastapi import BackgroundTasks, FastAPI

MARKER = os.environ.get("MARKER_FILE", "marker.txt")
app = FastAPI()


async def slow_job(order_id: int) -> None:
    await asyncio.sleep(1.0)
    with open(MARKER, "w") as f:
        f.write(f"receipt for order {order_id} sent\n")


@app.post("/orders/{order_id}/receipt", status_code=202)
async def receipt(order_id: int, tasks: BackgroundTasks) -> dict:
    tasks.add_task(slow_job, order_id)
    return {"accepted": order_id}


if __name__ == "__main__":
    uvicorn.run(app, host="127.0.0.1", port=int(sys.argv[1]), log_level="info",
                timeout_graceful_shutdown=5)

Task queues: Celery, RQ, arq, Dramatiq, TaskIQ Important ​

In plain words: The web process writes a small message ("send receipt for order 42") to a broker. Separate worker processes take messages, run them and confirm when done. If a worker dies before confirming, another worker gets the message again.

Common misunderstanding: "A queue gives exactly-once execution." Queues give at-least-once delivery: arq's docs say it plainly, "sometimes exactly once can be hard or impossible, arq favours multiple times over zero times". The task must be idempotent (database transactions, idempotency keys, a done-marker).

Definition: The vocabulary every queue shares:

  • Broker: Redis, RabbitMQ or SQS.
  • Worker: a separate process.
  • Acknowledgement: early or late. Celery acks on receipt by default. "If your task is idempotent you can set the acks_late option to have the worker acknowledge the message after the task returns instead."
  • Visibility timeout: on Redis, "the number of seconds to wait for the worker to acknowledge the task before the message is redelivered to another worker", with a default of 1 hour.
  • Retries with backoff.
  • Result backend: where return values and states are stored.
  • Scheduled tasks: Celery beat "is a scheduler; It kicks off tasks at regular intervals".

None of these libraries is installed in the snippet project, so the code below is "expected, not run".

QueueModelAsync tasksBrokerSchedulingNotes (from the saved docs)
Celery 5.7prefork workers, canvas (chains, groups)no (sync tasks)Redis, RabbitMQ, SQScelery beatacks_late, autoretry_for, retry_backoff; result backends
RQ 3.0function calls on Redis queuesnoRedis ≥ 5, Valkey ≥ 7.2enqueue_in / enqueue_at"function call can be put on an RQ queue"
arq 0.28asyncio worker, "a pool of asyncio Tasks"yesRediscron jobs"Job queues and RPC in python with asyncio and redis"
Dramatiq 2.2actors, middlewarenoRedis, RabbitMQdelayed messages (send_with_options(delay=...))"tasks are only ever acked when" processed; contrasts Celery's early ack
TaskIQ 0.13asyncio-first, state and dependenciesyesRabbitMQ (aio-pika), NATS, Redisscheduler ("Scheduling tasks" guide)docs recommend taskiq-aio-pika / taskiq-nats + taskiq-redis results
python
# Celery: the receipt as a durable job (expected, not run: no broker on the build machine)
from celery import Celery

celery_app = Celery("shop", broker="redis://localhost:6379/0", backend="redis://localhost:6379/1")
celery_app.conf.task_acks_late = True                       # ack after success: redelivery on crash
celery_app.conf.broker_transport_options = {"visibility_timeout": 3600}


@celery_app.task(bind=True, autoretry_for=(ConnectionError,), retry_backoff=True, max_retries=5)
def send_receipt(self, order_id: int) -> None:
    ...                                                      # must be idempotent: may run twice


# in the FastAPI route, after the transaction committed (or from the outbox relay):
# send_receipt.delay(order_id)

httpx.Client vs httpx.AsyncClient Must-know ​

In plain words: Both are the same HTTP client with a connection pool. Client blocks the thread while it waits; AsyncClient gives the event loop back while it waits. Use the one that matches the code around it.

Common misunderstanding: "httpx.get() is fine for one call." The top-level functions build and throw away a client each time. The httpx docs: "HTTPX has to establish a new connection for every single request (connections are not reused)."

Definition:

  • httpx.Client belongs in def routes, scripts, Celery and RQ workers.
  • httpx.AsyncClient belongs in async def routes and asyncio workers (arq, TaskIQ).
  • A sync client inside async def blocks the whole loop. That is measured in Async Python, with 20 calls taking 2.07 s.
  • Both clients take base_url, timeout, limits, headers, transport and event_hooks. Both must be closed (close() / aclose() or a with block). Both read proxy settings from the environment unless trust_env=False.

Real gotcha from this build:

  • The build machine's macOS reports a system proxy (127.0.0.1:1082), and Python's urllib.request.proxy_bypass('127.0.0.1') returned False.
  • httpx therefore sent requests for the local stub through that proxy, which answered 503 while the stub was still starting.
  • The tests set NO_PROXY=127.0.0.1,localhost in conftest.py. Set trust_env=False on clients that must never use a proxy.

Timeouts: connect, read, write, pool Must-know ​

In plain words: A timeout says how long you are willing to wait for each step. Without one, a stuck upstream holds your worker, your connection and your user forever.

Common misunderstanding: "httpx has no timeout by default, like requests." It does: "HTTPX is careful to enforce timeouts everywhere by default. The default behavior is to raise a TimeoutException after 5 seconds of network inactivity." Real: httpx.AsyncClient().timeout printed Timeout(timeout=5.0). The default is safe but rarely right. Five seconds is longer than most request budgets.

Definition:

  • httpx.Timeout(default, connect=..., read=..., write=..., pool=...). Real: httpx.Timeout(2.0, connect=1.0) printed Timeout(connect=1.0, read=2.0, write=2.0, pool=2.0).
  • connect bounds establishing the socket.
  • read bounds each wait for data. It is not a total deadline: a server that trickles one byte every second never trips a 2 s read timeout.
  • write bounds sending.
  • pool bounds waiting for a free connection from the pool.
  • For a total deadline, wrap the call in asyncio.wait_for (or asyncio.timeout on 3.11+), or use tenacity's stop_after_delay, which bounds the retries as a whole.

Real results:

  • read=0.1 against a 500 ms endpoint raised ReadTimeout after 0.103 s.
  • max_connections=1, pool=0.05 raised PoolTimeout for a second concurrent call.
  • A connect timeout needs an address that silently drops packets. It is not reproduced here; it raises httpx.ConnectTimeout (expected, not run).
py
"""httpx against the local stub: timeouts, pool limits, keep-alive and one client per app."""
import asyncio
import time

import httpx
import pytest

from app.external import make_client
from app.stub_server import STATE


@pytest.mark.asyncio
async def test_read_timeout(upstream):
    async with make_client(upstream, timeout=httpx.Timeout(2.0, read=0.1)) as client:
        t0 = time.perf_counter()
        with pytest.raises(httpx.ReadTimeout) as info:
            await client.get("/rates/EUR", params={"delay_ms": 500})
    print(f"\nread=0.1 against a 500 ms endpoint: {type(info.value).__name__} after "
          f"{time.perf_counter() - t0:.3f}s")


@pytest.mark.asyncio
async def test_pool_timeout_when_all_connections_are_busy(upstream):
    limits = httpx.Limits(max_connections=1)
    async with make_client(upstream, limits=limits, timeout=httpx.Timeout(2.0, pool=0.05)) as client:
        slow = asyncio.ensure_future(client.get("/rates/EUR", params={"delay_ms": 300}))
        await asyncio.sleep(0.05)                      # the only connection is now busy
        with pytest.raises(httpx.PoolTimeout) as info:
            await client.get("/rates/USD")
        assert (await slow).status_code == 200
    print(f"\nmax_connections=1, pool=0.05: second call -> {type(info.value).__name__}")


@pytest.mark.asyncio
async def test_pool_limit_bounds_concurrency(upstream):
    async with make_client(upstream, limits=httpx.Limits(max_connections=2)) as client:
        t0 = time.perf_counter()
        rs = await asyncio.gather(*(client.get("/rates/EUR", params={"delay_ms": 100}) for _ in range(6)))
        elapsed = time.perf_counter() - t0
    print(f"\n6 x 100 ms with max_connections=2: {elapsed:.3f}s, peak in flight upstream "
          f"{STATE.peak_in_flight}, connections {len(STATE.client_ports)}")
    assert all(r.status_code == 200 for r in rs)
    assert STATE.peak_in_flight == 2 and elapsed >= 0.3


@pytest.mark.asyncio
async def test_one_client_per_app_reuses_connections(upstream):
    t0 = time.perf_counter()
    for _ in range(20):                                # anti-pattern: a client per request
        async with httpx.AsyncClient(base_url=upstream) as c:
            await c.get("/rates/EUR")
    per_request = (time.perf_counter() - t0, len(STATE.client_ports))
    STATE.reset()
    t0 = time.perf_counter()
    async with make_client(upstream) as client:        # one client, keep-alive pool
        for _ in range(20):
            await client.get("/rates/EUR")
    shared = (time.perf_counter() - t0, len(STATE.client_ports))
    print(f"\n20 sequential GETs: client per request {per_request[0]:.3f}s, {per_request[1]} TCP connections; "
          f"one shared client {shared[0]:.3f}s, {shared[1]} TCP connection(s)")
    assert per_request[1] == 20 and shared[1] == 1


@pytest.mark.asyncio
async def test_connect_error_and_raise_for_status(upstream):
    async with make_client("http://127.0.0.1:1") as dead:
        with pytest.raises(httpx.ConnectError) as info:
            await dead.get("/rates/EUR")
    async with make_client(upstream) as client:
        r = await client.get("/rates/XXX")
        assert r.status_code == 404                    # httpx does not raise by itself
        with pytest.raises(httpx.HTTPStatusError) as status_info:
            r.raise_for_status()
    print(f"\nclosed port: {type(info.value).__name__}: {info.value}")
    print(f"raise_for_status: {str(status_info.value).splitlines()[0]}")
    assert isinstance(info.value, httpx.TransportError)


def test_sync_client_in_a_def_function(upstream):
    """httpx.Client: fine in `def` routes, scripts and Celery tasks; never inside `async def`."""
    with httpx.Client(base_url=upstream, timeout=httpx.Timeout(2.0)) as client:
        assert client.get("/rates/EUR").json() == {"currency": "EUR", "rate": 1.08}


def test_timeout_object_defaults():
    t = httpx.Timeout(2.0, connect=1.0)
    print(f"\n{t!r}; client default: {httpx.AsyncClient().timeout!r}")
    assert (t.connect, t.read, t.write, t.pool) == (1.0, 2.0, 2.0, 2.0)

Pool limits, keep-alive and the lifespan client Must-know ​

In plain words: Opening a connection costs a round trip (several with TLS). A client keeps finished connections open (keep-alive) and reuses them. One client per app means one pool, so every request shares warm connections and one global limit.

Common misunderstanding: "Creating an AsyncClient per request is just tidy scoping." It throws the pool away each time. The httpx async guide warns about "instantiating multiple client instances - for example by using async with inside a 'hot loop'". It recommends "a single scoped client that's passed throughout wherever it's needed".

Definition:

  • httpx.Limits(max_connections=100, max_keepalive_connections=20, keepalive_expiry=5) are the documented defaults. When all connections are busy, further requests wait up to the pool timeout.
  • Create the client in the FastAPI lifespan, which runs "once, before the application starts receiving requests" and once at shutdown. Store it on app.state and close it with await client.aclose().
  • base_url makes routes relative (client.get("/rates/EUR")).
  • HTTPTransport(retries=n) retries only ConnectError/ConnectTimeout. For "reacting to 503 Service Unavailable, consider general-purpose tools such as tenacity".

Real results:

  • 20 sequential GETs with a client per request opened 20 TCP connections in 0.068 s. One shared client opened 1 and took 0.020 s, on localhost, where a handshake is nearly free.
  • 6 concurrent 100 ms calls with max_connections=2 took 0.310 s with a peak of 2 in flight at the upstream.
1  lifespan start  -> AsyncClient(base_url, Timeout(connect=1, read=2, write=2, pool=0.5), Limits(20, 10, 30 s))
2  request A       -> pool empty: open TCP #1, GET /rates/EUR, keep #1 idle
3  request B       -> reuse #1 (no handshake)
4  21 concurrent   -> 20 connections busy; the 21st waits for the pool -> PoolTimeout after 0.5 s
5  idle 30 s       -> keepalive_expiry closes idle connections
6  lifespan end    -> await client.aclose(): pool closed, sockets released

Errors: raise_for_status and the exception tree Important ​

In plain words: httpx raises for network problems (could not connect, timed out), not for HTTP status codes. A 404 or 500 is a normal response until you call raise_for_status().

Common misunderstanding: "If the call did not raise, it worked." Real: GET /rates/XXX returned a 404 response silently. Only raise_for_status() raised Client error '404 Not Found' for url 'http://127.0.0.1:.../rates/XXX'.

Definition: The httpx exception tree:

  • HTTPError is the root.
  • RequestError covers network-level failures, which carry .request. Under it, TransportError contains:
    • TimeoutException, the parent of ConnectTimeout, ReadTimeout, WriteTimeout and PoolTimeout;
    • NetworkError, the parent of ConnectError, ReadError and WriteError;
    • ProtocolError, the parent of RemoteProtocolError.
  • HTTPStatusError is raised by raise_for_status() and carries .request and .response.

The After app maps them at the edge:

  • TimeoutException becomes 504;
  • CircuitOpenError becomes 503 with Retry-After;
  • other upstream errors become 502;
  • an upstream 404 becomes a negative cache entry and your own 404.

Retries with tenacity and backoff Must-know ​

In plain words: When a call fails for a reason that might go away (a timeout, a 503), wait a little and try again. Wait longer each time (exponential backoff), and randomise the wait (jitter) so a thousand clients do not retry in lockstep.

Common misunderstanding: "Exponential backoff alone prevents retry storms." Without jitter every client that failed at the same moment retries at the same moment again. The AWS post compares the variants and finds "Equal Jitter" the loser. The choice between "Decorrelated Jitter" and "Full Jitter" is close, and full jitter is the simple default.

Definition: tenacity ("an Apache 2.0 licensed general-purpose retrying library") composes a policy from parts:

  • stop: stop_after_attempt(4) combined with stop_after_delay(5) using |.
  • wait: wait_random_exponential(multiplier, max) is full jitter, a random wait between 0 and min(max, multiplier × 2^(n-1)).
  • retry: retry_if_exception(predicate).
  • before_sleep: for logging.
  • reraise=True: raise the last error rather than RetryError.

AsyncRetrying is the async form, used as async for attempt in AsyncRetrying(...) with with attempt:. backoff is the decorator-style alternative (@backoff.on_exception(backoff.expo, httpx.TransportError, max_tries=3, jitter=backoff.full_jitter)).

Real full-jitter samples with multiplier=0.1, max=2, from 1,000 draws per attempt:

AttemptCapMean waitMax wait
10.10 s0.051 s0.100 s
20.20 s0.105 s0.200 s
30.40 s0.195 s0.400 s
40.80 s0.403 s0.800 s
51.60 s0.785 s1.599 s

The real transcript of GET /flaky/a?fail=2 (structured log lines, one JSON object per event):

{"event": "outbound_call", "method": "GET", "url": ".../flaky/a?fail=2", "status": 503, "ms": 2.0, "attempt": 1}
{"event": "outbound_retry", "attempt": 1, "wait_s": 0.029, "method": "GET", "url": ".../flaky/a?fail=2", "reason": "RetryableStatus HTTP 503"}
{"event": "outbound_call", "method": "GET", "url": ".../flaky/a?fail=2", "status": 503, "ms": 1.3, "attempt": 2}
{"event": "outbound_retry", "attempt": 2, "wait_s": 0.04, "method": "GET", "url": ".../flaky/a?fail=2", "reason": "RetryableStatus HTTP 503"}
{"event": "outbound_call", "method": "GET", "url": ".../flaky/a?fail=2", "status": 200, "ms": 1.2, "attempt": 3}
-> 2 retries, success on attempt 3, total wait 0.069 s
py
"""tenacity retries gated on idempotency, Retry-After, the retry budget, and the backoff library."""
import logging
import time
import uuid

import httpx
import pytest
from tenacity import RetryCallState, wait_random_exponential

from app.external import (RetryableStatus, RetryBudget, call, get_with_backoff, make_client,
                          parse_retry_after)
from app.stub_server import STATE


@pytest.mark.asyncio
async def test_get_is_retried_and_every_retry_is_logged(upstream, caplog):
    caplog.set_level(logging.INFO, logger="outbound")
    async with make_client(upstream) as client:
        r = await call(client, "GET", "/flaky/a", params={"fail": 2})
    print("\n" + "\n".join(rec.getMessage() for rec in caplog.records))
    assert r.json() == {"key": "a", "attempt": 3}
    assert sum("outbound_retry" in rec.getMessage() for rec in caplog.records) == 2


@pytest.mark.asyncio
async def test_retry_after_is_honoured(upstream):
    async with make_client(upstream) as client:
        t0 = time.perf_counter()
        r = await call(client, "GET", "/flaky/b", params={"fail": 1, "status": 429, "retry_after": 1})
        elapsed = time.perf_counter() - t0
    print(f"\n429 + Retry-After: 1 -> second attempt succeeded after {elapsed:.3f}s")
    assert r.status_code == 200 and elapsed >= 1.0


@pytest.mark.asyncio
async def test_post_without_idempotency_key_is_not_retried(upstream):
    async with make_client(upstream) as client:
        with pytest.raises(RetryableStatus):
            await call(client, "POST", "/charges", params={"commit_then_fail": 1}, json={"amount": 500})
    print(f"\nPOST, no key, provider committed then answered 500: attempts {STATE.hits['/charges']}, "
          f"charges {len(STATE.charges)}")
    assert STATE.hits["/charges"] == 1 and len(STATE.charges) == 1


@pytest.mark.asyncio
async def test_post_with_idempotency_key_is_retried_safely(upstream):
    key = str(uuid.uuid4())
    async with make_client(upstream) as client:
        r = await call(client, "POST", "/charges", params={"commit_then_fail": 1}, json={"amount": 500},
                       headers={"Idempotency-Key": key})
    print(f"\nPOST + Idempotency-Key: attempts {STATE.hits['/charges']}, charges {len(STATE.charges)}, "
          f"replayed={r.headers.get('Idempotent-Replayed')}, body {r.json()}")
    assert STATE.hits["/charges"] == 2 and len(STATE.charges) == 1
    assert r.headers["Idempotent-Replayed"] == "true"


@pytest.mark.asyncio
async def test_4xx_is_never_retried(upstream):
    async with make_client(upstream) as client:
        with pytest.raises(httpx.HTTPStatusError):
            await call(client, "GET", "/rates/XXX")
    assert STATE.hits["/rates/XXX"] == 1


@pytest.mark.asyncio
async def test_retry_budget_caps_amplification(upstream):
    async def storm(budget):
        STATE.reset()
        async with make_client(upstream) as client:
            for i in range(20):
                with pytest.raises(RetryableStatus):
                    await call(client, "GET", f"/flaky/down{i}", params={"fail": 99}, attempts=3,
                               budget=budget, wait=lambda s: 0)
        return sum(STATE.flaky_seen.values())

    without = await storm(None)
    budget = RetryBudget(ratio=0.2, min_per_window=3)
    with_budget = await storm(budget)
    print(f"\nprovider down, 20 calls x 3 attempts: {without} requests without a budget, "
          f"{with_budget} with RetryBudget(0.2) (retries denied: {budget.denied})")
    assert without == 60 and with_budget == 20 + budget.retries and with_budget <= 24


def test_full_jitter_spread():
    w = wait_random_exponential(multiplier=0.1, max=2)
    rows = []
    for attempt in range(1, 6):
        state = RetryCallState(retry_object=None, fn=None, args=(), kwargs={})
        state.attempt_number = attempt
        samples = [w(state) for _ in range(1000)]
        rows.append(f"attempt {attempt}: cap {min(2, 0.1 * 2 ** (attempt - 1)):.2f}s, "
                    f"mean {sum(samples) / len(samples):.3f}s, max {max(samples):.3f}s")
    print("\n" + "\n".join(rows))


def test_parse_retry_after_both_forms():
    assert parse_retry_after("120") == 120.0
    assert parse_retry_after("Fri, 31 Dec 1999 23:59:59 GMT", now=946684799 - 30) == 30.0
    assert parse_retry_after(None) is None


@pytest.mark.asyncio
async def test_backoff_library_equivalent():
    calls = {"n": 0}

    def handler(request: httpx.Request) -> httpx.Response:
        calls["n"] += 1
        raise httpx.ConnectError("connection refused", request=request)

    async with httpx.AsyncClient(transport=httpx.MockTransport(handler), base_url="http://x") as c:
        with pytest.raises(httpx.ConnectError):
            await get_with_backoff(c, "/rates/EUR")
    print(f"\nbackoff.on_exception(expo, max_tries=3): {calls['n']} attempts, then the error")
    assert calls["n"] == 3

Retry only idempotent requests: the idempotency key Must-know ​

In plain words: Repeating a read is harmless. Repeating "charge 5 euros" is not, unless the provider can tell that the second request is the same as the first. The idempotency key is how it tells: a unique id the client generates once per logical operation and sends with every attempt.

Common misunderstanding: "A 500 means nothing happened." A 500 or a timeout tells you nothing about whether the side effect committed. The stub's commit_then_fail mode creates the charge and then answers 500, which is exactly the case a naive retry turns into a double charge.

Definition:

  • GET, HEAD, OPTIONS, PUT and DELETE are idempotent by HTTP semantics. POST and PATCH are not.
  • The snippet's predicate retries a request only if its method is idempotent or it carries Idempotency-Key. A 4xx is never retried.
  • Stripe's docs: "When creating or updating an object, use an idempotency key. Then, if a connection error occurs, you can safely repeat the request without risk of creating a second object". They suggest V4 UUIDs. For API v1 they save "the status code and body of the first request" and let keys be removed "after they're at least 24 hours old".
  • The After app requires the header from its client (Header(min_length=8); a missing header gives 422) and forwards it. That way a retry by the browser, by FastAPI's caller or by our own tenacity loop maps to one charge.

Real results:

  • POST without a key: 1 attempt, 1 charge, error raised.
  • POST with a key: 2 attempts, 1 charge, second response Idempotent-Replayed: true.
  • The Before app: 3 attempts, 3 charges.

How a provider stores keys and what it answers on a conflict is the API contract, which belongs to API Idempotency.

1  shop  POST /charges  Idempotency-Key: 4c0e...   -> provider creates ch_1, then crashes before answering
2  shop  sees 500 (or ReadTimeout): unknown outcome; the request has a key, so it may be retried
3  shop  wait 0.03 s (jitter), POST /charges  Idempotency-Key: 4c0e...
4  prov  key seen: return the stored response for ch_1, header Idempotent-Replayed: true
5  shop  1 charge. Without the key: step 4 creates ch_2 (the Before app reached ch_3)

Retry-After and the retry budget Important ​

In plain words:

  • When a server says "come back in 30 seconds" (429 or 503 with Retry-After), believe it.
  • When a dependency is down for everyone, cap how much extra load your retries may add. That cap is the retry budget, for example "retries may be at most 20 % of requests".

Common misunderstanding: "Three attempts per call is a small number." During an outage every call makes all three, so the failing service sees 3× its normal traffic exactly when it can handle the least. Layered services multiply it: AWS's 243× example.

Definition:

  • Retry-After is HTTP-date / delay-seconds (RFC 9110, section 10.2.3). The snippet parses both forms and caps the wait at 5 s so a hostile or buggy header cannot park a request for an hour.
  • The RetryBudget counts requests and retries per 10 s window and allows a retry while retries < max(3, 0.2 × requests).
  • It is plugged in as the last tenacity stop condition. tenacity evaluates the retry predicate first, then computes the wait, then checks stop, and stop_any short-circuits, so a token is spent only when the attempt and deadline limits would really allow another try (How tenacity decides).
  • The first version, which spent tokens inside the retry predicate, wasted one token on every final attempt. The test caught it: 23 requests sent, but the budget counted 4 retries.

Real results:

  • 429 with Retry-After: 1: the second attempt succeeded after 1.004 s.
  • Upstream down, 20 calls with 3 attempts each: 60 requests without a budget, 24 with (19 retries denied).

Circuit breaker and half-open Important ​

Retry decision (per call)Circuit breaker (per upstream)attempt failstimeout, ConnectError, 429, 5xx? (4xx: no)idempotent: GET/PUT/DELETE or Idempotency-Key?attempts left and deadline not passed?retry budget has a token (fleet-wide cap)?all yes: retry; any no: raise the last errorwait: Retry-After (capped) if sent, elserandom(0, min(max, base x 2^(n-1))) full jitterlog every retry: attempt, wait_s, url, reason(measured: 60 requests without a budget, 24 with)closedcalls passopenfail fast (503)half-openone trial call3 consecutive failures5 s reset timeouttrial succeedstrial fails: open againa success in closed resets the failure countreal run: 502, 502, 502, then 503 in 0.6 ms

In plain words: After several failures in a row, stop calling the upstream for a while and fail immediately. After the pause, let one test call through. If it works, resume. If not, pause again.

Common misunderstanding: "Retries and a breaker do the same job." Retries fight short, random failures of one call. A breaker reacts to a dependency that is down for everyone and protects both sides: your workers stop waiting on timeouts, and the upstream gets room to recover. AWS also warns that breakers "introduce modal behavior into systems that can be difficult to test", so keep the states few and log every transition.

Definition: The snippet's CircuitBreaker has three states:

  • closed: calls pass. Consecutive failures are counted, and a success resets the count.
  • open: after failure_threshold (3), fail fast with CircuitOpenError without calling.
  • half-open: after reset_timeout (5 s), one trial call passes and other callers fail fast. Success closes the breaker; failure re-opens it with a new timestamp.

The clock is injectable, so the test moves time instead of sleeping. Only outages count as failures: the After app turns an upstream 404 into None inside the breaker call, so three unknown currencies in a row leave the breaker closed and EUR still answers 200 (test test_404s_do_not_open_the_breaker). An earlier version handled the 404 outside the breaker; a review found that three unknown currencies would then have cut off every currency. Libraries: purgatory (3.0.2, "A circuit breaker implementation for asyncio", needs Python ≥ 3.11), aiobreaker (1.2.0, last release 2021-05-17) and pybreaker (sync). The pattern itself (thresholds, per-endpoint vs per-host breakers, fallbacks) is in Circuit Breaker.

Real results:

  • Transitions [('closed', 'open'), ('open', 'half_open'), ('half_open', 'closed')].
  • With the rates provider on a closed port the app answered 502, 502, 502, then 503 with Retry-After: 5 in 0.6 ms. The fourth call never reached the network.
py
"""A small circuit breaker: closed -> open after N consecutive failures, open -> half-open after
a cool-down, half-open lets ONE trial call through: success closes, failure re-opens.
Libraries with the same idea: purgatory, aiobreaker, pybreaker (sync)."""
import asyncio
import time
from typing import Any, Awaitable, Callable, List, Tuple, TypeVar

T = TypeVar("T")


class CircuitOpenError(Exception):
    pass


class CircuitBreaker:
    def __init__(self, name: str, failure_threshold: int = 3, reset_timeout: float = 5.0,
                 clock: Callable[[], float] = time.monotonic) -> None:
        self.name = name
        self.failure_threshold = failure_threshold
        self.reset_timeout = reset_timeout
        self.clock = clock
        self.state = "closed"
        self.failures = 0
        self.opened_at = 0.0
        self.trial_in_flight = False
        self.transitions: List[Tuple[str, str]] = []

    def _move(self, new: str) -> None:
        self.transitions.append((self.state, new))
        self.state = new

    def _before_call(self) -> None:
        if self.state == "open":
            if self.clock() - self.opened_at >= self.reset_timeout:
                self._move("half_open")
            else:
                raise CircuitOpenError(f"{self.name}: open, failing fast")
        if self.state == "half_open":
            if self.trial_in_flight:
                raise CircuitOpenError(f"{self.name}: half-open, trial call in flight")
            self.trial_in_flight = True

    def _on_success(self) -> None:
        if self.state == "half_open":
            self.trial_in_flight = False
            self._move("closed")
        self.failures = 0

    def _on_failure(self) -> None:
        if self.state == "half_open":
            self.trial_in_flight = False
            self.opened_at = self.clock()
            self._move("open")
            return
        self.failures += 1
        if self.failures >= self.failure_threshold:
            self.opened_at = self.clock()
            self._move("open")

    async def call(self, fn: Callable[..., Awaitable[T]], *args: Any, **kwargs: Any) -> T:
        self._before_call()
        try:
            result = await fn(*args, **kwargs)
        except asyncio.CancelledError:
            if self.state == "half_open":
                self.trial_in_flight = False
            raise
        except Exception:
            self._on_failure()
            raise
        self._on_success()
        return result
py
"""Circuit breaker state machine with a fake clock, then wired into the app."""
import time

import fakeredis
import httpx
import pytest

from app.breaker import CircuitBreaker, CircuitOpenError
from app.main import create_app


class Clock:
    def __init__(self) -> None:
        self.t = 0.0

    def __call__(self) -> float:
        return self.t


async def ok() -> str:
    return "ok"


async def boom() -> str:
    raise ConnectionError("upstream down")


@pytest.mark.asyncio
async def test_closed_open_half_open_closed():
    clock = Clock()
    cb = CircuitBreaker("rates", failure_threshold=3, reset_timeout=5.0, clock=clock)
    for _ in range(3):
        with pytest.raises(ConnectionError):
            await cb.call(boom)
    assert cb.state == "open"
    calls = {"n": 0}

    async def counted() -> str:
        calls["n"] += 1
        return "ok"

    with pytest.raises(CircuitOpenError):
        await cb.call(counted)                  # fails fast: the upstream is not called
    assert calls["n"] == 0
    clock.t = 5.0
    assert await cb.call(counted) == "ok"      # half-open trial succeeds
    assert cb.state == "closed"
    print(f"\ntransitions: {cb.transitions}")
    assert cb.transitions == [("closed", "open"), ("open", "half_open"), ("half_open", "closed")]


@pytest.mark.asyncio
async def test_failed_trial_reopens():
    clock = Clock()
    cb = CircuitBreaker("rates", failure_threshold=1, reset_timeout=5.0, clock=clock)
    with pytest.raises(ConnectionError):
        await cb.call(boom)
    clock.t = 5.0
    with pytest.raises(ConnectionError):
        await cb.call(boom)
    assert cb.state == "open" and cb.opened_at == 5.0
    clock.t = 7.0
    with pytest.raises(CircuitOpenError):
        await cb.call(ok)


@pytest.mark.asyncio
async def test_success_resets_the_failure_count():
    cb = CircuitBreaker("rates", failure_threshold=3)
    for _ in range(2):
        with pytest.raises(ConnectionError):
            await cb.call(boom)
    await cb.call(ok)
    for _ in range(2):
        with pytest.raises(ConnectionError):
            await cb.call(boom)
    assert cb.state == "closed"


@pytest.mark.asyncio
async def test_app_fails_fast_when_provider_is_down():
    app = create_app("http://127.0.0.1:1", lambda: fakeredis.FakeAsyncRedis())   # closed port
    async with app.router.lifespan_context(app):
        async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://t") as c:
            codes = []
            for cur in ["EUR", "USD", "GBP", "JPY", "CHF"]:
                t0 = time.perf_counter()
                r = await c.get(f"/rates/{cur}")
                codes.append((r.status_code, r.headers.get("retry-after"),
                              round((time.perf_counter() - t0) * 1000, 1)))
            breaker = app.state.breaker
    print(f"\nprovider down: (status, Retry-After, ms) {codes}; breaker {breaker.state}")
    assert [c for c, _, _ in codes] == [502, 502, 502, 503, 503]


@pytest.mark.asyncio
async def test_404s_do_not_open_the_breaker(shop):
    """Unknown currencies are business answers: three of them must not cut off EUR."""
    app, client = shop
    codes = [(await client.get(f"/rates/{cur}")).status_code for cur in ["XAA", "XBB", "XCC"]]
    eur = await client.get("/rates/EUR")
    print(f"\nthree unknown currencies {codes}, then EUR {eur.status_code}; breaker {app.state.breaker.state}")
    assert codes == [404, 404, 404] and eur.status_code == 200
    assert app.state.breaker.state == "closed" and app.state.breaker.failures == 0

Outbound rate limiting: aiolimiter, semaphore, bulkhead Important ​

In plain words: Two separate limits protect an upstream from you:

  • How many calls per second (the provider's published rate limit): a rate limiter.
  • How many calls at the same time (so one slow dependency cannot occupy every worker): a bulkhead, which is just a semaphore.

Common misunderstanding: "The pool's max_connections is my rate limit." It caps concurrency for one client in one process. It does not cap calls per second, and N workers have N pools. A provider limit of 10 per second with 4 Uvicorn workers needs a per-worker limit of 2.5 per second or a shared limiter in Redis.

Definition:

  • aiolimiter.AsyncLimiter(max_rate, time_period) ("An efficient implementation of a rate limiter for asyncio", using the "Leaky bucket algorithm") is used as async with limiter:.
  • asyncio.Semaphore(n) is the bulkhead.
  • The snippet's OutboundGuard applies the rate limit first, then the bulkhead.

Real results:

  • AsyncLimiter(10, 1.0) with 20 calls: the first 10 passed by 0.000 s and the last at 1.001 s.
  • Bulkhead(3) with 9 × 100 ms: 0.304 s, peak 3.
  • The combined guard (5 per 0.5 s, 2 concurrent) with 10 calls: 0.552 s, peak 2.

The algorithms behind it (token bucket, leaky bucket, sliding windows) are in Rate Limiting.

py
"""Protecting an upstream from us: a bulkhead (max concurrent calls) and an outbound rate limit
(max calls per period). Both are per process; N workers multiply them by N."""
import asyncio
from typing import Any, Awaitable, Callable, TypeVar

from aiolimiter import AsyncLimiter

T = TypeVar("T")


class Bulkhead:
    """asyncio.Semaphore with counters, so a test can prove the bound held."""

    def __init__(self, max_concurrent: int) -> None:
        self._sem = asyncio.Semaphore(max_concurrent)   # create inside a running loop (lifespan)
        self.in_flight = 0
        self.peak = 0

    async def run(self, fn: Callable[..., Awaitable[T]], *args: Any) -> T:
        async with self._sem:
            self.in_flight += 1
            self.peak = max(self.peak, self.in_flight)
            try:
                return await fn(*args)
            finally:
                self.in_flight -= 1


class OutboundGuard:
    """Rate limit first (calls per second the provider allows), then the bulkhead."""

    def __init__(self, rate: float, period: float, max_concurrent: int) -> None:
        self.limiter = AsyncLimiter(rate, period)        # leaky bucket: `rate` calls per `period`
        self.bulkhead = Bulkhead(max_concurrent)

    async def run(self, fn: Callable[..., Awaitable[T]], *args: Any) -> T:
        async with self.limiter:
            return await self.bulkhead.run(fn, *args)
py
"""Outbound rate limiting (aiolimiter) and a bulkhead (Semaphore), measured."""
import asyncio
import time

import pytest
from aiolimiter import AsyncLimiter

from app.ratelimit import Bulkhead, OutboundGuard


@pytest.mark.asyncio
async def test_async_limiter_spreads_calls():
    limiter = AsyncLimiter(10, 1.0)            # 10 per second, burst of 10
    stamps = []
    t0 = time.perf_counter()

    async def one() -> None:
        async with limiter:
            stamps.append(time.perf_counter() - t0)

    await asyncio.gather(*(one() for _ in range(20)))
    stamps.sort()
    print(f"\nAsyncLimiter(10, 1.0), 20 calls: first 10 by {stamps[9]:.3f}s, last at {stamps[-1]:.3f}s")
    assert stamps[9] < 0.05 and 0.9 <= stamps[-1] < 1.3


@pytest.mark.asyncio
async def test_bulkhead_bounds_concurrency():
    bulkhead = Bulkhead(3)

    async def work() -> None:
        await asyncio.sleep(0.1)

    t0 = time.perf_counter()
    await asyncio.gather(*(bulkhead.run(work) for _ in range(9)))
    elapsed = time.perf_counter() - t0
    print(f"\nBulkhead(3), 9 x 100 ms: {elapsed:.3f}s, peak {bulkhead.peak}")
    assert bulkhead.peak == 3 and elapsed >= 0.3


@pytest.mark.asyncio
async def test_guard_combines_both():
    guard = OutboundGuard(rate=5, period=0.5, max_concurrent=2)

    async def work() -> int:
        await asyncio.sleep(0.05)
        return 1

    t0 = time.perf_counter()
    assert sum(await asyncio.gather(*(guard.run(work) for _ in range(10)))) == 10
    print(f"\nOutboundGuard(5 per 0.5 s, 2 concurrent), 10 calls: {time.perf_counter() - t0:.3f}s, "
          f"peak {guard.bulkhead.peak}")
    assert guard.bulkhead.peak <= 2

In-memory caching: lru_cache, cachetools TTLCache, async caches, per-process limits Must-know ​

In plain words: The fastest cache is a dictionary in your own process: no network, no serialization. It is also the most limited one. Each worker has its own copy, it is empty after a restart, and nobody else can invalidate it.

Common misunderstanding: "Put @lru_cache on the async function." lru_cache caches the return value, and an async def function returns a coroutine object that can be awaited once. Real: RuntimeError: cannot reuse already awaited coroutine on the second call.

Definition:

  • functools.lru_cache(maxsize=128) has no TTL. It suits pure functions of small inputs whose answer never changes for the life of the process: config parsing, VAT tables, compiled regexes. Real: CacheInfo(hits=2, misses=3, maxsize=128, currsize=3).
  • cachetools.TTLCache(maxsize, ttl, timer=time.monotonic) is an "LRU Cache implementation with per-item time-to-live (TTL) value". Real: an entry was present at 9.9 s and gone at exactly 10.0 s, and maxsize=2 evicted the oldest key. The docs: "all these classes are not thread-safe", so def routes running in the thread pool need a lock.
  • Async caches. The snippet's AsyncTTLCache adds single-flight on top of TTLCache: the first miss for a key creates a Future, and concurrent misses await it. Errors are not cached. Real: 50 concurrent misses gave 1 load, then 1 hit.
  • Per-process cache. Two workers each loaded the key once. After a price change, invalidating worker A left worker B serving the old price (worker A 120, worker B 100). Keep per-process TTLs short, or put data that must be invalidated in Redis.
py
"""In-process caches: functools.lru_cache, cachetools.TTLCache, and an async TTL cache with
per-key single-flight (concurrent misses for one key share ONE load)."""
import asyncio
import functools
import time
from typing import Any, Awaitable, Callable, Dict, Hashable

from cachetools import TTLCache

CALLS = {"vat_rate": 0}


@functools.lru_cache(maxsize=128)
def vat_rate(country: str) -> float:
    """Pure, small, never changes while the process lives: the lru_cache sweet spot."""
    CALLS["vat_rate"] += 1
    return {"DE": 0.19, "FR": 0.20, "NL": 0.21}.get(country, 0.0)


@functools.lru_cache(maxsize=None)
async def broken_async_cache(x: int) -> int:
    """WRONG: lru_cache stores the coroutine object, which can be awaited only once."""
    await asyncio.sleep(0)
    return x * 2


class AsyncTTLCache:
    """cachetools.TTLCache for values + a dict of in-flight Futures for single-flight loads.

    Not thread-safe (one event loop); the docs ask for a lock when a cache is shared by threads.
    """

    def __init__(self, maxsize: int, ttl: float, timer: Callable[[], float] = time.monotonic) -> None:
        self._data: TTLCache = TTLCache(maxsize=maxsize, ttl=ttl, timer=timer)
        self._inflight: Dict[Hashable, "asyncio.Future[Any]"] = {}
        self.loads = 0
        self.hits = 0

    async def get_or_load(self, key: Hashable, loader: Callable[[], Awaitable[Any]]) -> Any:
        try:
            value = self._data[key]
            self.hits += 1
            return value
        except KeyError:
            pass
        fut = self._inflight.get(key)
        if fut is not None:                  # someone is already loading this key: wait for it
            return await asyncio.shield(fut)
        fut = asyncio.get_running_loop().create_future()
        self._inflight[key] = fut
        try:
            self.loads += 1
            value = await loader()
            self._data[key] = value
            fut.set_result(value)
            return value
        except BaseException as exc:
            fut.set_exception(exc)
            fut.exception()                  # mark retrieved if nobody else was waiting
            raise
        finally:
            del self._inflight[key]
py
"""lru_cache, cachetools.TTLCache, the async-cache trap and per-process caches."""
import asyncio

import pytest
from cachetools import TTLCache

from app.cache_memory import CALLS, AsyncTTLCache, broken_async_cache, vat_rate


def test_lru_cache_hits_and_info():
    vat_rate.cache_clear()
    CALLS["vat_rate"] = 0
    for c in ["DE", "FR", "DE", "DE", "NL"]:
        vat_rate(c)
    print(f"\n{vat_rate.cache_info()}")
    assert CALLS["vat_rate"] == 3


@pytest.mark.asyncio
async def test_lru_cache_on_async_def_caches_a_coroutine():
    assert await broken_async_cache(2) == 4
    with pytest.raises(RuntimeError) as info:
        await broken_async_cache(2)            # the same, already-awaited coroutine object
    print(f"\nlru_cache on async def, second await: RuntimeError: {info.value}")


def test_ttl_cache_expires_with_its_timer():
    now = {"t": 0.0}
    cache = TTLCache(maxsize=2, ttl=10, timer=lambda: now["t"])
    cache["EUR"] = 1.08
    now["t"] = 9.9
    assert cache.get("EUR") == 1.08
    now["t"] = 10.0
    assert cache.get("EUR") is None            # expired exactly at ttl
    cache.update({"a": 1, "b": 2, "c": 3})     # maxsize=2: the oldest is evicted
    assert len(cache) == 2 and "a" not in cache


@pytest.mark.asyncio
async def test_async_ttl_cache_single_flight():
    cache = AsyncTTLCache(maxsize=100, ttl=60)

    async def loader() -> float:
        await asyncio.sleep(0.1)
        return 1.08

    results = await asyncio.gather(*(cache.get_or_load("EUR", loader) for _ in range(50)))
    await cache.get_or_load("EUR", loader)
    print(f"\nAsyncTTLCache: 50 concurrent misses -> {cache.loads} load; then {cache.hits} hit")
    assert set(results) == {1.08} and cache.loads == 1 and cache.hits == 1


@pytest.mark.asyncio
async def test_async_ttl_cache_does_not_cache_errors():
    cache = AsyncTTLCache(maxsize=10, ttl=60)

    async def failing() -> float:
        raise TimeoutError("upstream")

    for _ in range(2):
        with pytest.raises(TimeoutError):
            await cache.get_or_load("EUR", failing)
    assert cache.loads == 2


@pytest.mark.asyncio
async def test_per_process_caches_diverge():
    """Two Uvicorn workers = two caches: each loads once, and invalidating one leaves the other stale."""
    worker_a, worker_b = AsyncTTLCache(10, 60), AsyncTTLCache(10, 60)
    price = {"v": 100}

    async def load() -> int:
        return price["v"]

    assert await worker_a.get_or_load("p1", load) == 100
    assert await worker_b.get_or_load("p1", load) == 100
    price["v"] = 120
    worker_a._data.pop("p1")                   # invalidation reached worker A only
    print(f"\nafter the price change: worker A {await worker_a.get_or_load('p1', load)}, "
          f"worker B {await worker_b.get_or_load('p1', load)}")
    assert (worker_a.loads, worker_b.loads) == (2, 1)

Cache patterns: cache-aside, read-through, write-through Must-know ​

In plain words:

  • Cache-aside: your code checks the cache, and on a miss loads from the source and stores the result.
  • Read-through: the cache library does that loading for you.
  • Write-through: every write goes to the cache and the source together.

Common misunderstanding: "Write-through means no stale reads." If the cache write and the database write are not atomic (they never are across Redis and PostgreSQL), a failure between them leaves them different. Most applications use cache-aside with delete on write and a TTL as the safety net.

Definition:

PatternRead pathWrite pathStale riskIn this project
Cache-aside (lazy loading)GET; miss: load, SET with TTLupdate DB, then DEL keybetween DB commit and DEL; bounded by TTLRedisCache.get_or_set, DELETE /rates/{c}/cache
Read-throughcache calls the loadern/asame as cache-asideaiocache @cached, fastapi-cache2 @cache
Write-throughalways hits cachewrite DB and cachepartial failure leaves them unequalnot used
Write-behind (write-back)cachecache now, DB laterdata loss if the cache diesnot used
Refresh-aheadcachen/anone on hot keysXFetch early recompute

The trade-offs (consistency, eviction policies, cache levels, CDN) are in Caching.

Redis caching with redis.asyncio: pool, serialization, TTL Must-know ​

In plain words: Redis is a shared, in-memory key-value server. Every worker reads the same cache, it survives deploys of your app, and you can delete one key for everybody. You store bytes, so you choose how to turn objects into bytes.

Common misunderstanding: "pickle is the easiest serializer, so use it." The Python docs open with "Warning: The pickle module is not secure. Only unpickle data you trust." Anyone who can write to your Redis can then run code in every worker. Real: an object with a custom __reduce__ made pickle.loads call a function of the writer's choice (PICKLE.LOADS JUST RAN CODE CHOSEN BY WHOEVER WROTE THE BYTES). Pickle also couples the cache to your class layout: rename a field and old entries break.

Definition:

  • redis.asyncio.Redis(...) holds a connection pool. redis-py: "By default, an internal connection pool is created on redis.Redis() and attached to the Redis instance". In async code "an explicit disconnect" (await client.aclose()) is required. Create it in the lifespan, close it at shutdown.
  • Serialization, pickle vs JSON:
    • JSON (json.dumps, or model_dump_json() / model_validate_json() for Pydantic) is portable, readable in redis-cli and safe. Real size for one product: 21 bytes JSON vs 172 bytes pickle.
    • msgpack or orjson are fine faster alternatives.
  • TTL: SET key value EX seconds ("Set the specified expire time, in seconds"). Add ±10 % jitter so keys written together do not expire together. Real: ttl=60 stored with TTL 56.

Real results:

  • Five GET /rates/eur made 1 upstream call.
  • The key was shop:v1:rate:EUR with value {"currency":"EUR","rate":1.08}.
py
"""Redis cache-aside with redis.asyncio: namespaced, versioned keys; JSON serialization; TTL with
jitter; negative caching; invalidation; stampede protection with a SET NX PX lock (token-checked
release) and probabilistic early recompute (XFetch)."""
import asyncio
import json
import math
import random
import secrets
import time
from typing import Any, Awaitable, Callable, Optional

from redis.asyncio import Redis

MISS = {"__negative__": True}          # what we store for "the upstream says it does not exist"

# Delete the lock only if it still holds OUR token (another worker may own it after expiry).
RELEASE_LUA = """
if redis.call('get', KEYS[1]) == ARGV[1] then
    return redis.call('del', KEYS[1])
end
return 0
"""


def xfetch_should_recompute(delta: float, expiry: float, now: float, beta: float = 1.0,
                            rand: Callable[[], float] = random.random) -> bool:
    """Vattani, Chierichetti, Lowenstein ("Optimal Probabilistic Cache Stampede Prevention"): recompute early with a probability that
    rises as expiry approaches. delta = how long the last recompute took."""
    return now - delta * beta * math.log(rand()) >= expiry


class RedisCache:
    def __init__(self, redis: Redis, namespace: str = "shop", version: int = 1,
                 default_ttl: int = 300, negative_ttl: int = 30, ttl_jitter: float = 0.1,
                 lock_ttl_ms: int = 5000, lock_wait_s: float = 2.0, poll_s: float = 0.01) -> None:
        self.r = redis
        self.namespace, self.version = namespace, version
        self.default_ttl, self.negative_ttl, self.ttl_jitter = default_ttl, negative_ttl, ttl_jitter
        self.lock_ttl_ms, self.lock_wait_s, self.poll_s = lock_ttl_ms, lock_wait_s, poll_s
        self._release = redis.register_script(RELEASE_LUA)
        self.recomputes = 0

    # --- key design -------------------------------------------------------------
    def key(self, *parts: Any) -> str:
        """shop:v1:rate:EUR - namespace, schema version, entity, id."""
        return ":".join([self.namespace, f"v{self.version}", *map(str, parts)])

    def _ttl(self, ttl: Optional[int]) -> int:
        base = ttl or self.default_ttl
        return max(1, int(base * (1 + random.uniform(-self.ttl_jitter, self.ttl_jitter))))

    # --- plain cache-aside --------------------------------------------------------
    async def get_json(self, key: str) -> Optional[Any]:
        raw = await self.r.get(key)
        return None if raw is None else json.loads(raw)

    async def set_json(self, key: str, value: Any, ttl: Optional[int] = None) -> None:
        await self.r.set(key, json.dumps(value, separators=(",", ":")), ex=self._ttl(ttl))

    async def invalidate(self, key: str) -> int:
        return await self.r.delete(key)

    async def get_or_set(self, key: str, loader: Callable[[], Awaitable[Optional[Any]]],
                         ttl: Optional[int] = None, lock: bool = True) -> Optional[Any]:
        cached = await self.get_json(key)
        if cached is not None:
            return None if cached == MISS else cached
        if not lock:
            return await self._load_and_store(key, loader, ttl)
        return await self._locked_recompute(key, loader, ttl)

    async def _load_and_store(self, key: str, loader: Callable[[], Awaitable[Optional[Any]]],
                              ttl: Optional[int]) -> Optional[Any]:
        self.recomputes += 1
        value = await loader()
        if value is None:
            await self.set_json(key, MISS, ttl=self.negative_ttl)   # negative caching
        else:
            await self.set_json(key, value, ttl=ttl)
        return value

    async def _locked_recompute(self, key: str, loader: Callable[[], Awaitable[Optional[Any]]],
                                ttl: Optional[int]) -> Optional[Any]:
        lock_key = f"lock:{key}"
        token = secrets.token_hex(8)
        deadline = time.monotonic() + self.lock_wait_s
        while True:
            if await self.r.set(lock_key, token, nx=True, px=self.lock_ttl_ms):
                try:
                    cached = await self.get_json(key)        # double-check: a peer may have filled it
                    if cached is not None:
                        return None if cached == MISS else cached
                    return await self._load_and_store(key, loader, ttl)
                finally:
                    await self._release(keys=[lock_key], args=[token])
            await asyncio.sleep(self.poll_s)                 # someone else recomputes: wait, re-read
            cached = await self.get_json(key)
            if cached is not None:
                return None if cached == MISS else cached
            if time.monotonic() > deadline:                  # lock holder died or is too slow
                return await self._load_and_store(key, loader, ttl)

    # --- probabilistic early expiration ------------------------------------------
    async def get_or_set_xfetch(self, key: str, loader: Callable[[], Awaitable[Any]], ttl: int,
                                beta: float = 1.0,
                                rand: Callable[[], float] = random.random) -> Any:
        raw = await self.r.get(key)
        now = time.time()
        if raw is not None:
            entry = json.loads(raw)
            if not xfetch_should_recompute(entry["delta"], entry["expiry"], now, beta, rand):
                return entry["value"]
        started = time.time()
        self.recomputes += 1
        value = await loader()
        delta = time.time() - started
        entry = {"value": value, "delta": delta, "expiry": time.time() + ttl}
        await self.r.set(key, json.dumps(entry), ex=ttl)
        return value

The same operations against a real Redis 7 (expected, not run: no Redis server on the build machine):

$ redis-cli SET shop:v1:rate:EUR '{"currency":"EUR","rate":1.08}' EX 60
OK
$ redis-cli TTL shop:v1:rate:EUR
(integer) 60
$ redis-cli SET lock:shop:v1:rate:EUR 9f2c41d0 NX PX 2000
OK
$ redis-cli SET lock:shop:v1:rate:EUR other NX PX 2000
(nil)                         -> somebody else holds the lock
$ redis-cli DEL shop:v1:rate:EUR
(integer) 1

Cache key design, namespacing keys, invalidation Important ​

In plain words: A key name answers three questions: whose data (namespace), which shape of data (version), which item (entity and id). Good names make invalidation a one-line DEL and a schema change a one-character version bump.

Common misunderstanding: "KEYS shop:* then DEL is how you clear a namespace." KEYS blocks Redis while it scans every key. Use a version in the key (old keys expire on their own TTL), SCAN in batches or a separate Redis database.

Definition: The snippet's keys are namespace:v{version}:entity:id, for example shop:v1:rate:EUR. Lock keys use the prefix lock: and the same name.

Invalidation strategies:

  • Delete on write: after the database commit, DEL the key. Real: two upstream calls around a DELETE /rates/EUR/cache.
  • TTL as the safety net: the TTL bounds how stale an entry can get.
  • Version bump: for a schema change. Real: a v2 cache did not see the v1 entry.
  • Tags or sets of keys: for "everything about product 7".

Put every input that changes the answer into the key (tenant, locale, currency, user role), or one tenant sees another's data. Never put secrets or personal data in key names: they show up in MONITOR, slow logs and metrics.

py
"""Redis cache-aside through the app, against fakeredis: hits, TTL, key design, negative caching,
invalidation, versioned namespaces and why the values are JSON, not pickle."""
import json
import pickle

import fakeredis
import pytest
from pydantic import BaseModel

from app.cache_redis import RedisCache
from app.stub_server import STATE


@pytest.mark.asyncio
async def test_cache_aside_through_the_route(shop, redis_server):
    app, client = shop
    for _ in range(5):
        r = await client.get("/rates/eur")
        assert r.json() == {"currency": "EUR", "rate": 1.08}
    probe = fakeredis.FakeAsyncRedis(server=redis_server, decode_responses=True)
    keys = await probe.keys("*")
    ttl = await probe.ttl("shop:v1:rate:EUR")
    raw = await probe.get("shop:v1:rate:EUR")
    print(f"\n5 GET /rates/eur -> upstream hits {STATE.hits['/rates/EUR']}; keys {keys}; TTL {ttl}s; value {raw}")
    assert STATE.hits["/rates/EUR"] == 1
    assert 54 <= ttl <= 66                      # ttl=60 with +-10 % jitter
    await probe.aclose()


@pytest.mark.asyncio
async def test_negative_caching(shop):
    app, client = shop
    codes = [(await client.get("/rates/XXX")).status_code for _ in range(3)]
    print(f"\nunknown currency x3: {codes}, upstream hits {STATE.hits['/rates/XXX']}")
    assert codes == [404, 404, 404] and STATE.hits["/rates/XXX"] == 1


@pytest.mark.asyncio
async def test_invalidation_after_a_write(shop):
    app, client = shop
    await client.get("/rates/EUR")
    assert (await client.delete("/rates/EUR/cache")).status_code == 204
    await client.get("/rates/EUR")
    assert STATE.hits["/rates/EUR"] == 2


@pytest.mark.asyncio
async def test_version_bump_invalidates_a_whole_namespace(redis_server):
    r = fakeredis.FakeAsyncRedis(server=redis_server)
    v1, v2 = RedisCache(r, version=1), RedisCache(r, version=2)
    await v1.set_json(v1.key("product", 7), {"name": "mug"})
    assert v1.key("product", 7) == "shop:v1:product:7"
    assert await v2.get_json(v2.key("product", 7)) is None     # new code reads new keys
    await r.aclose()


class Product(BaseModel):
    id: int
    name: str


class Evil:
    def __reduce__(self):
        return (str.upper, ("pickle.loads just ran code chosen by whoever wrote the bytes",))


def test_pickle_vs_json():
    p = Product(id=7, name="mug")
    as_json = p.model_dump_json().encode()
    as_pickle = pickle.dumps(p)
    assert Product.model_validate_json(as_json) == p
    print(f"\nJSON {len(as_json)} bytes {as_json!r}; pickle {len(as_pickle)} bytes")
    print(pickle.loads(pickle.dumps(Evil())))
    with pytest.raises(TypeError):
        json.dumps({"when": object()})         # JSON refuses what it cannot represent


@pytest.mark.asyncio
async def test_lock_is_released_only_by_its_owner(redis_server):
    r = fakeredis.FakeAsyncRedis(server=redis_server, decode_responses=True)
    cache = RedisCache(r)
    await r.set("lock:k", "someone-else", px=5000)
    assert await cache._release(keys=["lock:k"], args=["my-token"]) == 0
    assert await r.get("lock:k") == "someone-else"
    assert await cache._release(keys=["lock:k"], args=["someone-else"]) == 1
    await r.aclose()

Stampede (dogpile): lock-based recompute, early recompute, negative caching Must-know ​

Cache-aside with a stampede lock (50 concurrent misses, 100 ms recompute)50 requestsGET shop:v1:report:topall miss (nil)key expired / coldno lock: 50 recomputes hit the database(measured: 50 recomputes, 0.108 s)SET lock:shop:v1:report:top<token> NX PX 2000OK (1)winner1. GET key again (double-check)2. recompute once (100 ms)3. SET key json EX 60 (+-10 % jitter)4. EVAL release: DEL only if the value is still my tokennil (49)49 loserssleep 10 ms, GET key, repeat;after lock_wait_s: load themselvesvalue appears: losers return itmeasured (fakeredis, 50 clients on one server): 1 recompute, 0.111 s. Lock TTL must exceed the recompute time.Alternatives: in-process single-flight (1 load per worker), probabilistic early recompute (XFetch), stale-while-revalidate.

In plain words: A popular key expires. Every request in the next 100 ms misses, and every one of them runs the expensive query. The paper's own example: "if the cache item is accessed 10 times per second, and the recomputation of the item takes 3 seconds, then 30 requests will recompute the item." Protection means one request recomputes and the others wait or get the old value.

Common misunderstanding: "An asyncio.Lock per key solves it." It solves it inside one process: 8 workers still make 8 recomputes, and 20 pods make 160. Across processes you need a shared lock (Redis SET NX PX) or a strategy that needs no lock (early recompute).

Definition: The four tools:

  1. Lock-based recompute (_locked_recompute):
    • Claim the lock with SET lock:key token NX PX 2000. NX means "Only set the key if it does not already exist".
    • The winner double-checks the key, recomputes, writes it with a TTL and releases the lock with a Lua script that deletes the lock only if it still holds the winner's token. Otherwise an expired lock would be released for its next owner.
    • Losers sleep 10 ms and re-read the key. If the lock holder takes longer than lock_wait_s, they load the value themselves.
    • The lock TTL must exceed the recompute time. redis-py's docs warn that a lock's timeout "does not stop the work running inside the critical section. If that work outlives the timeout, another client can acquire the lock while the original client is still working."
  2. Single-flight in process: AsyncTTLCache above. Combine it with the Redis lock to get one Redis round trip per worker.
  3. Early recompute (XFetch, probabilistic early expiration). Store the recompute duration delta and the expiry with the value. Each read recomputes early if now - delta × beta × ln(rand()) ≥ expiry, so the probability rises as expiry approaches and the key is usually refreshed before anyone misses. Laravel's Cache::flexible (stale-while-revalidate) is the same idea with a fixed window.
  4. Negative caching: cache "does not exist" (a 404 from the upstream) for a short TTL (30 s here), so a stream of requests for a missing id does not hit the source every time. Real: GET /rates/XXX three times gave [404, 404, 404] with 1 upstream call.

Real measurement: 50 clients, each its own fakeredis connection to one server (as if 50 workers), missing the same key, with a 100 ms recompute:

StrategyRecomputesWall timeNote
no lock500.108 s50 × the database load
SET NX PX lock, 10 ms polling10.111 swaiters pay one poll interval
in-process single-flight (one worker)1n/aAsyncTTLCache test

XFetch probabilities, real (delta 0.1 s, beta 1, 10,000 trials each):

Seconds before expiryP(early recompute)
1.00.000
0.50.007
0.20.133
0.10.366
0.050.604
0.010.899
1  t=0      50 requests: GET shop:v1:report:top -> nil (all miss)
2  t=0      50 x SET lock:shop:v1:report:top <token> NX PX 2000 -> 1 x OK, 49 x nil
3  t=0      winner: GET key again (nil) -> recompute starts (100 ms)
4  t=10ms   49 losers: sleep 10 ms, GET key -> nil, repeat
5  t=100ms  winner: SET key json EX 60 ; EVAL release (token matches) -> lock deleted
6  t=110ms  losers: GET key -> value; return it. Recomputes: 1 (no lock: 50)
py
"""The measured stampede demo: 50 concurrent misses for one hot key, each from its own Redis
client (as if from 50 workers), against one fakeredis server. The recompute takes 100 ms."""
import asyncio
import random
import time

import fakeredis
import pytest

from app.cache_redis import RedisCache, xfetch_should_recompute

N = 50


async def run_storm(server: fakeredis.FakeServer, lock: bool):
    clients = [fakeredis.FakeAsyncRedis(server=server) for _ in range(N)]
    caches = [RedisCache(c, lock_ttl_ms=2000, poll_s=0.01) for c in clients]
    recomputes = {"n": 0}

    async def expensive_report():
        recomputes["n"] += 1
        await asyncio.sleep(0.1)               # the slow query / upstream call
        return {"top_products": [7, 3, 9]}

    key = caches[0].key("report", "top")
    t0 = time.perf_counter()
    results = await asyncio.gather(*(c.get_or_set(key, expensive_report, ttl=60, lock=lock) for c in caches))
    elapsed = time.perf_counter() - t0
    for c in clients:
        await c.aclose()
    assert all(r == {"top_products": [7, 3, 9]} for r in results)
    return recomputes["n"], elapsed


@pytest.mark.asyncio
async def test_stampede_without_and_with_lock():
    no_lock = await run_storm(fakeredis.FakeServer(), lock=False)
    with_lock = await run_storm(fakeredis.FakeServer(), lock=True)
    print(f"\n{N} concurrent misses, 100 ms recompute (fakeredis, one process):"
          f"\n  no lock:   {no_lock[0]} recomputes, {no_lock[1]:.3f}s"
          f"\n  SET NX PX: {with_lock[0]} recompute,  {with_lock[1]:.3f}s (waiters poll every 10 ms)")
    assert no_lock[0] == N
    assert with_lock[0] == 1


def test_xfetch_probability_rises_near_expiry():
    rng = random.Random(42)
    delta, expiry, trials = 0.1, 100.0, 10_000
    rows = []
    for left in [1.0, 0.5, 0.2, 0.1, 0.05, 0.01]:
        hits = sum(xfetch_should_recompute(delta, expiry, expiry - left, 1.0, rng.random) for _ in range(trials))
        rows.append((left, hits / trials))
    print("\nXFetch, delta=0.1 s, beta=1: P(early recompute) by seconds left: "
          + ", ".join(f"{left}s -> {p:.3f}" for left, p in rows))
    probs = [p for _, p in rows]
    assert probs == sorted(probs) and probs[0] < 0.001 and probs[-1] > 0.85


@pytest.mark.asyncio
async def test_xfetch_serves_cached_value_far_from_expiry():
    r = fakeredis.FakeAsyncRedis()
    cache = RedisCache(r)
    loads = {"n": 0}

    async def load():
        loads["n"] += 1
        return 42

    for _ in range(100):
        assert await cache.get_or_set_xfetch("k", load, ttl=300) == 42
    assert loads["n"] == 1
    await r.aclose()

Cache libraries and HTTP caching Good to know ​

In plain words: Libraries wrap the patterns above in a decorator. HTTP caching is a different layer: it lets the client or a CDN skip calling you at all.

Common misunderstanding: "fastapi-cache2 gives me stampede protection and invalidation." It gives a decorator, a backend and a key builder. Stampede protection and write-path invalidation are still your design.

Definition:

  • fastapi-cache2 (0.2.2, 2024-07-24, Python ≥ 3.8): FastAPICache.init(RedisBackend(redis), prefix="fastapi-cache") in the lifespan, then @cache(expire=60) on routes. It caches whole responses, supports "HTTP cache headers like ETag and Cache-Control" and has an InMemoryBackend.
  • aiocache (0.12.3, 2024-09-25): "multi backend asyncio cache". It provides SimpleMemoryCache, Redis and Memcached backends, the cached and multi_cached decorators and pluggable serializers.
  • Redis client-side caching ("Tracking"; "Redis 6 implements direct support for client-side caching"): the server tells clients when a key they cached locally changes. It is a two-level cache without manual invalidation (expected, not run).
  • HTTP caching (ETag, If-None-Match, Cache-Control: max-age, 304) belongs to Exception Handling & Responses and, at the edge, to the CDN.
python
# fastapi-cache2 (expected, not run: not installed in the snippet project)
from fastapi_cache import FastAPICache
from fastapi_cache.backends.redis import RedisBackend
from fastapi_cache.decorator import cache

@asynccontextmanager
async def lifespan(app):
    FastAPICache.init(RedisBackend(redis.asyncio.from_url("redis://localhost")), prefix="fastapi-cache")
    yield

@app.get("/catalogue")
@cache(expire=60)
async def catalogue(): ...

The outbox pattern for reliable side effects Important ​

In plain words: "Save the order" and "tell the warehouse" must both happen or neither. You cannot put a database write and a broker publish in one transaction, so you put the message in the database, in the same transaction as the order. A relay reads unsent messages and publishes them afterwards.

Common misunderstanding: "Commit, then add_task(publish) is equivalent." A crash after the commit loses the event (the background task was only in memory), and a publish failure is only logged. With an outbox the row stays until it is published.

Definition:

  • place_order() inserts into orders and outbox inside one engine.begin() block.
  • relay_once() selects rows WHERE published_at IS NULL ORDER BY id, publishes each and marks it.
  • A crash between publish and mark publishes the row again next time, so the relay is at-least-once and consumers dedupe by event id. Real: the relay crashed once after publishing, so evt_1 was published twice. The consumer's dedup table applied it once (results [True, False]).

The SQL is in Mechanics. Relay strategies (polling vs CDC), ordering and per-broker publishing belong to Transactional Outbox, and the consumer side to Idempotent Consumer & Inbox.

py
"""Transactional outbox with SQLAlchemy Core: the order row and the "order.placed" event are
written in ONE transaction; a relay publishes unpublished rows later (at-least-once).
Also the processed-webhooks table that makes webhook handling idempotent."""
import json
from datetime import datetime, timezone
from typing import Any, Callable, Dict, List

from sqlalchemy import (Column, DateTime, Integer, MetaData, String, Table, Text, create_engine,
                        insert, select, update)
from sqlalchemy.engine import Engine
from sqlalchemy.exc import IntegrityError
from sqlalchemy.pool import StaticPool

metadata = MetaData()

orders = Table(
    "orders", metadata,
    Column("id", Integer, primary_key=True),
    Column("email", String(255), nullable=False),
    Column("total_cents", Integer, nullable=False),
    Column("status", String(20), nullable=False, default="pending"),
)

outbox = Table(
    "outbox", metadata,
    Column("id", Integer, primary_key=True),
    Column("aggregate_id", Integer, nullable=False),
    Column("event_type", String(64), nullable=False),
    Column("payload", Text, nullable=False),
    Column("created_at", DateTime(timezone=True), nullable=False),
    Column("published_at", DateTime(timezone=True), nullable=True, index=True),
    Column("attempts", Integer, nullable=False, default=0),
)

processed_webhooks = Table(
    "processed_webhooks", metadata,
    Column("event_id", String(64), primary_key=True),     # the dedup key
    Column("received_at", DateTime(timezone=True), nullable=False),
)


def make_engine(url: str = "sqlite://", echo: bool = False) -> Engine:
    kwargs: Dict[str, Any] = {"echo": echo}
    if url == "sqlite://":
        kwargs.update(poolclass=StaticPool, connect_args={"check_same_thread": False})
    engine = create_engine(url, **kwargs)
    metadata.create_all(engine)
    return engine


def _now() -> datetime:
    return datetime.now(timezone.utc)


def place_order(engine: Engine, email: str, total_cents: int) -> int:
    with engine.begin() as conn:                     # one transaction: both rows or neither
        order_id = conn.execute(
            insert(orders).values(email=email, total_cents=total_cents, status="pending")
        ).inserted_primary_key[0]
        conn.execute(insert(outbox).values(
            aggregate_id=order_id, event_type="order.placed",
            payload=json.dumps({"order_id": order_id, "email": email, "total_cents": total_cents}),
            created_at=_now(), attempts=0))
    return order_id


def relay_once(engine: Engine, publish: Callable[[Dict[str, Any]], None], batch: int = 100,
               crash_after_publish: bool = False) -> int:
    """Publish up to `batch` rows, oldest first. A crash between publish and UPDATE means the row
    is published again next time: consumers must be idempotent (inbox / dedup table)."""
    with engine.connect() as conn:
        rows = conn.execute(
            select(outbox.c.id, outbox.c.event_type, outbox.c.payload)
            .where(outbox.c.published_at.is_(None)).order_by(outbox.c.id).limit(batch)
        ).all()
    sent = 0
    for row in rows:
        publish({"id": f"evt_{row.id}", "type": row.event_type, "data": json.loads(row.payload)})
        if crash_after_publish:
            raise RuntimeError("relay crashed after publish, before marking the row")
        with engine.begin() as conn:
            conn.execute(update(outbox).where(outbox.c.id == row.id)
                         .values(published_at=_now(), attempts=outbox.c.attempts + 1))
        sent += 1
    return sent


def mark_webhook_processed(engine: Engine, event_id: str, apply: Callable[[Any], None]) -> bool:
    """Insert the event id and apply the effect in the SAME transaction. False = duplicate."""
    try:
        with engine.begin() as conn:
            conn.execute(insert(processed_webhooks).values(event_id=event_id, received_at=_now()))
            apply(conn)
        return True
    except IntegrityError:
        return False


def order_status(engine: Engine, order_id: int) -> str:
    with engine.connect() as conn:
        return conn.execute(select(orders.c.status).where(orders.c.id == order_id)).scalar_one()


def pending_outbox(engine: Engine) -> List[int]:
    with engine.connect() as conn:
        return list(conn.execute(select(outbox.c.id).where(outbox.c.published_at.is_(None))).scalars())
py
"""Outbox: order + event in one transaction; the relay is at-least-once; the SQL it runs."""
import pytest
from sqlalchemy import event
from sqlalchemy.schema import CreateTable

from app.outbox import (make_engine, mark_webhook_processed, outbox, pending_outbox, place_order,
                        processed_webhooks, relay_once)


def test_order_and_event_commit_together():
    engine = make_engine()
    order_id = place_order(engine, "ana@example.com", 4999)
    assert pending_outbox(engine) == [1] and order_id == 1


def test_relay_is_at_least_once_and_consumers_dedupe():
    engine = make_engine()
    place_order(engine, "ana@example.com", 4999)
    published = []
    with pytest.raises(RuntimeError):
        relay_once(engine, published.append, crash_after_publish=True)
    assert pending_outbox(engine) == [1]                 # still unpublished in the table
    relay_once(engine, published.append)
    assert [e["id"] for e in published] == ["evt_1", "evt_1"]   # the consumer saw it twice
    consumer_db = make_engine()
    effects = []
    results = [mark_webhook_processed(consumer_db, e["id"], lambda conn: effects.append(1)) for e in published]
    print(f"\nrelay crashed once: published {len(published)} times, consumer applied {len(effects)} (results {results})")
    assert results == [True, False] and len(effects) == 1


def test_print_the_sql():
    engine = make_engine()
    print("\n-- DDL (SQLite dialect)")
    for table in (outbox, processed_webhooks):
        print(str(CreateTable(table).compile(engine)).strip() + ";")
    statements = []

    @event.listens_for(engine, "before_cursor_execute")
    def capture(conn, cursor, statement, parameters, context, executemany):
        statements.append(" ".join(statement.split()))

    place_order(engine, "ana@example.com", 4999)
    relay_once(engine, lambda e: None)
    print("-- statements, in order")
    for s in statements:
        print(s + ";")
    assert any(s.startswith("SELECT outbox.id") and "published_at IS NULL" in s for s in statements)

Webhooks: signature verification, idempotent processing, retries Must-know ​

In plain words: A webhook is the provider calling you. Anyone on the internet can call the same URL, so you check a signature: an HMAC of the exact bytes, made with a secret only you and the provider know. Providers retry until you answer 2xx, so the same event can arrive twice and you process each event id once. When you send webhooks, you sign them and retry with backoff.

Common misunderstanding: "Parse the JSON, then verify the signature of json.dumps(payload)." Re-serialising changes the bytes (spacing, key order, unicode escapes) and the signature no longer matches. Verify await request.body() before parsing. Real: the same event re-serialised with indent=2 got 400 {"detail": "signature mismatch"}.

Definition:

  • Signature: the snippet follows Stripe's scheme. The header is t=<unix>,v1=<hex HMAC-SHA256 of "t.body">. The timestamp is inside the signed payload, and the tolerance is 300 s; Stripe's libraries have "a default tolerance of 5 minutes", which defeats replay. Compare with hmac.compare_digest; GitHub: "Never use a plain == operator", use a "constant time" comparison. GitHub sends X-Hub-Signature-256 (sha256=<hex>) without a timestamp.
  • Idempotent webhook processing: insert the event id into processed_webhooks in the same transaction as the effect, so a duplicate fails the primary key and the handler answers 200 duplicate. The route is async def (it awaits the raw body) and the engine is sync, so the transaction runs through run_in_threadpool. Stripe: "Webhook endpoints might occasionally receive the same event more than once. You can guard against duplicated event receipts by logging the event IDs you've processed".
  • Answer fast: GitHub expects "a 2XX response within 10 seconds" and suggests a queue so the endpoint can "process the payload in the background".
  • Sending webhooks (webhook retries): sign the payload, reuse the event id as the idempotency key (so a POST may be retried) and retry with backoff. Real: a receiver failing twice was delivered on attempt 3 in 0.121 s, and the receiver verified the signature.

Real verification outcomes:

  • tampered body → signature mismatch;
  • wrong secret → signature mismatch;
  • 10 minutes old → timestamp outside tolerance (replay?);
  • no header → missing signature header;
  • v1=abc → malformed signature header;
  • first delivery processed, redelivery duplicate, order paid.

Key rotation, IP allow-lists and request signing in general are in API Keys, Request Signing & Webhook Security.

1  provider  POST /webhooks/payments  X-Signature: t=1764420000,v1=9be1...   body {"id":"evt_100",...}
2  shop      raw = await request.body(); verify(secret, header, raw): HMAC ok, |now - t| <= 300 s
3  shop      BEGIN; INSERT processed_webhooks(evt_100); UPDATE orders SET status='paid'; COMMIT -> 200 processed
4  provider  network blip: no 2xx seen -> retries the same event later
5  shop      INSERT processed_webhooks(evt_100) -> IntegrityError -> ROLLBACK -> 200 duplicate (no second effect)
py
"""Webhooks both ways. Receiving: HMAC-SHA256 over "<timestamp>.<raw body>", constant-time
compare, a replay window, then idempotent processing keyed by the event id. Sending: sign the
payload and retry with backoff (the receiver may be down)."""
import hashlib
import hmac
import json
import time
from typing import Any, Dict, Optional

import httpx

from .external import call

TOLERANCE_S = 300


class SignatureError(Exception):
    pass


def sign(secret: str, body: bytes, timestamp: Optional[int] = None) -> str:
    ts = int(time.time()) if timestamp is None else timestamp
    mac = hmac.new(secret.encode(), f"{ts}.".encode() + body, hashlib.sha256).hexdigest()
    return f"t={ts},v1={mac}"


def verify(secret: str, header: Optional[str], body: bytes, now: Optional[float] = None,
           tolerance: int = TOLERANCE_S) -> int:
    """Return the signed timestamp or raise SignatureError. `body` must be the RAW bytes."""
    if not header:
        raise SignatureError("missing signature header")
    try:
        parts = dict(item.split("=", 1) for item in header.split(","))
        ts = int(parts["t"])
        received = parts["v1"]
    except (KeyError, ValueError):
        raise SignatureError("malformed signature header")
    expected = hmac.new(secret.encode(), f"{ts}.".encode() + body, hashlib.sha256).hexdigest()
    if not hmac.compare_digest(expected, received):
        raise SignatureError("signature mismatch")
    if abs((now if now is not None else time.time()) - ts) > tolerance:
        raise SignatureError("timestamp outside tolerance (replay?)")
    return ts


async def deliver(client: httpx.AsyncClient, url: str, event: Dict[str, Any], secret: str,
                  attempts: int = 5) -> httpx.Response:
    """Send one webhook. The event id doubles as the idempotency key, so a POST may be retried."""
    body = json.dumps(event, separators=(",", ":")).encode()
    headers = {"Content-Type": "application/json", "X-Signature": sign(secret, body),
               "Idempotency-Key": event["id"]}
    return await call(client, "POST", url, content=body, headers=headers, attempts=attempts)
py
"""Receiving signed webhooks (HMAC, replay window, idempotent processing) and sending them with retries."""
import json
import time

import pytest

from app.external import make_client
from app.outbox import order_status, place_order
from app.stub_server import STATE
from app.webhooks import SignatureError, deliver, sign, verify

SECRET = "whsec_test"


def test_verify_accepts_valid_and_rejects_the_rest():
    body = b'{"id":"evt_1","type":"payment.succeeded"}'
    header = sign(SECRET, body, timestamp=1_700_000_000)
    assert verify(SECRET, header, body, now=1_700_000_010) == 1_700_000_000
    cases = {
        "tampered body": (header, body.replace(b"succeeded", b"failed"), 1_700_000_010),
        "wrong secret": (sign("whsec_other", body, 1_700_000_000), body, 1_700_000_010),
        "replayed after 10 min": (header, body, 1_700_000_600),
        "no header": (None, body, 1_700_000_010),
        "garbage header": ("v1=abc", body, 1_700_000_010),
    }
    for name, (h, b, now) in cases.items():
        with pytest.raises(SignatureError) as info:
            verify(SECRET, h, b, now=now)
        print(f"\n{name}: {info.value}", end="")


def _event(order_id: int, event_id: str) -> bytes:
    return json.dumps({"id": event_id, "type": "payment.succeeded", "data": {"order_id": order_id}}).encode()


@pytest.mark.asyncio
async def test_route_processes_each_event_once(shop):
    app, client = shop
    order_id = place_order(app.state.engine, "ana@example.com", 4999)
    body = _event(order_id, "evt_100")
    headers = {"X-Signature": sign(SECRET, body), "Content-Type": "application/json"}
    first = await client.post("/webhooks/payments", content=body, headers=headers)
    again = await client.post("/webhooks/payments", content=body, headers=headers)   # provider retried
    print(f"\nfirst delivery {first.json()}, redelivery {again.json()}, order {order_status(app.state.engine, order_id)}")
    assert first.json() == {"status": "processed"} and again.json() == {"status": "duplicate"}


@pytest.mark.asyncio
async def test_route_rejects_bad_signature(shop):
    app, client = shop
    body = _event(1, "evt_x")
    r = await client.post("/webhooks/payments", content=body,
                          headers={"X-Signature": sign("wrong", body)})
    reparsed = json.dumps(json.loads(body), indent=2).encode()       # what a framework re-serialises
    r2 = await client.post("/webhooks/payments", content=reparsed, headers={"X-Signature": sign(SECRET, body)})
    print(f"\nwrong secret -> {r.status_code} {r.json()}; re-serialised body -> {r2.status_code} {r2.json()}")
    assert r.status_code == 400 and r2.status_code == 400


@pytest.mark.asyncio
async def test_sending_webhooks_with_retries(upstream):
    STATE.hook_failures_left = 2
    event = {"id": "evt_200", "type": "order.placed", "data": {"order_id": 9}}
    async with make_client(upstream) as client:
        t0 = time.perf_counter()
        r = await deliver(client, "/hooks", event, SECRET)
    received = STATE.hooks[0]
    print(f"\ndelivery: {STATE.hits['/hooks']} attempts in {time.perf_counter() - t0:.3f}s, final {r.status_code}")
    assert r.status_code == 204 and STATE.hits["/hooks"] == 3
    verify(SECRET, received["signature"], received["body"].encode())   # the receiver can verify it

Mocking external APIs in tests: respx, stub servers, fakeredis Important ​

In plain words: Tests must not call the real payment provider. There are three levels of fake:

  • respx intercepts httpx inside the process and returns the responses you script.
  • A stub server is a real HTTP server on localhost, so timeouts and pools are real.
  • fakeredis is an in-memory Redis.

Common misunderstanding: "respx intercepts every httpx client." respx works by patching HTTPX's transport layer ("To patch HTTPX, and activate the RESPX router"). A client built with its own transport= (for example httpx.MockTransport) does not go through the patched layer, unless that transport is respx's router (httpx.MockTransport(router.handler)). The After app passes transport=None in production and in the respx tests, so respx sees its calls.

Definition:

  • respx: @respx.mock(base_url=..., assert_all_called=True) or the respx_mock fixture. route.mock(side_effect=[httpx.Response(503), httpx.Response(503), httpx.Response(200, json=...)]) scripts a sequence. Setting side_effect=httpx.ReadTimeout(...) simulates a timeout, and route.call_count and route.calls.last.request support assertions.
  • fakeredis: fakeredis.FakeAsyncRedis(server=FakeServer()) gives separate clients of one fake server. The [lua] extra (lupa) makes register_script/EVAL work.

Real results:

  • respx: 3 calls to /rates/EUR (503, 503, 200), and the app answered 200.
  • A ReadTimeout side effect became a 504 after 3 attempts.
  • A missing Idempotency-Key got 422, and a present one was forwarded to the provider.

The full testing chapter (pytest-httpx, VCR-style recording, contract tests) is Testing FastAPI.

py
"""Mocking the external API with respx instead of a stub server."""
import fakeredis
import httpx
import pytest
import respx

from app.main import create_app

UPSTREAM = "https://rates.example.test"


@pytest.mark.asyncio
@respx.mock(base_url=UPSTREAM, assert_all_called=True)
async def test_two_503_then_200(respx_mock):
    route = respx_mock.get("/rates/EUR").mock(side_effect=[
        httpx.Response(503), httpx.Response(503), httpx.Response(200, json={"currency": "EUR", "rate": 1.1}),
    ])
    app = create_app(UPSTREAM, lambda: fakeredis.FakeAsyncRedis())
    async with app.router.lifespan_context(app):
        async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://shop") as c:
            r = await c.get("/rates/EUR")
    print(f"\nrespx: {route.call_count} calls to /rates/EUR, app answered {r.status_code} {r.json()}")
    assert r.json() == {"currency": "EUR", "rate": 1.1} and route.call_count == 3


@pytest.mark.asyncio
@respx.mock(base_url=UPSTREAM)
async def test_timeout_becomes_504(respx_mock):
    respx_mock.get("/rates/USD").mock(side_effect=httpx.ReadTimeout("simulated"))
    app = create_app(UPSTREAM, lambda: fakeredis.FakeAsyncRedis())
    async with app.router.lifespan_context(app):
        async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://shop") as c:
            r = await c.get("/rates/USD")
    assert r.status_code == 504 and respx_mock.calls.call_count == 3


@pytest.mark.asyncio
@respx.mock(base_url=UPSTREAM)
async def test_payment_forwards_the_idempotency_key(respx_mock):
    route = respx_mock.post("/charges").mock(return_value=httpx.Response(201, json={"id": "ch_1", "amount": 500}))
    app = create_app(UPSTREAM, lambda: fakeredis.FakeAsyncRedis())
    async with app.router.lifespan_context(app):
        async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://shop") as c:
            missing = await c.post("/payments", json={"amount": 500})
            ok = await c.post("/payments", json={"amount": 500}, headers={"Idempotency-Key": "order-42-pay"})
    assert missing.status_code == 422 and ok.status_code == 201
    assert route.calls.last.request.headers["Idempotency-Key"] == "order-42-pay"

Observability of retries, timeouts and caches Good to know ​

In plain words: A retry that works is invisible to the user and therefore invisible to you, until the day retries are half your traffic. Log every attempt and every retry decision with the same fields, and count them.

Common misunderstanding: "Logging the final error is enough." The final error hides the two retries that preceded it, the time they cost and the budget they used. Latency spikes with no errors are usually retries.

Definition:

  • Structured logging: one JSON object per event, with the fields event, attempt, wait_s, method, url, status, ms and reason.
  • Metrics per upstream: outbound_requests_total{upstream,status}, outbound_retries_total{reason}, outbound_duration_seconds (a histogram), retry_budget_denied_total, circuit_state{upstream} and cache_hits_total / cache_misses_total / cache_recomputes_total.
  • Traces: a span per attempt, so a 2 s request shows three 0.6 s spans.
  • Background tasks: log their failures. The client never sees them, and the snippet logs background_task_failed before re-raising.

How logs, metrics and traces fit together is in Observability.

Mechanics ​

How Starlette runs a background task Important ​

FastAPI collects every BackgroundTasks the route and its dependencies asked for into one object and attaches it to the response. Starlette 0.49.3, responses.py:

python
# starlette/responses.py (0.49.3), Response.__call__
await send({"type": prefix + "http.response.start", "status": self.status_code, "headers": self.raw_headers})
await send({"type": prefix + "http.response.body", "body": self.body})
if self.background is not None:
    await self.background()

background.py runs for task in self.tasks: await task(). Each BackgroundTask awaits an async function directly or calls run_in_threadpool for a sync one. The consequences:

  • The ASGI call is not finished until every task has run, so the worker's connection slot is held for that long.
  • In-process test clients wait for the tasks.
  • Under Uvicorn, the client already has its bytes after http.response.body (0.006 s measured).
  • A slow task delays the next tasks of the same response, not other requests, as long as it awaits.
  • A sync task occupies one of the 40 thread-pool tokens.

What each httpx timeout measures Good to know ​

Timeout holds four numbers, and httpcore applies each to a different wait:

  • connect to opening the TCP connection and doing the TLS handshake;
  • write to each send of request bytes;
  • read to each receive of response bytes;
  • pool to acquiring a connection from the pool. With max_connections reached, the request waits on the pool, which is why PoolTimeout is a sign of a too-small pool or a too-slow upstream, not of the network.

None of the four bounds the total duration of a call. That is the job of asyncio.wait_for, the caller's deadline or tenacity's stop_after_delay.

How tenacity decides Important ​

For each failed attempt tenacity 9.1.2 (_begin_iter, _post_retry_check_actions, _post_stop_check_actions) runs, in this order:

  1. The retry predicate (self.retry(retry_state)). If it says no, the outcome is returned or raised as is.
  2. after, if set.
  3. wait, to compute the upcoming sleep (_run_wait).
  4. The stop condition (self.stop(retry_state)). If stop, raise the last exception when reraise=True, or RetryError otherwise.
  5. before_sleep (the snippet's log line).
  6. The sleep, then the next attempt.

Two consequences shaped the snippet:

  • A side effect inside the predicate (spending a budget token) also runs on the final attempt, where no retry follows. That is why the budget is a stop condition placed last.
  • stop_a | stop_b builds a stop_any, whose __call__ is any(x(retry_state) for x in self.stops). The generator short-circuits, so the budget is consulted only when the attempt and deadline stops both said "continue".

Exact errors and log lines Must-know ​

SituationExact text (real)
Background task failed under UvicornERROR: Exception in ASGI application … httpx.ConnectError: All connection attempts failed
Our own log for it{"event": "background_task_failed", "task": "welcome_email", "error": "ConnectError"}
SIGTERM with a running taskINFO: Waiting for background tasks to complete. (CTRL+C to force quit)
Read timeouthttpx.ReadTimeout
Pool exhaustedhttpx.PoolTimeout
Closed porthttpx.ConnectError: All connection attempts failed
raise_for_status() on 404Client error '404 Not Found' for url 'http://127.0.0.1:50028/rates/XXX'
Default client timeoutTimeout(timeout=5.0)
lru_cache on async def, second awaitRuntimeError: cannot reuse already awaited coroutine
Breaker open (app response)503 + Retry-After: 5, body {"detail": "rates provider unavailable"}
Bad webhook signature400 {"detail": "signature mismatch"}
Missing Idempotency-Key422 (FastAPI validation error for header idempotency-key)

The SQL: outbox and webhook dedup tables ​

Printed by tests/test_outbox.py::test_print_the_sql (real, SQLite dialect, SQLAlchemy 2.0.58), then a PostgreSQL version of the relay (expected, not run):

sql
-- DDL (real output)
CREATE TABLE outbox (
	id INTEGER NOT NULL,
	aggregate_id INTEGER NOT NULL,
	event_type VARCHAR(64) NOT NULL,
	payload TEXT NOT NULL,
	created_at DATETIME NOT NULL,
	published_at DATETIME,
	attempts INTEGER NOT NULL,
	PRIMARY KEY (id)
);
CREATE TABLE processed_webhooks (
	event_id VARCHAR(64) NOT NULL,
	received_at DATETIME NOT NULL,
	PRIMARY KEY (event_id)
);
-- statements, in order (real output)
INSERT INTO orders (email, total_cents, status) VALUES (?, ?, ?);
INSERT INTO outbox (aggregate_id, event_type, payload, created_at, attempts) VALUES (?, ?, ?, ?, ?);
SELECT outbox.id, outbox.event_type, outbox.payload FROM outbox WHERE outbox.published_at IS NULL ORDER BY outbox.id LIMIT ? OFFSET ?;
UPDATE outbox SET published_at=?, attempts=(outbox.attempts + ?) WHERE outbox.id = ?;

-- PostgreSQL (expected, not run): a partial index and several relays without double pickup
CREATE INDEX outbox_unpublished ON outbox (id) WHERE published_at IS NULL;
SELECT id, event_type, payload FROM outbox
WHERE published_at IS NULL ORDER BY id LIMIT 100
FOR UPDATE SKIP LOCKED;

Version matrix Important ​

PackagePinned here (Python 3.9)Latest on 2026-11-29Latest requiresChanges that matter
FastAPI0.128.80.165.0≥ 3.11lifespan since 0.93.0
Starlette0.49.31.10.0≥ 3.11BackgroundTask(s), send-then-run
httpx0.28.10.29.0≥ 3.101.0 only as dev releases
tenacity9.1.29.2.1≥ 3.10AsyncRetrying, wait_random_exponential
redis (redis-py)7.0.18.2.0≥ 3.11redis.asyncio, aclose()
cachetools6.2.68.0.3≥ 3.11TTLCache(timer=...)
aiolimiter1.2.11.3.0≥ 3.10AsyncLimiter(rate, period)
fakeredis2.41.02.41.0≥ 3.8[lua] extra for scripts
respx0.23.10.23.1≥ 3.8side_effect lists
TaskIQnot installed0.13.0≥ 3.10asyncio-first queue
purgatorynot installed3.0.2≥ 3.11asyncio circuit breaker

Solving the classic problems ​

BugSymptomFixCost
E-mail sent inlinep99 = provider latency; provider outage = signup outageBackgroundTasks (or a queue)none
Important job in BackgroundTasksjobs vanish on deploys / OOMoutbox or queue with late ackmedium
Client per request20 connections for 20 calls; TLS per callone AsyncClient per process in the lifespansmall
No explicit timeoutsrequests pile up behind a slow upstreamTimeout(connect, read, write, pool) + a total deadlinenone
Sync client in async defwhole worker stallsAsyncClient, or a def routesmall
Retry loop around POSTdouble / triple charges (3 measured)retry only idempotent; Idempotency-Keysmall
Retries without jitter or budgetretry storm, 3× load during outages (60 vs 24)full jitter + RetryBudget + breakersmall
Ignoring Retry-After429s continue, account suspendedhonour it, cappednone
Calling a dead upstreamevery request waits for timeoutscircuit breakersmall
No outbound limitprovider rate-limits or bans youAsyncLimiter + bulkhead, per workersmall
lru_cache on async defRuntimeError on second callasync TTL cache with single-flightsmall
Global dict cacheunbounded memory, never fresh, per workerTTLCache / Redis with TTLsmall
pickle in RedisRCE if Redis is writable; breaks on refactorJSON / Pydantic JSONnone
Hot key expiryDB spikes every TTL (50 recomputes)lock / single-flight / XFetch / jittered TTLsmall
404 stormsevery unknown id hits the sourcenegative caching with a short TTLnone
Webhook trusts JSONforged eventsHMAC over raw body + timestamp windownone
Webhook processed twicedouble fulfilmentevent-id dedup in the same transactionsmall

Making a side effect reliable ​

Ask what happens if the process dies right after the response:

  • If the answer is "the user gets no welcome mail and nobody cares", BackgroundTasks is right.
  • If it is "the warehouse never ships", write an outbox row in the transaction and let a relay or a queue worker publish it. Make the consumer idempotent.
  • If the work takes seconds of CPU or must be retried for hours, enqueue it (late ack, backoff, a dead-letter queue) and keep the web tier thin.

Calling an external API safely ​

The order of wrappers in the After app is deliberate, from outside in:

  1. cache;
  2. rate limit;
  3. bulkhead;
  4. breaker;
  5. retries;
  6. the timed-out request.

The reasons:

  • A cache hit costs nothing and must not consume rate-limit tokens.
  • A rate-limited or bulkheaded call must not count as a breaker failure.
  • The breaker counts one logical call (with its retries) as one failure.

Add an Idempotency-Key for every non-idempotent call, map errors to 502/503/504 at the edge, and log every attempt.

Surviving a stampede ​

Jitter the TTLs so keys written together expire apart. Add single-flight in process (cheap, always on), a Redis lock for keys whose recompute is expensive, and XFetch or stale-while-revalidate for the hottest keys so they rarely expire under load. Cache negative answers briefly. Watch cache_recomputes_total: a spike every TTL is a stampede.

Webhooks that cannot be forged or doubled ​

Verify the raw body's HMAC with compare_digest and a timestamp tolerance. Dedupe by event id in the same transaction as the effect, answer 2xx within a few seconds, and push slow work to the outbox or a queue. When sending, sign, retry with backoff and give receivers an event id to dedupe on.

Choosing ​

NeedUseNotWhy
Fire-and-forget, small, loss acceptableBackgroundTasksCeleryzero infrastructure
Must survive crashes / deploysoutbox + relay, or a queueBackgroundTasksdurability
Async codebase, Redis availablearq or TaskIQCeleryasyncio-native workers
Big ecosystem, canvas, beat, many brokersCeleryRQmaturity, features
Simplest Redis job queue, sync codeRQCeleryfewer moving parts
Reliable defaults (ack after processing), syncDramatiqRQits stated design goal
Outbound HTTP in async defhttpx.AsyncClient (lifespan)requests, httpx.Clientdoes not block the loop
Outbound HTTP in workers / def routeshttpx.Client (one per process)top-level httpx.getpooling
Retries in new codetenacityhand-written loopscomposable, testable
Decorator-only retriesbackofftenacityshorter for simple cases
Dependency down for everyonecircuit breakermore retriesfail fast
Provider rate limitAsyncLimiter (per worker) or a Redis limiter (fleet)max_connectionscalls per second, not concurrency
Pure function, fixed answerlru_cacheRedisno network
Per-worker TTL cachecachetools.TTLCache (+ single-flight)lru_cacheexpiry
Shared, invalidatable cacheRedis cache-asidein-processone copy for all workers
Whole-response cachingfastapi-cache2 / HTTP cachinghand-rolledheaders, CDN
Mock an HTTP API in unit testsrespxstub serverfast, scripted
Test timeouts and poolslocal stub serverrespxreal sockets

BackgroundTasks, outbox or queue? ​

QuestionBackgroundTasksOutboxQueue
Survives SIGKILLno (measured)yes (row in the DB)yes (broker)
Atomic with the DB writenoyesno (needs outbox for that)
Retriesnone (write your own)relay retriesbuilt in (backoff, max retries)
Schedulingnonoyes (beat, cron)
Result for a pollernonoresult backend
Runs whereweb workerweb DB + relayseparate workers
Visibilitylogs onlytabledashboards (Flower, Horizon-like tools)
Deliveryat-most-onceat-least-onceat-least-once (with late ack)

In architecture: from a single process to a distributed system ​

Monolith: one process, one database ​

One FastAPI app under Uvicorn and one PostgreSQL. It holds:

  • one httpx.AsyncClient per upstream, from the lifespan;
  • one Redis client, or none at first, since a TTLCache is enough while there is one worker;
  • BackgroundTasks for mail and audit lines;
  • an outbox table in the same database as the orders.

The relay can be a background loop started in the lifespan or a cron-run script. Every rule on this page still applies: timeouts on every call, idempotency keys on every POST and the webhook dedup table. Example: the shop's signup sends mail in a background task, checkout writes orders + outbox in one transaction, and the relay publishes order.placed to the warehouse's webhook with signed, retried deliveries.

Modular monolith and multiple databases ​

Several modules share the process, and with it the per-process resources. Give each upstream its own client, limits, breaker and rate limiter, so the slow tax-calculation API cannot fill the pool the payment API needs (a bulkhead per dependency). Namespace cache keys per module (billing:v3:..., catalog:v1:...) and give each its own TTL policy. With several databases, each module keeps its own outbox next to its own data, because the outbox only works inside one transaction.

Microservices ​

Every call to another service is an external API call:

  • Timeouts follow a deadline budget. The edge has 1 s, so a call two hops down gets what is left.
  • Retries happen at one layer only. AWS's 243× example is five layers of three retries.
  • Breakers and bulkheads are per downstream service.
  • Idempotency keys travel end to end. The browser's key becomes the order service's key to payments.
  • Events leave through the outbox, and consumers dedupe through an inbox.

Example: POST /checkout reaches orders, which writes the order and an order.placed outbox row. The relay publishes to the broker, payments consumes with an inbox table, calls the PSP with the same Idempotency-Key and receives the PSP's webhook, verified and deduped. Broker-side retry and delay are in Retry, Backoff & Delayed Messages.

Distributed data: replicas, caches, sharded databases, multi-region ​

Caches become a distributed-systems problem:

  • Invalidation must reach every copy. Use delete-on-write in Redis, short TTLs in process, or Redis client-side caching ("Tracking") for two-level caches.
  • Replication lag means a read right after a write can miss. Read your own writes from the primary, or delete the cache after the replica catches up.
  • Stampede protection must be cross-process. Use a Redis lock or XFetch, not an asyncio.Lock.
  • A Redis Cluster spreads keys by hash slot. Keys that must be read together need a {hash tag} in the name.
  • Multi-region means one cache per region. Cross-region invalidation goes through events, and every key carries a TTL as the bound on staleness.

Locks in Redis are advisory and lease-based: redis.io calls the simple SET NX lock pattern "discouraged in favor of the Redlock algorithm" when you need stronger guarantees. For correctness (not just efficiency) use database constraints or fencing tokens.

Scaling path: 1×, 10×, 100× ​

LoadWhat changesPractice
1× (one worker)defaults seem fineexplicit timeouts, one client per app, BackgroundTasks for small side effects, TTLCache, webhook dedup
10× (several workers and replicas)per-process limits multiply; caches diverge; deploys kill tasksRedis cache-aside with jittered TTL and locks; per-worker rate limits = provider limit ÷ workers; outbox for events; graceful shutdown; retry metrics
100× (many services, bursty traffic)retry storms, hot keys, provider bansretry budgets, breakers per dependency, deadline propagation, task queues for all heavy work, XFetch on hot keys, fleet-wide rate limiter in Redis, Load Shedding at the edge

Lab ​

All commands run from docs/snippets/python/background-tasks-caching-external-apis/. Outputs marked "real" were produced on CPython 3.9.6 (macOS) with the pinned versions. The full transcript is pipeline/sources/background-tasks-caching-external-apis/runs/pytest-fresh-install.txt.

1. Install and run the whole suite (real) ​

export PATH=$HOME/Library/Python/3.9/bin:$PATH                   # uv 0.13.10 lives here
uv venv ~/venvs/btc --python python3                             # keep the venv outside the repo
uv pip install --python ~/venvs/btc/bin/python '.[test]'         # or: -r requirements.lock
export PYTHONDONTWRITEBYTECODE=1                                 # pyproject sets -p no:cacheprovider
~/venvs/btc/bin/python -m pytest -s -v
# uvicorn: client had the 201 after 0.006s; e-mail sent 0.304s after the handler ran
# ASGITransport: client had the 201 after 0.305s (task already finished)
# SIGKILL: 202 received, exit code -9, marker written: False
# SIGTERM: 202 received, exit code -15, marker written: True
# 20 sequential GETs: client per request 0.068s, 20 TCP connections; one shared client 0.020s, 1 TCP connection(s)
# provider down, 20 calls x 3 attempts: 60 requests without a budget, 24 with RetryBudget(0.2) (retries denied: 19)
# 50 concurrent misses ... no lock: 50 recomputes, 0.108s | SET NX PX: 1 recompute, 0.111s
# ============================== 56 passed in 8.48s ==============================

The numbers on this page come from that first transcript (56 tests). After review fixes (404 handled inside the breaker call, plus a new test for it; webhook transaction moved to run_in_threadpool) the suite was rerun on the final code: runs/pytest-final-code.txt printed 57 passed in 8.76s with the same picture (Uvicorn 201 after 0.005 s, e-mail at 0.311 s; ASGITransport 0.313 s; 20 vs 1 TCP connections; 60 vs 24 requests; 50 vs 1 recomputes; three unknown currencies [404, 404, 404], then EUR 200; breaker closed).

On Python 3.12+ with uv: uv run --extra test pytest -s from this directory, after moving the pins to current releases (expected, not run: no 3.12 interpreter on the build machine).

2. Response first, then task (real) ​

~/venvs/btc/bin/python -m pytest -s tests/test_background.py
# uvicorn: client had the 201 after 0.006s; e-mail sent 0.304s after the handler ran
# ASGITransport: client had the 201 after 0.305s (task already finished)
# ERROR:    Exception in ASGI application ... httpx.ConnectError: All connection attempts failed
# app: {"event": "background_task_failed", "task": "welcome_email", "error": "ConnectError"}

Change email_delay_s in the first test to 2.0. The Uvicorn number stays near 0.006 s and the ASGITransport number becomes 2 s.

3. Retries, idempotency and the budget (real) ​

~/venvs/btc/bin/python -m pytest -s tests/test_retries.py tests/test_before.py
# 429 + Retry-After: 1 -> second attempt succeeded after 1.004s
# POST, no key, provider committed then answered 500: attempts 1, charges 1
# POST + Idempotency-Key: attempts 2, charges 1, replayed=true, body {'id': 'ch_1', 'amount': 500}
# Before: provider committed then 500 twice -> 3 charges for one payment (['ch_1', 'ch_2', 'ch_3'])

4. The stampede, measured (real) ​

~/venvs/btc/bin/python -m pytest -s tests/test_stampede.py
# 50 concurrent misses, 100 ms recompute (fakeredis, one process):
#   no lock:   50 recomputes, 0.108s
#   SET NX PX: 1 recompute,  0.111s (waiters poll every 10 ms)
# XFetch, delta=0.1 s, beta=1: ... 0.2s -> 0.133, 0.1s -> 0.366, 0.05s -> 0.604, 0.01s -> 0.899

Set N = 500 or the recompute to 1 s. Without the lock the recompute count follows N. With it the count stays at 1 and the wall time follows the recompute plus one poll interval. These are in-process fakeredis timings: against a real Redis each poll is a network round trip (about 0.1–0.5 ms on a LAN), so use a longer poll_s or Pub/Sub notification for big fleets.

5. The same against a real Redis (expected, not run) ​

docker run --rm -p 6379:6379 redis:7                    # not run: no Docker or Redis on the build machine
# in conftest.py: replace FakeAsyncRedis(server=...) with redis.asyncio.Redis.from_url("redis://localhost:6379/15")
~/venvs/btc/bin/python -m pytest -s tests/test_cache_redis.py tests/test_stampede.py
# expected: the same hit counts (1 upstream call for 5 GETs, 1 recompute for 50 misses); wall times grow by round trips
redis-cli -n 15 --scan --pattern 'shop:v1:*'            # expected: shop:v1:rate:EUR, shop:v1:report:top

For PHP/Laravel developers ​

Laravel ships most of this chapter in the framework:

  • Queues. dispatch(new SendReceipt($order)) pushes a job to Redis, SQS or a database table. php artisan queue:work --tries=3 runs workers, and "By default, Laravel will only attempt a job once". ->afterCommit() dispatches only after the transaction commits, the poor man's outbox. Unlike an outbox, a crash between commit and dispatch still loses the job. ShouldBeUnique keeps one instance of a job queued. Horizon "provides a beautiful dashboard and code-driven configuration for your Laravel powered Redis queues". FastAPI has no built-in equivalent: pick Celery with Flower, or arq/TaskIQ with your own metrics.
  • HTTP client. Http::retry(3, 100) takes "the maximum number of times the request should be attempted and the number of milliseconds" to wait, and Http::retry([100, 200]) gives explicit backoffs. Retries do not check idempotency for you, the same trap as the Before app. Http::timeout() (default 30 s) and connectTimeout() (default 10 s) map roughly to httpx's read/connect.
  • Cache. Cache::remember('key', $seconds, fn () => ...) is cache-aside. Cache::flexible('key', [5, 10], fn () => ...) serves stale data while it recalculates, the stale-while-revalidate cousin of XFetch. Cache::lock('foo', 10)->block(5) is the SET NX PX stampede lock.
  • Rate limiting. RateLimiter::attempt('send-message:'.$user->id, $perMinute = 5, fn () => ...) is the Redis-backed counterpart of AsyncLimiter, but shared by all workers.
php
<?php
// Laravel 13: the shop's after-app, side by side with app/main.py
use Illuminate\Support\Facades\{Cache, DB, Http, RateLimiter};

// POST /orders: order + job dispatched only after the commit (closest to place_order + outbox)
DB::transaction(function () use ($data) {
    $order = Order::create($data);
    SendReceipt::dispatch($order)->afterCommit();       // ShouldQueue job, worker: queue:work --tries=3
});

// GET /rates/{c}: Cache::remember = cache-aside; the lock = SET NX PX stampede protection
$rate = Cache::remember("shop:v1:rate:$c", 60, function () use ($c) {
    return Cache::lock("lock:shop:v1:rate:$c", 10)->block(5, function () use ($c) {
        // re-read inside the lock: a peer may have filled the key while we waited (the double-check)
        return Cache::get("shop:v1:rate:$c") ?? RateLimiter::attempt('rates-api', 50, function () use ($c) {   // 50 per minute, shared
            return Http::baseUrl(config('services.rates.url'))
                ->connectTimeout(1)->timeout(2)                 // httpx Timeout(connect=1, read=2)
                ->retry([100, 200])                             // GET: safe to retry
                ->get("/rates/$c")->throw()->json();            // throw() = raise_for_status()
        });
    });
});

// POST /payments: forward the client's Idempotency-Key before retrying a POST
Http::withHeaders(['Idempotency-Key' => $request->header('Idempotency-Key')])
    ->retry(3, 100)->post("$psp/charges", ['amount' => $amount]);
ConcernLaravel 13FastAPI (this page)
After-response worka queued job on the sync or Redis connection (no in-process twin shown here)BackgroundTasks.add_task
Durable jobsLaravel queues (ShouldQueue), queue:workCelery / RQ / arq / Dramatiq / TaskIQ
DashboardHorizonFlower (Celery), custom metrics
Outbound retriesHttp::retry(3, 100)tenacity AsyncRetrying
Cache-asideCache::rememberRedisCache.get_or_set
Stale-while-revalidateCache::flexibleXFetch / background refresh
Stampede lockCache::lock()->block()SET NX PX + Lua release
Rate limiterRateLimiter::attempt (shared)AsyncLimiter (per worker)
Webhook signaturemiddleware / package (e.g. Cashier for Stripe)hmac.compare_digest in the route

The Go angle ​

Go puts the same tools in the standard library and golang.org/x/sync:

  • Timeouts. http.Client{Timeout: 2 * time.Second}, where "The timeout includes connection time, any redirects, and reading the response body" and "A Timeout of zero means no timeout". The zero-value http.DefaultClient has no timeout at all, unlike httpx's 5 s. Per-call deadlines come from context.WithTimeout, and a context deadline cancels the request wherever it is.
  • Fan-out. errgroup.WithContext cancels the siblings: "The derived Context is canceled the first time a function passed to Go returns a non-nil error". SetLimit(n) is the bulkhead.
  • Single-flight. singleflight.Group.Do(key, fn) is "duplicate function call suppression", the exact twin of AsyncTTLCache's in-flight Futures.
  • Background work. There is no BackgroundTasks: a goroutine started from a handler is equally lost on crash, and the durable answer is the same outbox or queue.

The Go-side chapters are context, HTTP server & client and Rate Limiting in Go.

go
// Go: the rates call with a client timeout, a context deadline, singleflight and errgroup
var (
	client = &http.Client{Timeout: 2 * time.Second} // Go http.Client Timeout: whole request, body included
	group  singleflight.Group                       // one in-flight load per key, like AsyncTTLCache
)

func rate(ctx context.Context, cur string) ([]byte, error) {
	v, err, _ := group.Do("rate:"+cur, func() (any, error) {
		ctx, cancel := context.WithTimeout(ctx, time.Second) // context deadline < client timeout
		defer cancel()
		req, _ := http.NewRequestWithContext(ctx, http.MethodGet, base+"/rates/"+cur, nil)
		resp, err := client.Do(req)
		if err != nil {
			return nil, err
		}
		defer resp.Body.Close()
		if resp.StatusCode >= 400 { // like raise_for_status()
			return nil, fmt.Errorf("rates: %s", resp.Status)
		}
		return io.ReadAll(resp.Body)
	})
	if err != nil {
		return nil, err
	}
	return v.([]byte), nil
}

func rates(ctx context.Context, curs []string) error {
	g, ctx := errgroup.WithContext(ctx) // first error cancels the others
	g.SetLimit(5)                       // bulkhead
	for _, c := range curs {
		g.Go(func() error { _, err := rate(ctx, c); return err })
	}
	return g.Wait()
}
ConcernGoPython (this page)
Whole-request timeouthttp.Client{Timeout} (0 = none)asyncio.wait_for / stop_after_delay (httpx phases: 5 s each)
Per-call deadlinecontext.WithTimeoutasyncio.wait_for, asyncio.timeout (3.11+)
Connection poolhttp.Transport (MaxIdleConnsPerHost, default 2)httpx.Limits (max_keepalive_connections 20)
Bounded fan-outerrgroup.SetLimitSemaphore / bulkhead
Duplicate suppressionsingleflight.Group.DoAsyncTTLCache Futures, Redis lock
Retrieshand-written or a librarytenacity
After-response workgoroutine (lost on crash)BackgroundTasks (lost on crash)

Common misconceptions ​

BeliefReality
BackgroundTasks is a job queueSame process, same loop, no persistence: SIGKILL lost the job in the test
The task runs before the response because my test waitedIn-process test clients wait for tasks (0.305 s); real Uvicorn answered in 0.006 s
An exception in a background task becomes a 500The 201 is already sent; only Exception in ASGI application in the log
Graceful shutdown makes BackgroundTasks durableIt covers SIGTERM within the grace period; not OOM, kill -9, node loss
A queue runs each job exactly onceAt-least-once; arq "favours multiple times over zero times"; make jobs idempotent
httpx has no default timeout5 s for each phase (Timeout(timeout=5.0)), but no total deadline
A read timeout bounds the whole callIt bounds each wait for bytes; a trickling server never trips it
A new client per request is cleaner20 connections for 20 calls vs 1; no global limit; handshake each time
httpx raises on 404/500Only raise_for_status() does
Retrying always helpsOnly for idempotent requests; a naive POST retry made 3 charges
A 500 means nothing happenedThe provider may have committed; only an idempotency key makes the retry safe
Exponential backoff is enoughWithout jitter, clients retry in lockstep; without a budget, an outage triples load
A circuit breaker replaces retriesDifferent jobs: retries for blips, breaker for outages; they compose
max_connections is a rate limitIt bounds concurrency per client per process, not calls per second
@lru_cache works on async functionsIt caches a coroutine object: cannot reuse already awaited coroutine
An in-process cache is shared by workersEach worker has its own; invalidating one left the other at the old price
pickle is fine for a private RedisAnyone who can write a key can run code in every worker; JSON is 21 vs 172 bytes here
A per-key asyncio.Lock prevents stampedesPer process only; 8 workers still recompute 8 times
KEYS pattern + DEL is a fine invalidationKEYS blocks Redis; use versioned keys, TTLs or SCAN
Verifying the parsed JSON's signature worksRe-serialising changes the bytes: signature mismatch
respx catches every httpx callNot clients built with a custom transport=

Cheat sheet ​

TopicRemember
Background tasktasks.add_task(fn, *args); runs after the response, same process; small and losable only
Durable workoutbox row in the transaction, or a queue with late ack; idempotent consumers
QueuesCelery (beat, canvas), RQ (simple), arq / TaskIQ (asyncio), Dramatiq (ack after processing)
Clientone httpx.AsyncClient per process, created in the lifespan, aclose() at shutdown
Timeoutshttpx.Timeout(2, connect=1, pool=0.5); add a total deadline; default is 5 s per phase
Limitshttpx.Limits(max_connections=20, max_keepalive_connections=10, keepalive_expiry=30)
Errorsnetwork errors raise; status codes need raise_for_status()
Retrytenacity: attempts + deadline + full jitter + reraise=True + log in before_sleep
What to retrytimeouts, connect errors, 429, 5xx; idempotent methods or Idempotency-Key; never 4xx
Retry-Afterhonour it, cap it
Budgetretries ≤ 20 % of requests; stop condition placed last
Breaker3 failures → open → 5 s → half-open, one trial → closed / open
Outbound limitsAsyncLimiter(rate, period) per worker + Semaphore bulkhead
In-process cachelru_cache for pure functions; TTLCache + single-flight for async loads
Redisredis.asyncio, JSON values, SET k v EX ttl with jitter, shop:v1:entity:id keys
InvalidationDEL after commit; TTL as safety net; version bump for schema changes
StampedeSET lock NX PX > recompute time, token-checked release; XFetch; negative caching
Webhooks inHMAC over raw body, compare_digest, 5 min tolerance, dedup by event id, 2xx fast
Webhooks outsign, event id as idempotency key, retry with backoff
Testsrespx for scripted HTTP, a local stub for real timeouts, fakeredis[lua] for Redis

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — When does a FastAPI background task run, and why does your TestClient test seem to say otherwise? Must-know ​

Answer

Answer: After the response has been sent, in the same process and event loop. Starlette sends http.response.start and http.response.body, then awaits the background tasks in order (sync ones in the thread pool). Under real Uvicorn the client had its 201 after 0.006 s while the 300 ms e-mail task finished later. In-process test clients (TestClient, httpx.ASGITransport) return only when the whole ASGI call, tasks included, is done, so the same request "took" 0.305 s there. Test the ordering against a real server or by recording ASGI events, not by timing an in-process client.

2 — Your team wants to move order-confirmation e-mails and invoice generation into BackgroundTasks. What do you say? Must-know ​

Answer

Answer: E-mails whose loss is tolerable can go there. Invoices cannot: a background task is lost on crash (SIGKILL in the test: job accepted, never run), is never retried and leaves no record. Write an outbox row in the same transaction as the order and let a relay or a queue worker (Celery with acks_late, arq, Dramatiq, TaskIQ) do the work at-least-once, with an idempotent task and retries with backoff. Also move the work if it is CPU-heavy, scheduled (beat), needs a result backend or must be rate limited across workers.

3 — Which timeouts does httpx have, what are the defaults, and what does none of them cover? Must-know ​

Answer

Answer: connect (establishing TCP/TLS), read (each wait for response bytes), write (each send) and pool (waiting for a free connection), all 5 s by default (Timeout(timeout=5.0)). Real: read=0.1 raised ReadTimeout after 0.103 s, and a busy single-connection pool raised PoolTimeout. None of them bounds the total duration: a server that trickles bytes never trips the read timeout, and retries multiply the time. Add a total deadline with asyncio.wait_for / asyncio.timeout or tenacity's stop_after_delay, sized from the caller's budget.

4 — Why one AsyncClient per app, and how do you create and close it in FastAPI? Must-know ​

Answer

Answer: The client owns the connection pool. One client means reused keep-alive connections (real: 1 TCP connection for 20 calls instead of 20) and one global max_connections limit. A client per request pays a handshake per call and has no shared bound. Create it in the lifespan (async with or create, then await client.aclose() after yield) with explicit Timeout, Limits and base_url, store it on app.state and hand it to routes through a dependency. Loop-bound helpers (semaphores, limiters, locks) belong there too, because on Python 3.9 they bind to the running loop when created.

5 — Which requests may you retry automatically, and how does an idempotency key change the answer for a POST? Must-know ​

Answer

Answer: Retry only failures that might be transient (timeouts, connection errors, 408, 429, 500, 502, 503, 504: the snippet's RETRYABLE_STATUS) on idempotent requests (GET, HEAD, OPTIONS, PUT, DELETE), and never 4xx. A POST is unsafe because a 500 or timeout does not say whether the provider committed. Real: a naive loop made 3 charges for one payment. With an Idempotency-Key (a UUID chosen once per logical operation and sent on every attempt) the provider stores the first result and replays it. Real: 2 attempts, 1 charge, Idempotent-Replayed: true. Forward the key your own client sent you, so every layer's retries map to one operation.

6 — What are exponential backoff, jitter and a retry budget, and why do you need all three? Important ​

Answer

Answer: Backoff makes each wait longer (base × 2^(n-1)) so a struggling service gets breathing room. Full jitter draws the wait uniformly between 0 and that cap (real means: 0.051, 0.105, 0.195, 0.403, 0.785 s for attempts 1 to 5), so clients that failed together do not retry together. A retry budget caps retries as a fraction of requests (20 % here), so an outage does not multiply load. Real: 60 requests without it, 24 with it, for 20 calls. AWS's example of three retries at five layers is a 243× load increase, so retry at one layer and honour Retry-After.

7 — Describe the circuit breaker's states and where it sits relative to retries and the rate limiter. Important ​

Answer

Answer:

  • Closed: calls pass and consecutive failures are counted.
  • Open: after the threshold (3), every call fails fast without touching the network.
  • Half-open: after the reset timeout (5 s), one trial call passes. Success closes the breaker, failure re-opens it.

In the After app the order is cache → rate limiter → bulkhead → breaker → retries → request. A cache hit costs nothing, a call that was rate-limited is not a breaker failure, and one logical call with its retries counts once. Real: with the provider down the app answered 502, 502, 502, then 503 with Retry-After: 5 in 0.6 ms.

8 — Why is @lru_cache wrong on an async def, and what do you use instead? Important ​

Answer

Answer: lru_cache caches the return value, and an async function returns a coroutine object that can be awaited only once. Real: RuntimeError: cannot reuse already awaited coroutine on the second call. Use an async cache that stores the result: a cachetools.TTLCache for values plus a dict of in-flight Futures for single-flight (real: 50 concurrent misses gave 1 load), or aiocache's @cached. Remember it is per process: two workers loaded the value twice and diverged after an invalidation.

9 — How do you design Redis cache keys and values, and how do you invalidate? Important ​

Answer

Answer:

  • Keys: namespace:v{version}:entity:id (here shop:v1:rate:EUR), with every input that changes the answer (tenant, locale, currency) in the key and no secrets or personal data.
  • Values: JSON (real: 21 bytes vs 172 for pickle), never pickle, because pickle.loads runs code chosen by whoever wrote the bytes.
  • TTL: set one on every key, with jitter.
  • Invalidation: delete on write after the commit, with the TTL bounding staleness, and bump the version for schema changes so old keys simply expire.
  • Avoid KEYS: it blocks Redis; use SCAN if you must sweep.

10 — What is a cache stampede and which defences do you know? Must-know ​

Answer

Answer: A hot key expires and every concurrent request misses and recomputes it (dogpile). Real: 50 misses gave 50 recomputes of a 100 ms query. The defences:

  • Lock-based recompute: SET lock NX PX with a token, a double-check after acquiring and a Lua compare-and-delete release, with a lock TTL longer than the recompute. Waiters poll and re-read. Real: 1 recompute.
  • In-process single-flight: one load per worker.
  • Early recompute: XFetch, a probabilistic early expiration that rises from 0.7 % to 90 % in the last half second here, or stale-while-revalidate such as Laravel's Cache::flexible.
  • Jittered TTLs, so keys written together expire apart.
  • Negative caching for missing ids.

11 — How do you receive a webhook safely? Important ​

Answer

Answer:

  1. Read the raw body (await request.body()) and verify the HMAC-SHA256 signature over the exact bytes with hmac.compare_digest. Re-serialised JSON fails: real signature mismatch.
  2. Check the signed timestamp against a tolerance (Stripe's default is 5 minutes) to stop replays.
  3. Insert the event id into a dedup table in the same transaction as the effect, so a redelivery answers 200 duplicate without a second effect.
  4. Answer 2xx quickly (GitHub expects it within 10 seconds) and push slow work to an outbox or queue.

When sending webhooks, sign them, use the event id as idempotency key and retry with backoff.

12 — How do you test code that calls external APIs and Redis without the real services? Good to know ​

Answer

Answer:

  • respx scripts httpx responses in process (side_effect=[503, 503, 200], exceptions for timeouts) and asserts on calls and headers. It does not intercept clients built with a custom transport=.
  • A local stub server (a real Uvicorn on an ephemeral port) makes timeouts, pool limits and connection counts real.
  • fakeredis (FakeAsyncRedis(server=FakeServer()), [lua] for scripts) runs cache and lock logic with several clients of one fake server.

Run the app's lifespan explicitly with httpx.ASGITransport, set NO_PROXY for localhost, and remember that in-process clients wait for background tasks.

13 — What do Laravel and Go offer for the same problems? Good to know ​

Answer

Answer:

  • Laravel has queues with Horizon, dispatch()->afterCommit(), Http::retry(3, 100) (which does not check idempotency for you), Cache::remember (cache-aside), Cache::flexible (stale-while-revalidate), Cache::lock (stampede lock) and RateLimiter::attempt (a Redis-backed shared limit).
  • Go has http.Client{Timeout}, a whole-request timeout where zero means none. context.WithTimeout gives per-call deadlines, errgroup gives bounded fan-out with cancellation and singleflight gives duplicate suppression.
  • Both: in-memory work started from a handler (a goroutine, an in-process callback) is lost on crash just like BackgroundTasks.

Glossary ​

TermMeaning
BackgroundTasksFastAPI/Starlette object; add_task queues functions to run after the response, in-process
add_tasktasks.add_task(func, *args, **kwargs); async functions awaited, sync ones in the thread pool
Response first then taskStarlette sends the body, then awaits the background tasks
Lost on crashIn-memory work disappears when the process dies (SIGKILL, OOM)
Task queueBroker + workers that run jobs durably (Celery, RQ, arq, Dramatiq, TaskIQ)
At-least-onceA job or message may run more than once, never zero times; requires idempotency
Visibility timeoutTime a reserved message stays hidden before redelivery (Celery on Redis: 1 hour default)
acks_lateCelery option: acknowledge after the task returns, so a crash causes redelivery
Result backendStore for task states and return values
BeatCelery's scheduler for periodic (scheduled) tasks
OutboxTable of events written in the business transaction, published later by a relay
RelayProcess that reads unpublished outbox rows and publishes them
httpx.Client / httpx.AsyncClientSync / async HTTP client with a connection pool
Connect timeoutLimit on establishing the TCP/TLS connection
Read timeoutLimit on each wait for response bytes
Pool timeoutLimit on waiting for a free connection from the pool
Pool limitsmax_connections, max_keepalive_connections, keepalive_expiry
Keep-aliveReusing an open connection for further requests
Lifespan clientThe shared client created and closed in the FastAPI lifespan
base_urlPrefix for relative URLs on a client
raise_for_statusRaise HTTPStatusError for 4xx/5xx responses
tenacityRetry library: stop, wait, retry, before_sleep strategies
backoffDecorator-based retry library (on_exception, expo, full_jitter)
Exponential backoffWaits that grow geometrically between attempts
JitterRandomisation of waits; full jitter = uniform in [0, cap]
Retry budgetCap on retries as a share of requests
Idempotency keyClient-chosen id that makes repeated requests one operation
Retry-AfterResponse header with a delay in seconds or an HTTP-date
Circuit breakerClosed / open / half-open guard that fails fast while a dependency is down
Half-openBreaker state letting one trial call through
BulkheadConcurrency cap per dependency (Semaphore)
Outbound rate limitingCalls-per-period cap on your own requests (aiolimiter)
lru_cacheStandard-library memoisation with LRU eviction and no TTL
TTLCachecachetools LRU cache with a per-item time-to-live
Single-flightConcurrent requests for one key share one load
Per-process cacheA cache living inside one worker process
Cache-asideApplication reads cache, loads and stores on a miss, deletes on write
Read-through / write-throughCache loads on miss itself / writes go to cache and source together
redis.asyncioredis-py's asyncio client
SerializationTurning objects into bytes for the cache (JSON preferred over pickle)
TTLTime to live of a key (EX, PX, EXPIRE)
Namespacing keysPrefixes such as shop:v1: that group and version keys
InvalidationRemoving or replacing stale cache entries
Stampede (dogpile)Many concurrent misses recompute the same value
Lock-based recomputeOnly the holder of a SET NX PX lock recomputes
Probabilistic early expirationXFetch: recompute early with a probability rising toward expiry
Negative cachingCaching "not found" answers briefly
fastapi-cache2 / aiocacheDecorator-based caching libraries for FastAPI / asyncio
WebhookHTTP callback from a provider to your endpoint
Webhook signatureHMAC over timestamp + raw body, sent in a header
HMACKeyed hash (here SHA-256) proving the sender knows the secret
Idempotent webhook processingDedup by event id in the same transaction as the effect
respxLibrary that mocks httpx requests in tests
fakeredisIn-memory implementation of the Redis API for tests
Structured loggingLogs as key-value / JSON objects with fixed fields

References ​

Built by Morteza Negahi