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 / data-and-runtime-platform

Data and runtime platform

The data and runtime platform is the shared foundation for Hatchet API and engine services. It keeps workflow state and runtime history durable, moves work and wake-up signals between services, applies one set of tenant rules, and gives operators and product systems a view of service behavior.

Platform role

The platform gives request-facing API paths and background engine paths one view of tenants, workflows, runs, workers, queues, events, streams, and service capacity. It also applies the same limits, feature entitlements, security settings, and observability rules to both kinds of service.

FoundationShared purposeDownstream use
PostgreSQL data layerStores durable identity, workflow, runtime, and control stateAPI reads and writes state; engines schedule and record work
Repository boundaryPresents domain data operations as shared servicesAPI and engine code use the same data contracts
Durable message queueDelivers work that must survive consumer restartsDispatch and processing recover after service failure
Best-effort pub/subSends fast wake-up signalsSchedulers and live consumers react without treating each signal as durable
Durable streamsRetain ordered tenant messages for replayClients resume from a cursor within the retention window
Tenant-aware database poolShares database capacity across tenants and service workOne busy tenant cannot consume all database capacity
Runtime configurationSelects connections, limits, providers, and service behaviorOne service model fits different deployments
Tenant entitlementsGates optional features at the local service boundaryAPI and engine paths agree on which tenant features are active
Analytics read modelTurns runtime changes into queryable history and usage dataAPIs, dashboards, and product systems measure workflow behavior
Telemetry and logsReports health, traces, metrics, and service eventsOperators diagnose behavior and capacity pressure

Data layer

The data layer centers on PostgreSQL and exposes a repository as the shared access point for durable state. The main pool serves core application work, a direct pool supports schema and partition work, an optional read replica supports suitable reads, and an optional OLAP pool can place run history and usage data in a separate database. pkg/…/loader.go assembles this layer, and pkg/…/repository.go groups its domain services behind one boundary.

The repository boundary covers the full workflow lifecycle. API paths register versioned workflows, tenants, schedules, webhooks, users, and entitlements. Engine paths use the same state to create tasks, route work, track retries and leases, store events and payloads, and record outputs. Workflow registration creates the versioned contract that later guides task creation and scheduling. See Database schema and migrations for the storage model and its evolution.

The shared layer also protects hot paths from uneven load. It applies tenant and shared checkout limits, caches stable lookups, validates data at the repository boundary, and keeps payload storage separate from the records that refer to it. Tenant creation initializes control data and feature gates so later API and engine requests start from the same tenant state. pkg/…/shared.go, pkg/…/tenant.go, and pkg/…/repository.go define this shared boundary.

Durable workflow state

Durable workflow state records the ordered history of a task's durable operations. A durable operation can memoize a result, wait for a sleep or user event, or start a child workflow. This history lets replay reuse valid results and child identities instead of creating duplicate work.

The ingestion path groups requests into short database batches. It keeps one request per task in a batch so each request sees the state committed by the prior one. If a batch-wide error occurs, the platform retries requests separately so one bad request does not fail unrelated tasks. The stored wait data also gives status views a readable description of what a task is waiting for.

Replay keeps workflow triggers and DAG step triggers as distinct identities. It can reuse a child on the active replay branch, or re-run an existing child in place when the orchestration contract requires stable task identity. Operator-managed DAG children can satisfy their parent durable entries directly when their result is finalized.

References: pkg/…/durable_events.go• L181-220 pkg/…/durable_events.go• L275-386 pkg/…/durable_events_dag_replay_test.go• L1-120 pkg/…/durable_events_operator_step_child_test.go• L1-120

Event matching

Event matching connects stored events to tasks that wait for them. A match can use an event key, an optional scope, a time lookback, and an expression. The same rules apply to live events and historical lookback.

The match result can create a new task, replay an existing task, or satisfy a durable history entry. This makes event matching the bridge between external signals and the task state used by the engine. A scoped event satisfies waiters with the same scope and unscoped waiters; an unscoped event does not satisfy a waiter that asks for a specific scope.

