modal-classes-lifecycle
Skill4 starsChanged 3 months agoApache-2.0View on GitHub
Class-based Modal Functions with lifecycle hooks and parametrization. Use when loading models once per container, sharing state between method calls, parametrizing Functions by user/config, or managing container startup/shutdown.
We split this skill into the rules it gives an agent
7 rules. About 0 are common, 2 are distinctive, and 5 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈2
Distinctive · estimate
This author's own choices. Worth a look.
5
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 8
Use this skill when using class-based Functions for stateful workloads, lifecycle management, or parametrization.
- Distinctive: line 86
Create separate container pools per parameter combination:
- Very specific: line 171
Use @modal.enter() to load once per container
- Very specific: line 175
Use @modal.exit() for graceful cleanup
- Very specific: line 179
Use modal.parameter() to create per-user pools
- Very specific: line 199
Use @modal.method() (not @app.function()) for class methods
- Very specific: line 201
Do not put @modal.method on an @app.server class — use modal-servers for port-based serving
≈ “Common” is an estimate: at least 1 in 5 of the 308,232 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Modal Classes and Lifecycle
Use this skill when using class-based Functions for stateful workloads, lifecycle management, or parametrization.
When to Use This Skill
- Loading an ML model once per container (not per request)
- Sharing state between method calls
- Running setup/teardown logic per container
- Creating separate container pools per parameter set (e.g., per user)
- Combining GPU inference with lifecycle hooks
Core Pattern: Class with Lifecycle
import modal
app = modal.App()
@app.cls(gpu="A100")
class Model:
@modal.enter()
def setup(self):
self.model = load_model()
@modal.method()
def predict(self, prompt: str) -> str:
return self.model(prompt)
@modal.exit()
def cleanup(self):
del self.modelCalling
@app.local_entrypoint()
def main():
model = Model()
result = model.predict.remote("hello")Lifecycle Hooks
@modal.enter()
Runs once when a container starts. Use for expensive initialization:
@modal.enter()
def setup(self):
self.model = load_model("/models/llama")
self.tokenizer = load_tokenizer()@modal.exit()
Runs when a container shuts down. Use for cleanup:
@modal.exit()
def teardown(self):
save_metrics(self.metrics)@modal.exit() also runs on SIGTERM (preemption).
@modal.method()
Exposes a class method as an invokable Function:
@modal.method()
def predict(self, x):
return self.model(x)Parametrization
Create separate container pools per parameter combination:
@app.cls()
class Worker:
user_id: str = modal.parameter()
model_size: str = modal.parameter(default="small")
@modal.enter()
def setup(self):
self.model = load_model(self.model_size)
@modal.method()
def process(self, data):
return self.model(data)Calling parametrized classes
w1 = Worker(user_id="alice", model_size="large")
w1.process.remote(data) # runs in alice/large pool
w2 = Worker(user_id="bob")
w2.process.remote(data) # runs in bob/small pool (separate containers)Each unique parameter combination gets its own autoscaling pool.
with_options (Runtime Override)
Override class configuration dynamically:
Model = modal.Cls.from_name("my-app", "Model")
FastModel = Model.with_options(gpu="H100", max_containers=10)
FastModel().predict.remote("hello")Stackable: Model.with_options(gpu="H100").with_options(scaledown_window=300)
Go SDK — Calling Deployed Classes
mc, _ := modal.NewClient()
// Reference a deployed class
cls, _ := mc.Cls.FromName(ctx, "my-app", "Model", nil)
// Create a parameterized instance
instance := cls.Create(map[string]any{"model_size": "large"})
// Call a method
result, _ := instance.Method("predict").Remote(ctx, []any{"hello"}, nil)
// Spawn async
call, _ := instance.Method("predict").Spawn(ctx, []any{"hello"}, nil)
later, _ := call.Get(ctx, nil)TypeScript SDK — Calling Deployed Classes
import { ModalClient } from "modal";
const modal = new ModalClient();
// Reference a deployed class
const cls = await modal.cls.fromName("my-app", "Model");
// Create a parameterized instance
const instance = await cls.create({ model_size: "large" });
// Call a method
const result = await instance.method("predict").remote(["hello"]);
// Spawn async
const call = await instance.method("predict").spawn(["hello"]);
const later = await call.get();Note: Go/TS SDKs can only call deployed classes — defining classes with lifecycle hooks (@modal.enter, @modal.exit) is Python-only.
Symptom Triage
"Model loads on every request"
- Use
@modal.enter()to load once per container - Move model loading from
__init__or method body to@modal.enter()
"Container shutdown is abrupt"
- Use
@modal.exit()for graceful cleanup @modal.exit()receives SIGTERM on preemption
"Each user shares a container pool"
- Use
modal.parameter()to create per-user pools - Each unique parameter combination scales independently
Reference Map
references/classes-and-methods.md— @app.cls, @modal.method, invocation patternsreferences/lifecycle-hooks.md— @modal.enter, @modal.exit, execution orderreferences/parametrization.md— modal.parameter, per-user pools, with_options
Related Skills
modal-servers—@app.serveralso uses@modal.enter/@modal.exit, but exposes HTTP to a port (no@modal.method)modal-scaling-performance— memory snapshots with@modal.enter(snap=True), concurrency, batchingmodal-parallel-execution— calling class methods via.remote/.map/.spawn
Guardrails
@modal.enter()runs once per container, not once per input@modal.exit()is best-effort on container shutdown- Parameters are limited to 16 KiB total
- Use
@modal.method()(not@app.function()) for class methods @app.cls()replaces@app.function()for the class decorator- Do not put
@modal.methodon an@app.serverclass — usemodal-serversfor port-based serving
In this repository80 other files it gives its agents.
- a11y-accessibility-designSkill
- agentic-ui-patternsSkill
- ai-native-ui-designSkill
- ai-ui-anti-patternsSkill
- ai-ui-heuristicsSkill
- calm-technology-uiSkill
- conversion-growth-designSkill
- cross-platform-designSkill
- dark-mode-designSkill
- data-visualizationSkill
- design-systemsSkill
- design-thinking-processSkill
- error-empty-statesSkill
- ethical-design-patternsSkill
- form-uxSkill
- information-architectureSkill
- interaction-design-patternsSkill
- internationalization-uiSkill
- mobile-touch-designSkill
- modal-container-imagesSkill
- modal-dicts-queuesSkill
- modal-endpointsSkill
- modal-fundamentalsSkill
- modal-gpu-computeSkill
- modal-networkingSkill
- modal-observabilitySkill
- modal-parallel-executionSkill
- modal-sandboxesSkill
- modal-scaling-performanceSkill
- modal-schedulingSkill
- modal-secretsSkill
- modal-serversSkill
- modal-storageSkill
- modal-web-servingSkill
- modal-workspace-adminSkill
- motion-design-principlesSkill
- notifications-permissionsSkill
- onboarding-uxSkill
- rust-api-designSkill
- rust-async-programmingSkill
- rust-cargo-masterySkill
- rust-cli-applicationsSkill
- rust-clippy-lintsSkill
- rust-closures-iteratorsSkill
- rust-compiler-internalsSkill
- rust-concurrencySkill
- rust-design-patternsSkill
- rust-editionsSkill
- rust-embeddedSkill
- rust-error-handlingSkill
- rust-game-developmentSkill
- rust-lifetimes-borrowingSkill
- rust-macrosSkill
- rust-performanceSkill
- rust-rustdocSkill
- rust-rustup-toolchainSkill
- rust-smart-pointersSkill
- rust-testing-benchmarkingSkill
- rust-type-systemSkill
- rust-unsafe-ffiSkill
- The first 60 shown.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

