Introducing a new way to review your PRs.

Read the announcement

hatchet-dev / hatchet

🪓 An orchestration engine for background tasks, AI agents, and durable workflows

View on GitHub

31 documents · Updated Nov 23, 2026

docs / service-runtime-and-control-plane

Service runtime and control plane

The service runtime is the set of long-running control-plane services that moves durable workflow work from stored state to workers and back again. It keeps task state moving, routes work to live workers, removes expired data, and turns execution events into status and operational views. It also provides durable tenant streams for clients that need ordered events after a request or worker session ends.

System role

The control plane sits between workflow requests, durable storage, message transport, workers, and operator-facing status. It does not run user code itself. It decides what work is ready, where that work should go, how worker results change durable state, and which downstream systems must learn about the change.

The main services have separate responsibilities:

ServiceMain responsibilityPrimary result
Task controllerApply task events and run background task operationsUpdated task state and new work signals
SchedulerSelect runnable work and group assignments by worker dispatcherDispatcher-targeted assignment messages
DispatcherConnect assignments to registered workers and durable-task sessionsWorker actions and result events
Retention controllerRemove data that passed its retention periodBounded queue and session data
TickerMaintain cron schedules and periodic tenant checksTimely scheduled runs and alerts
OLAP controllerStore execution history and derive operational statusStatus updates, metrics, alerts, traces, audit rows, and workflow events
Durable streams servicePersist and deliver ordered tenant stream messagesResumable application event streams

These services share tenant-aware storage and message paths. The task and scheduling details are covered in Task and scheduling controllers. Worker transport is covered in Dispatcher and worker coordination. Operational data and monitoring are covered in OLAP and observability services.

Engine composition and lifecycle

Service selection

The engine starts service groups from the server profile. Controller groups can include task processing, scheduling, OLAP analysis, retention, ticker work, metrics, and tenant partition work. API groups can include dispatch, request ingestion, administrative access, durable streams, operators, and telemetry. The V1 profile can pause the task or OLAP controller while the other runtime groups stay active.

References: cmd/…/run.go• L128-169 cmd/…/run.go• L751-916 cmd/…/run.go• L918-1080

Startup and shutdown ordering

Startup records cleanup as each service starts. If a later step fails, the engine runs the cleanup already registered. This keeps listeners, queues, and background work from outliving a partially started process.

Normal shutdown follows the dependency direction of the runtime. The engine marks the dispatcher as draining, stops in-process operator registrations, cancels long-lived dispatcher and stream sessions, and then drains the API services. Health reporting remains active until the rest of the engine is no longer ready to receive work.

References: cmd/…/run.go• L92-123 cmd/…/run.go• L1143-1229

Service front doors

The RPC front door exposes the control plane to SDKs, workers, operators, administrators, stream clients, and telemetry senders. Request services turn accepted workflow, event, log, and stream actions into durable records or control-plane messages. Admin and ingestor requests can use local scheduling when the scheduler and dispatcher are in the same process. They keep the normal task-processing path as the fallback when local or RPC fast paths cannot complete.

Workflow creation also refreshes time-based triggers and wakes the scheduler for each new action queue. Trigger requests keep idempotency claims in the synchronous path when a key is present. This prevents a full trigger path from turning an idempotent request into an unsafe queued write.

References: cmd/…/run.go• L962-1080 cmd/…/run.go• L1130-1217 internal/…/server.go• L77-114 internal/…/server_v1.go• L284-405 internal/…/server.go• L724-830 internal/…/ingestor_v1.go• L69-212 internal/…/server.go• L38-113

RPC error boundary

The RPC error boundary gives all unary and streaming clients the same safe view of service failures. It keeps client-actionable codes and details, maps common storage and capacity conditions to stable responses, and hides server diagnostics for internal failures. Unexpected errors and handler panics remain available to logs and alerts while clients receive a generic internal error.

References: internal/…/error.go• L23-74 internal/…/error.go• L89-143 internal/…/error.go• L175-236 internal/…/error_test.go• L58-100 internal/…/server_compat_test.go• L474-514

Operator sessions

