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

Lab: Find the Call That Blocks the Loop

Prove with timing logs that one synchronous call inside an async endpoint stalls every other request, then fix it three ways: to_thread, a plain def endpoint, and a real async client.

Contentsand lesson path

What you will learn

  • Detect a blocking call inside an async endpoint and fix it by switching to an async library, a plain def endpoint or a thread-pool offload.

Prerequisites: Python Foundations

01. Goal and setup

By the end of this lab you will have a small FastAPI service whose /report endpoint calls a vendor SDK that only has a synchronous API, a probe script that fires one report and three health checks at the same time, and timing logs that show the health checks being stalled — and then not stalled, for each of three different fixes. This is the skill this lesson exists for: not believing that a call blocks, but measuring it.

You need: Python 3.12, the uv installer, and two terminal windows. Versions used for the outputs in this lab: Python 3.12.13, FastAPI 0.163.1, uvicorn 0.54.0, httpx 0.28.1; the install command below pins the same packages. Copy upstream.py from the task group lesson into lab/ to simulate the slow vendor on port 8137.

Project layout
lab/
├── .venv/           project environment (uv venv)
├── app.py           the service under test
├── vendor.py        a vendor SDK with only a synchronous API
├── probe.py         fires one report + three health checks, timed
└── upstream.py      copy from lesson 02 to serve the slow vendor
Terminal · one-off setup
cd lab
uv venv --python 3.12 .venv
uv pip install --python .venv/bin/python fastapi==0.163.1 uvicorn==0.54.0 httpx==0.28.1
# terminal 1: the slow upstream from the previous lessons
.venv/bin/uvicorn upstream:app --host 127.0.0.1 --port 8137
# terminal 2: the service under test
.venv/bin/uvicorn app:app --host 127.0.0.1 --port 8231 --reload

02. Step 1: write the blocking service and watch it stall

The vendor SDK is honest about being synchronous: httpx.Client, no async, no await, and a call that takes about two seconds at the upstream. There is nothing wrong with this module — plenty of real SDKs look exactly like it.

Python · lab/vendor.py
"""A vendor SDK with only a synchronous API: no async, no awaits."""

import httpx

UPSTREAM = "http://127.0.0.1:8137"

_client = httpx.Client(timeout=5.0)


def get_cover(isbn: str) -> dict:
    """Blocking: the calling thread waits until the response arrives."""
    response = _client.get(
        f"{UPSTREAM}/services/cover", params={"d": 2.0, "isbn": isbn}
    )
    response.raise_for_status()
    return response.json()
Python · lab/app.py (first version)
"""Reading-list service whose report endpoint calls a slow vendor."""

from fastapi import FastAPI

from vendor import get_cover

app = FastAPI()


@app.get("/healthz")
async def healthz() -> dict:
    return {"status": "ok"}


@app.get("/report")
async def report() -> dict:
    cover = get_cover("978-0134685991")  # blocks the loop for ~2 s
    return {"report": "reading-list", "cover": cover}
Python · lab/probe.py
"""Time one report call and three health checks fired together."""

import asyncio
import sys
import time

import httpx

BASE = sys.argv[1]
PATH = sys.argv[2] if len(sys.argv) > 2 else "/report"


async def timed(client: httpx.AsyncClient, label: str,
                 path: str) -> float:
    start = time.perf_counter()
    response = await client.get(f"{BASE}{path}")
    ms = (time.perf_counter() - start) * 1000
    print(f"{label:<12} {response.status_code}  {ms:7.0f} ms")
    return ms


async def main() -> None:
    async with httpx.AsyncClient(timeout=10.0) as client:
        times = await asyncio.gather(
            timed(client, "report", PATH),
            timed(client, "healthz #1", "/healthz"),
            timed(client, "healthz #2", "/healthz"),
            timed(client, "healthz #3", "/healthz"),
        )
    worst = max(times[1:])
    print(f"worst healthz while report ran: {worst:.0f} ms")


asyncio.run(main())
Terminal · check that the endpoint answers
curl -s http://127.0.0.1:8231/report | .venv/bin/python -m json.tool
Expected output
{
    "report": "reading-list",
    "cover": {
        "service": "cover",
        "delay": 2.0,
        "items": [
            "cover-1",
            "cover-2"
        ]
    }
}
Terminal · run the probe
.venv/bin/python probe.py http://127.0.0.1:8231 /report
Illustrative output (one run; timings vary by machine)
report       200     2089 ms
healthz #1   200     2013 ms
healthz #2   200     2014 ms
healthz #3   200     2014 ms
worst healthz while report ran: 2014 ms

