Delayed tasks¶
Delayed tasks are the Cloud Tasks half of the library: trigger any FastAPI endpoint later, with retries managed by the queue.
Defining a task¶
from fastapi_gcp_tasks import DelayedRouteBuilder, as_delayed_task
delayed_router = APIRouter(route_class=DelayedRouteBuilder(...))
class Recipe(BaseModel):
ingredients: list[str]
@delayed_router.post("/{branch}/make_chili")
@as_delayed_task
async def make_chili(branch: str, recipe: Recipe) -> None:
# Do a ton of work here. The secret is to undercook the onions.
...
app.include_router(delayed_router)
Because the task is a FastAPI endpoint, everything FastAPI offers works: path/query/header parameters,
Pydantic bodies, Depends, middlewares, and telemetry.
Triggering¶
make_chili.delay(branch="Scranton", recipe=Recipe(ingredients=["Ground beef", "Undercooked onions"]))
.delay() takes the same arguments as the endpoint (by keyword or by position), validates them, builds the
full task URL, and creates the task on Cloud Tasks. The return value of the endpoint is meaningless to the
queue — only the HTTP status matters (2xx acknowledges the task; anything else retries it).
To trigger 30 minutes later:
make_chili.options(countdown=1800).delay(branch="Scranton", recipe=Recipe(ingredients=["Ground beef", "Undercooked onions"]))
What you can pass¶
Each argument is sent the way FastAPI will read it back on the worker:
| Endpoint parameter | Sent as |
|---|---|
| Path parameter | Percent-encoded path segment. A trailing slash in the route or in a {name:path} value is kept. |
| Query parameter | Query string. Lists repeat the key, enums send their value, dates and durations use ISO 8601, Decimals keep their digits. |
Header() parameter |
Request header. Pass it by its Python name: x_request_id="..." is sent as x-request-id. A list header can carry one value, because a task request sends each header once. |
Cookie() parameter |
Cookie request header. |
| One Pydantic body | The JSON body. |
Several bodies, or Body(embed=True) |
One JSON object keyed by parameter name, or by its alias if it has one. |
A few rules keep mistakes at the call site instead of on the worker:
- Arguments you leave out fall back to the endpoint's default. A default of
Noneor an empty list sends nothing; any other default is sent explicitly. For a body parameter that acceptsNone, passingNonesends JSONnull, which is different from leaving it out. - An empty list cannot be expressed in a query string, header or cookie. Passing one raises
ValueError, unless the endpoint's own default is also empty, in which case the key is simply left out. The same applies to list fields of a parameter model. A cookie cannot carry a list at all, since it holds a single value. - Unknown arguments raise
TypeError, as they would in a normal function call. So does a value for an argument the worker resolves itself, such asdb: Session = Depends(get_db), and a value for a header the task request sets itself: theX-CloudTasks-*andX-CloudScheduler*headers, andContent-Type, which is alwaysapplication/json. - Values are validated against the endpoint's annotations before the task is created. A missing required
argument raises
MissingParamError. A path value the route segment would not match raisesValueError: an empty value or one containing/for a plain{name}segment (declare it as{name:path}to allow slashes), or a negative number for{n:int}. - Query, header and cookie parameters owned by a dependency are optional here. If
Depends(verify_token)reads anAuthorizationheader,.delay()does not ask for it, because a hook or Cloud Tasks' own OIDC token usually supplies it. You can still pass such a parameter by name when you need to. Body parameters are different: the JSON body is one document only the caller can supply, so a required body parameter is required wherever it is declared. - A name refers to one parameter. It is the endpoint's own parameter if there is one, otherwise a body parameter. A dependency's query, header or cookie parameter that shares that name cannot be passed.
Form()andFile()parameters are not supported. Task bodies are always sent as JSON.
Limits¶
- Secrets. Pydantic masks a
SecretStrwhen it is serialized. Outside the body, passing one raisesValueError; inside a body the worker receives the mask. Keep secrets out of task arguments. - Validators run on both sides. Path, query, header and cookie values are validated before sending and again on the worker, so a validator that is not idempotent, such as one that adds a prefix, is applied twice.
- Sets inside a body are sent in iteration order, which can differ between processes. For a scheduled job that makes the job look changed after a restart, so prefer a list or tuple in scheduled payloads.
- A body model must accept its own dump. Models are sent as
model_dump(mode="json", by_alias=True), so a field with only aserialization_alias, a computed field on a model that forbids extra fields, or aJson[...]field is rejected by the worker.
Per-endpoint defaults¶
Set default options once with the task_default_options decorator instead of at every call site:
from fastapi_gcp_tasks import task_default_options
# Trigger after 5 minutes by default
@delayed_router.get("/simple_task")
@task_default_options(countdown=300)
def simple_task() -> None: ...
Deduplication¶
Pass a task_id to make Cloud Tasks queue a given task at most once:
Note
Named task deduplication is not supported by the local emulator, and Cloud Tasks raises
google.api_core.exceptions.AlreadyExists when a task id is reused.
Retries¶
Cloud Tasks retries a task until it responds with a 2xx status. To cap retries from the worker side, use the
max_retries dependency.
See Configuration for every option accepted by DelayedRouteBuilder, .options(), and
task_default_options.