Triggers and scheduling
Triggers turn an event, a direct request, a clock rule, or a delayed condition into a workflow run. The system records the trigger context, creates the first task or DAG, and passes the work to the run queue. Scheduling then controls when that work becomes eligible and which worker can run it. See Workflow orchestration for the wider run model.
Trigger paths
Event triggers
An event trigger connects an incoming event key to the latest active workflow version that declares a matching event. An optional scope narrows the match for internal events. User-event conditions without a scope can match events from any scope. Event data and metadata become run input. Workflow filters then decide whether the run is created. A filter that fails or cannot be evaluated does not start the workflow.
The event path can create a single task or a DAG of tasks. It records the event-to-run relationship so the event can be traced after the run enters the queue. Trigger metadata keeps the event identity and source workflow context while removing reserved internal fields. The trigger path also preserves an existing trace parent or creates one for the new run.
This diagram shows how an incoming event becomes durable work and then enters worker scheduling.
flowchart LR
E[Incoming event] --> M[Match event key and scope]
M --> F{Filter passes?}
F -- No --> N[Record no run]
F -- Yes --> C[Create task or DAG]
C --> Q[Workflow task queue]
Q --> S[Worker scheduling]
References: pkg/…/triggers.sql• L1-41 pkg/…/trigger.go• L225-303 pkg/…/trigger.go• L321-372 pkg/…/trigger.go• L614-719 pkg/…/match.go• L392-489 internal/…/ingestor_v1.go• L146-199
Direct workflow triggers
Direct triggers start a named workflow from an API, SDK, admin action, or another internal service. The trigger request carries input, additional metadata, priority, and an external ID. The trigger path resolves the workflow name and version, creates the run records, and signals the new work for scheduling.
Idempotency can turn two requests into one run. When a workflow defines an idempotency rule, the trigger path evaluates the key and claims it before it creates tasks. A collision is reported instead of creating a second run. The claim and run creation share the trigger transaction, so a failed run write does not leave a successful claim without its run.
Operator-managed DAGs use one orchestrator task as the durable run entry. The system creates the reporting DAG view for that run without counting each later step handoff as another workflow run.
References: pkg/…/trigger.go• L43-105 pkg/…/trigger.go• L779-909 pkg/…/trigger.go• L467-510 pkg/…/trigger.go• L419-465 internal/…/trigger.go• L115-155
Child workflow triggers
Child workflow triggers start a workflow from a running workflow. A child spawn key gives repeated requests for the same parent task and logical child a stable child identity. The first request creates the child signal record. Later requests reuse it instead of creating another child run.
The durable event path records the child run before it hands the run to normal trigger processing. If a process stops after the record is committed but before the child task exists, a later invocation finds the untriggered entry and retries the handoff. If the child task already exists, replay uses the existing child identity. Parent output lookup also keeps terminal failure output available to downstream coordination. A completed result takes precedence when both terminal results exist for the same parent task.
References: pkg/…/durable_events.go• L1448-1585 pkg/…/durable_events.go• L1650-1724 pkg/…/trigger.go• L1956-2099 pkg/…/trigger.go• L3012-3055
Cron triggers
A cron trigger creates a recurring source for a workflow. Its cron expression, input, metadata, priority, and name are stored as a durable schedule. A ticker refreshes the schedules assigned to it and fires each matching expression in UTC. Each fire becomes a normal workflow trigger with the cron expression and fire time added to its metadata.
Cron schedules are separate from one-time scheduled runs. Removing or disabling a cron stops future fires. The ticker refreshes its in-memory jobs after schedule changes and during periodic polling, so a change does not require a service restart.
References: api/…/create_cron.go• L18-83 internal/…/ticker.go• L142-205 internal/…/cron.go• L17-67 internal/…/cron_v1.go• L19-63
One-time scheduled runs
A scheduled run stores one workflow invocation for a specific time. The caller supplies the workflow, trigger time, input, metadata, and optional priority. The ticker polls pending schedules and waits until each trigger time before sending a normal workflow trigger.
The run is idempotent by scheduled-run ID. The ticker claims an internal key before it sends the trigger, then removes the schedule after successful handoff. A past trigger time is treated as due and runs as soon as the schedule is found.
References: api/…/create_scheduled.go• L16-81 internal/…/schedule_workflow.go• L14-113 internal/…/schedule_workflow_v1.go• L16-58 pkg/…/workflow_schedules.go• L48-54
Delayed workflow conditions
Durable waits are the delayed-work path used by a workflow condition. A wait can use a sleep or a user event. Instead of keeping a worker blocked, the system stores the condition and later emits an internal event. Event matching checks the event type and key and can also check a scope. A satisfied condition then resumes the waiting task or creates the next task.
This path uses the same event and task signaling model as external events. It preserves workflow state across worker restarts and keeps delayed work out of the worker process. The durable event log keeps the condition identity stable across retries and rejects a changed condition as non-deterministic.
References: pkg/…/match.go• L208-270 pkg/…/match.go• L392-489 pkg/…/match.go• L1539-1581 pkg/…/durable_events.go• L427-568 pkg/…/durable_events.go• L1586-1634 pkg/…/trigger.go• L1263-1305 internal/…/process_sleeps.go• L12-43
Scheduling coordination
Trigger handoff
Trigger creation and worker assignment are separate stages. The trigger path writes the task or DAG and then signals the scheduler. The scheduler selects eligible workers and sends assignments through the dispatcher path described in Run dispatch and queue execution.
This separation lets a run remain durable when a worker is unavailable. A failure while sending a signal does not erase task records that were already written. For durable child runs, the event log also retains untriggered entries so later processing can complete a handoff that stopped between durable recording and task creation.
When optimistic scheduling is enabled, a direct or event trigger can use a bounded fast path. It creates the run and tries local assignment in one transaction. The path is optional and falls back to normal queue scheduling when no optimistic slot or matching local worker is available.
References: internal/…/trigger.go• L54-155 pkg/…/durable_events.go• L1538-1585 pkg/…/pool.go• L280-329 pkg/…/tenant_manager.go• L625-812 internal/…/scheduler.go• L221-306
Eligibility policies
The scheduler treats priority, worker affinity, rate limits, batching, concurrency, and scheduling timeouts as eligibility rules. A task is assigned only when a worker has the required capacity and matches the task's routing needs. A task that cannot run because of a rate limit can wait or leave the active queue until the limit permits it.
Batching groups compatible queued tasks by batch key and releases them when the configured size or time threshold is reached. The group consumes one scheduling slot for the batch. The scheduler then commits the grouped assignments together. Separate batch keys remain independent. Stale or already buffered items are removed during reconciliation.
Concurrency strategies add shared rules for queued work. They can release tasks to a queue, hand them to a later strategy, or cancel them when a concurrency rule or scheduling deadline applies. Parent and child strategies coordinate under shared protection. Lock contention defers a pass instead of blocking other scheduling work. Tenant-scoped strategies use the same scheduler view as step-scoped strategies and retire only when no current workflow uses them and no slots remain. New slot activity can reactivate them.
Queue polling backs off after repeated empty polls and adds jitter so idle queues do not keep a fixed database poll rate or create synchronized bursts. A queue notification wakes the loop early when new work arrives. Capacity restored while an assignment pass is being flushed is replayed after the flush when the item is eligible again. The queue requeues rate-limited work near its next refill time. A scheduling timeout removes work that can no longer be assigned. Empty rate-limit checks do not keep an idle queue active.
Rate-limit use is reserved before assignment and moves through acknowledged, rejected, and not-yet-flushed states. Refill checks use the stored next-refill time and can refresh the limit before the next background tick. A paused rate-limit key holds work until its pause ends. A rate-limit update wakes the tenant's queues so a new pause or released pause applies without waiting for the normal poll.
Worker capacity is a worker-level budget. Supporting several actions on one worker does not multiply its available slots. Assignment results drive queue replenishment, cancellation, retry, and monitoring signals. This keeps the in-memory view useful for fast assignment without making it the source of truth.
Concurrency definitions can change while work is queued. Safe limit or expression changes apply to the live in-memory strategy and wake its scheduling pass so idle groups see the new limit. Structural changes still require a rebuild because they change how work is grouped or ranked. Slot updates keep queue release, downstream strategy handoff, and cancellation results in one transaction when the caller already owns one.
References: pkg/…/scheduler_queue.go• L179-277 pkg/…/scheduler_queue.go• L280-573 pkg/…/scheduler_concurrency.go• L69-107 pkg/…/scheduler_concurrency.go• L1558-1695 pkg/…/queuer.go• L22-103 pkg/…/queuer.go• L181-273 pkg/…/queuer.go• L519-653 pkg/…/rate_limit.go• L121-211 pkg/…/rate_limit.go• L362-535 pkg/…/tenant_manager.go• L308-350 pkg/…/tenant_manager.go• L498-565 pkg/…/scheduler.go• L698-729 internal/…/scheduler.go• L455-718
Polling and ownership
The ticker uses durable schedule rows as the source of truth and keeps only the currently assigned work in memory. It refreshes cron work on a short polling interval and checks one-time schedules more often. A schedule that disappears from the durable result is cancelled in memory.
The refresh model supports multiple service instances by assigning schedule ownership through the ticker repository. Singleton refresh jobs prevent overlapping refresh work inside one ticker. The database and idempotency claim protect the handoff when a service restarts near a trigger time.
The scheduling pool applies the same ownership model to tenant state. Each active tenant has a manager for workers, queues, concurrency strategies, rate limits, and batch schedulers. Tenant changes add or remove these managers through lease notifications. Removal cancels their loops and releases their resources.
References: internal/…/ticker.go• L142-205 internal/…/cron.go• L17-74 internal/…/schedule_workflow.go• L14-63 internal/…/schedule_workflow_v1.go• L21-57 pkg/…/pool.go• L46-216 pkg/…/tenant_manager.go• L28-164 pkg/…/tenant_manager.go• L166-253
Controller maintenance schedules
Controller maintenance schedules run recurring work that keeps scheduling and run records usable without creating workflow runs. The OLAP controller starts these jobs with singleton execution so one controller does not overlap the same maintenance task with itself.
Audit log archiving runs hourly. It archives partitions that ended more than 24 hours ago and uses a five-minute lease so multiple service instances can coordinate ownership. If another table operation holds the partition lock, the job records the conflict and waits for the next interval instead of competing with that operation. The controller also creates table partitions on startup and refreshes them on a recurring interval.
References: internal/…/controller.go• L325-390 internal/…/controller.go• L366-385 internal/…/archive_audit_logs.go• L11-42
Workflow definition selection
Event and named triggers resolve a workflow version when the trigger is processed. Event matching selects the latest non-deleted version for the workflow. A scheduled row keeps the workflow version used for its pending invocation, so a later definition change does not silently rewrite an already scheduled run.
This distinction matters when a workflow is deployed while schedules are pending. Read Workflow definitions and versions for the rules that govern version creation and activation.
References: pkg/…/triggers.sql• L1-18 pkg/…/triggers.sql• L43-59 internal/…/schedule_workflow.go• L116-137
Trigger lifecycle
The main lifecycle moves from a source signal to durable run records and then to worker execution. The following diagram shows the shared handoff for event, direct, cron, and scheduled sources.
sequenceDiagram
participant Source as Event, request, or clock
participant Store as Trigger records
participant Ticker as Ticker or event path
participant Queue as Task queue
participant Scheduler as Scheduler
participant Worker as Worker and dispatcher
Source->>Store: Create or identify trigger
Ticker->>Store: Poll or claim due work
Source->>Queue: Submit trigger message
Ticker->>Queue: Submit trigger message
Queue->>Store: Create task or DAG
Store-->>Scheduler: Signal created work
Scheduler->>Worker: Assign eligible task
Worker-->>Store: Report run progress
The source differs, but the result is the same durable task and queue contract. The trigger context remains available through input or additional metadata, which lets downstream systems explain why a run started.
References: internal/…/cron_v1.go• L19-63 internal/…/schedule_workflow_v1.go• L21-57 internal/…/trigger.go• L54-155 pkg/…/trigger.go• L812-909 pkg/…/trigger.go• L1547-1743 pkg/…/tenant_manager.go• L625-812 pkg/…/queuer.go• L181-517 internal/…/scheduler.go• L283-306
Related coordination
Trigger and scheduling behavior is part of the larger orchestration path. Use Workflow orchestration for the run state model, Workflow definitions and versions for version selection, External integrations and events for event sources and delivery, Run dispatch and queue execution for worker assignment, and Worker lifecycle and listener for worker availability and listener behavior. Use Task and scheduling controllers for controller-level coordination.
Change checklist
When these files or sections are changed, remember to consider these:
- Changes to trigger metadata must stay aligned with the event, cron, and scheduled-run records that expose the trigger cause. Preserve trace parent and source workflow fields.
- Changes to child spawn keys or durable event identity must preserve reuse of the same child run across retries and replays.
- Changes to parent output lookup must keep failed terminal output available to on-failure coordination and prefer completed output when both terminal results exist.
- Changes to schedule polling or ownership must preserve the idempotent handoff for one-time schedules and the refresh path for cron updates.
- Changes to task creation signaling must keep database writes and queue notifications consistent. A missing signal can leave durable tasks unseen by the scheduler.
- Changes to workflow version lookup must preserve the difference between latest-version event or named triggers and version-bound pending schedules.
- Changes to eligibility rules must keep worker capacity shared across actions and keep rate-limit, batch, concurrency, and scheduling-timeout outcomes visible to the queue and monitoring paths.
- Changes to queue wake-up, backoff, or active-state refresh must preserve prompt handling for new work while allowing empty queues to become inactive.
- Changes to capacity wake replay must preserve retry of items that were still in flight when capacity changed, without replaying a batch after its failed database flush.
- Changes to rate-limit reservation, pause, or refill handling must preserve the ack and nack path so failed database writes do not consume capacity.
- Changes to rate-limited requeue must reactivate a queue when work returns without keeping every polled queue active. A new queuer must also inspect parked work after a restart.
- Changes to batch polling or flush thresholds must preserve batch-size limits, one-slot accounting, independent batch keys, and exclusion of already buffered rows.
- Changes to live concurrency definitions must preserve immediate re-evaluation of existing backlog and rebuild structural strategy changes when grouping or ranking changes.
- Changes to concurrency slot updates must preserve atomic release, queue upsert, downstream strategy handoff, and cancellation reason propagation when they share a transaction.
- Changes to tenant-scoped scheduling cleanup must preserve lease-driven resource removal and reactivation for new worker, queue, strategy, batch, or rate-limit activity.
- Changes to parent or child concurrency coordination must preserve lock contention handling and the shared concurrency limit across both strategy levels.
- Changes to in-progress concurrency cancellation must preserve the worker identity needed to notify the dispatcher after task runtime state is released.
- Changes to optimistic scheduling must preserve the bounded slot gate and transaction rollback path so a fast-path failure falls back without partial run state.
- Changes to operator-managed DAG trigger paths must preserve one metered count for the initial workflow run and avoid counting per-step handoffs again.
- Changes to controller maintenance intervals, partition leases, or archive lock handling must preserve singleton execution and retry after a concurrent table operation releases its lock.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| A cron expression cannot be parsed when the ticker loads it | The cron cannot fire and is removed from the stored cron set | Validate cron input at creation and remove invalid stored expressions during refresh |
| A one-time schedule fires while another ticker instance handles it | The same scheduled row could produce duplicate trigger attempts | Claim the internal idempotency key before sending the trigger |
| A scheduled run is deleted or updated while it is waiting in memory | The old timer can still fire unless the ticker refresh cancels it | Reconcile durable rows with in-memory timers and cancel removed schedules |
| An event filter does not match or its expression fails | The event is recorded but no workflow run is created | Treat failed filter evaluation as a non-triggering decision and record the evaluation failure |
| An event has a scope that does not match the condition | The event does not satisfy that condition and its workflow step stays waiting | Match the event key and scope together for scoped internal conditions |
| A durable child entry is committed before child task creation, then the process stops | The parent can wait forever or create a duplicate child on recovery | Keep the child external ID on the durable entry and retry only untriggered entries through the pending trigger path |
| Parent output lookup ignores failed terminal events | An on-failure task cannot receive the upstream task error during coordination | Include failed output events and keep a completed event when both completed and failed results exist |
| A worker has no matching capacity or the scheduling deadline passes | The task stays unassigned, is rate-limited, or is marked as scheduling timed out | Refresh worker capacity and return explicit unassigned, rate-limited, and timeout outcomes |
| A worker's slots are counted once per supported action | The scheduler reports more capacity than the worker can run | Keep replenishment and snapshots keyed to worker capacity rather than action count |
| A batch flush uses more rows than its configured size | A worker receives an oversized batch and batch limits no longer match the workflow contract | Flush the requested batch slice and use one representative scheduling slot for the group |
| A batch poll does not exclude rows already held in memory | The same rows are buffered again and can crowd other batch keys out of the poll window | Exclude buffered IDs from the next durable fetch and reconcile missing rows |
| A rate-limit reservation is acknowledged before its queue result is stored | A failed write can consume shared rate-limit capacity and delay later work | Keep reservations unacked until the database write succeeds, then flush acknowledged use |
| A paused rate-limit key is treated as an expired window | Work runs during an explicit pause | Give the pause deadline precedence and refresh the rate-limit snapshot before dispatch |
| A fresh queue loop skips parked rate-limited rows because its live queue is empty | Filled concurrency slots remain parked after a restart and later work cannot proceed | Run the scheduled rate-limit requeue check when a new queuer starts |
| A queue remains idle after several polls while a new item arrives | Work waits for the next backoff poll instead of running promptly | Wake the queue loop on enqueue and apply jitter only to timer-based polls |
| Capacity returns while a missed item is still being flushed | The wake-up can be consumed before the item is visible again and the item waits for the poll floor | Replay the queue after the flush only when the worker capacity epoch changed |
| A failed flush is treated as a capacity change | The queue retries itself rapidly and can hammer the database | Nack the assignment without advancing the capacity epoch; retry on the normal poll |
| A tenant is removed while its scheduling loops still run | Queues or rate-limit state can act on a tenant that no longer owns them | Cancel tenant loops before closing lease resources and remove the tenant from the pool |
| A concurrency limit changes while a group has queued work but no new messages arrive | The old limit remains in effect for idle backlog | Apply safe changes in place and re-arm the all-sub-queue scheduling pass |
| A concurrency slot is released outside the transaction that changes its queue or task state | The scheduler can expose capacity while the task remains held, or cancel a task without matching queue state | Use the transaction-aware slot update path when the caller already owns the transaction |
| A parent or child concurrency strategy cannot acquire its advisory lock | That scheduling pass makes no progress and later tasks remain queued | Return a lock-contention result and let a later scheduling pass retry without blocking |
| An optimistic scheduling slot is unavailable or its transaction fails | The trigger cannot use the fast path | Return the normal queue path when no optimistic slot or local assignment is available |
| An operator-managed DAG meters its orchestrator and each later step trigger | One logical workflow can consume task-run quota more than once | Meter the initial DAG's regular steps and exclude later operator step handoffs |
| A trigger message is published after task creation fails or is lost | A caller may see a trigger request without runnable task records, or durable records may wait for reconciliation | Keep task creation and trigger signaling as distinct contracts and monitor signal failures |
| Audit-log archiving meets a concurrent table operation | The archive pass cannot acquire its partition lock and leaves old partitions for a later pass | Use a lease-aware archive operation and retry at the next interval after a lock conflict |
Key files
| File | Why to read it |
|---|---|
| pkg/…/triggers.sql | Shows how event keys map to the latest workflow versions. |
| pkg/…/trigger.go | Defines shared rules for event and named triggers, filters, idempotency, metadata, child workflow signals, DAG creation, pause holding, and task metering. |
| pkg/…/match.go | Shows how user and internal events satisfy delayed conditions and resume work. |
| pkg/…/durable_events.go | Shows how durable waits and child workflow entries preserve delayed work and recover incomplete child trigger handoffs. |
| internal/…/trigger.go | Shows how created tasks and DAGs are signaled after a trigger request. |
| internal/…/cron.go | Shows how durable cron rows become recurring clock jobs. |
| internal/…/cron_v1.go | Shows the handoff from a cron fire to the normal task queue. |
| internal/…/schedule_workflow.go | Shows how one-time schedules are polled, waited on, and cancelled. |
| internal/…/schedule_workflow_v1.go | Shows the idempotent one-time schedule handoff and cleanup. |
| internal/…/controller.go | Shows how recurring controller maintenance jobs are started and kept from overlapping. |
| internal/…/archive_audit_logs.go | Shows how old audit-log partitions are archived with a lease and lock-conflict retry. |
| pkg/…/pool.go | Shows tenant manager ownership and the bounded optimistic scheduling path. |
| pkg/…/tenant_manager.go | Shows how worker, queue, concurrency, batch, and rate-limit changes reach a tenant's scheduler. |
| pkg/…/queuer.go | Shows queue wake-up, idle backoff, capacity replay, rate-limit requeue, and the durable result handoff for assignment outcomes. |
| pkg/…/rate_limit.go | Shows how shared rate-limit use and pause state are reserved, acknowledged, rejected, and refreshed. |
| pkg/…/concurrency.go | Shows how live concurrency definitions are applied or rebuilt during tenant reconciliation. |
| pkg/…/strategy.go | Shows how safe concurrency changes reach queued backlog and how timeout outcomes are separated from limit outcomes. |
| pkg/…/scheduler.go | Shows how worker capacity and queue policies affect task eligibility. |
| pkg/…/scheduler_queue.go | Shows the durable queue result contract behind assignment outcomes. |
| pkg/…/scheduler_concurrency.go | Shows how concurrency strategies release, hand off, or cancel tasks and how transactional slot updates protect scheduling state. |
| internal/…/process_sleeps.go | Shows how durable delays become internal events and resumed work. |