Skip to content

Concurrency limits

While rate limits bound frequency (requests per period), concurrency limits bound in-flight parallelism—protecting finite resources like database connection pools, slow upstreams, or worker memory.

Route-level concurrency limits

from paceapi import ConcurrencyLimit
# Ten reports at once, in this process. A request that finds all ten places held waits
# up to half a second for one before it is turned away.
reports = ConcurrencyLimit(10, wait=0.5)
# Two exports at once for each user, and no waiting.
exports = ConcurrencyLimit(2)
# A report holds a database connection for seconds. Only so many are built at once:
# one more waits a moment for a place, and is then answered 503 with Retry-After.
@app.get("/reports/{month}")
@reports.held()
async def report(month: str) -> dict[str, object]:
    return await db.report(month)

# Each user may have only so many exports on the go. The place is held until the
# last line has been sent, and let go if they stop listening.
@app.get("/export")
@exports.held(key="user")
async def export(user: Annotated[str, Depends(current_user)]) -> StreamingResponse:
    return StreamingResponse(db.orders_of(user), media_type="text/csv")

Place @limit.held() below the route decorator. A slot is acquired before the endpoint runs and released when it completes. Placed above the route decorator it has no effect and raises no error, because FastAPI has already registered the undecorated endpoint.

Slots are acquired after route dependencies resolve. A request that fails authentication never takes a slot, but anything a Depends(...) opens (such as a database session) is not bounded by the limit: 30 concurrent requests against ConcurrencyLimit(10) still open 30 sessions. Open the protected resource inside the endpoint, or use ConcurrencyLimitMiddleware, which acquires before the app runs.

Full example: examples/concurrency_limit.py.

Rejection response (503)

When no slot is available, paceapi raises ConcurrencyLimitExceeded (an HTTPException, customizable via exception handler), returning HTTP 503 with Retry-After (default 1s, configurable via retry_after=):

{"detail": "Too many requests in flight. Try again in 1 second."}

Bounded queueing (wait=)

Pass wait= (seconds) to queue requests briefly in strict FIFO order instead of rejecting immediately. Cancelled waiters leave the queue right away. Keep wait= short—queued requests keep open sockets and route dependencies alive while waiting.

Per-caller concurrency limits (key=)

Pass key= (an endpoint parameter name or callable over endpoint parameters) to enforce an independent concurrency limit per caller (e.g., 2 concurrent exports per user).

  • Returning None raises MissingKeyError by default; pass on_missing_key="skip" to bypass the limit for missing keys.
  • State is only stored while a caller has active or queued requests, so idle callers consume zero memory.

With on_missing_key="skip", a request whose key is None runs without taking a slot:

# One pool of slots per signed-in user. A request with no user takes no slot.
@app.get("/export")
@exports.held(key="user", on_missing_key="skip")
async def export(user: Annotated[str | None, Depends(signed_in)]) -> list[str]:
    return await db.orders_of(user)

Slot release lifecycle

  • Endpoints returning plain values/models: released when the endpoint returns.
  • Endpoints returning a Response / StreamingResponse: released after the final body chunk and background task complete, or when the client disconnects.
  • Cancelled or errored requests: always released before request exit.
  • Sync (def) endpoints: run in a worker thread that cannot be cancelled, so the slot stays held until the thread finishes, even if the request was cancelled first (for example by a deadline).

When combining with @ns.response, place @ns.response above @limit.held() so cache hits do not consume concurrency slots.

App-wide middleware

app.add_middleware(ConcurrencyLimitMiddleware, limit=busy)

ConcurrencyLimitMiddleware (imported from paceapi.integrations.starlette) takes a ConcurrencyLimit such as busy = ConcurrencyLimit(50, wait=0.5) and caps in-flight HTTP requests across the whole app (releasing after the last response byte). Its key= receives the HTTPConnection (e.g., client_ip or RequestHeader). WebSockets pass through untouched.

The middleware's 503 is generated outside the app, so app exception handlers are not invoked (unlike @limit.held()). To exempt a route such as a health check, see Always-answered routes.

Scope and limitations

  • Process-local: With 4 workers, a limit of 10 permits up to 40 in-flight requests total—size limits per worker.
  • Generators and WebSockets: @limit.held() rejects async-generator endpoints and WebSockets at decoration time (return StreamingResponse to stream under a concurrency limit).
  • Observability: Rejections are not sent to observers; inspect limit.in_flight for current usage.

Testing and standalone usage

  • Disable in tests with with limit.disabled(): or ConcurrencyLimit(10, enabled=False).
  • Acquire manually outside HTTP routes with slot = await limit.acquire() (returns None when saturated) and slot.release() (see ConcurrencyLimit).

enabled= can be set from configuration:

reports = ConcurrencyLimit(10, enabled=settings.concurrency_limits_on)

Code that acquires a slot itself can raise ConcurrencyLimitExceeded when none is free, adding response headers with headers=:

@app.get("/reports/{month}")
async def report(month: str) -> dict[str, object]:
    slot = await reports.acquire()
    if slot is None:
        # The same 503 and Retry-After as @reports.held(), plus an extra header.
        raise ConcurrencyLimitExceeded(reports, headers={"X-Limited-By": "reports"})
    try:
        return await db.report(month)
    finally:
        slot.release()