Server: local tasks
A local task is a Python function packaged inside the runner image. It is the simplest and cheapest option: no extra Lambda invocation.
The contract
Tip
Functions can also be written with the Celery-like API (natural arguments, retries, progress, time limits): see Server: the Celery-like task API. Both styles work in the same runner.
A local task is a function with exactly two positional parameters: the list of
positional arguments and the dict of keyword arguments sent by the client. It
returns the result, which must be JSON serialisable (anything else is stored as
its str()). Raise any exception to make the task fail.
"""Local tasks: plain functions packaged with the runner.
Every local task receives two parameters: the list of positional arguments and
the dict of keyword arguments that the client sent.
"""
from celery_cloud.logging import logger
def add(args: list[int], kwargs: dict[str, int]) -> int:
"""Add all the positional arguments (plus the optional ``extra`` keyword)."""
logger.info("add called with args={} kwargs={}", args, kwargs)
return sum(args) + kwargs.get("extra", 0)
def subtract(args: list[int], kwargs: dict[str, int]) -> int:
"""Subtract every value from the first one."""
if len(args) < 2:
# Any exception becomes a FAILURE state that the client can read
raise ValueError("subtract needs at least 2 values")
result = args[0]
for value in args[1:]:
result -= value
return result
def divide(args: list[int], kwargs: dict[str, int]) -> float:
"""Divide the first value by the second one (fails when it is zero)."""
return args[0] / args[1]
def total(args: list, kwargs: dict) -> int:
"""Chord body: receives ONE argument, the list of results of the header tasks."""
return sum(args[0])
def report_error(args: list, kwargs: dict) -> str:
"""Error callback (``link_error``): receives the id of the task that failed."""
logger.warning("task {} failed", args[0])
return f"handled failure of {args[0]}"
A local task runs inside the runner, so it is bound by the 15 minute limit of a Lambda function (see the execution time limit).
Use celery_cloud.logging.logger so your log lines carry the trace_id of the
invocation (see Logging).
Register the tasks
TASKS maps the Celery task name to the function: task://<module>/<function>.
The module path is the one Python can import inside the image.
{
"Variables": {
"TASKS": "{\"calculator.add\": \"task://calculator/add\", \"calculator.subtract\": \"task://calculator/subtract\", \"calculator.divide\": \"task://calculator/divide\", \"reports.summarize\": \"task://reports/summarize\", \"remote.sum\": \"lambda://arn:aws:lambda:eu-central-1:123456789012:function:remote-sum\"}",
"CELERY_BACKEND_TABLE": "lambda-runner-tasks",
"CELERY_BACKEND_REGION": "eu-central-1",
"LOG_LEVEL": "INFO"
}
}
Package the tasks
Build an image on top of the runner image and copy your modules next to the handler:
# The runner image already contains celery-cloud and the Lambda handler.
# Use a tag that exists in https://gallery.ecr.aws/e2b2x4l7/celery-cloud/lambda-runner
FROM public.ecr.aws/e2b2x4l7/celery-cloud/lambda-runner:<tag>
# Local tasks: copy them next to the handler so `task://calculator/add` can import them
COPY calculator.py reports.py ${LAMBDA_TASK_ROOT}/
# Extra dependencies of your tasks (reports.py uses pydantic, which the runner
# already ships, so nothing to install here)
# RUN pip install --no-cache-dir <package>
docker build --platform linux/amd64 --provenance=false \
-t 123456789012.dkr.ecr.eu-central-1.amazonaws.com/celery-cloud-runner:2 .
docker push 123456789012.dkr.ecr.eu-central-1.amazonaws.com/celery-cloud-runner:2
aws lambda update-function-code --function-name celery-cloud-runner \
--image-uri 123456789012.dkr.ecr.eu-central-1.amazonaws.com/celery-cloud-runner:2
The infrastructure around it (queue, table, role, function, event source mapping) is explained in Infrastructure.
If your tasks live in a package with its own dependencies, install it in the image
instead of copying single files (RUN pip install --no-cache-dir .) and use the
dotted module path: task://my_package.domain.calculator/add.
Tasks with structured data
Celery serialises arguments as JSON, so a pydantic model arrives as a plain dict:
validate it on entry and return model_dump(). The client side of this example
is Client: structured data.
"""A local task that works with structured data.
Celery serialises the arguments as JSON, so a pydantic model travels as a dict:
the client sends ``model_dump()`` and the task validates it with
``model_validate()``. The result is returned the same way.
"""
from pydantic import BaseModel, Field
class SummaryRequest(BaseModel):
"""What the client sends."""
id: str = Field(max_length=150)
text: str
class SummaryResponse(BaseModel):
"""What the task returns."""
id: str
words: int
first_words: str
def summarize(args: list, kwargs: dict) -> dict:
"""Count the words of a text and return its first five."""
request = SummaryRequest.model_validate(args[0])
words = request.text.split()
response = SummaryResponse(
id=request.id,
words=len(words),
first_words=" ".join(words[:5]),
)
return response.model_dump()
What the runner stores
For calculator.add with args=[10, 3] and kwargs={"extra": 5} the item in
DynamoDB holds a result like this (JSON, decoded):
{
"status": "SUCCESS",
"result": 18,
"traceback": null,
"children": [],
"date_done": "2025-01-01T10:00:00.123456+00:00",
"task_id": "8d58fa0a-f181-47ff-83e9-9ddfd2ee8af9"
}
If the function raises ValueError("subtract needs at least 2 values"):
{
"status": "FAILURE",
"result": {
"exc_type": "ValueError",
"exc_message": ["subtract needs at least 2 values"],
"exc_module": "builtins"
},
"traceback": "Traceback (most recent call last): ..."
}
The client receives a real ValueError with that message (Celery rebuilds the class
from exc_module and exc_type).