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 / repositories-messaging-and-configuration

Repositories, messaging, and configuration

Repositories, caches, queues, configuration, encryption, cleanup, and utility services connect durable Hatchet state to running API and engine processes. Together they make work recoverable, move it between services, protect stored values, control shared resources, and close live resources in a safe order.

Repository boundary

The repository boundary gives services one tenant-aware way to read and change durable state. It combines domain repositories with shared database access, payload access, validation, cache policy, limits, and callbacks.

Shared durable state

The repository in pkg/…/repository.go exposes task, workflow, worker, queue, event, stream, payload, tenant, user, serverless, and analytical access through one service-owned boundary. Shared state gives these areas the same database view and the same tenant rules. A single cleanup function closes the shared caches and background workers after the domain repositories stop.

The main database path serves normal work. A direct path serves schema maintenance and database listeners. This split keeps critical maintenance and long-lived listeners independent from transaction pooling and normal request load.

References: pkg/…/repository.go• L25-66 pkg/…/repository.go• L108-187 pkg/…/shared.go• L42-89

Tenant isolation and resource fairness

Tenant identity is part of repository access. It scopes reads, writes, lookups, caches, limits, events, and workflow-run identity so one tenant cannot resolve or change another tenant's work.

The database fairness layer limits how much shared capacity one tenant or engine workload can hold. Tenant work and shared engine work use separate limits. The limit follows a query, row set, transaction, or batch until that resource closes. A checkout also has a bounded wait when the underlying pool has no free connection. Readiness checks use an ungated path so a busy tenant does not make a healthy process report that it is unavailable.

Tenant state also carries entitlements, retention choices, membership, and resource counts. Tenant creation writes its core row, alert settings, and entitlements together. Partition heartbeats recreate missing partitions, while advisory locks serialize rebalances so concurrent controllers do not move the same tenants twice. Resource changes update their counts in the same durable transaction, while callbacks let limit and alert views refresh after commit.

References: pkg/…/pool.go• L17-43 pkg/…/pool.go• L124-207 pkg/…/pool.go• L240-283 pkg/…/tenant.go• L95-191 pkg/…/tenant.go• L264-356 pkg/…/tenant.go• L697-838 pkg/…/tenant.go• L939-957 pkg/…/tenants.sql• L1-29 pkg/…/tenants.sql• L237-318 pkg/…/tenants.sql• L331-492 pkg/…/trigger_fairpool_test.go• L20-100

Task and workflow state

Task repositories connect durable task rows to the current runtime, retry, queue, input, output, and event state. They support assignment, completion, failure, cancellation, timeout, retry, reassignment, eviction, replay, and cleanup after a process stops.

Task identity includes the task's durable identity and retry count. A late result therefore cannot change a newer retry. Dispatch reads include only tasks with a runtime for the current retry. External ID lookups stay tenant-scoped and distinguish one task from the tasks inside a workflow run.

Workflow registration turns a definition into a durable version. Trigger creation then uses that version to create workflow runs, tasks, match conditions, payload references, and idempotency claims in one coordinated write. A version change refreshes event-key lookups so a new event can reach the new version.

References: pkg/…/task.go• L296-398 pkg/…/task.go• L985-1083 pkg/…/task.go• L1085-1120 pkg/…/workflow.go• L257-305 pkg/…/workflow.go• L704-869 pkg/…/trigger.go• L192-217 pkg/…/trigger.go• L843-1020

Durable workflow history

Durable event state records child runs, waits, and memo values for workflows that must resume after a process or callback loss. Each entry has a stable position, branch, invocation, and idempotency identity. Replay reuses history when the operation still means the same thing and reports non-determinism when a later operation conflicts with that history.

Ingestion gathers requests into bounded batches. Requests for the same task wait for a later batch so they see the previous commit. A batch-wide error can split into single-task retries, which prevents one invalid request from failing unrelated work. Operator step children satisfy their parent entries directly during finalization, so they do not also enter the normal match path.

Child workflow identity is derived from the parent and child position. This lets normal retries find existing children and lets replay decide whether to reuse a child on the active branch or create a new one on a new branch.

This diagram shows how a durable operation becomes history and later resumes child work.

