Skip to content

Setting up the broker before the web server starts

Inside a FastPluggy app you normally do nothing: the plugin's on_load_complete starts the broker in a background thread, so a slow or unreachable broker does not block page rendering.

Call TaskWorker.setup_broker() yourself only when you need the broker ready before the first request, or want to apply per-topic concurrency limits at boot. It builds the configured broker, runs its setup() hook, applies topic_settings, and returns the broker (or None when BROKER_TYPE=none). Setup errors are logged, not raised.

FastAPI lifespan

from contextlib import asynccontextmanager

from fastapi import FastAPI
from fastpluggy_plugin.tasks_worker import TaskWorker


@asynccontextmanager
async def lifespan(app: FastAPI):
    # Safe in every uvicorn worker: the LocalBroker reuses a live sibling's server.
    app.state.broker = TaskWorker.setup_broker(
        topic_settings={"ocr": {"global_concurrency": 1}},  # optional
    )
    yield


app = FastAPI(lifespan=lifespan)

uvicorn main:app --workers 4 works with the local broker: the first worker spawns fp-brokerd and the others reuse it (see technical.md). The backend is chosen by TasksRunnerSettings.BROKER_TYPE (default local).