The operator service is the shared boundary for operator sessions. It registers or loads an operator, creates or resumes its worker, authorizes the session, and connects action delivery to the local dispatcher. The operator stream starts with an explicit worker selection, then carries heartbeats, action changes, and pause changes with acknowledgements. External operator hosts and operators hosted inside the engine use the same service contract.

Operator workers are pinned to the dispatcher that delivers their actions. A resumed worker clears its paused state before it becomes assignable again. When a dispatcher changes, inactive workers from the same claimed operator release their old action links so repeated replacement does not consume the operator's action budget.

References: internal/…/service.go• L1-14 internal/…/service.go• L39-71 internal/…/service.go• L318-386 internal/…/register.go• L21-146 internal/…/register.go• L170-193 internal/…/listen.go• L26-37 internal/…/listen.go• L76-193

Service topology

The services form a loop. A task controller changes durable state and signals the scheduler. The scheduler selects workers and routes grouped assignments to their dispatcher. The dispatcher sends work to a worker. Results return to task processing and OLAP. OLAP updates operational views and publishes downstream status.

The following diagram shows the high-level path from task state to worker execution and operational status.

flowchart LR
    A[Workflow request or trigger] --> B[Task controller]
    B --> C[(Durable task state)]
    B --> D[Task and scheduler messages]
    D --> E[Scheduler]
    E --> F[(Dispatcher assignment queue)]
    F --> G[Dispatcher]
    G --> H[Worker or operator session]
    H --> I[Worker result or heartbeat]
    I --> B
    I --> J[OLAP controller]
    B --> J
    J --> K[(Operational history and status)]
    J --> L[Metrics, alerts, traces, audit, and tenant events]
    L --> M[Streams and subscribers]
    N[Retention and cleanup] --> C

Task state coordination

The task controller is the state transition center for task execution. It consumes task, trigger, completion, failure, cancellation, and durable-event messages. It applies them to durable task state, then emits signals for scheduling, dispatch, callbacks, and status recording. Its periodic work also repairs paused or rate-limited queue items, releases retryable items when their delay ends, reassigns work whose worker is no longer usable, and expires items that remain paused too long.

DAG orchestrators use a separate status signal for terminal changes that the normal task event path already records. The signal is retried before the source message is acknowledged. This keeps the run-level status current without writing a duplicate task event. Terminal orchestrator events carry completion, failure, or cancellation details and can also drive cancellation of unfinished children when no worker remains. The detailed loops are covered in Task and scheduling controllers.

References: internal/…/controller.go• L355-490 internal/…/controller.go• L493-536 internal/…/controller.go• L538-632 internal/…/controller.go• L700-776 internal/…/controller.go• L792-901 internal/…/controller.go• L989-1125 internal/…/controller.go• L1454-1600

Work scheduling

The scheduler turns queue results into worker-targeted work. It reacts to new tasks, released slots, new workers, and rate-limit changes. It groups assignments by the dispatcher that owns each worker and can group compatible items into a batch. It records queue state changes as monitoring events while it makes these choices.

If an assignment cannot reach a dispatcher, the scheduler retries or sends the task back through task processing. Its dead-letter path also handles interrupted assignment, cancellation, batch start, and durable callback delivery. Durable callback redelivery is delayed and capped so a missing session does not create an endless message loop. This keeps queue selection separate from the live worker connection. The dispatch path is covered in Dispatcher and worker coordination.

References: internal/…/scheduler.go• L228-369 internal/…/scheduler.go• L372-500 internal/…/scheduler.go• L519-669 internal/…/scheduler.go• L906-932 internal/…/scheduler.go• L1069-1323 internal/…/scheduler.go• L1397-1612 internal/…/task.go• L289-323

Worker dispatch

The dispatcher is the live bridge between control-plane assignments and worker processes. It registers its ownership, maintains a heartbeat, receives assignments, tracks worker sessions, records heartbeats, sends actions, and accepts action results. A worker listener session owns the active state, so an older connection cannot deactivate a newer one. Worker and operator action changes use the same live dispatch boundary.

Each worker stream limits concurrent sends and bounds admission time so a stalled connection does not hide an unbounded backlog. The dispatcher also protects long-lived streams from late sends after shutdown and reports delivery uncertainty back to task processing.

