Concepts
Tasks
A task is an exported function that takes a payload and returns JSON. Bok Joy runs it on a worker, enforces its size and timeout, and retries it when it fails.
On this page
Write a task#
A task handler takes two arguments: the run's payload and a context. It may be synchronous or async, and whatever it returns becomes the run's output.
import {charges} from './payments.mjs'; // A task: a payload and a context in, JSON out.export async function sendReceipt({orderId, email}, ctx) { console.log(`receipt for ${orderId}, attempt ${ctx.attemptEpoch}`); // The same key on every attempt, so a retry never charges twice. const charge = await charges.capture(orderId, { idempotencyKey: ctx.idempotencyKey, }); return {orderId, email, chargeId: charge.id};}from payments import charges # A task: a payload and a context in, JSON out.def send_receipt(payload, ctx): order_id = payload["orderId"] print(f"receipt for {order_id}, attempt {ctx.attempt_epoch}") # The same key on every attempt, so a retry never charges twice. charge = charges.capture(order_id, idempotency_key=ctx.idempotency_key) return {"orderId": order_id, "email": payload["email"], "chargeId": charge["id"]}Payloads and outputs are JSON. A task's output is written the way JSON.stringify writes it: a Date becomes its ISO 8601 string, toJSON is honored, and a field that is undefined is left out. Python writes a datetime, date or time as its ISO 8601 string and a tuple as a list. In both, NaN and infinities become null. Integers must fit in JavaScript's safe range (up to 2^53 - 1), so use strings for larger IDs. A BigInt, a Map or Set (Python: a set or Decimal) and a value that contains itself fail the attempt with an error that says where it is. Metadata values and the inputs of ctx.trigger and ctx.callTask follow the same rules.
Register it in a manifest#
A manifest lists your tasks. Each entry names the file and the exported function:
{ "tasks": [ {"id": "receipts.send", "kind": "task", "runtime": "node", "entrypoint": "tasks/receipts.mjs", "handler": "sendReceipt", "compute": {"machine": "small", "timeout_ms": 60000}, "max_attempts": 5, "retry": {"minTimeoutInMs": 1000, "maxTimeoutInMs": 30000}} ]}| Field | Meaning |
|---|---|
id | The name you trigger it by. 1 to 128 bytes, unique in the manifest. |
kind | task, or workflow for a workflow. |
runtime | node or python. |
entrypoint | The handler's file, relative to the project root. |
handler | The exported function's name. |
compute | Optional. A machine size or explicit cpu_millis and memory_mib, and timeout_ms. |
max_attempts | Optional. Failed attempts allowed before the run fails, 1 to 10. Default 3. |
retry | Optional. How long a failed run waits before its next attempt (Retry options). |
hot | Optional. Keep warm workers for this task (Hot tasks). |
schedule | Optional. Run this task on a cron, in a time zone (Schedules). |
hooks | Optional. The lifecycle hooks Bok Joy runs after a run ends: one or more of onSuccess, onFailure, onComplete and onCancel, each once. Deploy writes it for the tasks it finds. |
A manifest may also set defaults for every task that does not set its own: timeout_ms and retry, like Trigger.dev's maxDuration (in milliseconds here) and retries.default:
{ "defaults": { "timeout_ms": 3600000, "retry": {"maxAttempts": 3, "minTimeoutInMs": 1000, "maxTimeoutInMs": 10000, "factor": 2, "randomize": true} }, "tasks": [ {"id": "receipts.send", "kind": "task", "runtime": "node", "entrypoint": "tasks/receipts.mjs", "handler": "sendReceipt"} ]}A task's own retry replaces the default one as a whole, as in Trigger.dev, and its own max_attempts wins over retry.maxAttempts. Deploying writes the values into each task, so a deployment keeps the ones it was deployed with.
A manifest holds 1 to 1,000 tasks. You can also build entries in code with defineTask (Node) or define_task (Python). Each validates an entry the way the control plane does and returns plain JSON for the manifest:
import {writeFileSync} from 'node:fs';import {defineTask} from '@bokjoy/sdk'; const sendReceipt = defineTask({ id: 'receipts.send', kind: 'task', runtime: 'node', entrypoint: 'tasks/receipts.mjs', handler: 'sendReceipt', compute: {machine: 'small', timeout_ms: 60000}, max_attempts: 5, retry: {minTimeoutInMs: 1000, maxTimeoutInMs: 30000},}); writeFileSync('manifest.json', JSON.stringify({tasks: [sendReceipt]}, null, 2));import json from bokjoy import define_task send_receipt = define_task( id="receipts.send", kind="task", runtime="python", entrypoint="tasks/receipts.py", handler="send_receipt", compute={"machine": "small", "timeout_ms": 60000}, max_attempts=5, retry={"min_timeout_in_ms": 1000, "max_timeout_in_ms": 30000},) with open("manifest.json", "w") as manifest: json.dump({"tasks": [send_receipt]}, manifest, indent=2)Define tasks the Trigger.dev way#
Tasks written for Trigger.dev keep their code. Import task, schemaTask and schedules from @bokjoy/sdk/trigger instead of @trigger.dev/sdk, and name their folders in the manifest's build.dirs. Deploy finds every task the files export and writes its manifest entry for you.
import { logger, metadata, task, tasks } from '@bokjoy/sdk/trigger';import { orderTotal } from '../../lib/orders'; export const processOrder = task({ id: 'orders.process', machine: 'small-1x', maxDuration: 120, retry: { maxAttempts: 2 }, run: async (payload: { orderId: string; lines: { qty: number; price: number }[] }, { ctx }) => { metadata.set('stage', 'counting'); for (const line of payload.lines) metadata.increment('items', line.qty); logger.info('order counted', { orderId: payload.orderId, attempt: ctx.attempt.number }); await tasks.trigger('orders.notify', { orderId: payload.orderId }); return { total: orderTotal(payload.lines) }; },});{ "dependencies": { "node": {"package_json": "package.json", "lockfile": "package-lock.json"} }, "build": {"dirs": ["src/trigger"]}}The tasks list can be left out, or keep entries you wrote by hand beside the ones deploy finds. Deploying explains how deploy finds them.
Each option becomes a manifest field:
| Option | Manifest field |
|---|---|
id | id. Each ID once across the folders and the manifest. |
machine | compute.machine. Trigger.dev's small-1x, medium-1x and large-1x become small, medium and large. micro, small-2x, medium-2x and large-2x keep their names. { preset } works too. |
maxDuration, in seconds | compute.timeout_ms, 100 ms to 24 hours. Without it, the manifest's defaults.timeout_ms, or 30 seconds. |
retry: maxAttempts, factor, minTimeoutInMs, maxTimeoutInMs, randomize | retry, with the same fields and Trigger.dev's backoff. maxAttempts becomes max_attempts, 1 to 10. Without retry, the manifest's defaults.retry, or 3 attempts. A task's own retry replaces defaults.retry as a whole. See Retries and timeouts. |
queue | queue: { name, concurrencyLimit }, inline or from queue(), with a limit of 1 to 100,000. Tasks that share a queue must give it the same limit. See Queues and concurrency limits. |
cron on schedules.task | schedule. pattern becomes cron, and PRODUCTION, STAGING and DEVELOPMENT become prod, staging and dev. Without environments, it fires in all three, as in Trigger.dev. A schedule you write in the manifest yourself fires in prod only unless it names more. |
schema on schemaTask | Nothing: the payload is parsed with it before run. A zod schema works, or any function that returns the payload or throws. |
description | Nothing. |
onStartAttempt, onStart, onSuccess, onFailure, onComplete, onCancel | hooks, listing the ones that run after a run ends, together with every hook tasks.onFailure and the like register in any file. See Lifecycle hooks. |
Deploy refuses the hooks Bok Joy has nothing for yet with the file and line, rather than run the task without them: onWait, onResume, catchError, middleware, locals, init, cleanup and handleError.
Inside a run#
run(payload, { ctx, signal }) gets Trigger.dev's context:
| Field | What it is |
|---|---|
ctx.run.id, ctx.run.idempotencyKey | The run's ID, and the key to send to services you call. |
ctx.task.id | The task's ID. |
ctx.attempt.number | Counts up with each attempt, from 1. |
ctx.environment | The run's environment: its slug and kind, as in the context, and Trigger.dev's type, such as PRODUCTION. |
ctx.bokjoy | Bok Joy's own context. Its fields, such as ctx.runId, also read through ctx. |
The globals work as in Trigger.dev, for the run that calls them:
metadata:set,get,current,increment,decrementandappendupdate the run's metadata, live, throughctx.metadata. A retry reads what earlier attempts stored, soincrementcounts on. Values go as JSON: anundefinedfield is left out and aDatebecomes its ISO string. Outside a run they do nothing.logger:debug,log,info,warnanderrorwrite one line to the attempt's logs, with the fields as JSON.tasks.onStartAttempt,tasks.onSuccess,tasks.onFailureand the other hooks register lifecycle hooks for every task, usually ininit.ts.tasks.trigger,myTask.triggerandbatchTriggerstart children linked to the run. A retried run that triggers in the same order starts no second child.idempotencyKey,machineandconcurrencyKeycarry over. Other trigger options are refused. Payloads go as JSON, as withmetadata.NaN,Infinity, aBigIntor a cycle fails the trigger.batchTriggerchecks every child against the attempt's limits before it starts the first, so a batch starts all of its children or none.idempotencyKeys.createhashes a key with its scope, as Trigger.dev does. As in Trigger.dev, a trigger inside a run uses a key of exactly 64 characters, which every made key is, as it is: it starts one child across all runs in the environment. Two runs that trigger with the same'global'key, or one made at a file's top level, start one child, which belongs to the run that triggered it first. AbatchTriggerwith a madeidempotencyKeygives each item a made key of its own, so the batch too starts once across the environment's runs. A key made with the default scope'run'holds the run's ID, so it still starts one child per run. In a retry from failure it holds the failed run's ID,ctx.firstRunId, so the retry makes the keys the failed run made and finds the children they started. A key you build yourself fromctx.run.idchanges in a retry: build it fromctx.firstRunId.'attempt'keeps the retry's own ID. Bok Joy's ownctx.triggerkeeps every key to its run unless you passscope: 'environment'.
Two runs in one process never see each other's metadata or children: each call finds its own run. Code that lost track of its run, such as a timer a file's top level started, finds the run when it is the only one in the process, as it always is on a worker. A task that names a hook deploy refuses, such as catchError, fails when it runs. triggerAndWait and batchTriggerAndWait inside a run wait for children. Deploy registers the tasks it finds as plain tasks, unless the manifest names them in build.workflows. In a plain task a wait holds the task's process until its children finish, so the code before it runs once (In a plain task). In a workflow the attempt ends at the wait, and the run replays. See Coming from Trigger.dev.
From @bokjoy/sdk/trigger, runs.retrieve and runs.poll answer with Trigger.dev's upper case statuses, as COMPLETED or CANCELED. The root @bokjoy/sdk keeps Bok Joy's lower case. Coming from Trigger.dev has the table.
The context#
| Node | Python | What it is |
|---|---|---|
ctx.runId | ctx.run_id | The run's ID. It stays the same on every attempt. |
ctx.firstRunId | ctx.first_run_id | For a retry from failure, the first run of its chain: the failed run, or for a retry of a retry, that one's first run. In any other run, the run's own ID. On a worker whose agent is too old to pass it on, reading it in a workflow throws an error that says to rebuild the worker (Python: FirstRunMissingError, an AttributeError). A plain task gets its own ID there. |
ctx.idempotencyKey | ctx.idempotency_key | The key to send to services you call. It is the run ID, so a retry sends the same key. |
ctx.attemptId | ctx.attempt_id | This attempt's ID. Diagnostic only. |
ctx.attemptEpoch | ctx.attempt_epoch | Counts up with each attempt, from 1. |
ctx.attempt.number | ctx.attempt.number | Which attempt this is, from 1. A retry is the next number. A workflow keeps its number while it resumes after each step. |
ctx.task.id | ctx.task.id | The task's ID. |
ctx.machine | ctx.machine | The machine this attempt runs on: name, cpuMillis and memoryMib (Python: name, cpu_millis, memory_mib). After an out-of-memory retry it is the larger machine. |
ctx.environment.slug, ctx.environment.kind | the same | The run's environment: dev, staging, prod or preview/<branch>, and its kind: development, staging, production or preview. |
ctx.metadata, ctx.milestone, ctx.trigger | the same | Live progress and fire-and-forget child runs. |
ctx.callTask, ctx.triggerAndWait, ctx.batchTriggerAndWait, ctx.waitEvent, ctx.sleep | ctx.call_task, ctx.trigger_and_wait, ctx.batch_trigger_and_wait, ctx.wait_event, ctx.sleep | Workflow steps. In a plain Node task, ctx.triggerAndWait and ctx.batchTriggerAndWait hold the task until the children finish (In a plain task). Any other call in a plain task fails. |
Retries and timeouts#
When a handler throws (Python: raises), the attempt fails. The run waits, then retries in a new attempt, until max_attempts attempts have failed. Then the run is failed, with the last error.
When a handler runs past its timeout_ms, Bok Joy stops it and the run is failed at once, with no retry, as Trigger.dev does with maxDuration. An attempt that ran out of time once would most likely run out again.
- The timeout applies to each attempt. It defaults to 30 seconds and can be 100 ms to 24 hours.
- A timeout ends the run only once the handler has started. An attempt that runs out of time before that, for example while its module is still loading, fails like any other attempt and is retried.
- An attempt ends when its handler returns. A timer, database client or thread the task left open does not keep it running: the process exits with the handler's result. Work the handler did not await is stopped when the run ends. In Python, threads and atexit hooks, such as an error reporter's final flush, get up to about 2 seconds first.
- The wait before a retry grows with each failure: 1 second, then 2, then 4. Each wait is also multiplied by a random 1 to 2, so the retries of many failed runs spread out, and no wait is longer than 60 seconds. A task's
retrychanges this. - While a run waits to retry, it is
queuedand itsretryfield says which attempt starts next and when. No worker takes it before then. The console shows the wait on the run. - A retry joins the queue when its wait ends, behind runs that were already waiting.
- An attempt that never started, for example because no worker could load its deployment yet, is deferred instead. It does not count against
max_attempts. - A retry starts the handler from the top. Anything the first attempt did before it failed may have happened.
Retry options#
retry is Trigger.dev's retry option, with the same names and defaults:
| Field | Meaning | Default |
|---|---|---|
maxAttempts | The task's attempts, 1 to 10. It is max_attempts by another name, so set one of the two. | 3 |
factor | Each wait is the one before times this, 1 to 10. | 2 |
minTimeoutInMs | The wait after the first failure, 0 to 86,400,000 (24 hours). | 1,000 |
maxTimeoutInMs | The longest wait, 0 to 86,400,000. | 60,000 |
randomize | Multiply each wait by a random number from 1 to 2, before maxTimeoutInMs caps it. | true |
outOfMemory | {machine}: a larger machine for the run to move to when an attempt runs out of memory. See Out of memory. | None: an attempt that runs out of memory fails its run |
The wait after failed attempt n is minTimeoutInMs * factor^(n-1), multiplied by the random number when randomize is on, then held to at most maxTimeoutInMs. Python's define_task takes the same fields in snake case (max_attempts, factor, min_timeout_in_ms, max_timeout_in_ms, randomize, out_of_memory) and writes them as the manifest takes them.
An attempt that runs out of memory is never retried on the same machine. The run moves to retry.outOfMemory.machine, or fails at once without one. An attempt that only probably ran out of memory moves the run when it can and is otherwise retried as usual. See Out of memory.
Stop retrying#
Throw AbortTaskRunError for a failure no retry can fix, such as a declined card or a malformed payload. The run fails at once with its message, whatever attempts it had left.
import {AbortTaskRunError} from '@bokjoy/sdk'; export async function chargeCard(payload, ctx) { if (!payload.cardId) throw new AbortTaskRunError('no card on file'); return {charged: payload.cardId};}from bokjoy import AbortTaskRunError async def charge_card(payload, ctx): if not payload.get("card_id"): raise AbortTaskRunError("no card on file") return {"charged": payload["card_id"]}Bok Joy knows the error by its name, so an error named AbortTaskRunError from Trigger.dev's SDK ends the run too, and ported code keeps working. One thrown while the task's module loads, before the handler runs, ends the run the same way.
Long attempts#
An attempt may run up to 24 hours. The worker renews its claim on the attempt every few seconds for as long as the handler runs, so a long attempt is never taken for a lost one. While long attempts keep every worker busy, new runs wait in the queue for a free one.
Logs#
Anything a handler prints goes to the attempt's logs: console.log in Node and print in Python. Bok Joy keeps 64 KiB of each attempt's output. Past that, it keeps the first half and the newest output, with a line between them that says how many bytes were dropped, so the error a task logs as it ends is never lost to a flood before it. A failed attempt's logs end with a line that starts [attempt failed], with its error and the stack its SDK reported, so each retry shows why the attempt before it failed. Standard output itself carries the runner's protocol, so the SDKs move your prints to standard error. A subprocess that inherits stdio, such as execSync(cmd, {stdio: 'inherit'}), or a direct write to standard output lands in the logs too, and never in the run's result. That output keeps to half of the 64 KiB, then a line says the rest was dropped, so a flood of it never hides the error your task logs after it.
Environment variables#
A task reads its environment's variables from process.env or os.environ. They are set before your module is imported, so module-level code sees them too.
What a task cannot do#
- Call
ctx.callTask,ctx.triggerAndWait,ctx.batchTriggerAndWait,ctx.waitEventorctx.sleep. Make it a workflow, or start a child without waiting withctx.trigger. - Return something JSON cannot hold, such as a
BigInt, aMapor a value that contains itself. - Return more than 10 MiB of output. The attempt fails. A deployment whose
sdkfolder predates large values can still fail an output over 1 MiB: deploy again with thesdkfolder from this release.