CodingNeed.

Production engineering workshop · 45 MIN

Django / FastAPI · Keep blocking work out of async handlers

The event loop stays responsive only while handlers cooperate.

FastAPI can run an async HTTP client without blocking the event loop. Reuse a client within application lifespan for connection pooling. Use timeouts, validate external JSON and translate expected upstream failures to a bounded error response. A Django async view has the same nonblocking requirement; use Django’s supported async ORM methods or sync_to_async at deliberate boundaries. This workshop uses FastAPI for the runnable project.

First reproduce the normal path. Then force a failure at each boundary and inspect what remains true.

Read the example

from contextlib import asynccontextmanager
import httpx
from fastapi import FastAPI, HTTPException, Request

@asynccontextmanager
async def lifespan(app):
    async with httpx.AsyncClient(timeout=5.0, follow_redirects=False) as client:
        app.state.client = client
        yield

app = FastAPI(lifespan=lifespan)

@app.get("/upstream-status")
async def upstream_status(request: Request):
    try:
        response = await request.app.state.client.get("https://example.com/status.json")
        response.raise_for_status()
        data = response.json()
        if not isinstance(data, dict) or type(data.get("healthy")) is not bool:
            raise ValueError("Invalid upstream response")
        return {"healthy": data["healthy"]}
    except (httpx.HTTPError, ValueError):
        raise HTTPException(status_code=502, detail="Upstream unavailable")
# The fixed example upstream is illustrative. Mock it in tests.
# For large responses, stream and cap bytes before parsing.
Check the expected output
Review the behavior in the stated project environment.

Your challenge

Create a FastAPI project with httpx. Serve this app with an ASGI server and replace the example upstream URL with a mock transport during tests. Cover timeout, 500, malformed JSON and a successful response. Apply authentication and rate limiting before exposing a paid or sensitive upstream.

Solution cost: Upstream latency plus payload parsing; concurrency is limited by pools and admission control. time · Response size and active-request state. space

Common trap

requests.get inside async def blocks the event loop. An async function name does not make synchronous I/O nonblocking.

Study the project implementation
from contextlib import asynccontextmanager
import httpx
from fastapi import FastAPI, HTTPException, Request

@asynccontextmanager
async def lifespan(app):
    async with httpx.AsyncClient(timeout=5.0, follow_redirects=False) as client:
        app.state.client = client
        yield

app = FastAPI(lifespan=lifespan)

@app.get("/upstream-status")
async def upstream_status(request: Request):
    try:
        response = await request.app.state.client.get("https://example.com/status.json")
        response.raise_for_status()
        data = response.json()
        if not isinstance(data, dict) or type(data.get("healthy")) is not bool:
            raise ValueError("Invalid upstream response")
        return {"healthy": data["healthy"]}
    except (httpx.HTTPError, ValueError):
        raise HTTPException(status_code=502, detail="Upstream unavailable")
# The fixed example upstream is illustrative. Mock it in tests.
# For large responses, stream and cap bytes before parsing.

Further reading: Official documentation

Essential cookies keep your account signed in. Optional analytics is not configured on this site. Your choice does not affect access to lessons.

Read the Privacy Policy. You can change this choice in the footer.