If delivery fails before an action starts, the task returns to the task-processing path so the control plane can retry or fail it according to task policy. If delivery has started but the caller stops waiting, the assignment stays in place because the worker may already have received it. A per-worker send lock limits concurrent actions and turns a saturated stream into a clear flow-control result. The dispatch path is covered in Dispatcher and worker coordination.

References: internal/…/dispatcher.go• L356-467 internal/…/dispatcher.go• L469-555 internal/…/dispatcher.go• L558-627 internal/…/dispatcher.go• L980-1252 internal/…/dispatcher.go• L1378-1504 internal/…/dispatcher.go• L1506-1514 internal/…/subscribed_worker_v1.go• L33-237 internal/…/timeout_lock.go• L22-53

Durable task coordination

Durable tasks use a long-lived dispatcher session to record durable events, trigger child runs, wait for external conditions, and receive satisfied entries. Durable event records remain the source of truth across reconnects and engine restarts. The same session contract supports gRPC workers and in-process operator workers.

The dispatcher routes live completions to the current session and checks invocation order so an old session cannot change a newer run. It holds out-of-order completions until their satisfied order is available. Worker status after reconnect can release entries that the worker already received. Repeated worker status messages are merged into one bounded, single-flight update so a slow stream does not create an unbounded handler backlog. Session and tenant budgets apply backpressure before durable requests start. A callback that misses its session enters the scheduler's delayed recovery path instead of blocking the task controller.

References: internal/…/server_v1.go• L355-581 internal/…/server_v1.go• L583-625 internal/…/server_v1.go• L658-862 internal/…/server_v1.go• L864-1004 internal/…/server_v1.go• L1120-1182 internal/…/server_v1.go• L1256-1380 internal/…/server_v1.go• L1383-1504 internal/…/dispatcher.go• L500-539 internal/…/task.go• L289-323 internal/…/server_v1_durable_task_test.go• L62-190 internal/…/worker_status_coalescer_test.go• L58-177 internal/…/worker_status_coalescer_test.go• L498-582

Cron and periodic work

The ticker keeps time-based workflow work and tenant checks moving. It loads cron schedules at startup, refreshes them on a short poll, and accepts immediate refresh notifications when workflow definitions change. The periodic refresh remains the recovery path if a notification is missed. It also maintains its own heartbeat and runs periodic resource and tenant alert checks.

References: internal/…/ticker.go• L21-48 internal/…/ticker.go• L156-302 internal/…/server.go• L879-923

Retention and cleanup

Retention keeps old queue, session, and related data from remaining in live operational state. Task cleanup also reconciles paused workflow queue state and emits cancellation status when a paused item reaches its time limit. Cleanup is part of control-plane correctness because expired work must not compete with current work and stale sessions must not appear active.

References: internal/…/controller.go• L19-64 internal/…/controller.go• L161-230 internal/…/process_paused_workflow_ttl.go• L27-79

Operational analysis

The OLAP controller builds queryable execution views outside the live task transition path. It consumes task lifecycle and workflow activity messages, stores task and workflow history, maps detailed events to readable status, and derives workflow-run completion from terminal state changes.

OLAP work is designed for contention and delayed processing. It samples optional high-volume data, retries work when a workflow-run lock is not available, and republishes items that cannot be applied within the retry limit. Orchestrator status-only events update the run's DAG status without creating a duplicate task event. Terminal status notifications are sent only for completed, failed, or cancelled states.

The controller also creates engine-owned trace spans for workflow runs, events, and task runs. It links these spans to source runs or SDK trace context when available. Optional Prometheus workers batch duration updates and discard updates when their bounded channels are full. An audit outbox can flush accepted audit records from the core database into OLAP, so an accepted audit entry does not depend on immediate OLAP availability. The related status and telemetry flows are covered in OLAP and observability services.

References: internal/…/controller.go• L337-528 internal/…/controller.go• L531-642 internal/…/controller.go• L985-1267 internal/…/controller.go• L1270-1328 internal/…/controller.go• L1367-1382 internal/…/engine_spans.go• L54-73 internal/…/engine_spans.go• L267-452 internal/…/process_dag_status_updates.go• L15-120 internal/…/process_task_status_updates.go• L15-132 internal/…/prometheus_worker.go• L35-177 internal/…/controller_monitoring_events_test.go• L53-134

Status and event delivery

