# Deploy a Serverless Worker on Modal

> For the complete documentation index, see [llms.txt](https://docs.temporal.io/llms.txt).
> Any documentation page is available as raw Markdown by appending `.md` to its URL.
> For related questions, query `https://docs.temporal.io/api/retrieve?q=<question>&jtb=<job-to-be-done>&src=md-page&agent=<your-name>` (no auth; returns JSON `{content, source_url, page_url}`, with `source_url` pointing to Markdown for docs pages). Don't include personal data or credentials.
> If this page is wrong or missing something you needed, or Temporal behaves differently from what it says, report it with `https://docs.temporal.io/api/feedback?title=<summary>&message=<what-happened>&category=documentation&page_url=/production-deployment/worker-deployments/serverless-workers/modal&src=md-page&agent=<your-name>` (use `category=product` when the product, not the page, is wrong). Report only a specific problem you hit, send it once, and don't include personal data or credentials.

> Package a Python Worker as a Modal function, configure credentials in both directions, and connect it to a Temporal Worker Deployment Version.

Deploy your Worker code as a Modal function and configure Temporal to invoke that function when Tasks need capacity.
The function starts a Worker that connects back to Temporal and polls its Task Queue. Modal builds and runs the
container image from your Python image definition; you do not need a separate image registry.

For the invocation lifecycle and scaling controls, see [Serverless Workers on Modal](/serverless-workers/modal).

## Prerequisites

- A Temporal Namespace with the Modal compute provider enabled, and permission to configure Worker Deployments
  and start Workflow Executions in that Namespace.
- Authorization for Temporal to invoke functions in your Modal workspace. This is separate from the credentials
  your Worker uses to connect to Temporal.
- Access to deploy apps and create secrets in a Modal workspace and environment.
- Python 3.12 and [uv](https://docs.astral.sh/uv/) for the example.
- A Temporal CLI build that provides `temporal worker deployment version compute-config modal-function`.
  Check that this command's `--help` works before continuing.
- A configured [Temporal CLI connection](/cli/cloud#connect-to-temporal-cloud). Use the same Namespace for every
  Temporal command in this guide.

The Python integration is experimental. Availability of its package does not establish availability of the Modal
compute provider in your Temporal environment. Confirm access with your administrator before deploying.

## 1. Write Worker code 

Use the Python Modal Worker integration to run a Temporal Worker inside a Modal function. The Worker connects to
Temporal, polls for Tasks, and shuts down before the function timeout.

Create a Python project and install the integration.

```bash
uv init --python 3.12 modal-worker
cd modal-worker
uv add temporalio-modal-function-worker==0.0.1
mkdir -p modal_worker
touch modal_worker/__init__.py
```

Create `modal_worker/activities.py` with an Activity that returns a greeting.

<!--SNIPSTART python-modal-worker-activities-->
[python-sandbox/workers/modal_worker/activities.py](https://github.com/temporalio/documentation-sdk-code-examples/blob/main/python-sandbox/workers/modal_worker/activities.py)
```py
from temporalio import activity

@activity.defn
async def greet(name: str) -> str:
    activity.logger.info("Processing greeting")
    return f"Hello, {name}!"
```
<!--SNIPEND-->

Create `modal_worker/workflows.py`. The Workflow calls the Activity and declares a
[versioning behavior](/worker-versioning#versioning-behaviors).

<!--SNIPSTART python-modal-worker-workflows-->
[python-sandbox/workers/modal_worker/workflows.py](https://github.com/temporalio/documentation-sdk-code-examples/blob/main/python-sandbox/workers/modal_worker/workflows.py)
```py
from datetime import timedelta

from temporalio import workflow
from temporalio.common import VersioningBehavior

with workflow.unsafe.imports_passed_through():
    from modal_worker.activities import greet

@workflow.defn(versioning_behavior=VersioningBehavior.PINNED)
class GreetingWorkflow:
    @workflow.run
    async def run(self, name: str) -> str:
        return await workflow.execute_activity(
            greet,
            name,
            start_to_close_timeout=timedelta(seconds=30),
        )
```
<!--SNIPEND-->

Create `modal_worker/worker.py`. The `configure` callback sets the Task Queue and registers the Workflow and Activity.
Temporal invokes the function without arguments. The Worker receives Workflow inputs when it polls the Task Queue.

<!--SNIPSTART python-modal-worker-worker-->
[python-sandbox/workers/modal_worker/worker.py](https://github.com/temporalio/documentation-sdk-code-examples/blob/main/python-sandbox/workers/modal_worker/worker.py)
```py
from datetime import timedelta

import modal
from temporalio.common import WorkerDeploymentVersion
from temporalio.worker_integrations.modal.function import ModalWorkerConfig, run_worker

from modal_worker.activities import greet
from modal_worker.workflows import GreetingWorkflow

FUNCTION_TIMEOUT = timedelta(minutes=5)
VERSION = WorkerDeploymentVersion(deployment_name="my-app", build_id="build-1")

image = (
    modal.Image.debian_slim(python_version="3.12")
    .pip_install("temporalio-modal-function-worker==0.0.1")
    .add_local_python_source("modal_worker")
)
app = modal.App("temporal-worker", image=image)

def configure(config: ModalWorkerConfig) -> None:
    config.client_connect_config["tls"] = True
    config.worker_config["task_queue"] = "my-task-queue"
    config.worker_config["workflows"] = [GreetingWorkflow]
    config.worker_config["activities"] = [greet]

@app.function(
    timeout=int(FUNCTION_TIMEOUT.total_seconds()),
    secrets=[modal.Secret.from_name("temporal")],
)
async def temporal_worker() -> None:
    await run_worker(
        VERSION,
        configure,
        modal_function_timeout=FUNCTION_TIMEOUT,
    )
```
<!--SNIPEND-->

Keep the function timeout in `@app.function` equal to the timeout passed to `run_worker`.

## 2. Deploy the function 

Deploy the function to the Modal environment where you want the Worker to run. During deployment, Modal builds the
image described in `worker.py`, installs its dependencies, and includes your source files.

### 2.1 Configure the Worker's Temporal credentials 

In Modal, select the workspace and environment where the Worker will run. Create a secret named `temporal` with
the following values.

| Key | Value |
| --- | --- |
| `TEMPORAL_ADDRESS` | Your Namespace's gRPC endpoint, from its connection settings. |
| `TEMPORAL_NAMESPACE` | Your Namespace name. |
| `TEMPORAL_API_KEY` | An API key authorized to access the Namespace. |

The Worker example explicitly enables TLS and attaches this secret through
`secrets=[modal.Secret.from_name("temporal")]`. Secrets are scoped to Modal environments. Create the secret in the
same environment as the function, unless you explicitly configure a cross-environment lookup.

For instructions on creating the secret in the dashboard, see the [Modal secrets guide](https://modal.com/docs/guide/secrets#deploy-secrets-from-the-modal-dashboard).

### 2.2 Deploy the app 

Authenticate the Modal CLI to the intended workspace if you have not already done so:

```bash
uv run modal setup
```

From the project root, deploy to an existing Modal environment. Replace `temporal-workers` with its name.

```bash
export MODAL_ENVIRONMENT=temporal-workers
uv run modal deploy --env "$MODAL_ENVIRONMENT" -m modal_worker.worker
```

Confirm that `temporal-worker` contains a function named `temporal_worker` in the intended environment.

### 2.3 Record the app version 

In the app's **Deployment History**, record the numeric version for this deployment. Set it for the commands below,
replacing `1` with that version:

```bash
export MODAL_APP_VERSION=1
```

Use the numeric app version when configuring Temporal. It identifies the deployed code for this Build ID.

## 3. Authorize Temporal to invoke the function 

Have your Temporal administrator confirm that the Namespace's account has an authorized connection to the Modal
workspace containing your function. Record the connected workspace identifier as `MODAL_WORKSPACE_ID` for the next step.
Creating a Modal secret with a Temporal API key does not grant this invocation permission.

Replace the placeholder with the connected workspace identifier:

```bash
export MODAL_WORKSPACE_ID="<connected-workspace-id>"
```

The compute provider selects a connected workspace through `--workspace-id` when Temporal uses per-workspace OAuth
credentials. A server configured to use a single Modal API key uses a different credential mode and omits this flag.
Use the mode configured by your administrator; do not omit the workspace identifier to work around an authorization error.

## 4. Create Worker Deployment Version 

Create the Worker Deployment if it does not already exist:

```bash
temporal worker deployment create --name my-app
```

Create a new Worker Deployment Version with Modal compute configuration:

```bash
temporal worker deployment version compute-config modal-function create \
  --deployment-name my-app \
  --build-id build-1 \
  --app-name temporal-worker \
  --function-name temporal_worker \
  --environment "$MODAL_ENVIRONMENT" \
  --workspace-id "$MODAL_WORKSPACE_ID" \
  --app-version "$MODAL_APP_VERSION"
```

The deployment name and Build ID must match the values in `modal_worker/worker.py`. The app, function, environment, and app version
must identify the code you deployed to Modal. Pinning the app version prevents a later app deployment from changing
the code used by this Worker Deployment Version.

For an existing version, use `modal-function update` instead of `create`. Provider details are replaced as a whole:
pass all provider fields, including the workspace identifier and app version, when changing them. Updating provider
details also resets scaler settings that are not supplied. See the [CLI reference](/cli/command-reference/worker#modal-function).

Inspect the saved configuration:

```bash
temporal worker deployment version compute-config describe \
  --deployment-name my-app \
  --build-id build-1
```

## 5. Set version as current 

Creating a version with compute configuration requests an initial Modal invocation to register the Worker's Task
Queues. You do not need to start a Workflow or manually invoke the function for this registration.

Confirm that the Worker has registered the expected Task Queue before directing new Workflows to it:

```bash
temporal worker deployment version describe \
  --deployment-name my-app \
  --build-id build-1
```

If `my-task-queue` is missing, follow [Troubleshoot Serverless Workers on Modal](/troubleshooting/serverless-workers/modal)
to check invocation and Worker startup. Do not bypass the missing-Task-Queue check.

Set `build-1` as the Current Version for this Worker Deployment:

```bash
temporal worker deployment set-current-version \
  --deployment-name my-app \
  --build-id build-1
```

## 6. Verify deployment 

After the initial Worker invocation exits, confirm that no Workers are polling the example Task Queue.
Start a Workflow to check that Temporal requests a new Modal invocation:

```bash
temporal workflow start \
  --workflow-id modal-greeting-test-1 \
  --type GreetingWorkflow \
  --task-queue my-task-queue \
  --input '"World"' \
  --execution-timeout 5m
```

Use a new Workflow ID for each test. Check the result:

```bash
temporal workflow show --workflow-id modal-greeting-test-1
```

The Workflow should complete with `"Hello, World!"`. Verify the deployment in both systems.

- **Temporal UI** — Check the Workflow's Event History for completed Tasks and confirm that the intended Worker
  Deployment Version processed them.
- **Modal** — Check the function's invocation history and logs for a new invocation after you started the Workflow.
  The Worker can keep polling until its invocation budget ends.

If the Workflow does not progress or Modal does not receive an invocation, see
[Troubleshoot Serverless Workers on Modal](/troubleshooting/serverless-workers/modal).