flowchart LR
    Call[Durable workflow call] --> Buffer[Bounded event buffer]
    Buffer --> Log[(Durable event history)]
    Log -->|memo| Memo[Stored value]
    Log -->|wait| Match[Event or time match]
    Log -->|run| Child[Child workflow]
    Match --> Log
    Child --> Log
    Log --> Replay[Replay after loss]

References: pkg/…/durable_events.go• L181-223 pkg/…/durable_events.go• L254-386 pkg/…/durable_events.go• L1090-1125 pkg/…/durable_events_dag_replay_test.go• L89-190 pkg/…/durable_events_operator_step_child_test.go• L76-163 pkg/…/ids.go• L28-65

Scheduling and worker state

Scheduling turns queued task state into worker assignments. It considers queue order, worker actions and labels, available slots, concurrency, batching, rate limits, and lease ownership. Assignment results are applied as one durable transition so queue removal, runtime creation, slot changes, and held work stay aligned.

Workers publish heartbeats, action sets, labels, and slot capacity. The scheduler treats these records as the current execution capacity. Action changes are applied as a complete delta and can be limited across all workers of one operator. A listener session can change a worker only while it still owns that worker's session identity.

Rate limits add a second form of back pressure. Usage and dynamic definitions are settled under a tenant lock. A paused key moves affected queued work to a held state and releases its concurrency capacity until the pause ends.

References: pkg/…/scheduler.go• L13-66 pkg/…/scheduler_queue.go• L91-159 pkg/…/scheduler_queue.go• L254-279 pkg/…/scheduler_queue.go• L388-555 pkg/…/worker.go• L115-220 pkg/…/rate_limit.go• L54-75 pkg/…/rate_limit.go• L87-179 pkg/…/rate_limit.go• L309-478

Event matches and identity

Match state connects incoming user or internal events to waiting work. Conditions can require a sleep, a user event, or a group of alternatives. A scope keeps separate event consumers isolated, including during historical lookback.

Idempotency claims and child-spawn keys prevent repeated requests from creating duplicate runs. These identities are tenant-scoped and remain part of the durable contract during retry and replay.

References: pkg/…/match.go• L39-193 pkg/…/match.go• L398-500 pkg/…/match_scope_test.go• L166-313 pkg/…/trigger.go• L829-1020 pkg/…/ids.go• L107-320 pkg/…/idempotency-keys.sql• L1-80

Analytical read model

The analytical repository is a read model for task runs, workflow runs, graphs, events, logs, traces, status, and usage. It serves API and dashboard reads without becoming the source of truth for task assignment or durable workflow history. It can use the main database or a separate OLAP database when operational reads and analytical load need separate capacity.

Runtime events update task and graph status in bounded work. A newer retry takes precedence over an older retry. Reconciliation can rebuild the view after delayed delivery or a restart. List and count operations use the same tenant, status, time, workflow, worker, event, parent, idempotency, and metadata meaning.

Payload inclusion is bounded by the rows returned, not only by a caller's requested page size. Aggregate views combine compacted minute data with newer source rows until the retained aggregate range is complete. This avoids false zeros while compaction or aggregate setup is still catching up. When the analytical store is separate, shared payloads still resolve through the core payload store.

References: pkg/…/olap.go• L272-423 pkg/…/olap.go• L430-476 pkg/…/olap.go• L501-637 pkg/…/olap.go• L907-998 pkg/…/olap.go• L1322-1363 pkg/…/config.go• L84-107 pkg/…/loader.go• L425-508 pkg/…/olap_status_update_test.go• L205-260 pkg/…/olap_list_workflow_runs_test.go• L127-187 pkg/…/olap_aggregates_test.go• L26-79

Payloads and logs

The payload store keeps task inputs, outputs, event data, and durable-event data behind typed references. The same reference can resolve an inline value or an external value, so large-payload movement does not change task, trigger, replay, or analytical contracts.

Log lines attach readable messages and metadata to task identity. They can be filtered by tenant, workflow, step, retry, level, time, or task. Payload and log retention follow the durable records that own them.

References: pkg/…/payloadstore.go• L28-60 pkg/…/payloadstore.go• L552-634 pkg/…/payloadstore.go• L789-869 pkg/…/log_line.go• L16-103 pkg/…/log_line.go• L115-229