Monitoring events build operational history and readable status. Tenant-stream events then carry task and workflow changes to subscribers such as workers, SDK clients, and workflow-run listeners. Terminal workflow notifications stay separate from non-terminal status changes so a client does not close a run while it is still active.

Workflow-run subscriptions use acknowledgements and bounded polling to avoid losing a final event when several control-plane services update the same run. Step events wait for their indexes. Terminal events wait for late stream chunks or a timeout. This gives clients ordered execution data and a clear end signal. A non-terminal status reaching a terminal workflow message is treated as an upstream contract error rather than converted into a false completion.

References: internal/…/process_dag_status_updates.go• L52-120 internal/…/process_task_status_updates.go• L51-132 internal/…/tenant_stream_events.go• L42-135 internal/…/tenant_stream_events.go• L224-252 internal/…/server.go• L723-1142 internal/…/server.go• L1144-1357 internal/…/tenant_stream_events_test.go• L23-90 internal/…/tenant_stream_events_test.go• L179-306

Durable stream delivery

The durable streams service provides tenant-scoped topics with ordered messages and resumable cursors. It checks producer sequence order, applies tenant entitlements and limits, and keeps data available for subscribers until retention removes it. Duplicate producer messages are safe to retry, but a skipped sequence stops later entries from being accepted.

A subscriber can resume from a cursor while the topic data remains retained. External delivery meters inline payload bytes for the tenant. In-process subscribers used by the engine are not billed as client reads. A payload reference is checked before publish and is billed when its data is fetched.

References: internal/…/server.go• L31-181 internal/…/server.go• L256-380 internal/…/server.go• L492-526 internal/…/usage_test.go• L122-176 internal/…/usage_test.go• L228-291

Lifecycle flow

The control plane uses durable state as the source of truth and messages as the way to move work between service responsibilities. A typical execution follows this sequence:

  1. A trigger, event, cron schedule, or API request creates or releases task work.
  2. The task controller records the transition and signals the scheduler or dispatcher path.
  3. The scheduler selects a live worker and routes the assignment to that worker's dispatcher.
  4. The dispatcher sends the task action to a worker or operator session.
  5. The worker reports start, completion, failure, cancellation, or durable status.
  6. The task controller applies the result and creates any next task or retry.
  7. The OLAP controller records the event and advances task or workflow-run status.
  8. Terminal status is published to tenant streams for subscribers and operational consumers.

Durable-task work follows the same loop with an added session path. A worker or operator records a durable event through the dispatcher. The control plane stores the event and creates child work. A later satisfied event returns to the active session while task and OLAP services continue to own durable state and operational views.

The engine starts only the configured service groups and keeps cleanup order aligned with these dependencies. Recovery work such as timeouts, missing heartbeats, delayed durable callbacks, and stuck evictions enters the control plane as periodic work or messages. A client does not need to repair state after a worker or service restart.

The diagram shows how request, scheduling, execution, and operational paths meet.

sequenceDiagram
    participant Client
    participant FrontDoor as Admin or ingestor
    participant Tasks as Task controller
    participant Scheduler
    participant Dispatcher
    participant Worker
    participant OLAP

    Client->>FrontDoor: Submit workflow or event
    FrontDoor->>Tasks: Durable state or task message
    Tasks->>Scheduler: Work-ready signal
    Scheduler->>Dispatcher: Worker-targeted assignment
    Dispatcher->>Worker: Action
    Worker-->>Dispatcher: Result or heartbeat
    Dispatcher->>Tasks: Execution result
    Dispatcher->>OLAP: Monitoring event
    Tasks->>OLAP: Task lifecycle event
    OLAP-->>Client: Status, event, or terminal update

Cross-service contracts

Durable state and message paths

Repository operations change durable records. Queue messages request work or carry execution results. Tenant topics fan out notifications. Monitoring payloads connect task transitions to operational history. Durable-task RPC messages add a session contract for event writes, acknowledgements, ordered completions, and worker status.

Task terminal events and paused-item expiry publish their status signals after the durable state change. Redelivery can then repair downstream views without creating a second state transition. Audit entries first use a core-database outbox and then move to OLAP. A change is safe only when these paths still agree on message meaning and terminal-state rules.

