> ## Documentation Index
> Fetch the complete documentation index at: https://docs.goldsky.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Compose task triggers: cron, HTTP, and onchain

> Configure cron, HTTP, and onchain event triggers for Compose tasks, including parallel processing, max concurrency, confirmations, and failure handling.

Your compose tasks can be triggered by several different mechanisms. Triggers are configured in your [manifest file](https://docs.goldsky.com/compose/app-configuration.md) for each task.
Each task can have multiple triggers (one of each type), so triggers are configured as an array. Below is an overview of all the supported trigger types: `cron`, `http`, and `onchain_event`.

## Local Task Execution

For locally testing tasks you can use the `callTask` CLI command. This works regardless of what trigger types a task has configured (and even for tasks with no triggers at all).

#### Trigger Task locally with CLI

```bash theme={"dark"}
goldsky compose callTask "my_task" '{ "foo": "bar" }' --env local
```

#### Task Code

```typescript theme={"dark"}
import { TaskContext } from "compose";

type Payload = {
  foo: string;
};

export async function main({ collection }: TaskContext, payload: Payload) {
  // the task will be called with the payload sent from the CLI callTask command
  console.log(payload.foo);
}
```

## Task To Task Execution

Tasks can call other tasks directly, with no trigger configuration required on the called task. This is done using the [callTask](https://docs.goldsky.com/compose/context/call-task.md) context function.

### Example

```typescript highlight={10-17} theme={"dark"}
import { TaskContext } from "compose";

type ProcessDataPayload = {
  dataId: string;
  operation: string;
};

export async function main({ callTask }: TaskContext, payload: ProcessDataPayload) {
  // Call another task with a payload
  const result = await callTask<{ success: boolean; processed: number }>(
    "process-data",
    {
      dataId: payload.dataId,
      operation: payload.operation,
    }
  );

  return {
    status: "completed",
    result,
  };
}
```

The `process-data` task will receive the payload and can return a response:

```typescript theme={"dark"}
import { TaskContext } from "compose";

type ProcessDataArgs = {
  dataId: string;
  operation: string;
};

export async function main({ collection }: TaskContext, payload: ProcessDataArgs) {
  // Process the data based on the operation
  const processed = await collection("data").findMany({ id: payload.dataId });

  return {
    success: true,
    processed: processed.length,
  };
}
```

## Chain Event Triggers

Tasks can be triggered by onchain events. The payload delivered to the task is the raw encoded log. Compose provides helpers for decoding the event in your task code. See [Contracts](https://docs.goldsky.com/compose/context/evm/contracts.md) for decoding details.

> [!WARNING]
>
> Onchain event triggers only fire when your app is **deployed** to the cloud. They do not fire during local development.
> To test a task with an onchain trigger locally, use `callTask` with a sample event payload:
>
> ```bash theme={"dark"}
> goldsky compose callTask "my_task" '{"blockNumber":48758053,"address":"0xb74de3F91e04d0920ff26Ac28956272E8d67404D","data":"0x","topics":["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"],"transactionHash":"0x2c50...","logIndex":343}' --env local
> ```
>
> You can copy a real event payload from a block explorer to use as test data.

#### Example event object sent as the payload to your task:

```json theme={"dark"}
{
  "blockNumber": 48758053,
  "blockHash":
    "0x6794a56583329794f184d50862019ecf7b6d8ba6b3210f68ca4b91a8fa81817d",
  "transactionIndex": 29,
  "removed": false,
  "address": "0xb74de3F91e04d0920ff26Ac28956272E8d67404D",
  "data": "0x",
  "topics": [
    "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef",
    "0x0000000000000000000000000000000000000000000000000000000000000000",
    "0x000000000000000000000000eec2ba9b9f0202c63bba29ea9a4ce5c23f9865fd",
    "0x0000000000000000000000000000000000000000000000000000000000001099",
  ],
  "transactionHash":
    "0x2c500a55f5c24d587e73805975d91395634a971dca5939f43d34d774d0f7147b",
  "logIndex": 343,
}
```

#### Example configuration for an onchain event trigger:

```yaml highlight={6-10} theme={"dark"}
name: "my-app"
tasks:
  - name: "on_transfer"
    path: "./tasks/on_transfer.ts"
    triggers:
      - type: "onchain_event"
        network: "base_sepolia"
        contract: "0xb74de3F91e04d0920ff26Ac28956272E8d67404D"
        events:
          - "Transfer(address,address,uint256)"
```

#### Task code

Here's an example in which we decode the event with a contract class we've generated with `goldsky compose codegen`, see [Contracts](https://docs.goldsky.com/compose/context/evm/contracts.md) for more info.

```typescript theme={"dark"}
import { TaskContext, OnchainEvent } from "compose";

// the payload for an onchain triggered task will always be our built in OnchainEvent interface
export async function main({ evm }: TaskContext, payload: OnchainEvent) {
  // we can decode the event with our ABI generated contract class
  // the type of this decodedEvent will be a union of all events that the ABI specifies, allowing you to conditionally process based on the eventName
  const decodedEvent = evm.contracts.MyNFT.decodeEventLog(payload);

  if (decodedEvent.eventName === "Transfer") {
    // in this code block typescript will know the decodedEvent is of type TransferEventDecoded
    // this pattern is useful when your trigger supports multiple event types
    console.log("Transfer event:", decodedEvent.args);
  }

  // alternative would be to cast, this is useful if your trigger is configured for a single event type
  const castEvent = evm.contracts.MyNFT.decodeEventLog<TransferEventDecoded>(payload);
}
```

#### Onchain Trigger Properties

| Property | Type | Required | Description |
| - | - | - | - |
| `type` | `"onchain_event"` | Yes | Type discriminator |
| `network` | string | Yes (No with `pipeline`) | The network slug in snake\_case (e.g. `base_sepolia`, `ethereum_mainnet`). See [Chains](https://docs.goldsky.com/compose/context/evm/chains.md) for the full list. |
| `contract` | string | Yes (not allowed with `pipeline`) | The contract address (`0x` followed by 40 hex characters). |
| `events` | string\[] | No (not allowed with `pipeline`) | Specific event signatures (human-readable, not encoded) to match, e.g. `"Transfer(address,address,uint256)"`. If omitted, all logs from the contract are delivered. |
| `dataset_version` | string | No (not allowed with `pipeline`) | Override the dataset version for chains that don't use `1.0.0` (e.g., `megaeth_testnet_v2`). If not specified, the server auto-detects the correct version. |
| `pipeline` | object | No | A full Turbo pipeline definition that replaces the pipeline built from `contract` and `events`. Needs non-empty `sources` and `sinks`, and at least one `compose_task` sink. See [Custom pipelines](#custom-pipelines). |
| `parallel_processing` | boolean | No | Process events concurrently through an internal durable queue instead of one at a time. Defaults to `false`. See [Parallel processing](#parallel-processing). |
| `max_concurrency` | integer | No | How many events are processed at the same time. Must be a positive integer; defaults to `10`. Only used when `parallel_processing` is `true`. |
| `confirmations` | integer | No | Hold each event until its block is this many blocks deep before running the task. Must be a non-negative integer; defaults to `0` (run immediately). Requires `parallel_processing: true`, and `network` when `pipeline` is set. See [Confirmations](#confirmations). |

#### Custom pipelines

The `contract` and `events` fields cover one contract's logs. For anything else, set `pipeline` to a full [Turbo pipeline](https://docs.goldsky.com/turbo-pipelines/pipeline-config.md) definition. It takes the same YAML as a standalone Turbo pipeline: any [source](https://docs.goldsky.com/turbo-pipelines/sources/overview.md), [transform](https://docs.goldsky.com/turbo-pipelines/transforms/overview.md) and [sink](https://docs.goldsky.com/turbo-pipelines/sinks/overview.md), plus top-level fields such as `resource_size`.

This example runs a copy-trader task only for `OrderFilled` events on the Polymarket CTF Exchange where a given wallet is the indexed `maker` topic (the third topic, left-padded to 32 bytes):

```yaml theme={"dark"}
name: "copy-trader"
api_version: "stable"
tasks:
  - name: "copy_trader"
    path: "./src/tasks/copy-trader.ts"
    triggers:
      - type: "onchain_event"
        pipeline:
          resource_size: s
          sources:
            fills:
              type: dataset
              dataset_name: matic.raw_logs
              version: 1.0.0
              start_at: latest
              filter: address = '0x4bfb41d5b3570defd03c39a9a4d8de6bd8b8982e'
          transforms:
            watched:
              type: sql
              primary_key: id
              sql: |
                SELECT id, block_number, transaction_hash, log_index, address, data,
                       string_to_array(topics, ',') AS topics
                FROM fills
                WHERE topics LIKE '0xd0a08e8c493f9c94f29311604c9de1b4e8c8d4c06bd0c789af57f2d65bfec0f6%'
                  AND split_part(topics, ',', 3) = '0x0000000000000000000000001234567890abcdef1234567890abcdef12345678'
          sinks:
            to_task:
              type: compose_task
              from: watched
```

* **`compose_task` sink.** Add at least one sink with `type: compose_task` and a `from` naming the source or transform that feeds it. Compose replaces it with a webhook sink that delivers rows to this task. Other sink types, such as `postgres`, pass through unchanged, so one pipeline can feed your task and a database.
* **Task payload.** Your task receives the rows of whatever feeds the `compose_task` sink, with the columns that source or transform outputs. Select the columns your task needs. To decode logs with `decodeEventLog`, keep `data` and `topics`.
* **Everything else is passed through.** The Turbo API validates sources, transforms and other fields, so Turbo semantics are checked there. The pipeline is validated at deploy time, before the app rolls out, and the same plan limits as standalone Turbo pipelines apply. For example, Starter plans are limited to `xs` and `s` resource sizes, and dedicated IPs need the entitlement.
* **`name` is set by Compose.** A `name` inside `pipeline` is ignored.
* **Not combined with simple fields.** `contract`, `events` and `dataset_version` cannot be set alongside `pipeline`. Put the address filter and event topics in the source `filter` or the SQL instead.
* **`network` is optional.** Set it only when you use `confirmations`, so Compose can look up the chain to watch. With `confirmations`, `network` must be the chain of the source dataset, because depth is measured against that chain's head.
* **Confirmations need `block_number`.** With `confirmations > 0`, each row the `compose_task` sink receives must include a numeric `block_number`. Rows without one skip the confirmation buffer and run immediately.
* **Parallel processing needs an `id`.** With `parallel_processing: true`, every row must contain a string `id` column. Parallel processing currently requires `api_version: "preview"`.

#### Parallel processing

By default, onchain events are delivered one at a time: Goldsky sends an event, waits for your task to finish, then sends the next one. If a task takes 30 seconds and 2,000 events land in a burst, the last event runs hours late.

Set `parallel_processing: true` to switch the trigger to queued, concurrent delivery. This currently requires `api_version: "preview"`. Events are written to an internal durable queue as they are indexed, and a worker in your app runs up to `max_concurrency` of them at the same time.

```yaml highlight={12-13} theme={"dark"}
name: "my-app"
api_version: "preview"
tasks:
  - name: "on_transfer"
    path: "./tasks/on_transfer.ts"
    triggers:
      - type: "onchain_event"
        network: "ethereum"
        contract: "0xb74de3F91e04d0920ff26Ac28956272E8d67404D"
        events:
          - "Transfer(address,address,uint256)"
        parallel_processing: true
        max_concurrency: 50
```

Your task code does not change. `main(context, payload)` still receives a single event, and each event still gets its own run ID, its own context function cache, and the same crash recovery as a serially delivered event.

**What to know before enabling it:**

* **Ordering is not preserved.** Events run concurrently, so a later event can finish before an earlier one. Only enable this if each event can be handled independently. Keep the default (serial) delivery if your task depends on events arriving in block order.
* **Concurrency is app-wide.** One queue worker drains the queue for the whole app, so the first `max_concurrency` it finds on an onchain trigger sets the limit for every parallel trigger in that app. Set the same value on each trigger to avoid confusion.
* **Backpressure is handled for you.** If the queue fills up, Compose rejects further deliveries with a `429` and Goldsky retries them with backoff, so events are not lost, just delivered later.
* **Reorgs cancel queued events.** If an event is retracted (a reorg) while it is still sitting in the queue, the queued entry is removed and the task never runs for it. Events that have already started running are unaffected.
* **Delivery is at-least-once.** If your app restarts while an event is running, the event stays in the queue and runs again after the restart, so no event is lost. Context calls that already finished, such as a `writeContract`, return their saved result instead of running again. Code between those calls can run twice, so make your task safe to repeat.
* **Operators can retune concurrency live.** Goldsky can override `max_concurrency` on a running app via the `COMPOSE_TRIGGER_CONCURRENCY` environment variable, without a redeploy. Reach out in [support](https://docs.goldsky.com/getting-support.md) if you need this while tuning.

#### Confirmations

Onchain triggers fire as soon as the event is indexed at the chain head, which means a reorg can retract an event your task already acted on. If the task moved real money (a settlement, a payout, a compliance gate), that is unrecoverable.

Set `confirmations: N` to hold each event in the queue until its block is `N` blocks deep. Compose polls the chain head and releases the event once `event block + N <= current block`.

```yaml highlight={10-11} theme={"dark"}
name: "my-app"
api_version: "preview"
tasks:
  - name: "settle_trade"
    path: "./tasks/settle_trade.ts"
    triggers:
      - type: "onchain_event"
        network: "ethereum"
        contract: "0xb74de3F91e04d0920ff26Ac28956272E8d67404D"
        parallel_processing: true
        confirmations: 10
```

* `confirmations` requires `parallel_processing: true`: the confirmation buffer is part of the queue. Setting it without parallel processing fails validation.
* `confirmations: 0` (the default) fires immediately, exactly as before.
* While an event waits, it is held in the queue. If a reorg retracts it before it is released, the event is cancelled and your task never runs for it.
* Choose the depth from your own risk tolerance: deeper is safer but adds latency roughly equal to `N` block times. Removing `confirmations` from your manifest releases anything still waiting on the next deploy.

This is the inbound counterpart to the outbound confirmation and reorg options on `writeContract`. See [Reorg handling](https://docs.goldsky.com/compose/context/evm/reorgs.md) for transactions your task sends.

#### Failure Handling

Onchain-triggered tasks honor the task's [`retry_config`](./app-configuration#retry-configuration). When a task throws (or otherwise fails), Compose retries it up to `max_attempts` with the configured backoff. If every attempt fails, **that event is dropped and the pipeline advances to the next one**. It is not replayed.

This means an unhandled exception in an onchain-triggered task only stalls delivery for the duration of your retry window, not indefinitely. If you want a failure to be visible without consuming retries, catch the error in your task and return normally. The run is recorded as successful and the pipeline moves on.

With `parallel_processing: true` the same retry rules apply per event, but a failing event never stalls the others: each event is claimed from the queue independently, and one exhausting its retries doesn't hold back the rest.

## Cron Triggers

Tasks can be triggered on a schedule. Tasks triggered by cron are invoked with an empty payload (`{}`), since each invocation is generic.

### Example

```yaml highlight={6-7} theme={"dark"}
name: "my-app"
tasks:
  - name: "hourly_sync"
    path: "./tasks/sync.ts"
    triggers: 
      - type: "cron"
        expression: "0 * * * *" # Every hour at minute 0
```

### 6-field (second-granularity) example

Pass a 6-field expression if you need second-level precision. The first field becomes seconds:

```yaml theme={"dark"}
triggers:
  - type: "cron"
    expression: "*/30 * * * * *" # every 30 seconds
```

#### Cron Trigger Properties

| Property | Type | Required | Description |
| - | - | - | - |
| `type` | `"cron"` | Yes | Type discriminator |
| `expression` | string | Yes | A cron expression. Supports both 5-field (`minute hour day month weekday`) and 6-field (`second minute hour day month weekday`) formats. Accepts `*`, numbers, ranges (`1-5`), lists (`1,3,5`), and step values (`*/2`). |

## HTTP Triggers

Tasks can be triggered by HTTP requests. This is often used to kick off compose tasks from your application logic. HTTP triggers accept any JSON payload.

### Example

```yaml highlight={6-7} theme={"dark"}
name: "my-app"
tasks:
  - name: "status"
    path: "./tasks/status.ts"
    triggers:
      - type: "http"
        authentication: "auth_token" # other option is "none"
```

#### Http Trigger Properties

| Property | Type | Required | Description |
| - | - | - | - |
| `type` | `"http"` | Yes | Type discriminator |
| `authentication` | `"auth_token" \| "none"` | Yes | Type of authentication to use on the endpoint. |
| `role` | `"Owner" \| "Admin" \| "Editor" \| "Viewer"` | No | The minimum RBAC role required to call the endpoint (only applies when `authentication` is `"auth_token"`). Defaults to `"Viewer"` (any team member). |
| `ip_whitelist` | string\[] | No | Restrict access to specific IPs. Supports IPv4, IPv6, and CIDR notation (e.g. `["192.168.1.0/24", "10.0.0.1"]`). |

Authenticated triggers require a Goldsky API token when the app is deployed, but can be called without auth when testing locally. Unauthenticated triggers can be called without auth both locally and when deployed.

### Base URL

Locally, Compose runs on `http://localhost:4000` by default. If port 4000 is taken, `start` picks the next free port up to 4009 and records it in `.compose/.port`. The base pattern for all task endpoints is:

```
http://localhost:4000/tasks/{taskName}
```

When deployed to the cloud, tasks with an authenticated HTTP trigger (`authentication: "auth_token"`) are reachable at:

```
https://api.goldsky.com/api/admin/compose/v1/{appName}/tasks/{taskName}
```

When deployed to the cloud, tasks with an unauthenticated HTTP trigger (`authentication: "none"`) are reachable at:

```
https://api.goldsky.com/api/public/compose/v1/{projectId}/{appName}/tasks/{taskName}
```

### HTTP Request Format

```bash theme={"dark"}
curl -X POST http://localhost:4000/tasks/{taskName} \
  -H "Content-Type: application/json" \
  -d '{"key": "value"}'
```

When deployed to the cloud with `authentication: "auth_token"`, you'll need to pass a Goldsky API token:

```bash highlight={2} theme={"dark"}
curl -X POST https://api.goldsky.com/api/admin/compose/v1/{appName}/tasks/{taskName} \
  -H "Authorization: Bearer {token}" \
  -H "Content-Type: application/json" \
  -d '{"foo": "foo"}'
```

### Execute HTTP trigger without parameters

```bash highlight={3} theme={"dark"}
curl -X POST http://localhost:4000/tasks/bitcoin_oracle \
  -H "Content-Type: application/json" \
  -d '{}'
```

### Execute an HTTP trigger with parameters

```bash highlight={4-5} theme={"dark"}
curl -X POST http://localhost:4000/tasks/bitcoin_oracle \
  -H "Content-Type: application/json" \
  -d '{
    "contractAddress": "0x742d35Cc6634C0532925a3b8D6Ac6E7D9C3c1234",
    "threshold": 1000
  }'
```

### Response Format

Tasks return JSON responses with the data returned by the task's `main` function.

Calling this task:

```typescript theme={"dark"}
import { TaskContext } from "compose";

export async function main(_context: TaskContext, payload: { name?: string }) {
  const name = payload?.name || "World";

  return { success: true, greeting: `Hello, ${name}!` };
}
```

via this request:

```bash theme={"dark"}
curl -X POST http://localhost:4000/tasks/greeting \
  -H "Content-Type: application/json" \
  -d '{
    "name":"Adam"
  }'
```

returns this JSON response:

```json theme={"dark"}
{
  "success": true,
  "greeting": "Hello, Adam!"
}
```

## Next Steps

> [card] [Using Packages](https://docs.goldsky.com/compose/packages.md)
>
> You can use any sandbox compatible typescript packages with any package manager.

> [card] [Debugging](https://docs.goldsky.com/compose/debugging.md)
>
> Debug and monitor your apps


## Related topics

- [Task Authoring Basics](https://docs.goldsky.com/compose/tasks.md)
- [Compose app manifest configuration reference](https://docs.goldsky.com/compose/app-configuration.md)
- [Migrate from Gelato W3F](https://docs.goldsky.com/compose/gelato.md)
- [Solana Transactions with Gill](https://docs.goldsky.com/compose/guides/solana-transactions.md)
- [Task to Task Execution (callTask)](https://docs.goldsky.com/compose/context/call-task.md)
