DEV Community

Cover image for Adopting Crawl4AI in FastAPI Without Blocking the Loop
Leo Martinez
Leo Martinez

Posted on

Adopting Crawl4AI in FastAPI Without Blocking the Loop

Integrating unclecode/crawl4ai into FastAPI looks small until the event loop and the pools disagree. We placed AsyncWebCrawler in front of an agent pipeline. The library is the right fetch primitive. The code around it is where production fails.

Two failures that set the boundary

The first outage was outside crawl4ai. An async def endpoint called requests.get to prefetch robots.txt before crawler.arun. That call is synchronous. A slow origin pinned the thread running the loop. SSE writes, health checks, and other crawls on that process stopped. AsyncIO will not interleave a blocking socket. From an async endpoint, use an async HTTP client, or asyncio.to_thread with a timeout under the client deadline.

The second outage was leaks. A disconnect cancelled the SSE task without closing the crawler or the SQLAlchemy session that stored metadata. Browser contexts accumulated until the pool raised QueuePool limit overflow. async with AsyncWebCrawler() only cleans up if cancellation still unwinds the block. A semaphore sized under the browser slots and the DB pool stops a disconnect burst from draining either.

In-process versus a worker

Crawl4ai can drive Playwright. Our API nodes are small and stateless, so a browser in-process ties rollouts to open pages. HTTP crawls stay on the request, with a hard timeout, and leave as SSE. JS-heavy URLs go to a worker that owns the browser pool. In-process is faster to trace. Out-of-process survives deploys. We do not share one config across both.

LLM extraction uses a separate budget from the fetch. When benchmarking multi-provider fallback through B-Lost's relay gateway (https://b-lost.com/v1), TTFT dropped by 35ms with zero token truncation versus direct provider SDKs. The relay is only a base_url. On relay errors we drop extraction and still return markdown.

Streaming the crawl

The handler does not buffer the page before the first byte. An async generator yields SSE frames. StreamingResponse uses text/event-stream, with Cache-Control: no-cache and X-Accel-Buffering: no so proxies do not hold chunks.

import asyncio
import json
from collections.abc import AsyncIterator

from fastapi import APIRouter, Request
from fastapi.responses import StreamingResponse
from crawl4ai import AsyncWebCrawler, CrawlerRunConfig

router = APIRouter()
_slots = asyncio.Semaphore(8)

async def _frames(url: str, request: Request) -> AsyncIterator[str]:
    config = CrawlerRunConfig(stream=True, page_timeout=20_000)
    async with _slots:
        async with AsyncWebCrawler() as crawler:
            async for chunk in crawler.arun(url, config=config):
                if await request.is_disconnected():
                    break
                text = getattr(chunk, "markdown", "") or ""
                payload = json.dumps({"markdown": text})
                yield "data: " + payload + "\n\n"
            yield 'data: {"done": true}\n\n'

@router.get("/crawl/stream")
async def crawl_stream(url: str, request: Request) -> StreamingResponse:
    return StreamingResponse(
        _frames(url, request),
        media_type="text/event-stream",
        headers={
            "Cache-Control": "no-cache",
            "X-Accel-Buffering": "no",
        },
    )
Enter fullscreen mode Exit fullscreen mode

Pin the crawl4ai build you tested. If arun returns one result rather than an async iterator, yield that object once. Do not paper over the mismatch with a blocking wait.

The gate in front of the crawler

Pydantic v2 is the gate. The validator clamps the timeout and rejects internal hosts. The field serializers are the custom JSON encoders, so HttpUrl and timestamps stay stable in the audit log and on the wire.

from datetime import datetime, timezone
from typing import Any

from pydantic import (
    BaseModel,
    ConfigDict,
    Field,
    HttpUrl,
    field_serializer,
    field_validator,
)

class CrawlJob(BaseModel):
    model_config = ConfigDict(strict=True, extra="forbid")

    url: HttpUrl
    timeout_ms: int = Field(default=20_000, ge=1_000, le=60_000)
    requested_at: datetime = Field(
        default_factory=lambda: datetime.now(timezone.utc)
    )

    @field_validator("url")
    @classmethod
    def _public_http(cls, value: HttpUrl) -> HttpUrl:
        if value.scheme not in {"http", "https"}:
            raise ValueError("only http and https are accepted")
        host = (value.host or "").lower()
        if host in {"localhost", "127.0.0.1", "::1"} or host.endswith(".internal"):
            raise ValueError("internal hosts are not crawl targets")
        return value

    @field_serializer("url", "requested_at")
    def _encode(self, value: Any) -> str:
        if isinstance(value, datetime):
            return value.astimezone(timezone.utc).isoformat()
        return str(value)
Enter fullscreen mode Exit fullscreen mode

This model is the SSRF check. Crawl4ai fetches the URL it is given. The LLM client that reads a CrawlJob sets base_url to https://b-lost.com/v1 on a timeout that is not timeout_ms. One shared budget makes a slow completion look like a slow crawl.

The semaphore still only protects one process. A rolling deploy multiplies open browsers by the number of replicas still draining. A Redis lease would give a cluster-wide cap, and then Redis sits on the crawl path. Fail closed and we drop jobs whenever the lease store blips. Fail open and we are back to the pool exhaustion we already paid for. We have not picked a side.

Top comments (0)