Back to Community & Earn Hub

Asyncio Event Loop Starvation in FastMCP Python Servers: How to offload CPU-bound PDF/AST parsing without blocking concurrent SSE heartbeats?

@karthik_sundaram7 hours ago 1479 views

We run a Python FastMCP server exposing document-ingestion and code-analysis tools over SSE/HTTP.

The Event Loop Freeze

Several MCP tools perform heavy parsing when invoked by an agent:

python
@mcp.tool()
async def extract_repo_ast(repo_path: str) -> dict:
    # Synchronous CPU-bound parsing of 400 Python/TS files (~4.5 seconds)
    return parse_directory_ast(repo_path)

Because parse_directory_ast() runs synchronously inside async def, it monopolizes the Python asyncio event loop for 4.5 seconds:

  1. All other concurrent agent tool calls stall.
  2. Outbound SSE : keepalive heartbeats stop firing, causing client proxies to drop active connections.
  3. Health checks (/healthz) time out, triggering Kubernetes liveness probe restarts!

I tried wrapping the call in asyncio.to_thread(parse_directory_ast, repo_path), which helps for C-extensions that release the GIL, but pure-Python pypdf parsing still spikes event-loop jitter due to GIL contention.

What is the cleanest pattern in FastMCP/AnyIO to isolate CPU-bound tools in a bounded ProcessPoolExecutor without leaking zombie worker processes on server reload?

1 Answers

Community Answers

@aarav_sharma Accepted Answer7 hours ago

You hit the exact Python concurrency boundary: asyncio.to_thread() (or anyio.to_thread.run_sync) works well for blocking I/O or GIL-releasing C/Rust extensions (like tree-sitter or numpy), but pure-Python CPU work (like pypdf tokenizing 200 pages) holds the GIL, starving the main event loop thread of CPU slices.

Here is the production pattern for offloading pure-Python CPU tools in FastMCP using a lifecycle-managed ProcessPoolExecutor:


1. Manage a Bounded ProcessPoolExecutor in Server Lifespan

Create the pool once on startup with mp_context=multiprocessing.get_context("spawn") (prevents fork-safety deadlocks with async SQLAlchemy/httpx pools) and shut it down cleanly on SIGTERM:

python
import asyncio
import multiprocessing
from concurrent.futures import ProcessPoolExecutor
from contextlib import asynccontextmanager
from fastmcp import FastMCP

CPU_POOL: ProcessPoolExecutor | None = None

# Top-level picklable worker function (must be importable at module scope)
def _cpu_parse_pdf_sync(file_bytes: bytes) -> dict:
    import pypdf, io
    reader = pypdf.PdfReader(io.BytesIO(file_bytes))
    text = "
".join(page.extract_text() or "" for page in reader.pages)
    return {"pages": len(reader.pages), "chars": len(text), "text": text}

@asynccontextmanager
async def lifespan(app):
    global CPU_POOL
    ctx = multiprocessing.get_context("spawn")
    CPU_POOL = ProcessPoolExecutor(max_workers=4, mp_context=ctx)
    try:
        yield
    finally:
        # Cancel pending futures and terminate workers cleanly on reload
        CPU_POOL.shutdown(wait=True, cancel_futures=True)

mcp = FastMCP("doc-analyzer", lifespan=lifespan)

@mcp.tool()
async def parse_pdf_document(file_path: str) -> dict:
    # 1. Read bytes asynchronously (never block loop on disk I/O)
    with open(file_path, "rb") as f:
        raw_bytes = f.read()

    # 2. Dispatch CPU parsing to separate OS process -> 0% GIL impact on event loop!
    loop = asyncio.get_running_loop()
    return await loop.run_in_executor(CPU_POOL, _cpu_parse_pdf_sync, raw_bytes)

2. Add a Concurrency Semaphore to Prevent OOM

Always cap concurrent process-pool submissions with an asyncio.Semaphore(8) so a burst of 20 simultaneous agent PDF calls queues gracefully instead of spiking memory or timing out /healthz.

With spawn + run_in_executor + cancel_futures=True, your Uvicorn event loop stays under 1ms event-loop lag even under heavy PDF/AST workloads, keeping SSE heartbeats and health probes 100% responsive.

Have a solution or working configuration?

Sign in or create a free account to answer this question (+10 pts, +25 pts if accepted) and tag helpful AIStoreHub repositories.