# Chalk Compute Reference: Remote Class
source: https://docs.chalk.ai/compute-docs#section-remote-class

Deploy Python classes with multiple methods as versioned remote functions.

Use `@chalkcompute.cls()` with `@chalkcompute.method()` to mark methods for deployment. Lifecycle hooks [`@before()`](https://docs.chalk.ai/compute-docs#before) and [`@after()`](https://docs.chalk.ai/compute-docs#after) run startup and shutdown logic in each method's container.

## `@cls(user_cls, image, cpu, compute_class, network_policy, execution_target, memory, gpu, name, env, secrets, volumes, tags, chalk_identity, authenticated, readiness_probe, min_replicas, max_replicas, shutdown_delay_seconds, scaling_interval_seconds, target_cpu_utilization_percentage, target_gpu_utilization_percentage, target_queue_depth, cron_scaling_trigger, scale_from_zero_request_policy, serialization_format, options, max_buffer_duration, max_batching_size, retries, rate_limit, concurrency, queue_policy, schedule, models, tracing)`
source: https://docs.chalk.ai/compute-docs#cls

Decorator that deploys a class as versioned remote functions.

Prefer `@cc.cls` or `@cc.cls(image=...)` without `name=`; the registered name defaults to the Python class's name. Add other options only for a concrete workload requirement. Normally omit `min_replicas`, `max_replicas`, and `concurrency`: defaults are one replica per method and no explicit concurrency policy. Document necessary tuning overrides rather than copying unrelated examples' settings or repeating defaults.

**Locally** (at decoration time):

1. Scans the class for [`@method`](https://docs.chalk.ai/compute-docs#method), [`@before`](https://docs.chalk.ai/compute-docs#before), [`@after`](https://docs.chalk.ai/compute-docs#after)
2. Builds a deploy image with per-method handler shims
3. Registers each method via `ExternalFunctionCatalogService`
4. If `CHALK_FUNCTION_LOCAL_SDK_COPY=1`, includes local SDK source in the deploy image for unreleased feature iteration.

**Remotely** (inside the container): Lifecycle methods become no-ops. Accessing a [`@method`](https://docs.chalk.ai/compute-docs#method) runs the local method body in-process when called; `.remote()` / `.defer()` dispatch to the deployed method (resolved lazily by name), so a method can invoke a sibling without `RemoteClass.from_name(...)`.

**Parameters**

- `user_cls`: `type | None` = `None`
- `image`: `_Image | None` = `None`
  Container image to deploy in. Defaults to `Image.debian_slim()`.
- `cpu`: `str | None` = `None`
  CPU resource request (e.g. `"1"`, `"500m"`).
- `compute_class`: `ComputeClass | None` = `None`
  Where to run replicas. Omit to use the server default; HOST requires fixed, positive replica counts.
- `network_policy`: `NetworkPolicy | None` = `None`
  Optional host egress policy. Omit for the server default; [`NetworkPolicy()`](https://docs.chalk.ai/compute-docs#NetworkPolicy) denies all egress. Kubernetes does not support it.
- `execution_target`: `ExecutionBackend | None` = `None`
  Optional [`ExecutionBackend`](https://docs.chalk.ai/compute-docs#ExecutionBackend); defaults to the environment cluster.
- `memory`: `str | None` = `None`
  Memory resource request (e.g. `"1Gi"`, `"512Mi"`).
- `gpu`: `str | None` = `None`
  GPU resource request (e.g. `"nvidia-l4"`, `"2:nvidia-a100"`).
- `name`: `str | None` = `None`
  Optional registered-name override. Omit this in normal usage to use the class's `__name__`. Set it only when a different registered name is intentional, such as preserving existing deployments after renaming the Python class. For a new class, choose a descriptive Python name instead of adding a prefix via this option. Changing or removing an override changes the target functions; it does not rename existing deployments.
- `env`: `Mapping[str, str | _Secret] | None` = `None`
  Environment variables as strings or single-value Secret references. The mapping key sets the injected name, overriding aliases and prefixes.
- `secrets`: `list[_Secret] | None` = `None`
  List of `Secret` references to inject.
- `volumes`: `list[tuple[str | Volume, str] | Volume | VolumeMount] | None` = `None`
  List of [`Volume`](https://docs.chalk.ai/compute-docs#Volume) handles, [`VolumeMount`](https://docs.chalk.ai/compute-docs#VolumeMount) specifications, or `(name_or_volume, mount_path)` tuples for persistent storage. Volume handles preserve their selected ref or pinned version.
- `tags`: `dict[str, str] | None` = `None`
- `chalk_identity`: `bool | ChalkIdentity` = `False`
- `authenticated`: `bool` = `False`
- `readiness_probe`: `_ReadinessProbe | None` = `None`
- `min_replicas`: `int` = `1`
  Minimum number of replicas per method. Defaults to 1; normally omit. Set to 0 only when deliberately choosing scale-to-zero behavior.
- `max_replicas`: `int` = `1`
  Maximum number of replicas per method. Defaults to 1; normally omit. Increase only when the workload needs additional replica capacity.
- `shutdown_delay_seconds`: `int | None` = `None`
  Graceful termination period in seconds before replicas are forcibly killed during scale-down. Defaults to 30s on the server.
- `scaling_interval_seconds`: `int | None` = `None`
  How often (in seconds) the autoscaler scrapes metrics to make scaling decisions. Defaults to 60s on the server.
- `target_cpu_utilization_percentage`: `int | None` = `None`
  Target CPU utilization percentage (0-100) that drives autoscaling.
- `target_gpu_utilization_percentage`: `int | None` = `None`
  Target GPU utilization percentage (1-100) that drives autoscaling, read from DCGM. Requires `gpu` and `min_replicas >= 1`: the utilization series exists only while replicas do, so this trigger cannot scale a group up from zero.
- `target_queue_depth`: `int | None` = `None`
  Target pending-request queue depth per replica. When set, the autoscaler scales on each method's own queue depth.
- `cron_scaling_trigger`: `_CronScalingTrigger | None` = `None`
  Sets a replica floor during specified cron-defined time windows, independent of the other autoscaling triggers.
- `scale_from_zero_request_policy`: `_ScaleFromZeroRequestPolicy | None` = `None`
- `serialization_format`: `SerializationFormat` = `'pyarrow'`
  Wire format for arguments and results. Currently only `"pyarrow"` is supported.
- `options`: `dict[str, str] | None` = `None`
  Arbitrary key-value options forwarded to the Chalk platform.
- `max_buffer_duration`: `int | None` = `None`
  Maximum time in milliseconds to buffer incoming items before invoking the handler. Defaults to 1000 ms when batching is enabled. When batching is enabled, handler args are lists.
- `max_batching_size`: `int | None` = `None`
  Maximum number of items to accumulate before invoking the handler. Defaults to 10 when batching is enabled.
- `retries`: `int | RetryPolicy | None` = `None`
  Retry policy for handler invocations. An [`int`](https://docs.python.org/3/library/functions.html#int) is the number of retries after the initial execution. Direct calls apply the policy's backoff and jitter client-side; Redis Stream queues apply the count with a fixed reclaim delay. Override per call using `with_options`. Exception filters and shared retry keys are not supported.
- `rate_limit`: `int | RateLimitPolicy | None` = `None`
  Rate limit policy for outbound calls. Pass an [`int`](https://docs.python.org/3/library/functions.html#int) for a simple "N per second" cap with a per-method key, or a `RateLimitPolicy` for full control (`rate`, `per`, `key`). Multiple methods sharing the same `key` share one bucket — used when a downstream service imposes a throughput limit across callers.
- `concurrency`: `int | ConcurrencyPolicy | None` = `None`
  Optional cap on in-flight handler invocations. Defaults to [`None`](https://docs.python.org/3/library/constants.html#None) (no explicit policy); normally omit. It does not enable parallel execution. Set only for a known in-flight limit. Pass an [`int`](https://docs.python.org/3/library/functions.html#int) for a simple `max_concurrent` cap with a per-method key, or a `ConcurrencyPolicy` for full control (`max_concurrent`, `key`). Multiple methods sharing the same `key` share one gate — independent of `rate_limit` (which caps rate, not in-flight count).
- `queue_policy`: `QueuePolicy | None` = `None`
  Queue configuration shared by the class's methods, including the pending-item cap and asynchronous result retention. Pass a `QueuePolicy`; terminal results are retained for one day by default or for `result_ttl_seconds` when configured.
- `schedule`: `str | None` = `None`
  Optional crontab or Chalk duration string applied to every no-input [`@method`](https://docs.chalk.ai/compute-docs#method) in the class (e.g. `"0 * * * *"` or `"1h"`).
- `models`: `Mapping[str, Any] | None` = `None`
- `tracing`: `TracingPolicyConfig | None` = `None`

## `method(func)`
source: https://docs.chalk.ai/compute-docs#method

Mark a class method for remote deployment.

## `before(func)`
source: https://docs.chalk.ai/compute-docs#before

Mark a method as the startup hook (called before the server starts).

## `after(func)`
source: https://docs.chalk.ai/compute-docs#after

Mark a method as the shutdown hook (called when the process exits).

## `RemoteClass`
source: https://docs.chalk.ai/compute-docs#RemoteClass

Class

A managed class backed by ExternalFunctionCatalogService.

Deploys each [`@method`](https://docs.chalk.ai/compute-docs#method) as a separate function version with its own scaling group, sharing a single container image. Lifecycle hooks ([`@before`](https://docs.chalk.ai/compute-docs#before) / [`@after`](https://docs.chalk.ai/compute-docs#after)) run in every method's container.

Most users should prefer the [`cls`](https://docs.chalk.ai/compute-docs#cls) decorator.

**Examples**

Deploy a stateful class with an expensive warm-up step, then call individual methods remotely:

```python
import chalkcompute
from chalkcompute import Image
img = (
    Image.debian_slim()
    .pip_install(["sentence-transformers"])
)
@chalkcompute.cls(
    image=img,
    cpu="2",
    memory="4Gi",
)
class Embedder:
    @chalkcompute.before
    def load(self):
        from sentence_transformers import SentenceTransformer
        self.model = SentenceTransformer("all-MiniLM-L6-v2")
    @chalkcompute.method
    def embed(self, text: str) -> list[float]:
        return self.model.encode(text).tolist()
    @chalkcompute.method
    def embed_batch(self, texts: list[str]) -> list[list[float]]:
        return self.model.encode(texts).tolist()
    @chalkcompute.after
    def shutdown(self):
        del self.model
Embedder.deploy()
e = Embedder()
vec = e.embed("hello world")
batch = e.embed_batch(["a", "b", "c"])
```

**Attributes**

- `class_name`: `str`
- `deployed`: `bool`

### `RemoteClass.from_name(name, chalk_client)`
source: https://docs.chalk.ai/compute-docs#RemoteClass.from_name

Attach to an existing remote class by name.

Discovers all function versions whose `functionName` starts with `{name}.` and rebuilds a [`RemoteClass`](https://docs.chalk.ai/compute-docs#RemoteClass) with callable methods.

**Parameters**

- `name`: `str`
  Class name previously used at deploy time.
- `chalk_client`: `Any | None` = `None`

**Returns**

`RemoteClass`

A handle bound to the existing versions.

**Raises**

- `ClassError`: If no function versions are found for the given name.

### `RemoteClass.deploy(poll_interval, build_timeout, ready_timeout, force_new_version)`
source: https://docs.chalk.ai/compute-docs#RemoteClass.deploy

Deploy all methods, reusing unchanged function versions.

`force_new_version=True` creates fresh versions while still reusing image builds and source uploads.

**Parameters**

- `poll_interval`: `float` = `0.5`
  Seconds between status polls.
- `build_timeout`: `float` = `600.0`
  Maximum seconds to wait for the image build.
- `ready_timeout`: `float` = `300.0`
  Maximum seconds to wait for scaling groups to become ready.
- `force_new_version`: `bool` = `False`

**Returns**

`RemoteClass`

`self` for chaining.

### `RemoteClass.wait_ready(timeout, poll_interval)`
source: https://docs.chalk.ai/compute-docs#RemoteClass.wait_ready

Wait until all backing scaling groups have ready replicas.

**Parameters**

- `timeout`: `float` = `120.0`
  Maximum seconds to wait per method.
- `poll_interval`: `float` = `2.0`
  Seconds between status polls.

**Returns**

`RemoteClass`

`self` for chaining.

### `RemoteClass.delete()`
source: https://docs.chalk.ai/compute-docs#RemoteClass.delete

Delete all function versions and clean up volumes.

### `RemoteClass.refresh()`
source: https://docs.chalk.ai/compute-docs#RemoteClass.refresh

Fetch latest info for all methods from the server.

**Returns**

`dict[str, FunctionVersionInfo]`

Mapping of method name to updated [`FunctionVersionInfo`](https://docs.chalk.ai/compute-docs#FunctionVersionInfo).

## `ClassError`
source: https://docs.chalk.ai/compute-docs#ClassError

Exception (bases: `Exception`)

Base exception for RemoteClass errors.

## `ClassBuildError`
source: https://docs.chalk.ai/compute-docs#ClassBuildError

Class (bases: `ClassError`)

Raised when the class image build fails.
