Dispatcher and worker coordination
The dispatcher connects control-plane decisions to running workers. It turns queued task work into worker actions, carries worker results back into task processing, and serves tenant-scoped event streams through durable topic transport. It also rejects stale assignment messages and avoids retrying actions whose transport send already started. Durable task streams use shared in-flight budgets so one stream or tenant cannot consume unbounded handler capacity.
Coordination model
Control-plane boundary
The dispatcher is the transport boundary between scheduling services and workers. The control plane places work on a queue. The dispatcher enriches that work from durable state and sends it over a worker session. Worker actions return through the dispatcher so task state, durable events, and observability can progress.
The main path is:
flowchart LR
A[Scheduler or task controller] -->|assignment message| B[Dispatcher queue]
B --> C[Dispatcher]
C -->|AssignedAction| D[Worker stream or operator session]
D -->|task or durable event| C
C --> E[Task processing and durable event queues]
C --> F[Monitoring and OLAP queue]
The dispatcher does not decide which work should run. Controllers and schedulers make that decision. The dispatcher delivers the decision to the worker that owns the assigned session and reports delivery problems for later task handling. See service runtime and control plane and task and scheduling controllers.
References: internal/…/dispatcher.go• L45-76 internal/…/dispatcher.go• L558-625 internal/…/subscribed_worker_v1.go• L33-106
Dispatcher lifecycle
Startup registration
Startup creates a dispatcher identity in persistent state before it accepts work. The service then starts a periodic heartbeat and subscribes to a queue named for that identity. This lets the control plane find a live dispatcher and lets assignment producers target its queue.
The dispatcher requires a task queue, tenant pub/sub, a repository, and a cache. It creates shared tenant readers for event subscriptions and separate publication buffers for task and durable-event traffic. On shutdown it stops intake, waits for active queue work, drains stream-backed workers, stops scheduled jobs, and removes its persistent identity. A caller can first mark the dispatcher inactive so new operator claims move to another dispatcher while the current one drains. Long-lived worker, durable-task, and event sessions are cancelled before graceful server stop so a pending receive cannot hold shutdown open.
References: internal/…/dispatcher.go• L290-352 internal/…/dispatcher.go• L356-465 internal/…/dispatcher.go• L80-85 internal/…/dispatcher.go• L1506-1513 internal/…/dispatcher_v1.go• L43-48
Assignment intake
The dispatcher queue carries control-plane messages for work that must reach workers. The important message groups are task assignments, task cancellation, durable callback completion, and batch starts. Each message is handled in the tenant context so the dispatcher can read the right task data and publish follow-up work to the right tenant.
Assignment handling is bounded so a slow worker does not hold queue visibility forever. Before delivery, the dispatcher compares the message's worker and retry information with current task state. A delayed assignment is skipped when the task has moved to another attempt. Work that cannot reach a worker is sent back through task processing as a failed or retryable task path. This keeps delivery failure inside the task state machine instead of losing the assignment at the transport boundary. The broader queue lifecycle is described in run dispatch and queue execution.
Batch starts use the same protection. If the named worker is not connected, the dispatcher rechecks that each batch item still belongs to that worker and batch before it asks task processing to retry the item. This prevents a late batch message from changing a task that was already reassigned.
References: internal/…/dispatcher.go• L469-492 internal/…/dispatcher.go• L558-625 internal/…/dispatcher.go• L980-1067 internal/…/dispatcher.go• L1116-1154 internal/…/dispatcher.go• L1156-1198
Worker sessions
Worker registration
Workers first register their capabilities and capacity with the dispatcher. Registration creates the worker record for the tenant and returns the worker identity used by later listen and heartbeat calls. The record can include actions, services, labels, runtime information, and slot capacity.
The worker then opens a long-lived listen session. The dispatcher marks that session as active and binds it to the current dispatcher identity. A session identifier protects the active state: when a newer session replaces an older one, cleanup from the old session cannot mark the newer one inactive. The worker-side view of this lifecycle is described in worker lifecycle and listener.
References: internal/…/server.go• L36-128 internal/…/server.go• L188-313 internal/…/server.go• L315-409 internal/…/server.go• L411-427
Execution context propagation
The worker execution context carries task identity and durable-task state into the task handler. It can hold the current durable response listener, invocation count, and waiting-state hook that supports durable-run eviction.
Worker middleware can replace the context used by a task handler. The next handler receives that replacement, which preserves request values and deadlines for task code and durable operations.
References: pkg/…/context.go• L43-54 pkg/…/context.go• L159-161 pkg/…/context.go• L201-225 pkg/…/context.go• L488-524 pkg/…/middleware_test.go• L239-263
Assignment delivery
The dispatcher keeps the active sessions for each worker in memory. For each assigned task it loads the task input, runtime data, parent outputs, and durable invocation count when needed. It then creates an AssignedAction and sends it to a worker stream or to an in-process operator handler.
The worker delivery path limits concurrent sends for a session. The dispatcher tries the active sessions for the worker until one accepts the action. A paused operator rejects new starts so the dispatcher can return them to the queue, while cancellation actions can still pass through. If no session accepts a task, the dispatcher requeues it through the task-processing path.
The stream send has an explicit admission boundary. A deadline or cancellation before admission returns a retryable error. After the transport send starts, the result is uncertain, so the dispatcher keeps the task assigned instead of retrying it and risking a duplicate start. A stalled stream also blocks sibling sends until its send completes or flow control rejects them.
Task assignment data is assembled before delivery. The dispatcher resolves task input, parent output, runtime data, and durable invocation state, then packages that data in an AssignedAction. Local assignments wait for all sends to finish so the scheduler keeps its work claim until delivery completes. Queue-driven assignments can finish their queue handler while delivery and retry work continues under the dispatch deadline.
References: internal/…/dispatcher.go• L642-709 internal/…/dispatcher.go• L717-884 internal/…/dispatcher.go• L980-1067 internal/…/subscribed_worker_v1.go• L33-106 internal/…/subscribed_worker_v1.go• L127-238
Worker availability
Heartbeats update worker liveness independently from task delivery. The dispatcher records the heartbeat before it checks whether the listen stream is active. This keeps an alive worker's in-flight tasks from being reassigned only because its stream needs to reconnect, while active-stream checks still prevent new work from using a streamless worker.
When a worker becomes available again, the dispatcher publishes a notification to the tenant’s scheduler partition. The publish runs with a short detached timeout so it can outlive the heartbeat request. The scheduler can then reconsider work without waiting for another unrelated scheduling event. A dispatcher change uses the same topic, while the scheduler cache timeout remains the fallback if that notice is lost. Delivery and status signals also feed the systems described in OLAP and observability services.
References: internal/…/server.go• L430-498 internal/…/worker_notify.go• L14-74
Tenant event streams
Tenant stream transport
Tenant events use pub/sub topics rather than the dispatcher’s identity queue. A shared tenant reader creates one underlying subscription for a tenant and fans each message out to the active consumers. The buffered reader groups messages for a short interval and delivers them in controlled batches.
The durable streams service is the tenant-facing topic boundary. It accepts ordered messages, checks the tenant entitlement and topic address, and persists valid entries with producer sequence numbers. Subscribers can start at a topic cursor or resume from a retained cursor. The dispatcher uses this durable topic flow to receive tenant events without creating one broker subscription for every client.
The dispatcher keeps two related contracts in step. Event converters map published task and workflow messages to client events. Workflow-run matchers use finished and candidate-finished messages to find only the runs requested by each client. The publish allowlist and these dispatcher maps must describe the same message set.
The service also supports in-process subscribers for engine work. Network subscribers are metered for inline payload bytes that are delivered successfully. In-process reads are not billed because they are internal coordination traffic. Payload references are counted when their payload is fetched rather than when the reference is sent.
This shared transport supports workflow event subscribers without creating one broker subscription for every client. It also gives the dispatcher a single place to clean up the tenant subscription when the last consumer leaves.
References: internal/…/shared_tenant_reader.go• L21-89 internal/…/shared_tenant_reader.go• L92-175 internal/…/dispatcher.go• L355-358 internal/…/tenant_stream_events.go• L42-47 internal/…/tenant_stream_events.go• L224-237 internal/…/server.go• L29-176 internal/…/server.go• L231-355
Event conversion
The dispatcher maps tenant message types to the workflow event contract. Task creation becomes a step start. Task completion, failure, cancellation, and stream chunks become step events. A workflow-run-finished message becomes a workflow terminal event only when its status is completed, failed, or cancelled.
The mapping is also the allowlist for the workflow event streams. A non-terminal status in a terminal message is treated as an upstream error instead of being changed into a successful finish. This prevents a bad control-plane event from closing a client stream too early. Tests protect the terminal-status mapping and the related stream behavior.
References: internal/…/tenant_stream_events.go• L19-136 internal/…/tenant_stream_events.go• L166-204 internal/…/tenant_stream_events.go• L224-252 internal/…/tenant_stream_events_test.go• L23-90
Stream ordering
Stream chunks can arrive out of order because they travel through separate message paths. The dispatcher buffers indexed chunks per task run and releases them in index order. It holds the workflow hangup until buffered chunks drain or the wait limit expires, so a terminal signal does not hide a late stream chunk.
Unindexed chunks pass through without ordering. Terminal step events pass through as state events while the buffer keeps enough history to release late chunks during a short grace period. When that period ends, remaining chunks are flushed in index order instead of being discarded. Buffer shutdown uses cancellation so active senders can exit without racing a closed channel.
References: internal/…/server.go• L718-766 internal/…/server.go• L918-1002 internal/…/server.go• L1004-1142 internal/…/tenant_stream_events_test.go• L145-306
Workflow run subscriptions
Workflow-run subscriptions track the run IDs requested by a client. Tenant messages nominate matching finished runs. The dispatcher reads the finalized run data, converts task output into a finished-run response, and records an acknowledgement so concurrent delivery paths do not send the same run twice.
If a finish message is missed, a periodic check revisits unacknowledged run IDs. This recovery path makes the stream depend on durable task state rather than on delivery of one pub/sub message.
References: internal/…/server.go• L1144-1357 internal/…/tenant_stream_events.go• L206-252
Durable task coordination
Durable task sessions
Durable tasks use a bidirectional session for requests and asynchronous responses. A worker can register durable task IDs, write memo or wait-for actions, trigger child runs, and report evictions. The dispatcher stores the session route by tenant and task ID so completions found later can return to the current worker session.
The worker execution context uses the session listener to send durable requests and receive completions. Its invocation count identifies the current replay, so a completion for an older run can be rejected rather than applied to a newer one.
The same coordination model supports in-process operator sessions. The transport changes from a network stream to channels, but durable responses use the same routing and handler rules. Operator sessions register their task route before the first request and remove it before their response channel closes, so asynchronous responses cannot target a closed channel.
Durable task request handling has two limits. Each stream has a byte budget for active request handlers, and all streams for one tenant share a larger tenant budget. When a limit is full, the dispatcher pauses reading that stream until a handler finishes. This applies backpressure before requests build up in memory while still allowing independent tenants to make progress.
Request failures return an error response for requests that wait for an acknowledgement. Handler panics are recovered per request, so one bad request does not stop the worker-status runner or the rest of the session.
References: internal/…/server_v1.go• L355-425 internal/…/server_v1.go• L658-862 internal/…/server_v1.go• L864-1054 internal/…/durable_task_budget.go• L34-38 api-contracts/…/dispatcher.proto• L10-16
Worker status coalescing
Worker status messages report durable-task entries that are still waiting for completion. The dispatcher coalesces these messages per durable-task session before it checks durable state. This prevents a slow response stream from creating one concurrent handler for every status heartbeat.
The session registers task IDs from a status message before it checks invocation counts. This lets a worker that reconnects during a wait receive pushed completions, while the count check can remove a stale route and send an eviction notice instead. The coalescer keeps the newest invocation for each durable task. It merges entries for the same invocation by branch and node, keeps the highest received satisfied order, runs one status handler at a time, and emits whole-task batches up to the request limit. The handler then checks for stale invocations, reads satisfied durable events, sends completions, and performs the required eviction work. New status messages merge into pending work while the current handler runs, so a slow response stream does not create a handler for every heartbeat. A cancelled session does not start its pending batches.
sequenceDiagram
participant W as Worker
participant D as Dispatcher
participant C as Status coalescer
participant S as Durable state
W->>D: WorkerStatus(waiting entries)
D->>C: merge status
C-->>D: one pending batch
D->>S: check invocation and satisfied entries
S-->>D: completions or stale state
D-->>W: EntryCompleted or ServerEvict
References: internal/…/worker_status_coalescer.go• L9-138 internal/…/server_v1.go• L791-861 internal/…/server_v1.go• L1682-1817 internal/…/worker_status_coalescer_test.go• L58-326 internal/…/worker_status_coalescer_test.go• L498-582
Change checklist
When these files or sections are changed, remember to consider these:
- Keep the dispatcher task-message handlers aligned with the producers that publish assignment, cancellation, durable callback, and batch-start messages.
- Preserve current-attempt checks when changing assignment or batch retry paths so delayed messages cannot requeue or deliver a task after reassignment.
- Keep tenant-stream message IDs aligned across the publish allowlist, event converters, and workflow-run matchers.
- Preserve the distinction between worker process liveness and an active worker listen session when changing heartbeat or reconnect behavior.
- Keep scheduler-partition worker notices best-effort; dispatcher and worker cache expiry must still recover when a notice is lost.
- Preserve invocation-count checks when changing durable worker status handling or response routing.
- Keep worker durable listeners, invocation counts, and eviction hooks aligned with dispatcher durable-task responses.
- Keep per-stream and per-tenant durable request budgets aligned with the maximum message size and the capacity expected for each tenant.
- Preserve stream cancellation before graceful server shutdown, and keep channel-backed operator sessions safe to close while responses are in flight.
- Preserve context replacement through worker middleware so task handlers retain the values and deadlines used by dispatcher calls.
- Keep
AssignedActionfields aligned with worker and operator consumers when task identity, retry, batch, or durable metadata changes. - Keep shutdown able to cancel long-lived worker and durable-task streams before server shutdown waits for them.
- Keep durable stream entitlement, topic validation, cursor retention, and producer sequence rules aligned between stream publishers and subscribers.
- Keep stream usage accounting aligned with the boundary between stored payload bytes, delivered inline bytes, fetched payload references, and internal subscribers.
- Preserve the send admission boundary: only sends that fail before transport admission may be retried automatically.
- Keep worker-status coalescing aligned with the status request cap and with invocation-count and satisfied-order recovery rules.
- Keep durable session teardown ordered so invocation routes are removed before channel-backed response channels close.
- Keep per-request durable error responses available for requests that wait for acknowledgements, including recovered handler panics.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| Dispatcher identity is not created or its heartbeat stops | Control-plane work can target a missing or stale dispatcher | Startup registers the identity and updates its heartbeat on a schedule |
| A worker session cannot accept an assigned task | The task may remain unprocessed or lose its queue visibility | The dispatcher requeues failed delivery through task processing |
| A delayed assignment names a worker or retry that no longer owns the task | A previous attempt can run after the task was reassigned | The dispatcher filters assignments against current worker and retry state |
| A late batch-start message names a worker that is no longer connected | A task from the old batch can be retried after reassignment | Batch recovery checks the current worker and batch before requeueing |
| A worker send is cancelled after the transport starts | Retrying the task can start it twice because delivery is uncertain | The send retains ownership until the transport returns and treats the in-flight result as assigned |
| A worker stream stalls while several actions wait to send | Sibling actions can build up behind the stalled transport | Per-session flow control admits one send path and rejects waiting sends after its timeout |
| Durable task request handlers use all stream or tenant budget | The dispatcher can accumulate too many active handlers or hold too much response state | Weighted byte budgets pause stream reads until active handlers release their request cost |
| A terminal workflow message carries a non-terminal status | A client stream could close while a workflow is still running | The event converter rejects the message as an upstream error |
| A stream chunk arrives after a terminal event | Ordered output can be lost or appear in the wrong order | The stream buffer holds indexed chunks and delays hangup release |
| An old durable invocation reports waiting entries | A stale worker can receive completions for a newer attempt | Worker status compares the worker count with the server count and sends eviction |
| Worker status handling blocks on a slow response stream | Status heartbeats can create unbounded concurrent handlers | The coalescer merges pending entries and runs one handler per session |
| A handler panic stops the durable session's status runner | Later worker status updates are not processed | Each request recovers panics and returns an error response when the request needs an acknowledgement |
| A long-lived durable stream remains active during shutdown | Graceful server stop can wait for a receive call that never returns | Stream cancellation interrupts the session before shutdown waits for handlers |
| Worker middleware drops a replaced context | Task code can lose deadlines or values needed for durable requests | Middleware passes the updated Hatchet context to the next handler |
| A publisher skips a producer sequence or sends an invalid stream entry | The stream rejects the publish and later entries can remain stored ahead of the gap | The stream service validates entries and detects sequence gaps after ordered persistence |
| A subscriber uses an expired or mismatched cursor | It can read from the wrong topic or fail to resume from retained history | Cursor decoding checks the topic address and retained range |
| A network send fails after stream processing or an internal subscriber is metered as external traffic | Usage totals can overcount delivered bytes or bill internal coordination | Metering runs after a successful network send and excludes in-process subscriptions |
| An operator session closes its response channel before removing its route | An asynchronous durable response can send to a closed channel | Session teardown cancels sends, removes routes, then closes the response channel |
Key files
| File | Why to read it |
|---|---|
| internal/…/dispatcher.go | Dispatcher construction, startup, queue intake, assignment delivery, current-attempt checks, retries, and shutdown |
| internal/…/server.go | Worker registration, listen sessions, heartbeats, event subscriptions, and stream ordering |
| internal/…/worker_notify.go | Scheduler-partition notices for worker availability and dispatcher changes |
| internal/…/server_v1.go | Durable-task sessions, asynchronous response routing, worker-status handling, ordered responses, and session shutdown |
| internal/…/durable_task_budget.go | Per-stream and per-tenant limits that apply backpressure to durable task request handling |
| internal/…/dispatcher_v1.go | Construction of the V1 dispatcher service and its durable-task coordination state |
| internal/…/tenant_stream_events.go | Tenant message conversion and workflow-run matching rules |
| internal/…/worker_status_coalescer.go | Coalescing rules for durable worker status updates |
| internal/…/subscribed_worker_v1.go | The boundary that sends assigned actions to streams or operator handlers |
| internal/…/subscribed_worker_stream_test.go | Guarantees for send admission, in-flight cancellation, flow control, and closed-stream behavior |
| internal/…/shared_tenant_reader.go | Shared and buffered tenant-topic subscription behavior |
| internal/…/server.go | Durable topic publishing, cursor-based subscription, in-process subscription, and stream usage boundaries |
| internal/…/streams.go | Durable streams service construction, session cancellation, and cleanup contracts |
| internal/…/usage_test.go | Guarantees for stored-message and delivered-payload usage accounting |
| pkg/…/context.go | Worker-side context, durable listener, invocation, and eviction contracts |
| pkg/…/middleware_test.go | Context propagation contract for the worker middleware chain |
| api-contracts/…/dispatcher.proto | Worker registration, assignment, heartbeat, and workflow event contracts |
| api-contracts/…/dispatcher.proto | Durable-task request, response, and worker-status contracts |
| internal/…/server_v1_durable_task_test.go | Guarantees for durable stream shutdown, operator-session cleanup, panic recovery, request failures, and request-budget backpressure |
| internal/…/worker_status_coalescer_test.go | Guarantees for status merge, single-flight handling, whole-task batch limits, satisfied-order recovery, and cancellation |