References: internal/…/controller.go• L538-632 internal/…/controller.go• L719-776 internal/…/controller.go• L792-901 internal/…/controller.go• L989-1125 internal/…/dispatcher.go• L469-539 internal/…/server_v1.go• L1120-1182 pkg/…/audit_log.go• L80-136

Tenant isolation and partitioning

Every service operation is tenant-scoped. Partitions divide tenant work across controller instances and scheduler topics. Task, OLAP, dispatcher, and stream activity keep the tenant context through each path. This prevents one tenant from becoming an implicit global workload.

References: internal/…/process_task_status_updates.go• L20-35 internal/…/process_dag_status_updates.go• L20-35 internal/…/signal.go• L42-57 internal/…/server.go• L36-88 internal/…/server.go• L54-75

Dispatcher ownership

Worker sessions are part of the dispatch contract. The dispatcher records which engine replica owns a worker and tells the scheduler when ownership changes. Listener session fences prevent an older connection from deactivating a newer one. A send lock also prevents one slow worker stream from accepting overlapping actions that could reorder delivery.

References: internal/…/dispatcher.go• L356-467 internal/…/dispatcher.go• L630-710 internal/…/server.go• L215-261 internal/…/server.go• L363-428 internal/…/subscribed_worker_v1.go• L150-237 internal/…/tenant_stream_events_test.go• L220-274

Durable task session ownership

Durable-task completion routing depends on the active session for a tenant and task. A reconnect replaces the live route. Invocation counts prevent an older session from completing or evicting a newer invocation. When a session closes, later callbacks can use the durable retry path.

References: internal/…/server_v1.go• L685-737 internal/…/server_v1.go• L963-1003 internal/…/server_v1.go• L1120-1182 internal/…/server_v1.go• L1516-1541 internal/…/scheduler.go• L1529-1612

Operator session ownership

Operator workers are pinned to the dispatcher that delivers their actions. Named registrations upsert contract operators. Claimed registrations load a tenant-owned operator and create a worker linked to that operator. Inactive workers can remain in durable state after a dispatcher stops, so a later claimed registration releases their action links while preserving the links of its active or resumed worker.

References: internal/…/register.go• L81-146 internal/…/register.go• L170-193 internal/…/register.go• L223-309 internal/…/service.go• L222-225

Change checklist

When these files or sections are changed, remember to consider these:

  • Keep service-profile selection aligned with the local scheduler, dispatcher, streams service, and operator runtime that each API path expects.
  • Keep startup cleanup registration aligned with every new background loop or listener. A failed start must remove work that already began.
  • Keep workflow-trigger fast paths aligned with the queued fallback and with the synchronous idempotency claim path.
  • Keep paused-workflow reconciliation aligned with both the unpause path and the scheduler notification path.
  • Keep retry release aligned with scheduler wake-up messages and the queued monitoring event.
  • Keep reassignment and timeout events aligned with the task response that decides whether the attempt will retry.
  • Keep orchestrator status-only events aligned with OLAP DAG status updates so one lifecycle change is not counted twice.
  • Keep the task terminal event contract aligned with OLAP status mapping and workflow-run terminal notifications.
  • Keep worker-send timeout behavior aligned with retry behavior. A send that has started must not be retried as if it never reached the worker.
  • Keep durable completion ordering aligned with reconnect status. The worker's highest received order must release buffered entries safely.
  • Keep dispatcher and durable-task session fences aligned with reconnect behavior so old sessions cannot change current state.
  • Keep durable status coalescing aligned with its single-flight and whole-task batch limits.
  • Keep stream producer sequence handling aligned with duplicate retries and gap errors.
  • Keep stream usage accounting aligned with stored payload bytes and delivered inline payload bytes. In-process reads must remain outside client billing.
  • Keep stream cursor validation aligned with retention so a resumed client receives an explicit expiry result.
  • Keep workflow-run terminal conversion aligned with OLAP's terminal-only publish rule. Non-terminal status must fail loudly.
  • Keep trace correlation attributes aligned with SDK span context and OLAP lookup records.

Important failure modes