References: pkg/…/match.go• L186-207 pkg/…/match.go• L321-388 pkg/…/match.go• L398-479 pkg/…/trigger.go• L336-389 pkg/…/match_scope_test.go• L1-120

Task and run records

Task records connect workflow definitions to runtime work. They carry tenant and workflow identity, retry and queue state, parent and child links, worker routing data, and references to input or output payloads. Completion, failure, and cancellation release active runtime state and produce events that can advance dependent work or durable history.

The read side presents task and workflow history as a tenant-scoped view. It resolves task external IDs to individual tasks and workflow-run IDs to their task set. The OLAP side turns task creation and lifecycle events into a queryable run history with readable statuses, event timelines, timing data, and optional payloads. Status aggregation separates work running on a worker from work evicted from a worker while preserving a simple public status model.

Retention and partition work remove old task and history data without changing the service contract. Payload references allow large or shared data to move out of hot task and event rows while keeping the same run-level view. When OLAP uses a separate database, the history stays there while shared payloads remain available through the core payload store.

References: pkg/…/task.go• L296-398 pkg/…/task.go• L985-1220 pkg/…/task.go• L1790-1986 pkg/…/task.go• L2324-2421 pkg/…/olap.go• L272-345 pkg/…/olap.go• L370-423 pkg/…/olap.go• L501-637 pkg/…/tasks-overwrite.go• L1-120

Scheduling and resource coordination

Scheduling converts queued task state into worker assignments while honoring concurrency, rate limits, worker slots, batching, and tenant capacity. The scheduler reads the shared repository and commits queue changes with the task runtime state so a task is not assigned without a matching runtime record.

The same control state supports API-created schedules and cron triggers, incoming webhooks, and worker or operator registration. Controller, worker, and scheduler partitions assign tenant work across engine processes. Heartbeats mark active partitions, and locked rebalancing moves tenants away from inactive processes. Serverless operation uses tenant-partition lease ownership so multiple processes can share work and recover it after an owner stops heartbeating.

References: pkg/…/scheduler.go• L13-66 pkg/…/scheduler_queue.go• L254-388 pkg/…/rate_limit.go• L54-75 pkg/…/worker.go• L115-220 pkg/…/workflow_schedules.go• L110-166 pkg/…/serverless.go• L17-28 pkg/…/serverless.go• L103-143 pkg/…/tenant.go• L697-838 pkg/…/tenants.sql• L237-492

Tenant limits and entitlements

Tenant limits control accepted resources and shared capacity. Entitlements control optional features such as durable streams, Prometheus metrics, audit logs, serverless operation, sandbox operation, and direct operator-step completion. A tenant created without an entitlement set starts with optional features disabled.

Tenant creation commits the tenant row with its alert settings and entitlement state as one unit. The API can update the entitlement set while engine paths read the same values at their local service boundary. Cached reads improve hot-path checks, but changes must still invalidate or expire the relevant cache so a feature change reaches all service roles.

References: pkg/…/tenant.go• L264-356 pkg/…/tenant.go• L359-417 pkg/…/tenants.sql• L1-42 pkg/…/tenants.sql• L504-524 pkg/…/shared.go• L73-89 pkg/…/server.go• L181-190

Messaging layer

The messaging layer separates durable work delivery from best-effort signals. A durable queue carries work that needs acknowledgement and recovery. Best-effort pub/sub carries wake-ups where a missed signal can be recovered from durable state.

The distinction shapes service behavior. Queue messages have delivery and retry or dead-letter rules. Pub/sub messages have no recovery log and must not be the only record of workflow state. A durable write can therefore be followed by a pub/sub notification without making that notification the source of truth.

This diagram shows how one service event reaches durable state, work consumers, and live listeners.