Caches and change signals

Caches provide process-local speed for values that can be rebuilt from durable state. Short lifetimes suit workflow versions, event routing, rate-limit pauses, and tenant changes. Stable identity mappings can live longer because their meaning does not change while the record exists.

Writes invalidate local values and use callbacks or live signals for other processes. These signals reduce wake-up time but do not replace durable reads. A cache miss or an expired entry always returns to the database as the authority.

References: pkg/…/shared.go• L91-181 pkg/…/tenant.go• L192-211 pkg/…/tenant.go• L403-415 pkg/…/workflow.go• L302-321 pkg/…/trigger.go• L205-207

Database diagnostics

The database debugger explains pool pressure when debug logging is enabled. It records which callers acquire connections and reports active callers when the pool reaches its limit. This turns a process-wide connection shortage into a set of useful call sites without changing query behavior.

References: pkg/…/debugger.go• L17-85 pkg/…/debugger.go• L88-178 pkg/…/loader.go• L251-279

Messaging

Messaging separates work that must survive a restart from signals that only help live processes react sooner. The queue, pub/sub, and stream choices therefore have different durability and recovery contracts.

Durable queues

A durable message queue carries work that must survive a consumer or connection failure. It provides durable storage, exclusive delivery, expiry, acknowledgement, quality of service, and a failure path for messages that cannot be processed.

PostgreSQL and RabbitMQ provide the durable queue choices. Their common contract lets service code send and consume work without depending on one transport. A message that fails before acknowledgement can be delivered again. A message above the shared size limit fails because one message cannot be split safely.

References: internal/…/msgqueue.go• L12-38 internal/…/msgqueue.go• L159-175 pkg/…/server.go• L617-697 pkg/…/loader.go• L504-577

Live pub/sub

Best-effort pub/sub carries live signals such as cache refresh or wake-up notices. It is at-most-once and is not a recovery store. A consumer that is disconnected can miss a signal, so restart-safe work must use a durable queue or durable state.

Pub/sub can use RabbitMQ, PostgreSQL, or NATS. PostgreSQL listeners use a dedicated pool from the direct database URL. RabbitMQ pub/sub uses separate connections from the durable queue. An unset kind or RabbitMQ URL inherits the durable queue setting for compatibility, while NATS remains an explicit pub/sub-only choice.

References: internal/…/pubsub.go• L15-27 internal/…/pubsub.go• L114-229 pkg/…/loader.go• L1089-1219 pkg/…/server.go• L629-681

Durable streams

Durable streams provide tenant-scoped ordered message history for consumers that must resume after a disconnect. A stream is addressed by a namespace and topic. Producer identity and sequence protect the history from duplicate or out-of-order writes.

Consumers resume with a cursor while its range remains in retention. Pages are bounded by both row count and byte size. Large values can use an uploaded reference. Published and delivered bytes feed separate tenant usage totals, so delayed reporting does not remove stream data.

This diagram shows the durable stream path and its separate usage path.

flowchart LR
    Producer[Producer] --> Topic[(Ordered topic history)]
    Topic --> Page[Cursor and byte-bounded page]
    Page --> Consumer[Resuming consumer]
    Topic --> Retention[Retention cleanup]
    Producer --> Usage[Usage totals]

References: pkg/…/streams.go• L23-46 pkg/…/streams.go• L104-180 pkg/…/streams.go• L301-477 pkg/…/streams.go• L646-691 pkg/…/olap_stream_bytes.go• L13-49

Service configuration

Configuration turns files and environment values into the runtime contract for API, engine, scheduling, authentication, analytics, queues, pub/sub, encryption, and maintenance. The loader applies defaults, merges input, validates related settings, and creates the resources that services share.

Runtime assembly

The loader creates the data layer first. It then builds repositories, authentication, encryption, queues, pub/sub, scheduling, analytics, security checks, and internal clients around that layer. Optional services use no-op or disabled forms when their feature is off, while required dependencies fail startup when their contract is incomplete.

The resulting server configuration is the service graph used by running controllers. It carries the repository, queue, pub/sub, payload, auth, encryption, scheduler, and retention contracts instead of making each controller load settings independently.

