GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Guide
  • Examples
  • Log in
  • Sign up

This view

  • Original page
  • New address

GeezerVison is showing modal.com — Container lifecycle hooks

Guide Introduction to Modal Getting started Functions Functions Invocation methods Function lookups Container lifecycle management Parametrized Functions Dynamic configuration Sandboxes Sandboxes Running commands Networking and security File access Snapshots Exit Snapshots BetaPricing and resources Sidecars BetaSecret injection BetaModel APIs Model APIs Models and pricing Agent integrations Endpoints Endpoints Supported models Candidates Training Quickstart Tinker-compatible API BetaMulti-node training Images Defining Images Using existing container images Named images Fast pull from registry GPUs and other resources GPU acceleration Using CUDA on Modal Configuring CPU, memory, and disk Scaling out Scaling out Input concurrency Batch processing Job queues Dynamic batching Multi-node Clusters Deployment Apps, Functions, and entrypoints Managing deployments Continuous deployment Scheduled Functions Observability HTTP Applications Servers Sticky Sessions Web Functions Streaming endpoints Web Function URLs Request timeouts Proxy Tokens Networking Tunnels Proxies BetaCluster networking Data sharing and storage Passing local data Volumes Storing model weights Cloud bucket mounts Dicts Queues Dataset ingestion Secrets and environment variables Secrets Environment variables Performance Cold start performance Memory Snapshots High-performance LLM inference Reliability and robustness Failures and retries Preemption Timeouts GPU health Troubleshooting Security and privacy Security and privacy Data residency Customer-supplied encryption keys AlphaAudit logs Integrations Using OIDC to authenticate with external services Connecting Modal to your Datadog account Connecting Modal to your OpenTelemetry provider Slack notifications Workspace & account settings Workspaces Environments Service users User groups Role-Based Access Control (RBAC) Billing Network egress billing Budgets Identity and provisioning Okta SSO Microsoft Entra SSO Google Workspace SSO Custom SAML SSO SCIM Integration Other topics Feature maturity Restricted Functions JavaScript/Go SDKs BetaModal 1.0 migration guide File and project structure Developing and debugging Jupyter notebooks Asynchronous API usage Global variables Region selection Localized placement GPU Metrics Search syntax

Container lifecycle hooks

Since Modal will reuse the same container for multiple inputs, sometimes you might want to run some code exactly once when the container starts or exits.

To accomplish this, you need to use Modal’s class syntax and the @app.cls decorator. Specifically, you’ll need to:

  1. Convert your function to a method by making it a member of a class.
  2. Decorate the class with @app.cls(...) with same arguments you previously had for @app.function(...).
  3. Instead of the @app.function decorator on the original method, use @modal.method or the appropriate decorator for a Web Function.
  4. Add the correct method “hooks” to your class based on your need:
    • @modal.enter for one-time initialization (remote)
    • @modal.exit for one-time cleanup (remote)

@modal.enter 

The container entry handler is called when a new container is started. This is useful for doing one-time initialization, such as loading model weights or importing packages that are only present in that image.

To use, make your function a member of a class, and apply the @modal.enter() decorator to one or more class methods:

import modal

app = modal.App()

@app.cls(cpu=8)
class Model:
    @modal.enter()
    def run_this_on_container_startup(self):
        import pickle
        self.model = pickle.load(open("model.pickle"))

    @modal.method()
    def predict(self, x):
        return self.model.predict(x)


@app.local_entrypoint()
def main():
    Model().predict.remote(x=123)

When working with an asynchronous Modal app, you may use an async method instead:

import modal

app = modal.App()

@app.cls(memory=1024)
class Processor:
    @modal.enter()
    async def my_enter_method(self):
        self.cache = await load_cache()

    @modal.method()
    async def run(self, x):
        return await do_some_async_stuff(x, self.cache)


@app.local_entrypoint()
async def main():
    await Processor().run.remote.aio(x=123)

Note: The @modal.enter() decorator replaces the earlier __enter__ syntax, which has been deprecated.

@modal.exit 

The container exit handler is called when a container is about to exit. It is useful for doing one-time cleanup, such as closing a database connection or saving intermediate results. To use, make your function a member of a class, and apply the @modal.exit() decorator:

import modal

app = modal.App()

@app.cls()
class ETLPipeline:
    @modal.enter()
    def open_connection(self):
        import psycopg2
        self.connection = psycopg2.connect(os.environ["DATABASE_URI"])

    @modal.method()
    def run(self):
        # Run some queries
        pass

    @modal.exit()
    def close_connection(self):
        self.connection.close()


@app.local_entrypoint()
def main():
    ETLPipeline().run.remote()

Exit handlers are also called when a container is preempted. The exit handler is given a grace period of 30 seconds to finish, and it will be killed if it takes longer than that to complete.

Lifecycle hooks for Web Functions 

Modal Web Functions can be converted to the class syntax as well. Instead of @modal.method, simply use whichever Web Function decorator (@modal.fastapi_endpoint, @modal.asgi_app or @modal.wsgi_app) you were using before.

from fastapi import Request

import modal

image = modal.Image.debian_slim().pip_install("fastapi")
app = modal.App("web-function-cls", image=image)

@app.cls()
class Model:
    @modal.enter()
    def run_this_on_container_startup(self):
        self.model = pickle.load(open("model.pickle"))

    @modal.fastapi_endpoint()
    def predict(self, request: Request):
        ...
Container lifecycle hooks@modal.enter@modal.exitLifecycle hooks for Web Functions
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.