Server: the Celery-like task API

A function decorated with @celery_cloud.task is a Celery-like task. It keeps working side by side with the plain f(args, kwargs) functions of Server: local tasks: the decorator is what switches the convention.

Plain function

@task function

Signature

f(args, kwargs)

f(x, y=0), the natural arguments (f(self, x, y=0) with bind=True)

Retries, progress, revocation

no

yes (self.retry, self.update_state, self.is_revoked)

Options

none

retries, backoff, time limits, hooks

The route in TASKS is the same: task://jobs/fetch.

jobs.py
"""Tasks written with the Celery-like API (``@task``).

Unlike the plain ``f(args, kwargs)`` functions of ``calculator.py``, a decorated task
is called with its natural arguments and can be *bound*: ``self`` gives access to the
request, ``retry()``, ``update_state()`` and ``is_revoked()``.
"""

import time

from celery_cloud import SoftTimeLimitExceeded, task
from celery_cloud.logging import logger


@task(bind=True, max_retries=3, default_retry_delay=5)
def fetch(self, url: str) -> dict:
    """Pretend to download a page; ``flaky`` URLs fail twice before working."""
    if "flaky" in url and self.request.retries < 2:
        # a retry: the runner sends the same task again after 5 seconds
        raise self.retry(exc=ConnectionError(f"cannot reach {url}"))
    return {
        "url": url,
        "attempts": self.request.retries + 1,
        "bytes": len(url) * 100,
    }


@task(
    autoretry_for=(ConnectionError,),  # retry without writing try/except
    retry_backoff=True,  # 1 s, 2 s, 4 s... (with jitter), at most...
    retry_backoff_max=60,  # ...60 s between attempts
    max_retries=5,
)
def sync_account(account_id: int, attempts_needed: int = 1) -> str:
    """A call that raises ``ConnectionError`` until it is retried enough times."""
    if sync_account.calls.get(account_id, 0) < attempts_needed - 1:
        sync_account.calls[account_id] = sync_account.calls.get(account_id, 0) + 1
        raise ConnectionError("the service is down")
    return f"account {account_id} synchronised"


sync_account.calls = {}  # type: ignore[attr-defined]


@task(bind=True)
def import_rows(self, rows: int) -> dict:
    """Report progress while working: the client reads it with ``result.info``."""
    for done in range(1, rows + 1):
        time.sleep(0.2)  # the real work for one row
        self.update_state(state="PROGRESS", meta={"done": done, "of": rows})
    return {"imported": rows}


@task(bind=True, soft_time_limit=2)
def export_report(self, seconds: float) -> str:
    """Stopped by the soft time limit; it can still return something useful."""
    try:
        time.sleep(seconds)  # the real work
        return "complete report"
    except SoftTimeLimitExceeded:
        logger.warning("report {} ran out of time", self.request.id)
        return "partial report (stopped by the soft time limit)"


@task(bind=True)
def long_job(self, steps: int) -> str:
    """Cooperative cancellation: look at ``is_revoked()`` between the steps."""
    for step in range(steps):
        if self.is_revoked():
            return f"stopped after {step} steps because it was revoked"
        time.sleep(0.5)  # the real work of one step
    return f"finished all {steps} steps"

The decorator

from celery_cloud import task

@task                                     # natural arguments
def add(x, y=0): ...

@task(bind=True, max_retries=5)           # bind=True: the first parameter is the context
def fetch(self, url): ...

The functions stay directly callable, which makes them easy to unit test (for a bound task pass any object as self).

Option

Default

Meaning

bind

False

The first parameter is a TaskContext (self)

max_retries

3

Retries before the task fails (None = forever)

default_retry_delay

180

Seconds before a retry that does not say otherwise

autoretry_for

()

Exception classes that are retried automatically

retry_backoff

False

True or a number: exponential delay factor * 2**retries

retry_backoff_max

600

Largest backoff, in seconds

retry_jitter

True

Pick a random delay between 0 and the backoff

soft_time_limit, time_limit

None

Limits in seconds; a limit sent by the client wins

on_success, on_failure, on_retry

None

Functions called at the end (see below)

The context (self)

self.request

id, task, args, kwargs, retries, eta, expires, parent_id, root_id, group, hostname, delivery_info and the canvas fields.

raise self.retry(exc=None, countdown=None, eta=None, max_retries=None)

Run the task again later. Without countdown or eta the delay is default_retry_delay. When the retries run out it raises exc (or MaxRetriesExceededError if there is none). See Retries.

self.update_state(state=..., meta=...)

Store a custom state, e.g. PROGRESS. The client reads it with result.state and result.info. Nothing is stored for tasks sent with ignore_result.

self.is_revoked()

True when the client revoked the task: use it between the steps of a long job.

Ending a task in other ways

from celery_cloud import Ignore, Reject

raise Ignore()                      # end without touching the state (set it yourself first)
raise Reject("busy", requeue=True)  # give the message back to SQS, the task runs again later
raise Reject("not for me")          # drop the message, state REJECTED

Time limits

soft_time_limit raises SoftTimeLimitExceeded inside the task, which can catch it and return something (see export_report above); time_limit raises TimeLimitExceeded. The limits of the client’s apply_async win over the decorator’s. See Execution time limit for how they interact with the Lambda timeout.

Hooks

def on_failure(exc, task_id, args, kwargs, traceback):
    alert(f"{task_id} failed: {exc!r}")

@task(on_failure=on_failure)
def charge(order_id): ...

on_success(retval, task_id, args, kwargs), on_failure(exc, task_id, args, kwargs, traceback) and on_retry(exc, task_id, args, kwargs, traceback) have the arguments of the Celery Task methods of the same name. A hook that raises is logged and ignored.

Signals

For hooks that apply to every task use celery_cloud.signals (task_prerun, task_postrun, task_success, task_failure and task_retry). Connect the receivers in a module and list it in INIT_MODULES so it is imported when the function starts:

signals_setup.py (INIT_MODULES=signals_setup)
"""Signal receivers, loaded once when the function starts.

Put the module in the ``INIT_MODULES`` setting (``INIT_MODULES=signals_setup``) so the
receivers are connected before the first task runs.
"""

import time

from celery_cloud.logging import logger
from celery_cloud.signals import task_failure, task_postrun, task_prerun

_started: dict[str, float] = {}


@task_prerun.connect
def remember_start(task_id=None, task=None, **kwargs):
    _started[task_id] = time.monotonic()


@task_postrun.connect
def log_duration(task_id=None, task=None, state=None, **kwargs):
    seconds = time.monotonic() - _started.pop(task_id, time.monotonic())
    logger.info("{} [{}] {} in {:.2f} s", task, task_id, state, seconds)


@task_failure.connect
def alert(task_id=None, task=None, exception=None, **kwargs):
    # send it to your alerting system here
    logger.error("{} [{}] failed: {!r}", task, task_id, exception)

Receivers are called with keyword arguments: declare **kwargs. One that raises is logged and does not affect the task. The arguments of each signal are in celery_cloud.signals.

Metrics

With METRICS_ENABLED=true the runner writes CloudWatch metrics through the Embedded Metric Format, with the task name as dimension: TaskSucceeded, TaskFailed, TaskRetried, TaskSkipped, TaskDelayed, TaskIgnored, TaskRejected and TaskDuration (milliseconds). They need no extra IAM permission.