References: pkg/…/loader.go• L146-421 pkg/…/loader.go• L544-574 pkg/…/loader.go• L832-897 pkg/…/loader.go• L949-1003 pkg/…/loader.go• L1048-1086

Data connections

The data layer can use a main pool, an optional read replica, a direct pool for schema work, and an optional separate OLAP pool. Tenant and shared-work fairness applies to the main and analytical application pools. The direct path bypasses transaction pooling where listeners or schema operations need a stable connection.

OLAP settings inherit the main pool settings when their values are unset. This allows a deployment to select a separate analytical database without duplicating every connection and fairness setting. PostgreSQL pub/sub still creates its own small pool from the direct database URL because listener state does not survive transaction pooling.

Pool settings also define connection timeouts, retention checks, cache duration, task operation limits, payload compatibility, status update limits, durable-event batching, and tenant limit behavior. These values change how running services share durable rows, not only how fast a query runs.

References: pkg/…/config.go• L22-107 pkg/…/config.go• L119-218 pkg/…/loader.go• L161-347 pkg/…/loader.go• L425-508 pkg/…/loader.go• L1089-1146 pkg/…/database_config_test.go• L11-50

Queue and workflow controls

Runtime settings bound durable-event batch size and flush concurrency, task operation batches, optimistic scheduling, queue work, status projection batches, payload consolidation, and retention. These settings balance write latency against database load while keeping bursts and cleanup passes bounded.

Rolling changes must keep readers compatible with new payload references before writers emit them. Generated SQL types and query methods are part of the repository contract because their row shape, nullable values, arrays, and enums cross service boundaries.

References: pkg/…/server.go• L126-178 pkg/…/server.go• L240-262 pkg/…/server.go• L398-420 pkg/…/sqlc.yaml• L1-80 pkg/…/tasks-overwrite.go• L1-120 pkg/…/models.go• L1-80

Serverless settings

The in-engine serverless operator has a separate runtime contract for endpoint partitions, process leases, routing refresh, health checks, delivery limits, and relay limits. Static and local token modes are mutually exclusive. The partition count applies when a tenant is first created and does not silently reshape existing tenant rows.

References: pkg/…/server.go• L707-794 pkg/…/loader.go• L1028-1032 pkg/…/serverlessoperator.go• L18-100

Encryption

Encryption protects values stored in the database and supplies key handles for token signing and verification. Ciphertext is bound to a required data identity, so encrypted bytes cannot be moved to another record and remain valid.

Protected values and tokens

Startup selects one data-key source: a local master keyset or Google Cloud KMS. Services that mint or verify tokens also require the matching public and private JWT key material. Processes that only protect data can load a data-only service without JWT keys.

Webhook credentials and serverless endpoint secrets reach repositories as encrypted values. The repository stores the protected form and leaves decryption to the service that owns the credential use.

References: pkg/…/service.go• L5-27 pkg/…/loader.go• L1226-1361 pkg/…/webhooks.go• L50-72 pkg/…/serverless_endpoint.go• L23-49

Serverless coordination

The serverless repository coordinates API-owned endpoint state with operator-owned process heartbeats and lease units. It lets several processes serve entitled tenants without allowing an expired or old process to keep ownership.

Routing and ownership

Endpoint state includes routing, health, registered actions, partition, and deletion version. Operators refresh a routing cache by full load, incremental version, and anti-entropy repair. Deletion first remains visible as a tombstone, then is purged after all caches have had time to observe it.

A lease unit is a tenant and endpoint-partition pair. A live process claims units according to endpoint weight. Heartbeat expiry makes units available for takeover. Claim and release operations check the current process identity, so an old process cannot release a unit after a new process owns it.

This diagram shows durable endpoint state flowing to operator routing and lease ownership.

flowchart LR
    API[Endpoint changes] --> DB[(Durable endpoint state)]
    DB --> Refresh[Full, incremental, and repair refresh]
    Refresh --> Cache[Operator routing cache]
    Cache --> Serve[Endpoint delivery]
    Process[Process heartbeat] --> Lease[(Tenant-partition lease)]
    Lease --> Serve

References: pkg/…/serverless.go• L17-28 pkg/…/serverless.go• L43-143 pkg/…/serverless_endpoint.go• L23-180 pkg/…/serverless_endpoint.go• L258-394 pkg/…/serverless_lease.go• L15-74

