This page defines the core terminology and fundamental concepts used throughout the Trigger.dev platform. Understanding these concepts is essential for working with any part of the codebase, from task definition to execution orchestration.
For information about the overall system architecture and component interactions, see System Architecture.
A task is the fundamental unit of work in Trigger.dev. Tasks are defined using the SDK and represent reusable, retriggerable operations that can be executed asynchronously.
Code Representation:
task(), schemaTask(), toolTask() in @trigger.dev/sdkBackgroundWorkerTask in @trigger.dev/databasetaskIdentifier (string, unique per environment)Key Properties:
id: Unique identifier for the taskexportName: The exported name from the task filefilePath: Location of the task definitionqueue: Associated queue configurationretry: Retry configuration with limit, factor, minTimeout, maxTimeoutmachine: Machine preset specification (CPU/memory allocation)Task Definition State Machine (Deployment):
Sources: packages/trigger-sdk/package.json internal-packages/run-engine/src/engine/systems/runAttemptSystem.ts44-91
A run (also called task run) is a single execution instance of a task. Each time a task is triggered, a new run is created.
Code Representation:
TaskRun in @trigger.dev/databaseRunEngine in internal-packages/run-engine/src/engine/index.ts76run_[ulid] via RunId typeRun Lifecycle States:
| Status | Description | Counts Against Concurrency? |
|---|---|---|
PENDING_VERSION | Waiting for worker deployment | No |
QUEUED | Waiting in queue for execution | No |
DELAYED | Scheduled for future execution | No |
DEQUEUED | Removed from queue, being sent to worker | Yes |
EXECUTING | Currently running | Yes |
WAITING | Paused (waitpoint/checkpoint) | No |
COMPLETED | Successfully finished | No |
CANCELED | User-canceled | No |
FAILED | Failed after retries | No |
CRASHED | Worker crashed (OOM, etc.) | No |
SYSTEM_FAILURE | Platform error | No |
EXPIRED | TTL exceeded | No |
TIMED_OUT | maxDuration exceeded | No |
Key Properties:
id: Unique run identifierfriendlyId: Human-readable ID (e.g., run_abc123)status: Current state in the state machinepayload: Input data for the runoutput: Result data after completionmetadata: User-defined key-value pairscontext: Execution context (attempt, run IDs, environment)traceId, spanId: OpenTelemetry correlation IDsRun State Machine:
Boolean Helper Methods:
isQueued(): Returns true for QUEUED, PENDING_VERSION, DELAYEDisExecuting(): Returns true for EXECUTING, DEQUEUEDisWaiting(): Returns true for WAITINGisCompleted(): Returns true for any terminal stateisSuccess(): Returns true for COMPLETEDisFailed(): Returns true for FAILED, CRASHED, SYSTEM_FAILURE, TIMED_OUTisCanceled(): Returns true for CANCELEDSources: internal-packages/run-engine/src/engine/index.ts388-523 internal-packages/run-engine/src/engine/statuses.ts packages/trigger-sdk/CHANGELOG.md446-486
An attempt is a single try at executing a run. A run may have multiple attempts if retries are configured.
Code Representation:
TaskRunAttempt in @trigger.dev/databaseRunAttemptSystem in internal-packages/run-engine/src/engine/systems/runAttemptSystem.ts63Key Properties:
number: Sequential attempt number (1, 2, 3, ...)status: Current state (mirroring run status during execution)startedAt: When this attempt begancompletedAt: When this attempt finishederror: Error information if failedbackgroundWorkerId: Worker that executed this attemptRetry Logic:
factor, minTimeout, maxTimeoutMAX_TASK_RUN_ATTEMPTS)retryOutcomeFromCompletion() functionretryWarmStartThresholdMs), reuse the worker processSources: internal-packages/run-engine/src/engine/systems/runAttemptSystem.ts63-673 internal-packages/run-engine/src/engine/consts.js1
Workers are processes that execute tasks. There are two types:
trigger dev CLI commandDevSupervisor class to manage task executiontrigger deployCode Representation:
BackgroundWorker in @trigger.dev/databaseSupervisor class in apps/coordinatorTaskExecutor in apps/supervisorWorker Registration Flow:
Sources: apps/webapp/app/runEngine/services/triggerTask.server.ts internal-packages/run-engine/src/engine/systems/dequeueSystem.ts88
An environment represents a deployment target with its own configuration, API keys, and concurrency limits.
Code Representation:
RuntimeEnvironment in @trigger.dev/databaseRuntimeEnvironmentType with values DEVELOPMENT, PRODUCTION, STAGING, PREVIEWEnvironment Types:
| Type | Purpose | Concurrency Default | API Key Prefix |
|---|---|---|---|
DEVELOPMENT | Local dev runs | 10 | tr_dev_ |
PRODUCTION | Production workloads | 100 | tr_prod_ |
STAGING | Pre-production testing | 50 | tr_stag_ |
PREVIEW | Branch previews | 25 | tr_prev_ |
Key Properties:
id: Unique environment IDtype: Environment type enumslug: URL-safe identifierapiKey: Authentication tokenpkApiKey: Public API key (for frontend)organizationId: Parent organizationprojectId: Parent projectConcurrency Configuration:
maximumConcurrencyLimit: Environment-wide concurrency capconcurrencyBurstFactor: Multiplier for burst capacity (default: 2.0x)maximumConcurrencyLimit * concurrencyBurstFactorSources: apps/webapp/app/env.server.ts263-267 internal-packages/run-engine/src/engine/index.ts146-161
Organizations are top-level tenant entities that contain projects. Projects group related tasks and environments.
Code Representation:
Organization, Project in @trigger.dev/databaseOrganization → Project → RuntimeEnvironment → TaskRunOrganization:
id: Unique org IDslug: URL-safe identifiertitle: Display nameOrgMember records with rolesProject:
id: Unique project IDslug: URL-safe identifier (unique within org)externalRef: External reference ID (e.g., proj_abc123)organizationId: Parent organizationOrganizational Hierarchy:
Sources: apps/webapp/app/models/organization.server.ts apps/webapp/app/models/project.server.ts
Lifecycle hooks are functions that execute at specific points during task execution, providing extension points for cross-cutting concerns.
Available Hooks (12 total):
| Hook | When It Fires | Use Case |
|---|---|---|
init | Once per worker process startup | Initialize connections, load config |
onStartAttempt | Before each attempt's run() function | Per-attempt setup, logging |
onStart | Before first attempt only (deprecated) | Use onStartAttempt with ctx.run.attempt.number === 1 |
middleware | Around the run() function | Wrapping logic, timing |
onSuccess | After successful completion | Cleanup, notifications |
onFailure | After failed attempt | Error handling, alerts |
onComplete | After any completion (success/failure) | Guaranteed cleanup |
cleanup | After attempt finishes (always runs) | Resource cleanup |
onWait | When entering WAITING state | Log waitpoint entry |
onResume | When resuming from WAITING | Log resume, reset state |
onCancel | When run is canceled | Cancelation handling |
catchError | When uncaught error occurs | Error transformation |
Hook Execution Order:
Global vs Task-Level Hooks:
task() optionstasks.onStartAttempt(), tasks.onSuccess(), etc.Error Handling in Hooks:
onSuccess, onFailure, onComplete do NOT fail the run (logged only)middleware, run() DO fail the runcatchError can transform errors before retry logicSources: packages/trigger-sdk/CHANGELOG.md38-73 packages/core/CHANGELOG.md98
An execution snapshot captures the state of a run at a point in time. Snapshots enable state recovery, monitoring, and debugging.
Code Representation:
TaskRunExecutionSnapshot in @trigger.dev/databaseExecutionSnapshotSystem in internal-packages/run-engine/src/engine/systems/executionSnapshotSystem.ts16Snapshot Types (by status):
| Status | Description | Triggers Action |
|---|---|---|
PENDING | Initial creation | No |
EXECUTING | Run started | No |
EXECUTING_WITH_WAITPOINTS | Has blocking waitpoints | No |
SUSPENDED | Checkpointed, worker shutdown | Resume when ready |
DEQUEUED | Removed from queue | No |
Key Properties:
id: Unique snapshot ID (SnapshotId format: snap_[ulid])status: Current execution statusdata: Serialized RunExecutionData containing contextheartbeatAt: Last heartbeat timestamp (for stall detection)completedAfter: Conditions for resuming suspended runSnapshot Heartbeat Monitoring:
HeartbeatTimeouts typeDefault Heartbeat Timeouts:
Snapshot Lifecycle:
Sources: internal-packages/run-engine/src/engine/systems/executionSnapshotSystem.ts16-292 internal-packages/run-engine/src/engine/types.ts66-71
A waitpoint is a synchronization primitive that allows a run to pause execution and wait for external events before continuing.
Code Representation:
Waitpoint in @trigger.dev/databaseWaitpointSystem in internal-packages/run-engine/src/engine/systems/waitpointSystem.ts40wait_[ulid] via WaitpointId typeWaitpoint Types:
| Type | Description | Use Case |
|---|---|---|
TASK_RUN | Wait for child task run to complete | triggerAndWait() |
TASK_RUN_BATCH | Wait for batch of runs to complete | batchTriggerAndWait() |
WEBHOOK | Wait for webhook callback | Human-in-the-loop workflows |
TOKEN | Wait for token completion | Custom external triggers |
Waitpoint States:
Key Properties:
id: Unique waitpoint IDtype: Waitpoint type enumstatus: Current state (PENDING, COMPLETED, EXPIRED, CANCELED)taskRunId: Associated run that is waitingcompletedAfter: Optional time threshold before completionoutput: Result data after completion (stored as IOPacket)Blocking Behavior:
EXECUTING_WITH_WAITPOINTScontinueRunIfUnblocked() methodWait Token Flow:
Sources: internal-packages/run-engine/src/engine/systems/waitpointSystem.ts40-584 packages/trigger-sdk/CHANGELOG.md142-143
A checkpoint is a snapshot of a run's state that allows it to be suspended, shutdown, and later resumed from the same point.
Code Representation:
TaskRunCheckpoint in @trigger.dev/databaseCheckpointSystem in internal-packages/run-engine/src/engine/systems/checkpointSystem.ts15check_[ulid] via CheckpointId typeCheckpoint Types:
| Type | Description | When Created |
|---|---|---|
MANUAL | Explicitly requested via SDK | checkpoint() API call |
DURATION | Auto-created by threshold | Task running > CHECKPOINT_THRESHOLD_IN_MS |
Key Properties:
id: Unique checkpoint IDtype: Checkpoint type enumreason: Why checkpoint was createddata: Serialized execution statecreatedAt: When checkpoint was takenrestoredAt: When checkpoint was resumed (if applicable)Checkpoint Lifecycle:
Checkpoint Threshold:
CHECKPOINT_THRESHOLD_IN_MS environment variable (default: 30 seconds)Concurrency Release:
WAITING state, concurrency slots are releasedSources: internal-packages/run-engine/src/engine/systems/checkpointSystem.ts15-226 apps/webapp/app/env.server.ts405 packages/trigger-sdk/CHANGELOG.md252-257
A queue manages the ordering and concurrency of task execution. Each task is assigned to a queue, which controls how many runs can execute concurrently.
Code Representation:
TaskQueue in @trigger.dev/databaseRunQueue in internal-packages/run-engine/src/run-queue/index.tsRunQueueFullKeyProducer in internal-packages/run-engine/src/run-queue/keyProducer.tsQueue Properties:
name: Queue identifier (must be URL-safe via sanitizeQueueName())concurrencyLimit: Max concurrent runs for this queuerateLimit: Optional rate limiting configurationQueue Types:
| Type | Description | Concurrency Scope |
|---|---|---|
| Task-specific | One queue per task | Task-level concurrency control |
| Shared | Multiple tasks share queue | Shared concurrency limit |
| Default | Fallback queue | Environment default |
Fair Queue Selection Strategy:
The system uses a FairQueueSelectionStrategy to fairly distribute execution capacity across queues:
Queue Selection Algorithm:
Concurrency Enforcement:
Sources: internal-packages/run-engine/src/run-queue/index.ts internal-packages/run-engine/src/run-queue/fairQueueSelectionStrategy.ts internal-packages/run-engine/src/engine/index.ts142-185
A batch is a coordinated group of task runs triggered together, with shared completion tracking.
Code Representation:
Batch in @trigger.dev/databaseBatchSystem in internal-packages/run-engine/src/engine/systems/batchSystem.tsBatchQueue using DRR algorithm in internal-packages/run-engine/src/batch-queue/batch_[ulid] via BatchId typeBatch Properties:
id: Unique batch IDfriendlyId: Human-readable IDstatus: Current state (PENDING, PROCESSING, COMPLETED, FAILED, CANCELED)items: Array of batch items (runs)concurrencyLimit: Max concurrent items in this batchBatch Triggering Methods:
| Method | Wait for Completion? | Use Case |
|---|---|---|
batchTrigger() | No | Fire-and-forget multiple runs |
batchTriggerAndWait() | Yes | Wait for all runs to complete |
Batch Completion Tracking:
DRR (Deficit Round Robin) Batch Queue:
The batch queue uses a Deficit Round Robin algorithm to fairly schedule batch items across multiple batches:
Batch Item States:
| State | Description |
|---|---|
PENDING | Waiting to be triggered |
TRIGGERED | Run has been created |
COMPLETED | Run completed successfully |
FAILED | Run failed |
CANCELED | Run was canceled |
Waitpoint Integration:
When using batchTriggerAndWait():
type=TASK_RUN_BATCHtype=TASK_RUN_BATCHWAITING stateSources: internal-packages/run-engine/src/batch-queue/types.ts internal-packages/run-engine/src/engine/systems/batchSystem.ts internal-packages/run-engine/src/engine/index.ts331-358
A deployment represents a versioned release of tasks to a specific environment. Each deployment contains a Docker image with task code and dependencies.
Code Representation:
WorkerDeployment in @trigger.dev/databasetrigger deploy in packages/cli-v3/Deployment Properties:
id: Unique deployment IDfriendlyId: Human-readable ID (e.g., deploy_abc123)version: Semantic version stringimageReference: Docker image URIstatus: Current deployment statepromotedAt: When deployment was promoted to liveworker: Associated BackgroundWorker recordDeployment States:
Deployment Process Flow:
Image Build Methods:
| Method | Location | Use Case |
|---|---|---|
| Local | Developer machine | Quick deploys, local Docker |
| Depot | Remote build service | Faster builds, no local Docker needed |
| Native Build Server | Platform-side | CI/CD pipelines |
Version Labels:
Deployments can be labeled with the CURRENT_DEPLOYMENT_LABEL constant (value: "latest") to indicate the active version for task lookups.
Task Version Pinning:
Runs can be locked to specific deployment versions using:
lockedToVersionId: Specific deployment IDtaskVersion: Semantic version stringThis ensures runs execute on the exact code version they were triggered with, even after new deployments.
Sources: packages/cli-v3/CHANGELOG.md73-94 internal-packages/run-engine/src/engine/systems/dequeueSystem.ts151-224 apps/webapp/app/env.server.ts290-343
The RunEngine is the central orchestrator for task execution. It coordinates all subsystems and manages the complete lifecycle of runs.
Code Representation:
RunEngine in internal-packages/run-engine/src/engine/index.ts76engine in apps/webapp/app/v3/runEngine.server.ts11Key Responsibilities:
Major Subsystems:
RunEngine Initialization:
Event Bus:
RunEngine uses an EventBus (EventEmitter) to coordinate between systems:
runStarted, runCompleted, runFailed, runCanceled, waitpointCreated, waitpointCompletedWorker Catalog:
The workerCatalog defines background jobs processed by RunEngine:
finishWaitpoint: Complete a waitpointheartbeatSnapshot: Check for stalled snapshotsrepairSnapshot: Recover from snapshot errorsexpireRun: Handle TTL expirationcancelRun: Cancel a runqueueRunsPendingVersion: Enqueue runs waiting for deploymenttryCompleteBatch: Attempt batch completioncontinueRunIfUnblocked: Resume run if waitpoints resolvedenqueueDelayedRun: Trigger delayed runSources: internal-packages/run-engine/src/engine/index.ts76-384 internal-packages/run-engine/src/engine/types.ts23-171 apps/webapp/app/v3/runEngine.server.ts11-130
The run context (TaskRunContext) is the object passed to the task's run() function and lifecycle hooks, providing access to run metadata and utilities.
Code Representation:
TaskRunContext in @trigger.dev/core/v3/schemasctx parameter in task functionsContext Properties:
Backwards Compatibility:
The BackwardsCompatibleTaskRunExecution type includes deprecated fields for compatibility:
task.exportName: Now always providedattempt.id, attempt.backgroundWorkerId, attempt.backgroundWorkerTaskId, attempt.status: Legacy fieldsrun.context: Deprecated (use ctx instead)run.durationMs, run.costInCents, run.baseCostInCents: Computed fieldsSources: internal-packages/run-engine/src/engine/systems/runAttemptSystem.ts75-91 packages/core/CHANGELOG.md233-246
Metadata is user-defined key-value data associated with runs, enabling runtime state sharing and hierarchical data propagation.
Code Representation:
metadata object from @trigger.dev/sdkFlushedRunMetadata type, stored as TaskRun.metadata JSON columnMetadata Scopes:
| Scope | Method | Description |
|---|---|---|
| Current | metadata.set(key, value) | Set on current run |
| Current | metadata.get(key) | Get from current run |
| Current | metadata.current() | Get all current run metadata |
| Parent | metadata.parent.set(key, value) | Set on parent run |
| Parent | metadata.parent.get(key) | Get from parent run |
| Root | metadata.root.set(key, value) | Set on root run |
| Root | metadata.root.get(key) | Get from root run |
Metadata Flushing:
Metadata operations are batched and flushed periodically for performance:
BATCH_METADATA_OPERATIONS_FLUSH_INTERVAL_MS (default: 1000ms)Metadata Streaming:
The metadata.stream() API enables real-time metadata updates to frontends:
Sources: packages/core/CHANGELOG.md87-88 apps/webapp/app/env.server.ts555-557
Trace context enables correlation between Trigger.dev spans and external OpenTelemetry traces.
Code Representation:
TriggerTraceContext in @trigger.dev/core/v3traceparent, tracestate (W3C Trace Context format)Trace Propagation:
Trace Context Format:
traceparent: 00-{traceId}-{spanId}-{flags}
tracestate: vendor1=value1,vendor2=value2
External Trace Integration:
The SDK provides otel.withExternalTrace() to propagate trace context when calling external APIs:
This ensures external traces are correlated with Trigger.dev spans in APM tools (Datadog, New Relic, Axiom, etc.).
Sources: packages/trigger-sdk/CHANGELOG.md162-229 packages/core/CHANGELOG.md319-403
Sources: All sections above
Refresh this wiki