# Templates and Options

These instructions apply to the current Admin Console.

{% hint style="info" %}
Contextual Workers are in early access and may not be available in your account. [Contact Contextual support](mailto:help@contextual.io) to request that Workers be enabled for your tenant.
{% endhint %}

A managed Worker combines two things: your app's release manifest, `worker.json`, and a managed template with its options. The manifest says what your app can do. The template and its options say how this Worker runs it.

## The Release Manifest

The adapter image's `package` command reads `worker.json` and refuses an invalid one before it writes anything.

| Field | Required | Meaning |
| --- | --- | --- |
| `workerId` | Yes | The app's name: lowercase words joined by hyphens. It must match the name your code gives the Worker: `name` in TypeScript's default export, and the name passed to the Worker in Rust, Go, and Python. |
| `version` | Yes | A semantic version, such as `1.0.0`, matching the version in your code. Raise it for each release. |
| `handlers` | Yes | 1 to 64 handlers. Each name starts with a letter and uses letters, digits, or underscores. Each handler lists the triggers it accepts: `event`, `http`, or `cron`. |
| `configSchema` | No | A JSON Schema object for the Worker's `CONFIG` option. The TypeScript adapter checks `CONFIG` against it when the Worker starts. The Rust, Go, and Python adapters don't, so check the values you read. |
| `connections` | No | Up to 32 connection aliases the app uses, such as `["crm"]`. Each deployment binds every alias to a tenant connection. See [Connections](https://docs.contextual.io/build/contextual-workers/managed-workers/capabilities.md#connections). |
| `entrypoint` | TypeScript | The file to load: the bundled `.cjs` file in TypeScript, or in Python the `.py` file in `src` that defines the handlers, `main.py` by default. Rust and Go releases are a binary and have no entrypoint. |

A release can declare several handlers. Each Worker runs one of them, which it selects with the `HANDLER` option. This lets one image serve, for example, an HTTP API Worker and an event-processing Worker. In TypeScript, `default` is the default export and another handler is a named export, such as `export async function audit(event, context) { … }`. In Rust, Go, and Python, register each handler by name, as the default handler is registered.

## Choose a Template

| Template | Trigger Your Handler Receives | Platform Access the Host Requests |
| --- | --- | --- |
| `managed-event-worker` | `topic`: one event from the Worker's topic | Consuming the Worker's topic with backlog scaling, plus everything below |
| `managed-http-worker` | `http`: one request to the Worker URL | Everything below |
| `managed-scheduled-worker` | `cron`: one tick of the Worker's UTC schedule | Everything below |

The console can also list the earlier `event-worker` and `scheduled-worker` templates. They run Node.js apps on a different, older contract, and do not use these runtime adapters. Use the `managed-*` templates for new Workers.

Use the template version released with your adapter version, and upgrade them together. See [Release Versions](https://docs.contextual.io/build/contextual-workers/managed-workers.md#release-versions).

The manifest names a delivered event's trigger `event`, but the handler sees `trigger.type` as `topic`. Check the trigger type explicitly when one handler accepts several triggers.

An event Worker processes one event at a time in each replica; scale it with replicas. An HTTP Worker runs requests concurrently in each replica, but an app built on an adapter older than HTTP multiplexing is served one request at a time.

The host requests all platform access. Your app requests none and never receives credentials. With every managed template, your handler can use records, actions, attachments, AI, AI Search, connections, cloud storage, logging, and sending to event Agents, all through the host. From template 0.10.0, it can also call the other platform services you grant in `PLATFORM_SERVICES`.

## Options

Set options in the admin console in the **Managed worker** fields, or with the CLI's `--option NAME=VALUE` and `--option-from-file NAME=PATH` flags. Option values are strings of at most 4096 characters, which also limits the size of `CONFIG` and `CONNECTION_BINDINGS`. Keep large configuration in a record and put its ID in `CONFIG`.

### All Templates

| Option | Default | Meaning |
| --- | --- | --- |
| `IMAGE` | Required | The app image that `package` produced. With `--build .worker-image`, the CLI builds, pushes, and sets it. |
| `CONFIG` | `{}` | The Worker's configuration as a JSON object. Only the TypeScript adapter checks it against `configSchema`. Your handler reads it as its config. |
| `HANDLER` | `default` | The handler to run. It must accept the template's trigger. |
| `CONNECTION_BINDINGS` | `{}` | A JSON object that binds each alias in `connections` to a tenant connection, such as `{"crm":"native-object:api-configuration/salesforce-prod"}`. It must bind exactly the declared aliases, or the Worker does not deploy. |
| `PLATFORM_SERVICES` | None | From template 0.10.0. The platform services the app can call with `services.request`, as a comma-separated list such as `logsApi,observabilityApi`. Empty grants none. The typed capabilities and declared connections don't need it. `connectionsApi` cannot be granted: the host does not start. See [Call Platform Services](https://docs.contextual.io/build/contextual-workers/managed-workers/platform-services.md). |

### Event Template

| Option | Default | Meaning |
| --- | --- | --- |
| `MIN_REPLICAS` | `0` | Fewest replicas. `0` scales the Worker to zero while its backlog is empty. |
| `MAX_REPLICAS` | `1` | Most replicas. |
| `POLLING_INTERVAL` | `20` | Seconds between backlog checks, at least 5. |
| `COOLDOWN_PERIOD` | `5` | Seconds without backlog before scaling to zero. |
| `LAG_THRESHOLD` | `100` | Backlog per replica that adds another replica, at least 2. |

### HTTP Template

| Option | Default | Meaning |
| --- | --- | --- |
| `HTTP_CONCURRENCY` | `10` | Requests each replica handles at the same time, 1 to 100. |
| `HTTP_QUEUE_CAPACITY` | `min(10, 101 − HTTP_CONCURRENCY)` | Requests that can wait for a free slot. `0` disables waiting. |
| `HTTP_ADMISSION_TIMEOUT_MS` | `1000` | How long a request can wait for a slot, 1 to 30000 milliseconds. |

`HTTP_CONCURRENCY` plus `HTTP_QUEUE_CAPACITY` must be at most 101, or the host does not start. A request that finds no slot within the admission timeout, or a full queue, gets a 503 with `Retry-After: 1`. A replica that is shutting down also answers 503.

The HTTP Worker's replica and CPU settings are ordinary Worker settings. The Worker environment variables `BODY_SIZE_LIMIT` (default `1mb`, at most 1 GiB) and `HTTP_TIMEOUT_MS` (default 30000, from 1000 to 1800000) set the request body limit and the request deadline. A larger body gets a 413 response, and a body cut short gets a 400. A request past the deadline gets a 504. Raise `HTTP_TIMEOUT_MS` for long requests, such as large file transfers.

### Scheduled Template

The scheduled template has only the common options. Set the schedule with the Worker's **Schedule** setting or `--schedule` in UTC cron syntax. Each tick runs your handler once in a new pod. A run is stopped after 30 minutes, a failed run is not retried, and a tick is skipped while the previous run is still in progress.

How long a handler can run depends on its trigger. An HTTP handler is cut off at `HTTP_TIMEOUT_MS`. An event handler that runs past 30 minutes stops the host, and the event is redelivered. A scheduled run is stopped after 30 minutes.

## Add Services With a Compose File

Instead of setting a template's image option, a Worker can send a Compose file beside its options. The file defines the app service, which is the service whose image is the template's image option. The file can also add services of its own, such as a cache or a migration step, to the same Pod. This works with every managed template and every organization template that has an image option. For example, in the `managed-event-worker` template, the image option is `IMAGE` and the app service is `app`.

This example adds a cache to a `managed-event-worker` Worker:

```yaml
x-contextual:
  version: 1
services:
  app:
    build: .worker-image
    depends_on:
      cache: { condition: service_healthy }
  cache:
    image: images.<org>.my.contextual.io/redis:7
    volumes:
      - { type: volume, source: cache, target: /data }
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
volumes:
  cache: {}
```

Pass the Compose file with `--compose` when you select the managed template.

```sh
ctxl workers create orders \
  --size small \
  --managed managed-event-worker:0.10.0 \
  --compose compose.yaml \
  --option MIN_REPLICAS=1 \
  --config-id my-config \
  --pretty
```

The CLI builds and pushes each service that declares `build:`. In the console, choose **Configuration → Compose** under the template. To rebuild the app later, update the Worker with `--compose` again. See [Use Compose or a Managed Template](https://docs.contextual.io/build/contextual-workers/contextual-cli.md#use-compose-or-a-managed-template).

The file combines with the template as follows:

* **The app service.** Defining the app service fills the image option, so set one or the other. Its settings are added to the template's. Mappings such as `environment`, `depends_on`, `healthcheck`, and `x-contextual` merge key by key, and `expose` adds ports. A value the template already sets cannot change. `command`, `entrypoint`, `working_dir`, `ports`, and the health check's `test` must match the template's when both set them.
* **Mounts.** A mount you add, on the app service or on a service of your own, must use a volume, config, or secret your file declares. The template's own volumes stay the template's. On the app service, no added mount may sit at, inside, or above a path the template mounts there. Repeating one of those mounts exactly is allowed. For example, in the `managed-event-worker` template, `host-tls`, `worker-tls`, and `release` are the template's volumes, and `app` mounts `/worker-tls` and `/shared/release`.
* **New names.** Other services, volumes, configs, and secrets must use names the template does not use. For example, in the `managed-event-worker` template, `host` is taken.
* **The public service.** A service is public only when it sets `x-contextual.public`. A service you add can be public only when the template has no public service of its own. For example, in the `managed-http-worker` template, the host stays the public service.
* **Checks.** Every rule for a Worker's own Compose file applies to the combined file. The file you send cannot use variables; write `$$` for a literal `$`. Its images are pinned to digests when the Worker is saved.
* **One Pod.** The added services share the Worker's size and environment variables. On an event Worker, they start with every replica, including each scale-up from zero.

## What Your Handler Receives

Every invocation has an `id` and a `trigger`. For an event, the `id` comes from the topic and message, so it stays the same when the event is redelivered. The context's invocation ID is new for every attempt. The other fields depend on the trigger:

| Trigger | `payload` | `trigger` Fields |
| --- | --- | --- |
| `topic` | The event's JSON value | `topic`, `subscription`, `messageId`, `key`, `publishedAt`, `redeliveryCount`, `properties` |
| `http` | Empty. The managed host always streams the request body (`bodyEncoding` is `stream`), so read it from the request body stream. See [Read a Request Body](https://docs.contextual.io/build/contextual-workers/managed-workers/capabilities.md#read-a-request-body). | `method`, `path` (with the query string), `headers`, `bodyEncoding` |
| `cron` | None | `schedule`, `timeZone` (`Etc/UTC`), `startedAt` |

The handler also receives a context: the Worker's config, a logger, the platform capabilities, and a cancellation signal. See [Platform Capabilities](https://docs.contextual.io/build/contextual-workers/managed-workers/capabilities.md).

## How Results Are Settled

* **Event:** The host acknowledges the event only after your handler returns successfully. An unhandled failure in your handler stops the host with the event unacknowledged, on the first failure. The container restarts, and the event is redelivered, possibly to another replica. The only failure retried without stopping the host is a failed send to another Agent with `messaging.sendToAgent`, because the broker was at fault. There is no dead-letter queue, so an event that always fails makes the Worker restart repeatedly. Catch failures that retrying cannot fix, such as invalid input: log them and return successfully. An event payload that is not JSON, or that is larger than 8 MiB, also stops the host. Delivery is at least once, so make side effects safe to repeat. Use the event's `id` as the idempotency key.
* **HTTP:** Return a response: `status` from 200 to 599, optional `headers`, and a string `body`. Set `bodyEncoding` to `base64` for binary bodies. A returned body can be at most 4 MiB, with at most 64 headers in 32 KiB. Hop-by-hop headers, such as `connection` and `transfer-encoding`, are dropped. Returning nothing sends 204. A handler failure, an invalid status, or an unknown response field sends 500. To send a larger body, stream it. See [Stream HTTP Requests and Responses](https://docs.contextual.io/build/contextual-workers/managed-workers/capabilities.md#stream-http-requests-and-responses).
* **Schedule:** The run succeeds when the handler returns and fails when it fails.

If your handler catches a platform failure and returns successfully, the host treats the invocation as a success. Return or raise the failure, or an error caused by it, to fail the invocation. The host then records which call failed, which is how it recognizes a failed send to another Agent as the broker's fault.

## Move from the Earlier Templates

A Worker on `event-worker` or `scheduled-worker` runs a TypeScript module built `FROM` `event-worker-node`. To move it to `managed-event-worker` or `managed-scheduled-worker`:

1. **Keep the handler.** Keep its `run(event, context)` logic. The trigger types (`topic` and `cron`), `context.logger`, and `context.records.get` and `patch` work the same way.
2. **Move configuration into `CONFIG`.** The earlier `parseConfig` received the container's environment variables. The managed templates pass the `CONFIG` option, checked against `configSchema`. Move non-secret settings into `CONFIG`. Keep secrets in Worker environment variables, and read them from `process.env`.
3. **Add a `worker.json`** with the `workerId`, `version`, handler, `configSchema`, and `entrypoint`. See [The Release Manifest](#the-release-manifest).
4. **Build with the TypeScript adapter.** Drop the `event-worker-node` import: with adapter 0.10.0, the module default-exports the Worker definition and imports nothing from the adapter. Bundle, and run `package`. Then update the Worker with `--managed managed-event-worker:0.10.0 --build .worker-image` and the scaling options you used before. See [Build Your First Managed Worker](https://docs.contextual.io/build/contextual-workers/managed-workers/get-started.md).
5. **Replace retries and dead-lettering.** The earlier template's `MAX_ATTEMPTS`, `RETRY_DELAY_MS`, and `DEAD_LETTER_QUEUE` options have no equivalent. In a managed template, an unhandled failure stops the host and the event is redelivered. To dead-letter an event, catch the failure, send the event to another event Worker with `messaging.sendToAgent`, and return successfully.

Test the moved Worker in your tenant with events that succeed and events that fail before completing the migration.

## Environment Variables

Your app receives the Worker's environment variables, such as API keys set under **Environment variables** in the admin console. Saving a Worker refuses names that start with `CONTEXTUAL_`. Names that start with `WORKER_`, `PULSAR_`, or `MESSAGING_` are saved, but the platform uses those prefixes, so don't use them either. The TypeScript adapter doesn't pass them to your app. Keep secrets in Worker environment variables, not in the image or `CONFIG`. The request deadline also applies to an HTTP request that waits on a slow platform call, so set `HTTP_TIMEOUT_MS` from the slowest operation your handler performs.