The curl call should pause for about two seconds and then print the JSON above; if it does not, fix that first (see Troubleshooting). In the probe output, the report taking two seconds is expected — the vendor genuinely is slow. The evidence is the other three lines: /healthz returns a constant dictionary, does no I/O, and should cost a few milliseconds, yet every probe took two full seconds. The health checks were not slow; they were parked.

03. Step 2: name the culprit precisely

Work through what the numbers already tell you. The stall affects requests to an endpoint that never touches the vendor, so the problem is not the vendor call being slow but where the wait happens: inside an async def endpoint, get_cover(...) is an ordinary function call with no await in front of it, so the single thread executes it synchronously and holds the loop until the response arrives. Every other request waits for the loop, which is the one worker from the event loop lesson. The rule to take away: inside async def, any call you do not await runs synchronously and blocks the loop for its whole duration.

The timing probe is the tool that generalises: fire one suspicious request and one trivial request together, and see whether the trivial one degrades. Python can also point at the culprit itself — asyncio's debug mode (run with python -X dev, or set PYTHONASYNCIODEBUG=1) logs a warning for any step of a task that holds the loop longer than 100 ms. Stop the app in terminal 2, restart it as PYTHONASYNCIODEBUG=1 .venv/bin/uvicorn app:app --port 8231, call /report, and the terminal shows a line like Executing <Task finished name='Task-5' coro=<RequestResponseCycle.run_asgi() done, ...> took 2.008 seconds. Under uvicorn every request runs in a task with that same generic name, so the warning tells you that the loop was held and for how long, not which endpoint did it; the access-log line printed next to it names the request. That message plus the probe is usually enough to find the line without guessing.

04. Step 3: fix one — offload with asyncio.to_thread

You cannot make the vendor async, but you can stop holding the loop while it works. asyncio.to_thread runs the synchronous function in a worker thread and gives you an awaitable for its result:

Python · lab/app.py (added)
import asyncio


@app.get("/report-thread")
async def report_thread() -> dict:
    cover = await asyncio.to_thread(get_cover, "978-0134685991")
    return {"report": "reading-list", "cover": cover}
Terminal · probe the offloaded endpoint
.venv/bin/python probe.py http://127.0.0.1:8231 /report-thread
Illustrative output (one run; timings vary by machine)
healthz #1   200        7 ms
healthz #2   200        7 ms
healthz #3   200        7 ms
report       200     2046 ms
worst healthz while report ran: 7 ms

Same two-second vendor, same endpoint shape, but the worst health check is now a few milliseconds (7 ms in this run): while the worker thread waits on the vendor, the loop serves everyone else. Note that the lines print in completion order this time — the health checks finished first, which is the point.

05. Step 4: fix two — declare the endpoint with plain def

FastAPI itself offers the same offload. A path operation written with plain def instead of async def is run by Starlette in a thread pool (AnyIO worker threads, at most 40 at a time by default), so the blocking call happens off the loop automatically:

Python · lab/app.py (added)
@app.get("/report-def")
def report_def() -> dict:
    cover = get_cover("978-0134685991")
    return {"report": "reading-list", "cover": cover}
Terminal · probe the plain def endpoint
.venv/bin/python probe.py http://127.0.0.1:8231 /report-def
Illustrative output (one run; timings vary by machine)
healthz #1   200        6 ms
healthz #2   200        7 ms
healthz #3   200        7 ms
report       200     2058 ms
worst healthz while report ran: 7 ms

The health checks are free again, and this fix required no new concepts — the FastAPI fundamentals skill introduced both endpoint kinds. The trade-off is capacity: AnyIO worker threads are shared by every plain def endpoint in the app (limited to 40 tokens by default). Forty concurrent two-second vendor calls fill that pool, and the forty-first waits for a thread — the same stall, one level up. Note that asyncio.to_thread runs on the event loop's default ThreadPoolExecutor instead, sized min(32, os.cpu_count() + 4) on Python 3.12 (3.13 and later count only the CPUs the process may use, os.process_cpu_count()), so they are two separate thread pools with separate ceilings; knowing both limits is what keeps concurrency predictable.