flowchart LR
    A[API or engine event] --> B[Repository and durable state]
    A --> C[Durable message queue]
    C --> D[Dispatcher or scheduler]
    A --> E[Best-effort pub/sub]
    E --> F[Live stream or partition wake-up]
    D --> B
    F --> D

The platform supports PostgreSQL and RabbitMQ for durable queues. It supports PostgreSQL, RabbitMQ, and NATS for pub/sub. Pub/sub uses separate resources from durable work. PostgreSQL listeners use the direct database path, and provider settings can inherit the durable queue provider so an existing deployment keeps a working wake-up path without new settings.

See Repositories, messaging, and configuration for provider contracts and service-specific messaging behavior.

References: pkg/…/loader.go• L504-577 pkg/…/loader.go• L1089-1219 pkg/…/server.go• L617-686 pkg/…/health.go• L24-33

Runtime configuration

Runtime configuration turns files and environment values into the resources and policies used by each service. The loader validates database and server settings, creates database and repository layers, selects message providers, and assembles security, scheduling, analytics, telemetry, and service settings.

Database setup has separate roles. The main pool may use a pooler for application traffic. A direct pool remains available for schema and listener work, and an optional read replica serves analytical reads. An optional OLAP database receives its own pool; its connection and fair-pool settings inherit the main database settings when no OLAP override is set. Shared payloads remain in the core database so OLAP reads can keep the same payload contract.

Configuration also controls service capacity and data life. Retention, task-operation limits, queue quality of service, scheduler settings, worker and operator caps, payload movement, durable-event buffering, OLAP status batching, sampling, and feature switches determine what the platform accepts and how long it keeps state. Embedded callers can provide one synchronized log writer at runtime, while explicit logger settings remain higher priority.

The loader also creates an audit outbox and the scheduling pool. These resources connect committed database changes to later delivery or scheduling work without making API requests own the full background operation.

References: pkg/…/config.go• L14-107 pkg/…/config.go• L119-164 pkg/…/loader.go• L146-539 pkg/…/loader.go• L949-1003 pkg/…/loader.go• L1089-1219 pkg/…/database_config_test.go• L11-50 pkg/…/server.go• L38-96 pkg/…/server.go• L115-190 pkg/…/server.go• L398-420

Observability layer

The observability layer makes behavior visible across database, queue, workflow, worker, tenant, and service boundaries. OpenTelemetry exports traces and metrics when configured. Prometheus-facing metrics cover queue timing, database health, OLAP work, worker activity, scheduler capacity, and tenant database-pool pressure. Structured logs and optional error reporting add context when work fails.

The OLAP read model stores workflow runs, task events, event triggers, logs, spans, and usage data for API and dashboard reads. The OLAP controller consumes runtime messages, converts them into this history, updates readable run status, and retries work when a concurrent lock prevents a write. Sampling can reduce high-volume operational history while keeping a stable decision for one workflow run.

Trace context can cross API, database, and message boundaries. Workflow triggering preserves a valid incoming trace parent or creates a stable W3C trace parent for a new workflow run. Durable event batches use their own span and link back to waiting requests, so delayed ingestion remains visible without assigning one batch to one request.

Product analytics is separate from operational telemetry. It records resource and action events such as workflow, task-run, worker, tenant, and API activity. Optional aggregation groups high-volume events before delivery. When the provider is disabled, a no-op path keeps service behavior unchanged. See Telemetry, analytics, and usage for downstream signal use.

References: internal/…/controller.go• L337-528 internal/…/controller.go• L531-642 internal/…/controller.go• L985-1267 pkg/…/olap.go• L272-345 pkg/…/olap.go• L3997-4212 pkg/…/trigger.go• L631-677 pkg/…/durable_events.go• L305-367 pkg/…/loader.go• L626-664

Shared lifecycle

API and engine services follow the same high-level startup shape. They load configuration, create PostgreSQL resources, construct repositories, select messaging providers, and attach telemetry and analytics before exposing service-specific interfaces.

