# Serverless Workers 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=/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.

> Modal function invocations host Temporal Workers that poll for Tasks, shut down before their deadline, and scale through Temporal and Modal.

When a Task Queue needs more Worker capacity, Temporal invokes a deployed Modal function. Each invocation starts a
Worker that polls for Tasks and shuts down before the function times out.

For setup, see [Deploy a Serverless Worker on Modal](/production-deployment/worker-deployments/serverless-workers/modal).
For Python configuration and defaults, see [Serverless Workers on Modal with Python](/develop/python/workers/serverless-workers/modal).

## Autoscaling 

Temporal uses the same [event-driven scaling algorithm as AWS Lambda](/serverless-workers/aws-lambda#autoscaling).
The [Worker Controller Instance (WCI)](/serverless-workers#worker-controller-instance) requests Modal function
invocations based on demand on the Task Queue. Modal supplies container capacity for those invocations.

### Scale-out 

When a Task cannot be matched to an available Worker, the WCI can request a new function invocation. Periodic checks
can also trigger an invocation when backlog exceeds the configured threshold. Each scale-out action requests a Worker
invocation.

Modal can serve the invocation in an available container or start a new one. For warm capacity and container limits,
see [Container capacity](#instance-model). Set Temporal's scaling thresholds with the
[Modal compute-config commands](/cli/command-reference/worker#modal-function).

#### Scale-up pauses for rate-limited Task Queues 

If the dispatch rate stays flat while Tasks are waiting, the scaler can pause demand-driven Worker starts. This can
avoid starting Workers that cannot increase throughput on a [rate-limited Task Queue](/design-patterns/downstream-rate-limiting).
Worker replacement starts governed by `--max-worker-lifetime-ms` can still occur. See
[Configure scale-up for rate-limited Task Queues](/production-deployment/worker-deployments/serverless-workers/modal#configure-rate-limited-scaling).

### Scale-in 

Worker shutdown and Modal's idle container policy determine when capacity goes away. Each Worker polls until it nears
its execution deadline, even if the Task Queue is empty. When the invocation exits, Modal can keep the container ready
for a later invocation or remove it.

### Sharing a Task Queue with long-lived Workers 

Modal Workers can provide extra capacity on a Task Queue served by a fixed-size fleet of long-lived Workers. Temporal
starts Modal Workers when the existing Workers cannot keep up and the scaler detects unmet demand. Keep the long-lived
fleet at a fixed size so one scaler responds to demand on the shared Task Queue.

## Container capacity 

Modal manages a container pool for the Worker function. When Temporal requests an invocation, Modal assigns it to an
available container or starts a new one. By default, the pool can scale to zero after all invocations finish.

Set these options on `@app.function` to control when containers are available and how many Modal can run.

| Setting | What it changes | When to adjust it |
| --- | --- | --- |
| `min_containers` | Keeps a minimum number of containers warm, including between invocations. | Set a nonzero minimum if cold starts after quiet periods push Task pickup past your latency target. |
| `buffer_containers` | Keeps spare containers ready while the function is active. | Raise it when bursts of invocations arrive while other Workers are already running. |
| `max_containers` | Limits the total number of containers for the function. If all containers are busy at this limit, additional invocations wait for capacity. | Cap concurrent compute use and limit costs during bursts, especially for GPU Workers. |
| `scaledown_window` | Sets the maximum time in seconds that Modal can keep a container idle during scale-down. Modal can remove a container sooner. | Increase it when invocations tend to arrive in short bursts separated by gaps and can benefit from reusing recently active containers. |

For example, with `max_containers=4` and one active invocation per container, a fifth invocation waits if all four
containers are busy. A warm container can reduce startup time. The Client and Worker start when the invocation
begins, and the Worker controls how many Temporal Tasks it processes concurrently.

Keeping containers warm can increase the cost of idle capacity. See [Modal autoscaling](https://modal.com/docs/guide/scale)
and [Modal cold start performance](https://modal.com/docs/guide/cold-start).

## Run GPU workloads 

When a Task Queue needs more GPU Worker capacity, Temporal invokes the configured Modal function. Modal runs each
invocation in a container with the GPU type and count you request with `gpu` on `@app.function`. Once invocations
finish, Modal can scale down idle containers between batches. See [Modal GPU configuration](https://modal.com/docs/guide/gpu).

This fits workloads that can split a burst of GPU work across Activities. For example:

- **Reinforcement learning rollouts.** Use GPU Activities to generate groups of rollout attempts in parallel. The
  Workflow waits for those attempts to be scored before starting the next training step.
- **Model evaluations.** Split a test set into groups, evaluate each group in an Activity, and compare model scores
  once the required results are available.

If a GPU Worker is preempted, Temporal can retry interrupted Activities according to their Retry Policy. The Workflow
can use Activity results already recorded in [Event History](/workflow-execution/event). To resume within an individual
Activity, save checkpoints in storage a replacement Worker can access. Record the latest checkpoint location in an
[Activity Heartbeat](/encyclopedia/detecting-activity-failures#activity-heartbeat) and load it on retry.

Size the work in each Activity attempt to fit the Worker's [invocation lifetime](#lifecycle). Allow time for Worker
startup, model loading, and shutdown. If your pipeline mixes CPU and GPU work,
[route GPU Activities to a dedicated Task Queue](/guides/route-specialized-workloads) so GPU Workers process the
Activities that need that hardware.

## Worker Versioning 

With [Worker Versioning](/worker-versioning), deploy a new Modal function for each Build ID. Temporal routes Tasks
to a Worker Deployment Version, which identifies the Modal App, function, and environment to invoke. The function
starts a Worker that reports the matching deployment name and Build ID.

Keep the previous function and its Worker code available while its Worker Deployment Version can receive Tasks.
For example, deploy a new function in a separate Modal App for `build-2`, and keep the App and function for `build-1`
deployed for Workflows that still use `build-1`. If you keep both functions in the same App, preserve the previous
function, its Worker code, and its dependencies when you redeploy the App.

### How the versioning behavior changes rollout 

Pinned and Auto-Upgrade determine which Worker Deployment Version processes Tasks when you change the Current Version.

| Versioning behavior | Effect after changing the Current Version |
| --- | --- |
| **Pinned** | Existing Workflows stay on their assigned Worker Deployment Version. Temporal continues to invoke that version's Modal function when it needs Worker capacity. |
| **Auto-Upgrade** | Existing Workflows can move to the new Current Version on their next Workflow Task. Temporal uses the Modal function configured for the new version. |

For setup, see [Deploy a function for each Build ID](/production-deployment/worker-deployments/serverless-workers/modal#deploy-a-function-for-each-build).

## Lifecycle 

Modal can reuse a container across invocations. Each invocation creates a fresh Client and Worker, and the Worker can
process Tasks from multiple Workflow Executions during that invocation.

The Worker goes through three phases:

- **Init.** The integration initializes the Worker and connects to Temporal.
- **Work.** The Worker polls the Task Queue and processes Tasks.
- **Shutdown.** The Worker stops polling, gives in-flight Activities time to finish, and runs shutdown hooks.

![Serverless Worker lifecycle showing initialization, polling, and shutdown](https://docs.temporal.io/diagrams/serverless-worker-lifecycle.svg)

The Modal integration uses the function timeout you pass to `run_worker` and sets its default execution deadline
15 seconds earlier. It starts shutting down before that deadline, with time for the configured graceful shutdown
period (five seconds by default) plus two seconds for cleanup. Pass the same timeout to the Modal function and the
integration. See
[Python Worker configuration](/develop/python/workers/serverless-workers/modal#configure-the-invocation-lifetime).

### Tuning for long-running Activities 

Size the graceful shutdown timeout for the longest Activity attempt the Worker needs to finish after polling stops.
The default shutdown deadline buffer grows with that timeout. If you set the buffer explicitly, include the graceful
shutdown timeout and time for shutdown hooks.

Set the Modal function timeout high enough for connection setup, Activity processing, the shutdown deadline buffer,
and the 15-second safety margin. A Workflow Execution can continue on another Worker invocation. For Activities that
need to resume after an interruption, record progress with
[Activity Heartbeats](/encyclopedia/detecting-activity-failures#activity-heartbeat).
