# 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.

> **Pre-release**
> Modal support is in Pre-release, and its APIs may change in backwards-incompatible ways.
> To request Temporal Cloud access, create a [support ticket](/evaluate/cloud/support#support-ticket) or contact your
> account team. You can also [sign up for updates](https://temporal.io/pages/serverless-workers-updates).

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 to Temporal and polls its Task Queue.

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

## Prerequisites 

- A Temporal Cloud Namespace where you can configure Worker Deployments and start Workflow Executions.
- A Modal account with permission to deploy apps and create secrets in your target environment.
- Python 3.12. This guide also uses [uv](https://docs.astral.sh/uv/) to manage dependencies.
- Temporal CLI v1.10.0 or later.
- A Workflow with a [versioning behavior](/worker-versioning#versioning-behaviors) and the Activities it uses.

> **💡 Tip:**
>
> If you don't have a Workflow ready, use the Workflow and Activity files from the
> [Python Modal Worker sample](https://github.com/temporalio/documentation-sdk-code-examples/tree/7042739821901183868b53b350727fdae999f6b9/python-sandbox/workers/modal_worker).
>

## 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 project directory and the Worker package.

```bash
mkdir -p modal-worker/modal_worker
cd modal-worker
touch modal_worker/__init__.py
```

Create `modal_worker/worker.py`. Import your Workflow and Activity definitions and register them in the
`configure` callback. The example registers `GreetingWorkflow` and `greet` on `my-task-queue`.

<!--SNIPSTART python-modal-worker-worker-->
[python-sandbox/workers/modal_worker/worker.py](https://github.com/temporalio/documentation-sdk-code-examples/blob/7042739821901183868b53b350727fdae999f6b9/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-cloud-credentials")],
)
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`.

For GPU Activities, set `gpu` on `@app.function` to request the GPU resources for the Worker container. See
[Modal GPU configuration](https://modal.com/docs/guide/gpu).

## 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 Prepare the deployment 

From the project root, initialize the Python project and install the integration.

```bash
uv init --python 3.12
uv add temporalio-modal-function-worker==0.0.1
```

In Modal, select the workspace and environment where the Worker will run. Create a secret named `temporal-cloud-credentials` 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` | A [Temporal Cloud API key](/cloud/api-keys) authorized to access the Namespace. |

The Worker example explicitly enables TLS and attaches this secret through
`secrets=[modal.Secret.from_name("temporal-cloud-credentials")]`. 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
```

> **💡 Limit compute costs during bursts:**
>
> You can set `max_containers` on `@app.function` to cap how many containers run at once. See
> [Container capacity](/serverless-workers/modal#instance-model).
>

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 Deploy a function for each Build ID 

Deploy a new Modal function for each Build ID. The sample uses `temporal_worker` in the `temporal-worker` App for
`build-1`. To deploy `build-2` in a separate App, set `build_id="build-2"` in `WorkerDeploymentVersion`, name the
function `temporal_worker_build_2`, and set the `modal.App` name to `temporal-worker-build-2`. Deploy the new App as
in [step 2.2](#deploy-the-app) and use its App and function names in [step 4](#configure-the-worker-deployment-version).

Keep the `temporal-worker` App deployed with its original code while `build-1` can still receive Tasks.

## 3. Authorize Temporal to invoke the function 

In Temporal Cloud, open your Namespace and go to **Workers** > **Create Worker Deployment**. Select **Modal** under
**Compute**. In **Access** > **Modal Workspace**, look for the workspace that contains your App.

If the workspace is already connected, continue to [step 4](#configure-the-worker-deployment-version). The steps
below require the **Account Owner** or **Global Admin** role. If you can't confirm the connection, ask someone with
one of those roles to check or connect the workspace.

> **⚠️ Shared grants can interrupt Worker starts:**
>
> When you connect the same Modal workspace to multiple Temporal Cloud accounts, authorize each connection with a
> different Modal user. Modal issues a grant for each combination of OAuth client, workspace, and Modal user. If two
> accounts share a grant, disconnecting the workspace from either account can revoke the grant and prevent the other
> account from starting Workers in that workspace.
>

1. In Temporal Cloud, go to **Settings** > **Connections**.
2. Under **Modal**, select **Connect Modal** for the first workspace. If the account already has a Modal connection,
   select **Connect Workspace**.
3. In the popup, sign in to Modal if prompted.
4. Select the workspace where you deployed your App and approve the authorization request.
5. Reopen the **Create Worker Deployment** form, select **Modal**, and confirm that the workspace appears in
   **Access** > **Modal Workspace**.

Each authorization connects one workspace. Select **Connect Workspace** again to connect another workspace.

The workspace can appear as **Connected, not verified**. This is the status of the workspace authorization.
The initial Worker invocation happens when you configure the Worker Deployment Version in
[step 4](#configure-the-worker-deployment-version).

## 4. Create Worker Deployment Version 

Create a Worker Deployment Version that points to the Modal function for this build. The deployment name and Build ID
must match the values in `modal_worker/worker.py`.

When the version needs to register its Task Queues, Temporal invokes the configured Modal function. The Worker
registers its Task Queues when it polls them under that version.

**Temporal UI**

1. In Temporal Cloud, open your Namespace and select **Workers**.
2. Select **Create Worker Deployment**.
3. Enter `my-app` for the deployment name and `build-1` for the Build ID.
4. Under **Compute**, select **Modal**. Enter the following values under **Resource**.

   | Field | Value |
   | --- | --- |
   | **App Name** | `temporal-worker`. |
   | **Function Name** | `temporal_worker`. |
   | **Environment** | The Modal environment you deployed to in [step 2.2](#deploy-the-app). |

5. Under **Access** > **Modal Workspace**, select the connected workspace that contains your App.
6. Save the Worker Deployment. The creation form validates the compute configuration and sets the initial version as
   current. Continue to [Verify deployment](#verify-automatic-invocation).

**Temporal CLI**

Before running the Temporal CLI commands, set `TEMPORAL_ADDRESS` to your Namespace's gRPC endpoint and
`TEMPORAL_NAMESPACE` to its name. Configure your credentials using the [Temporal Cloud CLI connection instructions](/cli/cloud#connect-to-temporal-cloud).

The Temporal CLI uses your account's [Modal workspace connection](#authorize-temporal-to-invoke-modal).
Set `MODAL_WORKSPACE_ID` to the identifier of the connected workspace that contains your App.

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

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"
```

| Flag | Description |
| --- | --- |
| `--deployment-name` | The Worker Deployment name in `worker.py`. |
| `--build-id` | The Build ID in `worker.py`. |
| `--app-name` | The deployed Modal app containing the Worker function. |
| `--function-name` | The Modal function that starts the Worker. |
| `--environment` | The Modal environment where you deployed the app. |
| `--workspace-id` | The identifier of the connected Modal workspace. |

In Temporal Cloud, go to **Workers** > **Deployments** and select your deployment. On the version, select
**Actions** > **Validate Connection**. Temporal uses the current workspace credentials to look up the configured
Modal function. To check that Task Queue demand triggers an invocation and the Worker processes Tasks,
[verify the deployment](#verify-automatic-invocation).

## 5. Set version as current 

If you created the deployment in the Temporal UI, continue to [Verify deployment](#verify-automatic-invocation).
For a version created through the CLI, wait for the initial Modal invocation to register the Worker's Task Queue,
then set the version as current.

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 

Use a Task Queue dedicated to this test. In Modal, check that the initial invocation has finished. Then check
the Task Queue's poller information.

```bash
temporal task-queue describe --task-queue my-task-queue
```

Start a Workflow to check that Temporal requests a new Modal invocation. Replace the Workflow Type and input if
you registered your own Workflow.

```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 sample 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).

## Configure scale-up for rate-limited Task Queues 

If your Modal Workers poll a rate-limited Task Queue, set the dispatch-rate epsilon to `0.05` in the scaling group.
While the queue has a backlog, the scaler can pause new Worker starts when the dispatch rate stays within the
configured band. See the [Modal CLI reference](/cli/command-reference/worker#modal-function) for the related
settings.

```bash
temporal worker deployment version compute-config modal-function update \
  --deployment-name my-app \
  --build-id build-1 \
  --scale-up-dispatch-rate-epsilon 0.05
```

Add `--scaling-group <SCALING_GROUP>` if the group has a name other than `default`. The update replaces the
group's scaler settings. Include any other scaler flags you want to keep.
