Skip to content

Deadlines

Bound how long a request may run before its work is cancelled and the client receives HTTP 504 Gateway Timeout.

Route-level deadlines

from paceapi import Deadline
from paceapi.integrations.starlette import DeadlineMiddleware
reports = Deadline(5)
everything = Deadline(30)
# Route-level deadline: cancels the handler and returns 504 if exceeded.
@app.get("/reports/{month}")
@reports.enforced()
async def report(month: str) -> dict[str, object]:
    return await db.report(month)

Place @deadline.enforced() below the route decorator. The timer spans endpoint invocation through return. On timeout, the task is cancelled and DeadlineExceeded (HTTP 504) is raised:

{"detail": "The request took longer than its deadline of 5 seconds."}

Full example: examples/deadline.py.

Code that enforces a time limit itself can raise DeadlineExceeded directly, adding response headers with headers=:

@app.get("/reports/{month}")
async def report(month: str) -> dict[str, object]:
    try:
        async with asyncio.timeout(upstream.seconds):
            return await db.report(month)
    except TimeoutError:
        # The same 504 as @upstream.enforced(), plus an extra header.
        raise DeadlineExceeded(upstream, headers={"Retry-After": "30"}) from None

App-wide deadline middleware

# App-wide safety net: bounds time to first response headers across middleware,
# dependencies, and endpoints.
app.add_middleware(DeadlineMiddleware, deadline=everything)

DeadlineMiddleware bounds time-to-first-response-headers (including route dependencies and inner middleware). Once response headers are sent, the deadline ends—streaming bodies are not cut off mid-stream.

Pair a generous app-wide deadline (safety net) with tighter route-level deadlines on specific endpoints.

  • Handlers are bypassed: The middleware's 504 is generated outside the app, so app exception handlers are not invoked (unlike @deadline.enforced()).
  • Request bodies count: The timer starts when the request arrives, so slow uploads and long-polling endpoints are cut off with 504 at the deadline.

Limitations

  • Uncancellable work: Code that suppresses CancelledError, shields tasks, or blocks the event loop without yielding cannot be interrupted immediately. Under @enforced(), a blocking endpoint that finishes returns its normal response rather than 504; under DeadlineMiddleware, once the loop unblocks, the response is discarded and 504 is sent (shielded tasks continue running).
  • Thread-pool endpoints: @enforced() rejects synchronous def endpoints at decoration time because worker threads cannot be cancelled cleanly, including sync endpoints wrapped by @limit.held() or @ns.response. Any async wrapper whose __wrapped__ or functools.partial chain ends in a sync function is rejected the same way, because it may run that function in a thread. Work offloaded to threads from async endpoints likewise continues after 504.
  • Already-started streams: Returning a StreamingResponse before the deadline satisfies the deadline regardless of stream duration.
  • Starlette < 1.0 + BaseHTTPMiddleware: Placing DeadlineMiddleware outside a BaseHTTPMiddleware (including @app.middleware("http")) cancels generator-dependency teardown at its first await on timeout. Place DeadlineMiddleware inside BaseHTTPMiddleware or avoid critical async cleanup in yield dependencies on Starlette < 1.0.

Interaction with rate-limiter stores

When DeadlineMiddleware wraps a rate limit and cancels a request while it is waiting on a hung store (for example when the request deadline is shorter than store_timeout), that cancellation counts as a store timeout toward the limiter's circuit breaker and observers—provided the store received at least half of the request's deadline budget. Requests that spent most of their budget in earlier work or pool queueing do not falsely blame a healthy store (see Failure modes). The cancellation must also reach the limiter within 100 ms of the deadline; a store client that takes longer than that to release a call is governed by store_timeout alone.

Testing and debugging

Use with deadline.disabled(): in tests or debugger sessions, or construct Deadline(5, enabled=False).

enabled= can be set from configuration:

reports = Deadline(settings.report_seconds, enabled=settings.deadlines_on)