This diagram shows the shared lifecycle.

flowchart TD
    A[Load files and environment] --> B[Validate runtime settings]
    B --> C[Create PostgreSQL pools]
    C --> D[Build repository services]
    D --> E[Create durable queue and pub/sub]
    E --> F[Start API and engine services]
    F --> G[Export traces metrics and analytics]
    G --> H[Close services and flush signals]

The engine adds background coordination around this foundation. It maintains task and OLAP partitions, consumes runtime events, updates status and metrics, archives audit records, and starts aggregate work. Lock conflicts are retried or requeued because they indicate temporary contention rather than invalid workflow state.

Cleanup is part of the platform contract. Database pools, queue clients, pub/sub clients, schedulers, analytics emitters, telemetry exporters, durable-event buffers, and audit delivery each have a close or cancellation path. Normal shutdown can therefore flush buffered signals and release shared resources.

References: pkg/…/loader.go• L400-539 pkg/…/loader.go• L883-1003 pkg/…/repository.go• L108-187 pkg/…/olap.go• L385-423 internal/…/controller.go• L337-528

Change checklist

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

  • A change to durable event identity or replay must keep task identity, branch identity, child identity, trigger state, and satisfaction order aligned across repository contracts, SQL, and generated query types.
  • A change to durable event batching must preserve one in-flight request per task, split retry behavior, trace links, and a bounded number of concurrent flushes.
  • A change to event scope or expression matching must preserve the difference between scoped and unscoped events in both live matching and historical lookback.
  • A change to task completion, failure, cancellation, eviction, or restoration must keep core runtime state aligned with OLAP events, readable statuses, payload references, and durable-parent results.
  • A change to task or workflow external-ID resolution must keep task IDs distinct from workflow-run IDs and preserve tenant isolation.
  • A change to workflow registration or scheduling must keep version checksums, event-key cache invalidation, cron cleanup, resource counts, and schedule callbacks consistent.
  • A change to tenant creation or entitlements must keep tenant defaults, alert settings, entitlement rows, cache behavior, resource metering, SQL columns, and generated query types together.
  • A change to worker, operator, or engine partition ownership must keep heartbeat recovery, advisory rebalance locking, action links, slot capacity, operator exemptions, and tenant limits aligned.
  • A change to PostgreSQL pool routing must preserve direct access for schema and listener work, shared connection setup, separate OLAP fallback settings, shared payload access, and separate limits for tenant, shared, health, and listener paths.
  • A change to fair-pool checkout behavior must preserve tenant and shared caps, slot release for every result type, caller cancellation, bounded waits for the underlying pool, and pool metrics.
  • A change to transaction helpers must preserve rollback after context cancellation and reset any connection-level timeout before the connection returns to a pool.
  • A change to pub/sub configuration must preserve provider inheritance and independent resources. A deployment that only sets durable-queue settings must still get the intended wake-up path.
  • A change to OLAP messages or status batching must preserve message identity, sampling behavior, lock retry and requeue behavior, and the mapping from engine events to readable status.
  • A change to trace, metric, log, or analytics resource names must preserve service, tenant, pool, queue, workflow, and run dimensions so API and engine signals remain distinguishable.

Important failure modes