Cleanup and resource lifecycle

Cleanup has two roles. Service shutdown closes pools, clients, caches, queues, pub/sub, schedulers, outboxes, and background loops. Database maintenance removes stale, expired, orphaned, and out-of-retention rows.

Maintenance uses bounded work and coordination locks. It releases abandoned task, queue, retry, match, runtime, worker, concurrency, stream, payload, and partition state. Partition work uses the direct database path and bounded lock waits so application queries do not wait forever for schema maintenance.

Transactions and temporary connections must also release their pool resources when work fails or the caller's context ends. The transaction helpers provide a rollback path that still runs after cancellation, and connection helpers reset temporary timeouts before they return a connection to the pool.

The cleanup helper runs registered functions in dependency order within a bounded shutdown window. New live resources must join the owning cleanup path.

References: pkg/…/repository.go• L172-187 pkg/…/task.go• L518-698 pkg/…/payloadstore.go• L999-1059 pkg/…/olap.go• L448-637 pkg/…/tx.go• L24-105 pkg/…/tx.go• L114-195 pkg/…/loader.go• L979-1003 pkg/…/cleanup.go• L30-96

Change checklist

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

  • Keep tenant identity on every repository lookup, cache key, queue transition, event match, payload reference, and analytical filter.
  • When changing tenant creation or partition assignment, preserve the atomic creation of tenant defaults, the internal-tenant rule, heartbeat recovery, stable scheduler partition identities, and serialized rebalances.
  • When changing task completion, failure, retry, replay, or dispatch, preserve the task-and-retry identity and the link between queue state, runtime state, terminal events, and payloads.
  • When changing durable-event batching or replay, preserve same-task ordering, invocation counts, branch identity, idempotency checks, child claims, direct operator completion, and non-determinism errors.
  • When changing event matches, preserve event scope in both live matching and historical lookback. Keep user-event and internal-event paths distinct.
  • When changing workflow registration or triggering, preserve idempotency claims, child-spawn identity, event-key cache invalidation, workflow-version selection, and payload ownership.
  • When changing scheduling, keep assignment, batching, rate-limit holding, concurrency slots, retry state, and queue removal in the same tenant-and-retry contract.
  • When changing worker action sets or listener sessions, keep the action hash, operator action budget, tenant ownership, and current session identity aligned with their SQL queries.
  • When changing analytical status or aggregate reads, keep retry precedence, reconciliation, list/count filters, returned-row payload caps, raw-data fallback, and delta compaction aligned.
  • When changing generated SQL, update the query source and generated contract together. Array order, nullable fields, enum values, and row shapes affect running services.
  • When changing database pools, preserve the separate OLAP inheritance rules, tenant and shared-work caps, checkout timeout behavior, direct DDL path, read-replica requirements, and UTC checks.
  • When changing queue or pub/sub configuration, preserve separate resources, inheritance rules, the direct connection requirement for PostgreSQL listeners, and the explicit NATS choice.
  • When changing payload compatibility or external storage, upgrade readers before writers and preserve inline fallback, shared references, external indexes, and retention ownership.
  • When changing tenant, webhook, schedule, or stream resources, preserve their allocated counts, post-commit callbacks, producer watermarks, cursors, and cleanup paths.
  • When changing encryption configuration, allow exactly one master-key source and keep stored ciphertext identities and JWT verification material compatible.
  • When adding a pool, client, cache worker, listener, outbox, or goroutine, register its shutdown with the owning lifecycle.

Important failure modes