TriggerConsequenceGuard
Startup fails after listeners or loops have startedA partial engine keeps ports, queues, or background work aliveRun the cleanup steps registered during startup
An idempotent trigger falls back to an asynchronous queue claimThe request can return before its uniqueness claim is securedKeep idempotent trigger claims in the synchronous path
A paused queue item survives after its workflow is unpausedWork remains hidden from schedulingReconcile paused items and notify the scheduler
A released retry does not wake its queue or concurrency strategyA ready task waits for a slow scheduler pollNotify the scheduler and publish the queued monitoring event
A worker send times out before admissionThe assignment can be lost or delayedReturn a retryable admission error
A caller cancels after a worker send startsRetrying can execute the same action twiceKeep the assignment and wait for transport ownership to finish
An older worker stream closes after a newer stream connectsThe current worker can be marked inactiveFence session activation and deactivation
A durable completion arrives for an old invocationA newer durable run can be completed or evicted by stale workCompare invocation counts before routing completion or eviction
A durable completion arrives out of orderThe worker can observe an invalid event sequenceBuffer entries until the next satisfied order is available
Worker status floods a blocked durable streamRequest handlers pile up and memory growsMerge statuses into one single-flight bounded runner
A durable callback has no active session and retries without a boundDead-letter traffic can loop during a worker outageDelay redelivery and stop after the configured cap
A stream producer skips a sequence numberLater messages are stored ahead of an unrecoverable gapReject the gap and require the producer to fill it
A stream cursor is no longer retainedA subscriber cannot resume from its last positionValidate the cursor and return an expiry error
A non-terminal status reaches the workflow-finished converterA live run can appear completed to a subscriberReject the message and fix the OLAP publish contract
An uncoded RPC failure reaches the error boundaryBackend details can leak or the client sees unstable behaviorAlert and log the cause, then return a generic internal error
Dispatcher drain starts before long-lived sessions stopFinal events have no live delivery pathCancel stream sessions before graceful server stop

Key files

FileWhy to read it
cmd/…/run.goShows service selection, runtime assembly, controller activation, and startup and shutdown order
internal/…/server_v1.goShows workflow trigger fast paths, idempotency handling, and fallback to the task queue
internal/…/server.goShows workflow creation, scheduler queue notifications, and rate-limit control messages
internal/…/server.goShows administrative cancellation, replay, workflow creation, and scheduler notifications
internal/…/ingestor_v1.goShows event ingestion, local scheduling, and the task-processing fallback
internal/…/controller.goShows the task controller boundary, terminal status signaling, and downstream execution signals
internal/…/process_retry_queue_items.goShows delayed retry release, scheduler wake-up, and queued monitoring events
internal/…/process_paused_workflow_ttl.goShows paused queue reconciliation and expiry handling
internal/…/process_reassignments.goShows worker loss recovery and reassignment status signals
internal/…/durable_callbacks.goShows durable task restoration and scheduler notification after recovery
internal/…/scheduler.goShows queue results becoming dispatcher-targeted assignments, batch work, and dead-letter recovery
internal/…/dispatcher.goShows dispatcher registration, heartbeat, assignment delivery, worker routing, and lifecycle
internal/…/server.goShows worker streams, heartbeats, workflow-run subscriptions, and ordered event buffering
internal/…/subscribed_worker_v1.goShows worker send admission, cancellation uncertainty, and retry boundaries
internal/…/server_v1.goShows durable-task sessions, ordered completion, reconnect recovery, and eviction
internal/…/tenant_stream_events.goShows how tenant messages become task and workflow stream events
internal/…/controller.goShows operational event ingestion, status processing, lock retries, traces, and audit flushing
internal/…/engine_spans.goShows engine-owned trace relationships for workflow, event, and task spans
internal/…/process_dag_status_updates.goShows terminal workflow status publication and alert triggers
internal/…/prometheus_worker.goShows bounded asynchronous duration metric processing
internal/…/signal.goShows how task state changes become OLAP and scheduler signals
internal/…/server.goShows durable stream publish, sequence checks, cursor resume, retention checks, and subscriber sessions
internal/…/usage_test.goShows stream usage rules for stored messages, delivered payloads, and in-process subscribers
internal/…/ticker.goShows cron refresh, schedule polling, ticker heartbeat, and periodic tenant checks
internal/…/olap.goShows the monitoring event contract and status-only or retry-state flags
internal/…/task.goShows task result, cancellation, replay, durable callback, and scheduler message contracts