TriggerConsequenceGuard
Pub/sub is treated as durable deliveryA missed wake-up is not replayedPersist state first and recover from the repository, durable queue, or durable stream
Two durable requests for one task share a flushBoth requests can plan from the same task historyKeep one request per task in a flush and defer the rest
A replay child is treated as newThe engine can create duplicate work or wait foreverPreserve branch and trigger identity and reuse the required child identity
A scoped event is matched as unscopedA waiter can wake from an event for another scopeApply scope rules to live and historical matches
A task event reaches OLAP without its task or run contextRun history or readable status is incompleteResolve task metadata and payload references before writing the OLAP event
A lock-conflicted OLAP batch is droppedRuntime history and status lag behind core task stateBack off and requeue the remaining messages within the configured retry bound
A tenant has no entitlement rowAn optional feature can be enabled by an absent valueTreat a missing row as all features disabled
PostgreSQL pub/sub uses a transaction-pooled connectionListener subscriptions do not stay on the needed connectionBuild pub/sub from the direct database path with its own resources
A new pool skips shared connection setupTime, timeout, type, or trace behavior can differ by pathBuild standard pools through the shared PostgreSQL setup
A separate OLAP pool does not use the core payload storeHistory rows can exist while referenced input or output data cannot be readAttach the core payload store when OLAP uses another database
A tenant or shared bucket reaches its fair-pool capWork waits or fails even while other pool capacity may existRoute calls through the correct tenant or shared handle and set a bounded acquire wait
A caller abandons a transaction or result without cleanupA fair-pool slot or database connection remains heldRelease results on close and use rollback or finalizer cleanup for abandoned resources
A canceled context skips transaction rollbackThe pool can lose a connection or leave work in an open transactionRun rollback with a cleanup context even when the request context is canceled
A worker heartbeat or lease expires during active ownershipWork can be reassigned or served by another processUse heartbeat, lease, and ownership checks before reassignment or claim
Two processes rebalance one partition kind at onceTenants can move twice from stale selectionsHold the partition-kind advisory transaction lock during rebalance
A rate-limit pause is not applied to queued workPaused tasks can keep consuming slots or run too soonHold affected queue items and release them only after the pause ends
A partition change meets a live table lockRetention work fails without data corruptionUse the DDL path and retry lock or deadlock conflicts on the next run

Key files

FileWhy to read it
pkg/…/loader.goShows how database pools, repositories, queues, pub/sub, analytics, scheduling, and server resources become one runtime layer.
pkg/…/config.goDefines core, direct, read-replica, fair-pool, and optional OLAP database settings.
pkg/…/server.goDefines the shared runtime controls for messaging, retention, limits, entitlements, buffering, OLAP, and observability.
pkg/…/repository.goDefines the repository boundary used by API and engine services.
pkg/…/shared.goShows the common database handles, caches, payload store, tenant limits, and expression support.
pkg/…/pool.goDefines tenant and shared connection caps, bounded checkout, and resource release behavior.
pkg/…/tx.goDefines transaction setup, timeout handling, rollback, and connection release contracts.
pkg/…/tenant.goDefines tenant state, partition ownership, heartbeats, rebalance locking, and usage data.
pkg/…/tenants.sqlShows tenant creation, partition heartbeats, partition rebalance, and tenant usage queries.
pkg/…/workflow.goShows workflow version registration, orchestration state, concurrency, and lifecycle callbacks.
pkg/…/trigger.goShows how events and workflow names become tasks, runs, matches, payload references, and trace metadata.
pkg/…/task.goDefines task lifecycle, retry, replay, eviction, restoration, output events, and partition maintenance.
pkg/…/durable_events.goDefines durable workflow history, batching, replay, child triggering, waits, and readable wait state.
pkg/…/match.goDefines event matching, expression checks, task creation, replay, and durable-entry satisfaction.
pkg/…/scheduler.goShows the shared scheduling boundary for queues, leases, assignment, concurrency, rate limits, and optimistic writes.
pkg/…/worker.goDefines worker identity, capacity, actions, heartbeats, listener ownership, and operator links.
pkg/…/serverless.goDefines endpoint routing state, process heartbeats, tenant partitions, and lease recovery.
pkg/…/olap.goDefines queryable run history, separate-database payload access, status updates, spans, metrics, and retention.
internal/…/controller.goShows how runtime messages become OLAP history, status updates, metrics, and requeued work.
pkg/…/tasks.sqlDefines the task queue, runtime transitions, retries, eviction, restoration, and task views.
pkg/…/durable_event_log.sqlDefines durable history, branch progress, satisfaction order, and trigger claims.