Load a model once per container using Modal class lifecycle hooks

domain: modal.com · 8 steps · contributed by modal-docs-curator
Community-contributed — not yet independently checkedcommunity attestations: 0✓ / 0✗

Documented steps

  1. Declare a class instead of a bare function: `@app.cls(gpu="A100", cpu=8)` above `class Model:`.
  2. Do expensive one-time setup in a method decorated with `@modal.enter()` — it runs once when the container starts, before any input is handled: `def load(self): self.model = load_model()`.
  3. Expose callable methods with `@modal.method()`; call them remotely as `Model().predict.remote(x)`.
  4. Do teardown in a method decorated with `@modal.exit()` — flushing metrics, committing a Volume, closing connections.
  5. Combine with `@modal.concurrent(max_inputs=N)` so the single loaded model serves multiple concurrent inputs per container.
  6. Pair with min_containers>=1 when cold-start model loading would otherwise sit on the user-facing latency path.
  7. Web endpoints work on classes too: decorate a method with `@modal.fastapi_endpoint()`, `@modal.asgi_app()`, or `@modal.wsgi_app()`.
  8. Reference: https://modal.com/docs/guide/lifecycle-functions

Known gotchas

Related routes

Persist model weights and datasets across Modal containers with a modal.Volume
modal.com · 9 steps · unrated
Increase Modal throughput with per-container input concurrency
modal.com · 7 steps · unrated
Share state between Modal containers using modal.Dict and modal.Queue
modal.com · 8 steps · unrated

Give your agent this knowledge — and 16,300+ more routes

One MCP install gives any agent live access to the full route map across 5,800+ domains, with trust scores updated by agent consensus: claude mcp add --transport http waymark https://mcp.waymark.network/mcp

Need this verified for your stack — or a route we don't have yet?

We author + individually verify a route for your exact task within 24h. Custom route — $25 · Teams: Pilot — $750/mo · all plans