Client: sending a task

Your application uses a plain Celery client. It declares the tasks (name and signature), sends them to SQS and reads the result from DynamoDB. It does not need celery-cloud.

pip install "celery[sqs,dynamodb]"

Configure the client

celery_app.py
"""Celery client configuration shared by the examples.

The client only *declares* the tasks (name and signature). The bodies never run
here: they run on the runner, wherever ``TASKS`` points.
"""

import os
from typing import Any

from celery import Celery

REGION = os.environ.get("AWS_REGION", "eu-central-1")
QUEUE_NAME = os.environ.get("CELERY_QUEUE_NAME", "lambda-runner-queue")
QUEUE_URL = os.environ["CELERY_QUEUE_URL"]  # https://sqs.<region>.amazonaws.com/<account>/<queue>
TABLE = os.environ.get("CELERY_BACKEND_TABLE", "lambda-runner-tasks")

app = Celery("task_client")
app.conf.update(
    broker_url="sqs://",
    result_backend=f"dynamodb://@{REGION}/{TABLE}",
    task_default_queue=QUEUE_NAME,
    broker_connection_retry_on_startup=True,
    broker_transport_options={
        "region": REGION,
        # The queue must already exist: the client does not create it
        "predefined_queues": {QUEUE_NAME: {"url": QUEUE_URL}},
    },
)


# The name must be exactly the key used in the TASKS setting of the runner
@app.task(name="calculator.add")
def add(x: int, y: int, extra: int = 0) -> int:
    raise NotImplementedError


@app.task(name="calculator.subtract")
def subtract(*values: int) -> int:
    raise NotImplementedError


@app.task(name="calculator.divide")
def divide(x: int, y: int) -> float:
    raise NotImplementedError


@app.task(name="reports.summarize")
def summarize(request: dict[str, Any]) -> dict[str, Any]:
    raise NotImplementedError


@app.task(name="remote.sum")
def remote_sum(*values: int) -> int:
    raise NotImplementedError


@app.task(name="calculator.total")
def total(values: list[int]) -> int:
    raise NotImplementedError


@app.task(name="calculator.report_error")
def report_error(task_id: str) -> str:
    raise NotImplementedError


@app.task(name="jobs.fetch")
def fetch(url: str) -> dict[str, Any]:
    raise NotImplementedError


@app.task(name="jobs.sync_account")
def sync_account(account_id: int, attempts_needed: int = 1) -> str:
    raise NotImplementedError


@app.task(name="jobs.import_rows")
def import_rows(rows: int) -> dict[str, Any]:
    raise NotImplementedError


@app.task(name="jobs.export_report")
def export_report(seconds: float) -> str:
    raise NotImplementedError


@app.task(name="jobs.long_job")
def long_job(steps: int) -> str:
    raise NotImplementedError

Points that matter:

  • @app.task(name=...) must equal the key of TASKS in the runner. If you leave the name out, Celery derives it from the module (celery_app.add), which is easy to get wrong.

  • The task bodies are never executed on the client: they only document the signature.

  • The queue must already exist (predefined_queues): the client does not create it.

  • Credentials and region come from the standard AWS mechanisms (environment, profile, role). The client needs sqs:SendMessage on the queue and, on the table, dynamodb:GetItem and dynamodb:DescribeTable (see IAM roles and permissions).

Send and wait

basic.py
"""Send a task and wait for its result."""

from celery_app import add

# Positional and keyword arguments both reach the task
result = add.apply_async(args=(10, 3), kwargs={"extra": 5})
print(f"Sent task {result.id}")

# Always use a timeout: if the runner dies the task stays in STARTED forever
print(f"Result: {result.get(timeout=60)}")  # 18
print(f"State:  {result.state}")  # SUCCESS
export CELERY_QUEUE_URL=https://sqs.eu-central-1.amazonaws.com/123456789012/lambda-runner-queue
export AWS_PROFILE=my-profile
python basic.py
# Sent task 8d58fa0a-f181-47ff-83e9-9ddfd2ee8af9
# Result: 18
# State:  SUCCESS

delay, apply_async and send_task

All the usual ways to send a task work:

add.delay(10, 3)                                   # positional shortcut
add.apply_async(args=(10, 3), kwargs={"extra": 5})  # full control
app.send_task("calculator.add", args=(10, 3))       # by name, no declaration needed

send_task is useful when the client should not import the task declarations at all.

Options the runner honours

# The result is not stored (nothing can be read back, not even failures)
add.apply_async(args=(1, 2), ignore_result=True)

# Skip the task (REVOKED) if the runner receives it more than 60 seconds after sending
add.apply_async(args=(1, 2), expires=60)

countdown and eta are not supported: the task runs as soon as the message arrives.