# 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 Worker capacity, Temporal invokes a deployed Modal function. Each invocation starts a
Worker that polls for Tasks until its execution budget expires. Modal provides the containers that run these
invocations and can reuse a container for later invocations.

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

## Invocation and container lifetimes 

A Modal function invocation and its container have separate lifetimes:

| Phase | Function invocation | Container |
| --- | --- | --- |
| Start | Temporal requests a function invocation. | Modal assigns available capacity or starts a container from the app's image. |
| Initialize | The integration configures a fresh Client and Worker and connects to Temporal. | The container supplies the packaged code, dependencies, and configured secrets. |
| Process | The Worker polls the Task Queue and executes Tasks. | The container hosts the active invocation. |
| Shut down | The integration stops polling, allows time for Activity shutdown, runs cleanup hooks, and exits. | Modal can keep the container for another invocation. |
| Idle | No Worker is running after the invocation exits. | Modal can remove idle containers according to its autoscaling configuration. |

An invocation can process Tasks from multiple Workflow Executions. Completing a Workflow, or temporarily emptying
the Task Queue, does not by itself end the invocation. The integration continues polling within its execution budget.

Sequential invocations can reuse a container, but each invocation creates a fresh Temporal Client and Worker.
Do not rely on a previous invocation's in-memory Workflow cache. A Worker can reconstruct Workflow state from
[Event History](/workflow-execution/event) when it receives a Workflow Task.

The Modal function timeout bounds one invocation, not the entire Workflow Execution. A Workflow can wait between
Tasks and continue on another invocation. In-flight Activities still need enough time to finish or respond to
cancellation; use [Activity Heartbeats](/encyclopedia/detecting-activity-failures#activity-heartbeat) to record progress
when a retry must resume work.

## Shutdown budget 

The Python integration reserves 15 seconds before the configured Modal function timeout. Configuration, connection
setup, polling, Worker shutdown, and cleanup hooks must fit in the remaining execution budget.

With a five-minute function timeout and the default five-second graceful shutdown timeout, the approximate timeline
from the start of `run_worker` is:

| Time | Action |
| --- | --- |
| 0:00 | Begin configuration and connection setup. |
| 4:38 | Stop polling and begin Worker shutdown. |
| 4:43 | End the default graceful Activity shutdown period. |
| 4:45 | Target completion, including the two-second cleanup reserve. |
| 5:00 | Reach the configured Modal function deadline. |

Setup time consumes the budget, so the Worker may spend less than 4 minutes 38 seconds polling. These times describe
the configured budget, not a guarantee that arbitrary user cleanup code completes before the deadline.

Increasing `graceful_shutdown_timeout` also increases the default shutdown reserve and moves the stop-polling time
earlier. If you override `shutdown_deadline_buffer`, leave enough time for Activity shutdown and cleanup hooks.
Pass the same function timeout to Modal and to the integration.

## Autoscaling 

Temporal decides when to request another Worker invocation. Modal decides how to provide container capacity for
those invocations. Modal does not inspect the Temporal Task Queue directly.

| Controller | Input | Action |
| --- | --- | --- |
| Temporal's [Worker Controller Instance (WCI)](/serverless-workers#worker-controller-instance) | Task arrival signals and Task Queue metrics for the Worker Deployment Version. | Request another invocation of the configured Modal function. |
| Modal's autoscaler | Function inputs and available container capacity. | Start containers for inputs and remove idle containers, within the function's configured limits. |

The Modal compute provider uses the no-sync scaler. A Task that cannot be immediately matched to an available
Worker can trigger another invocation, subject to the scale-up cooldown. Periodic Task Queue metrics checks can also
trigger an invocation when backlog exceeds the configured threshold.

Each scale-up action requests one new function invocation. It does not set a desired number of containers.
The WCI submits the invocation without waiting for the function to finish.

The WCI does not actively terminate Modal Workers to scale in. Invocations exit according to their Worker lifetime,
and Modal manages the containers afterward. While a Worker is polling, its invocation is active even if the Temporal
Task Queue is empty. Modal's idle-container scale-down settings do not shorten that invocation.

### Controls in Temporal

Configure scaling through the
[Modal compute-config commands](/cli/command-reference/worker#modal-function). The controls include the scale-up
cooldown, backlog threshold, and metrics polling interval. Keep defaults initially and tune them after measuring
startup time, Task latency, and invocation volume.

`--max-worker-lifetime-ms` tells the scaler to request replacement capacity periodically while backlog remains.
It does not set the Modal function timeout or terminate an existing Worker. Configure the invocation timeout
separately in the Modal function and the Python integration.

### Container pool controls

Set these options on `@app.function` to control the container pool:

| Option | Effect |
| --- | --- |
| `max_containers` | Caps the number of containers that can run the function. |
| `min_containers` | Keeps a minimum number of containers warm, including while the function is inactive. |
| `buffer_containers` | Maintains spare container capacity while the function is active. |
| `scaledown_window` | Controls how long containers can remain idle during scale-down. |

By default, Modal can scale the container pool to zero when there are no inputs to process. Keeping containers warm
can reduce cold starts, but does not start a Temporal Worker until the function is invoked. A low container cap can
limit how quickly requested invocations begin. Account for Modal workspace limits as well.

Do not enable concurrent Modal inputs for the Worker function. Configure concurrency within the Temporal Worker
instead. See [Modal autoscaling](https://modal.com/docs/guide/scale).

## Worker Versioning 

Associate each Worker Deployment Version with a stable copy of the Worker code. The deployment name and Build ID
reported by the Worker must match the Worker Deployment Version whose compute configuration invokes it.

Modal's app version and Temporal's Build ID are separate identifiers. The compute configuration selects a Modal
app, function, environment, and optionally a numeric app version. A positive `--app-version` selects a particular
deployed app version; omitting it or setting it to `0` selects the current deployed version.

For production configuration, pin the Modal app version so redeploying the app does not change the code invoked for
an existing Worker Deployment Version. Pinned Workflows remain on their Temporal version, but that routing alone
does not protect them from changes to an unpinned Modal target.

Choose Pinned or Auto-Upgrade for each Workflow according to your rollout requirements. See
[Worker Versioning](/worker-versioning) for routing behavior and rollout strategies.
