Routers & Decorators
Two decorators connect your viewset classes to the outside world:
route_viewset— registers a viewset on a FastAPI router (HTTP endpoints)celery_viewset— moves a viewset's execution to a Celery worker (transparent task delegation)
Both decorators follow the same class-decoration pattern and can be combined: the same viewset class is decorated with celery_viewset in the worker process and with route_viewset in the FastAPI process.
route_viewset
Collects all routes defined by the mixin hierarchy, resolves generic type parameters, and registers them on a FastAPI APIRouter.
Signature
def route_viewset(
router: APIRouter,
base_path: str,
lifecycle: LifecycleType = "singleton",
pk_field_name: str | None = None,
register_muxws: bool | None = None,
register_rest: bool | None = None,
) -> Callable[[type], type]:Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
router | APIRouter | — | The FastAPI router to register routes on, for REST and muxws alike; include it in the application |
base_path | str | — | URL prefix for all endpoints, e.g. "/items" |
lifecycle | LifecycleType | "singleton" | Instance lifecycle — see ViewSet Lifecycle |
pk_field_name | str | None | None | Name of the PK field; when set, a POST request body does not carry it — see below |
register_muxws | bool | None | None | Publish on the muxws transport; None defers to settings.viewsets_register_muxws |
register_rest | bool | None | None | Publish on REST; None means yes |
Usage
from fastapi import APIRouter
from fastapi_viewsets.decorators.route_viewset import route_viewset
router = APIRouter()
@route_viewset(router, base_path="/items", pk_field_name="id")
class ItemViewSet(CollectionViewSet[int, Item], BulkViewSetMixin[int, Item]):
def __init__(self):
super().__init__(container=database, pk_field="id")Lifecycle modes and state hooks
lifecycle controls how the viewset class becomes the instance that handles a request ("singleton", "per-request", or "instance-key"), and whether that instance's own load_state()/save_state() hooks get called around each request. This is its own dedicated topic — see ViewSet Lifecycle for the full picture, including the race-condition caveat and a worked example.
Response-level side effects: Command Middleware
An action's return value is JSON-serializable data — but sometimes an endpoint needs to affect the response itself (most commonly: setting a cookie), not just the response body. This matters especially when the action is also wired through celery_viewset: the method body may run in a Celery worker, which has no live Response object at all (and its return value must survive a JSON round trip through Redis), so the response-level side effect has to be applied separately, once the result is back in the FastAPI process.
Command middleware is the mechanism for this: a middleware in settings.viewsets_command_middleware can inspect/replace the ViewSetResult that call_next() returns and set .headers/.cookies (set_cookie(), delete_cookie()) on it - route_viewset applies those onto the real Response once the result is back in the FastAPI process, regardless of whether the action ran in-process or was celery_viewset-dispatched to a worker. An endpoint returns a ViewSetResult itself for the same. See the Command Middleware guide for the full picture.
Automatic OpenAPI tags
The decorator derives an OpenAPI tag from the class name with default_tag_name(cls) (fastapi_viewsets.decorators):
- The
ViewSetsuffix is removed. An empty remainder gives the routes no tag. - The remainder is split into words. Underscores separate words, as do a lowercase letter or digit followed by an uppercase letter and the last uppercase letter of an uppercase run followed by a lowercase letter.
- A word with at least two uppercase letters is an acronym and stays as it is; every other word is lowercased.
- The words are joined with single spaces and the first character is uppercased.
| Class | Tag |
|---|---|
ItemViewSet | Item |
UserProfileViewSet | User profile |
APIKeyViewSet | API key |
HTTPSProxyURLViewSet | HTTPS proxy URL |
IPv4AddressViewSet | I pv4 address |
OAuthTokenViewSet | O auth token |
URLsViewSet | UR ls |
A word that mixes cases within itself (IPv4, OAuth) or a plural acronym (URLs) is split at its case changes, as the last rows show.
settings.viewsets_tag_name replaces this rule. It receives the viewset class and returns the tag; an empty string gives the routes no tag. The tag is used for the routes, for the operations of /schema, for the tag description and for the muxws registration. A function that names only some classes returns default_tag_name(cls) for the others:
from fastapi_viewsets.conf import settings
from fastapi_viewsets.decorators import default_tag_name
TAG_NAMES = {"IPv4AddressViewSet": "IPv4 address", "OAuthTokenViewSet": "OAuth token"}
def tag_name(cls: type) -> str:
return TAG_NAMES.get(cls.__name__) or default_tag_name(cls)
settings.viewsets_tag_name = tag_nameThe tag is also part of the Swagger UI deep-link anchors of the group's operations, the key of the group in apply_viewset_tags(app, extra=...) and the tag a custom route passes in tags=[...] to join the group.
The setting is read when a viewset is decorated, so it is assigned before the modules that declare the viewsets are imported.
A sub-viewset takes the tag of the viewset at the top of its mounts.
Route ordering
Routes are registered most specific first, so a literal segment is matched before {pk} would take it:
/items/bulk,/items/lookupand other literal paths — bulk operations, lookup, custom endpoints/items/{pk}— retrieve / update / destroy/items— list / create
Within one path the order is DELETE, PATCH, PUT, POST, GET.
The viewsets a class mounts with ViewSetRouter.sub_viewset are registered before all of these, so /items/{pk} never takes a mounted /items/archive; see Nested Viewsets.
pk_field_name and request body
When pk_field_name is set, the body of a POST route without {pk} in its path is a subclass of the model in which the primary key is not in the JSON schema and is None. The body leaves the primary key out or gives it as null; any other value answers 422 with the field error fastapi-viewsets.pk_assigned_by_server. The server assigns the primary key.
Every other field is validated as the model declares it: its annotation, Field constraints and alias, the model's model_config and its validators. The endpoint receives the model itself, without the primary key unless the model gives it a default; its model_fields_set names the fields the body stated.
A validator of the primary key runs as follows:
- a
@field_validatorof the primary key inaftermode does not run; - one in
before,wraporplainmode runs on a value other than null, which is then rejected; - a
@model_validatorinaftermode sees the primary key as None.
celery_viewset
Moves the execution of a viewset's actions, all of them or the ones include / exclude select, to a Celery worker. The decorator auto-detects the execution context and applies the correct mode:
- FastAPI process (client mode) — replaces the methods of the deferred actions with async wrappers that send Celery tasks and await results via a Redis result queue.
- Celery worker process (server mode) — registers each deferred action as a named Celery task that runs the actual implementation.
The same decorator call works in both processes — no conditional code needed in your application.
A viewset whose data lives in process memory, such as a CollectionViewSet, has one copy of it per worker process.
Signature
def celery_viewset(
celery_app: Celery,
task_prefix: str,
lifecycle: LifecycleType = "singleton",
redis_client: redis.Redis | None = None,
result_timeout: float | None = 3600.0,
include: Iterable[str | re.Pattern[str]] | None = None,
exclude: Iterable[str | re.Pattern[str]] | None = None,
) -> Callable[[type], type]:Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
celery_app | Celery | — | The Celery application instance |
task_prefix | str | — | Prefix for all registered Celery task names, e.g. "items" |
lifecycle | LifecycleType | "singleton" | Instance lifecycle on the worker side (same semantics as route_viewset — see ViewSet Lifecycle) |
redis_client | redis.Redis | None | None | Redis client used to pass results back to FastAPI. Required in both modes; without it the decorator raises ValueError. |
result_timeout | float | None | 3600.0 (DEFAULT_RESULT_TIMEOUT) | Client mode: seconds a call waits for its result before it raises ResultTimeoutError (504, fastapi-viewsets.result_timeout). None waits without a limit. Ignored in worker mode. |
include | Iterable[str | re.Pattern[str]] | None | None | The actions that run in the worker; every other action runs in the FastAPI process. See Choosing the deferred actions |
exclude | Iterable[str | re.Pattern[str]] | None | None | The actions that run in the FastAPI process; every other action runs in the worker. With neither include nor exclude, every action runs in the worker |
Usage
The same class definition is used in both processes. The decorator is typically applied in viewsets.py and imported by both main.py (FastAPI) and celery_worker.py:
# viewsets.py
from fastapi_viewsets.decorators.celery_viewset import celery_viewset
from fastapi_viewsets.collection_viewset import CollectionViewSet
from fastapi_viewsets.mixins import BulkViewSetMixin
database = {}
@celery_viewset(celery_app, task_prefix="items", redis_client=redis_client)
class ItemViewSet(CollectionViewSet[int, Item], BulkViewSetMixin[int, Item]):
def __init__(self):
super().__init__(container=database, pk_field="id")# main.py (FastAPI) — also applies route_viewset on top
from .viewsets import ItemViewSet
from fastapi_viewsets.decorators.route_viewset import route_viewset
@route_viewset(router, base_path="/items", pk_field_name="id")
class ItemViewSet(ItemViewSet): ...# celery_worker.py — importing viewsets.py is enough; tasks are registered as a side-effect
import myapp.viewsets # noqa: F401
from myapp.celery_app import celery_app
app = celery_appChoosing the deferred actions: include and exclude
An action that runs in the worker is deferred; an action that runs in the FastAPI process is local. include names the deferred actions, exclude the local ones. One viewset then keeps one route table, one /schema and its URLs, while only its heavy actions run in Celery:
import re
@celery_viewset(
celery_app,
task_prefix="members",
redis_client=redis_client,
include=[re.compile(r"bulk_.*"), "export_pdf"],
)
class MemberViewSet(AdormViewSet[int, Member], BulkViewSetMixin[int, Member]):
model = Member
__router = APIRouter()
@__router.get("export-pdf")
async def export_pdf(self, context: Context) -> Response: ...list_items, retrieve, create, update, partial_update and destroy run in the FastAPI process; the four bulk actions and export_pdf in the worker. exclude=["list_items", "retrieve"] instead keeps those two local and defers every other action, a custom action added later included.
An entry is one of:
| Entry | Matches |
|---|---|
str | The action with exactly this name; the string has no pattern semantics |
re.Pattern[str] | Every action whose name the pattern matches whole (fullmatch) |
An action's name is its route's name, the method's name unless the route states one, the same name the task is named by (see Task naming): list_items for every list mixin, retrieve, create, bulk_create, update, partial_update, bulk_update, bulk_partial_update, destroy, bulk_destroy, lookup, and the method name of a custom endpoint.
The decorator raises ValueError when both include and exclude are given, and when a string names no action of the class or a pattern matches none; the message names the entry and lists the class's action names. Both processes resolve the entries the same way: the FastAPI process patches only the methods of the deferred actions, and the worker registers tasks only for them.
A local action is an ordinary action of the viewset: Middleware.execute() runs around it once, in the FastAPI process, and executor_started() and on_transition() are not called for it. It has no time limits.
Calls between the actions of one class follow the patched methods:
- a local action that calls
self.<deferred action>()dispatches that action's task; - a deferred action that calls
self.<local action>()in the worker runs it in the worker, since the worker patches no method.
Context auto-detection
The decorator detects the execution context by inspecting sys.argv:
- If
"celery"appears insys.argv[0]→ server mode (worker) - Otherwise → client mode (FastAPI)
For explicit control (e.g. in tests), use set_is_celery_worker():
from fastapi_viewsets.decorators.celery_viewset import set_is_celery_worker
set_is_celery_worker(True) # force worker mode
set_is_celery_worker(False) # force client modeTask naming
Each deferred action is registered as a Celery task named {task_prefix}.{route_name}, the route's name, which is the method's name unless the route states one:
| Method | Task name (prefix "items") |
|---|---|
list_items | items.list_items |
retrieve | items.retrieve |
create | items.create |
update | items.update |
partial_update | items.partial_update |
destroy | items.destroy |
bulk_create | items.bulk_create |
bulk_update | items.bulk_update |
bulk_partial_update | items.bulk_partial_update |
bulk_destroy | items.bulk_destroy |
lookup | items.lookup |
Result passing
Results are passed from the worker back to FastAPI via a Redis list (not via the Celery result backend). Each call is correlated with a UUID so that concurrent requests are handled correctly.
Each FastAPI process receives its results on its own list, {queue_key}:{host name}:{process id} (get_process_queue_key(queue_key)): the task carries the list of the process that dispatched it, and that process's reader pops it. Any number of FastAPI processes, on any number of hosts, can share one Redis. The worker pushes a result with RPUSH and EXPIRE in one round trip: every push renews the list's expiry to one hour, so the list of a process that has exited is removed from Redis. In the async processes of Celery with async tasks (see Async processes) the push runs on the event loop with a redis.asyncio client built from the connection settings of redis_client, one per event loop; the other pools push with redis_client.
A call raises ResultTimeoutError (504, fastapi-viewsets.result_timeout) when its result does not arrive within result_timeout seconds, one hour by default. Every outcome the worker observes reaches the caller as soon as it happens (see Outcomes of a call); result_timeout covers what the worker cannot observe: a supervisor process that is itself killed, or a task message that cannot be decoded.
A call pending when stop_result_reader stops the reader of its queue_key, or when that reader task is cancelled, raises ResultReaderStoppedError (503, fastapi-viewsets.result_reader_stopped, param queue_key). A cancelled call removes its pending entry; its result, if the worker still sends one, is logged as having no pending call and dropped.
Arguments and results cross as the types the action declares; see Arguments and results.
Dispatch
A call publishes its task without blocking the event loop. When the Celery app has Celery.asend_task (the Celery of velis74/celery provides it), the call awaits celery_app.asend_task(...): with a Redis broker it pushes the message from the event loop and sends the tasks published in one iteration of the event loop to Redis in one pipeline; with any other broker it runs send_task in a worker thread. Without asend_task, the call runs send_task in a worker thread, so a slow broker does not block the event loop.
The task message's argsrepr is (...), or () for an action without arguments, and its kwargsrepr holds only the call's correlation id ({'_correlation_id': '<id>'}): the arguments are not rendered for the worker's log or for monitoring tools. A publish that fails raises ActionDispatchError (reason send).
Result readers
A result reader background task must be started in the FastAPI lifespan for each queue_key (i.e. each distinct task_prefix used by a celery_viewset-decorated class) — start_result_reader keeps one reader task per queue_key, so calling it once per prefix is required and sufficient. Every celery_viewset_client decorator registers its own queue_key at import time (before lifespan ever runs), so instead of maintaining your own list of prefixes, iterate get_registered_queue_keys() — it can't drift out of sync with your actual viewsets:
from fastapi_viewsets.decorators.celery_viewset import (
check_result_readers, get_registered_queue_keys, start_result_reader, stop_result_reader,
)
@asynccontextmanager
async def lifespan(app: FastAPI):
for queue_key in get_registered_queue_keys():
await start_result_reader(redis_client, queue_key)
check_result_readers() # logs a warning for any queue_key that still has no running reader
yield
await stop_result_reader() # stops all readers; pass a queue_key to stop just oneThe reader waits on its process's list with BLPOP, two seconds at a time, so it notices a lost connection, and then takes every result already in the list with LPOP key count; results resolve in the order they were pushed. LPOP with a count needs Redis 6.2 or later; on an older server the reader takes one result per LPOP. While it waits, the reader holds one connection of the client passed to start_result_reader (redis-py's default pool allows 100 connections in current versions): its pool needs room for one connection per reader beside the application's own use, and its socket_timeout, if set, must be longer than two seconds. start_result_reader(redis_client, queue_key, poll_interval=0.05): poll_interval is the number of seconds the reader pauses after a Redis error before it reads again.
One reader per queue_key, not automatic
start_result_reader(redis_client, queue_key) starts (and reuses) exactly one reader task per queue_key — calling it for a new queue_key always starts an additional reader; it never replaces or interferes with readers for other keys. But nothing starts a reader for a prefix you never call it for: if your app has more than one celery_viewset-decorated class with different task_prefix values (a very common shape) and you forget to start a reader for one of them, results for it are never picked up — the Celery task runs fine, but the client-side await on the result waits until result_timeout passes and raises ResultTimeoutError. check_result_readers() is a safety net for exactly this: it compares every registered queue_key against the ones with an actual running reader and logs "No result reader is running for queue_key=..." for each mismatch — call it once, right after starting your readers in lifespan, so a missing reader shows up as a log line at startup instead of as timed-out requests.
Arguments and results
An action receives in the worker, and its caller receives back, values of the types they have when the action runs in the FastAPI process. Both processes encode and decode them by the action's type hints (TypeVars of a generic viewset resolved against the decorated class, Annotated metadata included), with a pydantic TypeAdapter built once per hint; the task message is JSON.
| Value | How it crosses |
|---|---|
| A model, an optional model, a list or tuple of models | Dumped by field name, validated as its model in the worker. A create body crosses without its primary key and a partial update body with the fields the request stated; the action receives them as it does in the FastAPI process |
Any other annotation (date, datetime, time, timedelta, UUID, Decimal, enums, Literal, set, frozenset, tuple, paths, unions, collections of these, a model inside a collection, a type of your own) | Dumped in pydantic's JSON mode, validated from JSON with the same hint. An Any inside the annotation crosses as an unannotated value |
bytes (also inside unions and collections) | Base64. Inside a model, the model's own ser_json_bytes / val_json_bytes configuration applies |
UploadFile (also list[UploadFile]) | Read whole in the FastAPI process (in a worker thread) and rebuilt in the worker as a Starlette UploadFile with the same filename, headers (and so content_type), size and content, positioned at its start, readable and seekable. Content above 1 MiB is spooled to a temporary file |
Request (any parameter annotated with it) | Its ASGI scope without the body, as the request parameter (see Call data in the worker) |
A SerializableObject, at any depth of lists and dicts | Its __serialize__ payload, rebuilt with __deserialize__ |
None | null, whatever the annotation |
No annotation, Any | to_jsonable(): the JSON form, with every SerializableObject in it rebuilt |
| An annotation pydantic cannot validate | Refused: the call fails |
A value its annotation does not describe (a datetime declared date, a dict declared as a model in a collection) | Refused: the call fails |
The result crosses by the value the action returns:
| Result | How it crosses |
|---|---|
A Response whose body is in memory (Response, JSONResponse, HTMLResponse, PlainTextResponse, RedirectResponse and their subclasses) | Its class, status code, raw headers (Set-Cookie, Content-Disposition, Content-Length included), body and media type, unchanged. A subclass defined inside a function crosses as its nearest importable base class |
A ViewSetResult | Its status code, headers and cookies (a Cookie or DeleteCookie with all of its options), and its body by the type argument of the -> ViewSetResult[X] annotation |
| Any other value | By the return annotation, -> ViewSetResult[X] read as X, as an argument by its parameter's annotation: refused when the annotation is one pydantic cannot validate or does not describe the value |
A value annotated by its type validates again in the worker, so its validators run in both processes. A pydantic model's fields are encoded by the model itself.
Some values exist only in the process that holds them, and are refused whatever the annotation:
| Value | Why |
|---|---|
WebSocket | A connection held open by the FastAPI process |
BackgroundTasks, or a Response with a background task | Background tasks run in the FastAPI process after the response is sent |
StreamingResponse | Its body is produced by an iterator in the process that returned it |
FileResponse | Its body is a file read from the file system of the process that returned it |
A refused argument fails the call with ActionDispatchError (reason serialization) and nothing is sent; a refused result fails it with ActionFailedError (reason result). The error's __cause__, which is logged, is a TypeError naming the action and the parameter or the result, and the declared type and the value's type, or the reason the value does not cross.
Uploads travel through the broker
An UploadFile argument is base64-encoded into the task message: the broker stores about 4/3 of the file's size, and the FastAPI process and the worker each hold the encoded content in memory while they encode and decode it. FastAPI has received the whole upload before the action is called, so a size check in the action runs in the worker, after the content has crossed. Bound the size of a request body at the server or proxy in front of the application (e.g. nginx client_max_body_size), and keep actions that accept large files local with exclude.
Types of your own
A class of the application's own crosses when it declares its pydantic schema with __get_pydantic_core_schema__, encoding itself in JSON mode and accepting that encoding back:
from pydantic_core import core_schema
class Money:
def __init__(self, cents: int, currency: str):
self.cents, self.currency = cents, currency
@classmethod
def __get_pydantic_core_schema__(cls, _source, _handler):
return core_schema.no_info_plain_validator_function(
lambda value: value if isinstance(value, cls) else cls(value["cents"], value["currency"]),
serialization=core_schema.plain_serializer_function_ser_schema(
lambda money: {"cents": money.cents, "currency": money.currency}, when_used="json"
),
)
@celery_viewset(celery_app, task_prefix="payments", redis_client=redis_client)
class PaymentViewSet:
__router = APIRouter()
@__router.post("pay")
async def pay(self, amount: Annotated[Money, Depends(read_amount)]) -> Money: ...A class the application does not own crosses when the annotation carries the conversion:
from pydantic import PlainSerializer, PlainValidator
ColorParam = Annotated[
Color,
PlainValidator(lambda value: value if isinstance(value, Color) else Color(value)),
PlainSerializer(lambda color: color.hex, when_used="json"),
]
async def paint(self, color: Annotated[ColorParam, Depends(read_color)]) -> ColorParam: ...A value without an annotation, or annotated Any, crosses as a SerializableObject subclass, which encodes itself with __serialize__ and is rebuilt with __deserialize__:
class Token(SerializableObject):
def __serialize__(self):
return {"key": self.value.key}
@classmethod
def __deserialize__(cls, data):
return cls(load_token(data["key"]))
async def revoke(self, token: Any = Depends(read_token)) -> None: ...Low-level decorators
For explicit control over which mode is applied, use the low-level decorators directly:
| Decorator | Use in |
|---|---|
celery_viewset_client | FastAPI process only |
celery_viewset_server | Celery worker process only |
from fastapi_viewsets.decorators.celery_viewset import celery_viewset_client, celery_viewset_serverBoth take the same include and exclude parameters as celery_viewset, and resolve them the same way.
Result queue helpers
| Function | Description |
|---|---|
get_result_queue_key(task_prefix) | The queue key of a prefix, which start_result_reader takes |
get_process_queue_key(queue_key) | The Redis list this process receives a queue key's results on |
get_registered_queue_keys() | Every queue key a celery_viewset_client registered |
get_running_queue_keys() | The queue keys that have a running reader task |
push_result(redis_client, queue_key, correlation_id, result=None, error=None, task=None) | Pushes a result or an error for one call to queue_key, the _result_queue_key the task carries, and renews the list's expiry. An HTTPException or RequestValidationError error reaches the caller as it is; any other error as ActionFailedError naming task |
Call data in the worker
Every task carries, beside the action's own arguments, the call's data under reserved kwargs:
| Kwarg | Content |
|---|---|
_context | The call's context, serialized whether or not the action declares a context parameter. A LazyObject crosses as its recipe, resolved only where it is awaited |
_request | The call's ASGI scope without the body: method, path, query string, headers, path parameters, client and server address |
_parent | The ExecutionRef of the execution in which the call was dispatched |
_untyped | The names of the arguments that crossed untyped (see Arguments and results); absent when there are none |
_correlation_id, _result_queue_key | Where the result goes (see Result passing) |
The worker consumes them before the action is called. An action that declares context receives the call's context, and one that declares request receives a Request built from the scope, which has no body, no app and no state. Middleware.execute() receives both either way.
A call made from inside another action's execution (an action calling a celery_viewset method) carries that execution's context and request, unless it passes a context of its own, and that execution as its parent. A call made outside any call carries an empty context and no request.
A call whose arguments cannot be serialized raises ActionDispatchError (503, fastapi-viewsets.action_dispatch_failed, reason serialization), and a call whose task cannot be sent raises it with reason send; the error that prevented the dispatch is its __cause__. The scope key of a call of a scoped class is resolved before the arguments are serialized; an exception of its resolver propagates unchanged and no task is sent.
Outcomes of a call
No Celery, billiard or kombu exception reaches the caller, Middleware.execute() or the action's own except clauses at the points listed below; each outcome arrives as one of this package's errors (see Error Codes):
| What happens | Caller receives | Observed in the worker by |
|---|---|---|
| The action returns | its result | execute() |
The action raises an HTTPException | that exception: a DfViewSetError of a class fastapi_viewsets.exceptions defines keeps its class, code, params and headers, any other one is rebuilt as HTTPException or DfViewSetError with the same fields | execute() |
The worker finds the request invalid (RequestValidationError, e.g. a filter value that does not convert) | that RequestValidationError, answered 422 fastapi-viewsets.validation_failed | execute() |
The action raises Django's ValidationError | a RequestValidationError with its field errors; the response is 422 fastapi-viewsets.validation_failed | execute() |
The action raises anything else (a Celery Retry, Ignore or Reject included), or an argument fails validation in the worker | ActionFailedError (500, reason error); the original error is logged in the worker | execute() |
| The result cannot be serialized (see Arguments and results), or deserialized by the caller | ActionFailedError (500, reason result) | — |
| Soft time limit | ActionInterruptedError (504, reason time_limit) | execute() (ActionInterruptedError from call_next()) |
| Hard time limit | ActionInterruptedError (504, reason time_limit) | on_transition("interrupted"); in a gevent pool and an async process also execute() (ActionInterruptedError from call_next()) |
revoke(..., terminate=True) | ActionInterruptedError (503, reason terminated) | on_transition("interrupted"); in an async process also execute() (ActionInterruptedError from call_next()) |
| The worker process exits | ActionInterruptedError (503, reason lost) | on_transition("interrupted") |
SystemExit or KeyboardInterrupt ends the execution in a process no supervisor outlives (any pool but prefork) | ActionInterruptedError (503, reason terminated) | execute() (SystemExit / KeyboardInterrupt from call_next()), then on_transition("interrupted") from that process |
| Revoked or expired before it started | ActionDispatchError (503, reason revoked / expired) | on_transition("not_run") |
The worker has no task of that name under a registered task_prefix | ActionDispatchError (503, reason unknown_task) | on_transition("not_run") |
| The worker rejects the message | ActionDispatchError (503, reason rejected) | on_transition("not_run") |
The worker's own machinery fails, or executor_started() raises | ActionFailedError (500, reason executor) | on_transition("failed") / — |
| The caller stops waiting | ResultTimeoutError / ResultReaderStoppedError, both ActionOutcomeUnknownError | — |
A hard time limit, a termination and a lost process end the process executing the action. Celery stops it with SIGTERM: the execution unwinds as SystemExit through finally blocks and execute() only as far as it gets before the process is killed, so save_state() is not guaranteed to run. The supervisor process sends the caller its error and then calls on_transition().
In a gevent pool a hard time limit ends the execution's greenlet, not the process. Celery raises gevent.Timeout in it: the action sees that exception where it runs synchronously and asyncio.CancelledError where it is suspended at an await, execute() sees ActionInterruptedError from call_next(), and finally blocks and save_state() run. The worker process then sends the caller its error and calls on_transition("interrupted"). The time limit interrupts only code that yields to gevent; synchronous code that does not runs on.
Async processes
The task of each action carries an async implementation for Celery with async tasks (velis74/celery, tag v5.7.0+async). A worker of that Celery started with --aconcurrency runs the actions in its async processes, many at a time on the event loop of each process; other Celery versions and pools run the task's sync function, which runs the action on an event loop of its own.
A singleton viewset serves every execution of a process on one instance, many of them at the same time in an async process, so it keeps no per-call state on self.
A DjangoORMViewSet runs its queries through Django's async API, which calls the ORM with sync_to_async(thread_sensitive=True): one thread per process runs them, one at a time, whatever --aconcurrency is (see Django integration). The worker logs a warning once per process and viewset class when it executes one in an async process.
In an async process:
- A soft time limit cancels the execution: the action gets
asyncio.CancelledErrorat its currentawait,execute()seesActionInterruptedError(reasontime_limit) fromcall_next(), and the worker sends the caller its error. revoke(..., terminate=True)cancels the execution the same way, with reasonterminated; the process keeps running its other executions. The supervisor sends the caller its error and callson_transition("interrupted").- A hard time limit cancels the execution with reason
time_limit, and the supervisor sends the caller its error and callson_transition("interrupted"). The process then takes no new executions and is replaced: it is ended when its other executions have finished, at the latest after Celery'sworker_async_recycle_timeout; executions still running then end aslost. - Synchronous code in an action blocks every execution of the process until it returns. A soft time limit and a termination interrupt it only at its next
await; a hard time limit ends the process if the code does not reach one.
Celery's current_task.retry() publishes the retry before it raises, so the task runs again while its caller has already received ActionFailedError; the second run's result is dropped. A celery_viewset action does not retry through Celery.
The tasks are registered with ignore_result=True, acks_late=False, reject_on_worker_lost=False and store_errors_even_if_ignored=False, which override a global task_acks_late: a call is acknowledged when its execution starts and is never delivered to the worker a second time, since its caller receives one outcome only.
Redis broker: ack_emulation
With kombu's Redis transport a worker keeps every message it has fetched and not yet acknowledged in Redis (ack_emulation, on by default), so that a message of a worker that dies is delivered again after the transport's visibility_timeout. That costs Redis round trips on every message. Since the tasks of a celery_viewset are acknowledged when their execution starts, a worker that runs only these tasks can turn it off in its own configuration:
# celery_worker.py — the worker's Celery app only
celery_app.conf.broker_transport_options = {
**celery_app.conf.broker_transport_options,
"ack_emulation": False,
}The worker then keeps its prefetch accounting in memory, one Redis round trip per message. The trade-off: messages the worker has prefetched but not started are lost if the worker dies, instead of being delivered again after the visibility timeout; their callers raise ResultTimeoutError when result_timeout runs out. The FastAPI processes that publish the tasks keep their default.
Time limits
An action's time limits are configured with @action_configuration under the TimeLimits key, not in Celery's configuration; the client sends them with each call as the task's soft_time_limit and time_limit:
from fastapi_viewsets.action_configuration import action_configuration, TimeLimits
@celery_viewset(celery_app, task_prefix="reports", redis_client=redis_client)
class ReportViewSet(...):
@action_configuration({TimeLimits: TimeLimits(soft=30, hard=60)})
async def perform_create(self, data: Report) -> Report: ...settings.default_action_configuration = {TimeLimits: TimeLimits(...)} sets them for every action. An action without a TimeLimits entry runs under the worker's own limits (--soft-time-limit, --time-limit). Soft time limits need the prefork pool (async processes included), hard time limits the prefork or gevent pool; the solo, threads and eventlet pools enforce neither. An action executed in the FastAPI process has no time limit. A TimeLimits entry on the method of a local action (the action method or its perform_* method) raises ValueError at decoration, in both processes; a class-level entry and settings.default_action_configuration apply only to the deferred actions.
Combining both decorators
There are two valid ways to apply celery_viewset and route_viewset together. Pick based on whether the FastAPI process needs its own subclass (e.g. to override something FastAPI-only) or not.
Pattern 1: subclassing (FastAPI-only overrides)
celery_viewset decorates a base class in viewsets.py (shared by both processes), and route_viewset decorates a subclass in main.py (FastAPI only):
viewsets.py ← @celery_viewset (shared by FastAPI and worker)
main.py ← @route_viewset (FastAPI only, wraps the viewset)
celery_worker.py ← imports viewsets (tasks registered on import)See demo/backend/viewsets.py + demo/backend/main.py in the repository for a full working example.
Pattern 2: stacking on the same class
Both decorators can instead be stacked directly on one class, in a single file imported by both processes:
@route_viewset(router, base_path="/items", pk_field_name="id")
@celery_viewset(celery_app, task_prefix="items", redis_client=redis_client)
class ItemViewSet(CollectionViewSet[int, Item], BulkViewSetMixin[int, Item]):
def __init__(self):
super().__init__(container=database, pk_field="id")Order matters: celery_viewset must be the inner decorator (closer to the class), route_viewset the outer one, exactly as written above. Both decorators call an internal, memoizing build_schema(cls) to collect the class's routes; whichever decorator runs first is the one that actually populates it. If celery_viewset runs first (correct order), route_viewset still detects its own, FastAPI-specific build hasn't run yet and rebuilds the route table correctly. If the order is reversed, celery_viewset's own build_schema(cls) call is skipped (it sees a route table already built), so it iterates route_viewset's FastAPI-wrapped routes instead of the raw viewset methods — including the auto-added /items/schema endpoint — which silently registers a bogus schema Celery task and patches a schema method onto the class that was never meant to exist.
Prefer Pattern 1 when the FastAPI-only class needs its own overrides (e.g. extra endpoints, a different lifecycle); prefer Pattern 2 for simple viewsets where a single file is enough — but respect the decorator order.
Context processors & command middleware
Every standard mixin action (create, list_items, retrieve, ...) also accepts a context parameter (a Context instance), built from a global list of processor callables (Django-style context_processors) and forwarded into perform_*. This is the recommended way to make per-request data (e.g. the authenticated user) available to perform_* without re-deriving it, and it survives the celery_viewset client/worker boundary. See Architecture for how this fits together with the rest of the request pipeline, and Context Processors / Command Middleware for the two mechanisms themselves.