TriggerConsequenceGuard
A durable-event batch plans two requests for one taskBoth requests use one log snapshot and can collideDefer duplicate same-task requests until the first flush commits
Replay changes an event kind or idempotency identityDurable workflow history becomes inconsistentReturn a non-determinism error
A queued operator child enters both direct completion and match processingThe parent receives duplicate completion signalsSatisfy the durable entry during finalization and skip the normal match path
A result uses an old retry countA late result changes a newer retryMatch task identity and current retry before applying it
A workflow or event lookup omits tenant scopeOne tenant can resolve another tenant's stateInclude tenant identity in the query and cache key
A tenant or shared engine bucket holds its fairpool capIts next operation fails or waits while other buckets can continueUse separate tenant and shared caps, release every checkout, and bound the wait
A caller holds all pool connections and asks for another oneThe process can wait forever and stop serving database workBound each checkout with AcquireTimeout and release held resources
A trigger preflight keeps its connection while starting the write transactionA tenant with a small cap hits a false connection-limit errorFinish and release preflight work before the tenant write transaction
A live pub/sub signal carries restart-safe workA disconnected consumer misses the workUse a durable queue or durable state
PostgreSQL pub/sub uses a transaction-pooled connectionListener state is not stable for the subscriberUse the direct database URL and a dedicated listener pool
A status event from an older retry overwrites a newer viewAPI status becomes staleApply retry precedence before status precedence
Payload consolidation starts before all readers support referencesOlder services return missing task inputUpgrade readers before enabling the writer mode
A partition operation waits without a lock boundSchema maintenance can block application work indefinitelyUse the direct pool, leases, and bounded lock waits
Local keys and Cloud KMS are both configuredEncryption startup is ambiguousSelect exactly one master-key source
A transaction returns without rollback after context cancellationIts connection remains unavailable to the poolRun rollback with a usable cleanup context
An old serverless process releases a unit after takeoverThe new owner loses routing workRelease only when the current process ID still owns the unit
An endpoint is purged before caches observe deletionA cache can route to a removed endpointKeep the deletion tombstone through the cache grace period
A resource outlives its repository or serviceBackground work or connections remain active after shutdownRegister the resource with the owning cleanup path

Key files

FileWhy to read it
pkg/…/repository.goDefines the repository boundary and shared cleanup contract.
pkg/…/shared.goShows shared database access, cache policy, payload access, and tenant limits.
pkg/…/task.goShows the durable task lifecycle, retry identity, replay, and cleanup.
pkg/…/durable_events.goShows durable waits, child runs, memo state, batching, replay, and operator completion.
pkg/…/trigger.goShows event and workflow triggering, idempotency, matches, and payload ownership.
pkg/…/workflow.goShows workflow version registration, concurrency validation, schedules, and cache invalidation.
pkg/…/scheduler.goDefines queue, lease, assignment, batch, rate-limit, and optimistic scheduling boundaries.
pkg/…/scheduler_queue.goShows how assignment results update queue, runtime, batching, and held work.
pkg/…/worker.goShows worker capacity, action sets, listener sessions, and stale-worker cleanup.
pkg/…/match.goShows event scopes, waits, condition groups, and match completion.
pkg/…/tenant.goShows tenant defaults, membership, queue metrics, partition heartbeats, and rebalancing.
pkg/…/tenants.sqlShows tenant creation, partition ownership, heartbeats, and rebalance rules.
pkg/…/olap.goShows analytical reads, status projection, payload bounds, aggregates, and retention.
pkg/…/payloadstore.goShows typed payload access, external cutover, fallback reads, and retention.
pkg/…/log_line.goShows task log storage and filtered log reads.
pkg/…/streams.goShows ordered stream writes, cursors, payload bounds, usage, and retention.
pkg/…/serverless.goDefines endpoint, process, lease, tenant, and event coordination.
pkg/…/serverless_endpoint.goShows routing refresh, health state, encrypted secrets, and deletion grace.
pkg/…/rate_limit.goShows rate-limit usage, pauses, and held queue work.
pkg/…/webhooks.goShows webhook authentication values, encryption boundaries, and resource accounting.
internal/…/msgqueue.goDefines durable queue behavior and the common queue interface.
internal/…/pubsub.goDefines best-effort live delivery.
pkg/…/config.goDefines main, direct, replica, OLAP, timeout, and fairness settings.
pkg/…/loader.goShows how configuration becomes pools, repositories, queues, pub/sub, encryption, and cleanup.
pkg/…/server.goDefines runtime, queue, pub/sub, batching, payload, retention, and serverless settings.
pkg/…/service.goDefines data encryption and JWT key protection.
pkg/…/pool.goDefines tenant and shared database checkout fairness.
pkg/…/tx.goDefines transaction rollback and temporary connection timeout cleanup.
pkg/…/cleanup.goDefines bounded ordered graceful shutdown.