06. Step 5: fix three — use a real async client

When an async version of the library exists, offloading a sync call is treating the symptom. The upstream is plain HTTP, so httpx.AsyncClient can do natively what the SDK does badly. The client belongs to the whole app, created once in the lifespan you met in the FastAPI routers lab — one client, one connection pool, closed on shutdown. The lifespan must exist before app is created, so this step changes the top of the file. Replace lab/app.py with the complete version below: it keeps all four earlier routes, imports asyncio once and creates app once, with the lifespan. Appending a second app = FastAPI(...) at the bottom instead would rebind app and drop the earlier routes:

Python · lab/app.py (complete final version: replace the whole file)
"""Reading-list service whose report endpoint calls a slow vendor."""

import asyncio
from contextlib import asynccontextmanager

import httpx
from fastapi import FastAPI

from vendor import get_cover


@asynccontextmanager
async def lifespan(app: FastAPI):
    app.state.covers = httpx.AsyncClient(timeout=5.0)
    yield
    await app.state.covers.aclose()


app = FastAPI(lifespan=lifespan)


@app.get("/healthz")
async def healthz() -> dict:
    return {"status": "ok"}


@app.get("/report")
async def report() -> dict:
    cover = get_cover("978-0134685991")  # blocks the loop for ~2 s
    return {"report": "reading-list", "cover": cover}


@app.get("/report-thread")
async def report_thread() -> dict:
    cover = await asyncio.to_thread(get_cover, "978-0134685991")
    return {"report": "reading-list", "cover": cover}


@app.get("/report-def")
def report_def() -> dict:
    cover = get_cover("978-0134685991")
    return {"report": "reading-list", "cover": cover}


@app.get("/report-async")
async def report_async() -> dict:
    response = await app.state.covers.get(
        "http://127.0.0.1:8137/services/cover", params={"d": 2.0}
    )
    response.raise_for_status()
    return {"report": "reading-list", "cover": response.json()}
Terminal · probe the async endpoint
.venv/bin/python probe.py http://127.0.0.1:8231 /report-async
Illustrative output (one run; timings vary by machine)
healthz #1   200        9 ms
healthz #2   200        9 ms
healthz #3   200        8 ms
report       200     2040 ms
worst healthz while report ran: 9 ms

The health checks are fast, and — the long-term win — the endpoint is now a first-class coroutine: it can be combined with the task groups, semaphores and timeouts of the previous lesson without any bridging. Prefer this fix whenever the ecosystem gives you the choice; reach for to_thread or a plain def endpoint when it does not.

07. Troubleshooting

08. Check your understanding

Practice check · 3 questions

Reading the evidence

Three follow-ups from the lab.

Q1. A colleague probes four endpoints and records the worst healthz during each: `/report` 2,019 ms, `/report-thread` 11 ms, `/report-def` 38 ms, `/report-async` 11 ms. Which endpoints still block the loop?
Q2. The team load tests `/report-def` with 60 simultaneous requests. Forty requests finish in about 2 s, but the last twenty take about 4 s, while `/healthz` stays fast (11 ms). Most likely cause?
Q3. On a standard CPython build, a new endpoint computes a heavy hash in pure Python code (about 2 s of work) inside `async def`. Moving it to `asyncio.to_thread` keeps health checks fast, but overall throughput barely rises. Why?
Practice only: not graded, not saved, not evidence.

09. Apply it

Add a /report-cpu endpoint that runs about two seconds of real computation inside async def (a pure-Python loop such as sum(i * i for i in range(30_000_000)) is enough; avoid hashlib on a large buffer, because it releases the GIL while hashing and would run in parallel across threads, hiding the effect). Probe it, record the stall, then try the to_thread fix and probe again: health checks should recover, but watch the report time — the computation is not getting faster, and with several reports at once the GIL shows up as rising latencies across the board.

Write up the three numbers (blocked, thread-offloaded, concurrent CPU load) and the conclusion you would give a teammate: for CPU-bound work, the honest fix is a process pool or a worker queue such as the background jobs skill, not threads.

10. Review prompt

Without looking back: describe the probe (what it fires, what it measures, what a blocked loop looks like in its output). Then give the three fixes from this lab with one sentence each on when to choose it, and explain why a plain def endpoint protects the loop but 60 concurrent calls can still stall the service.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

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