API and access layer
The API and access layer is the service boundary for Hatchet. It lets users and clients manage tenants, workflows, runs, workers, webhooks, streams, serverless endpoints, and operational data through HTTP and gRPC. The CLI gives operators another path to the same services.
Service boundary
Resource operations
The boundary presents platform resources as user-facing operations. Tenant operations establish the workspace and its members. Workflow and run operations then let clients inspect definitions, start work, view progress, cancel or replay work, pause workflows, and read execution data. Worker, webhook, schedule, stream, serverless, concurrency, and observability operations connect application code to workflow execution and daily operations.
Tenant creation is an account setup operation. When sign-up is enabled, the service validates the request, applies configured defaults such as retention and entitlements, and makes the creating user the owner. Tenant invites extend this setup flow to new members. They carry a role and payload visibility choice. They expire after a fixed period and follow instance policy, duplicate checks, pending-invite limits, and owner-only rules for granting ownership.
The versioned run surface gives clients one view of workflow runs and task runs. Clients can filter by time, status, workflow, worker, parent, event, idempotency, and metadata. Responses can include child tasks, attempts, event history, names, external IDs, and payloads when the caller has access. The public status model keeps evicted work visible as running work with an eviction marker, so clients can distinguish execution state from data placement.
Operational resources explain how work moves through the platform. Event and durable-task event-log views expose the signals that caused work to wait or continue. Concurrency views expose strategies, keys, queue counts, and running counts. Worker views expose worker health and supported operator details. Task statistics expose queued and running work by task name. These views help operators understand pressure without changing execution state.
Webhooks provide an external event entry point. A tenant defines the source, event mapping, optional scope mapping, static data, and one supported credential type. The service validates basic authentication, API keys, or signed requests before it converts JSON or supported form data into a tenant event. Source-specific challenges and signatures stay inside this boundary. Validation failures return safe client errors and remain available for operations. Static payload fields take precedence over incoming fields when both use the same key.
Scheduled workflow operations let clients change or remove schedules created through the API. Schedules created by code definitions remain controlled by the workflow definition and cannot be changed through these operations. Bulk deletion accepts either explicit schedule IDs or a filter. It reports per-item failures when a selected schedule is not eligible or disappears during the operation.
The API also exposes tenant-scoped event filters, retention-aware reads, entitlement state, metrics, health, and metadata. These views tell clients which optional capabilities are available and whether the instance is ready to accept normal traffic.
References: api/…/create.go• L18-115 api/…/create_invite.go• L22-128 api/…/list.go• L25-37 api/…/list.go• L343-377 api/…/get-status.go• L11-19 api/…/tasks.go• L23-31 api/…/list.go• L20-138 api/…/event_log.go• L17-44 api/…/list.go• L22-33 api/…/create.go• L20-74 api/…/receive.go• L36-116 api/…/delete_scheduled.go• L14-33 api/…/update_scheduled.go• L17-60 api/…/bulk_delete_scheduled.go• L19-172 api/…/tenant.go• L92-154
Request path
Each request passes through a common boundary before a resource operation runs. The boundary identifies the route from the API contract, loads the tenant and related resource context, authenticates the caller, checks access, applies limits, and then invokes the operation.
The main path is:
flowchart LR
Client[HTTP or gRPC client] --> Contract[Versioned service contract]
Contract --> Bind[Request binding]
Bind --> Context[Route and tenant context]
Context --> Identity[Authentication]
Identity --> Policy[Authorization and tenant scope]
Policy --> Limits[Route and resource limits]
Limits --> Operation[Resource operation]
Operation --> Platform[Workflow and runtime services]
Route metadata controls which security methods and resources apply to an operation. The HTTP layer also provides request binding, rate limits, recovery, telemetry, and safe error responses. The gRPC boundary uses the same tenant token model for worker-facing and client-facing calls, then carries the resolved tenant in request context. Public health, metadata, and webhook entry points remain available when the contract marks them as public.
The generated API model is part of this boundary. Shared values such as tenant roles, run statuses, webhook types, schedule methods, and serverless kinds must match the values used by the service and its data layer. A consistency check compares these shared values with the OpenAPI schema. This keeps clients from receiving a contract that accepts values the service cannot process.
The boundary uses two kinds of request throttling. General route limits use an operation and client address as the key. Task-stat requests use the resolved tenant as the key and run after authentication and authorization, so one tenant cannot consume another tenant's allowance and rejected callers do not spend the bucket. A throttling error carries retry information and becomes an HTTP 429 with Retry-After. A resource-exhausted error without retry information remains a quota or service error.
References: api/…/middleware.go• L40-77 api/…/middleware.go• L224-242 api/…/ratelimit.go• L30-94 api/…/task_stats.go• L14-56 api/…/run.go• L831-919 api/…/enums_spec_test.go• L20-91 api/…/openapi.gen.go• L28-31 api/…/openapi.gen.go• L881-932
Internal proxy requests
Internal proxy requests let one server-side API operation call a tenant-scoped gRPC service without exposing a long-lived credential to the caller. The proxy creates a short-lived tenant token, carries request source information when present, and removes the temporary access record after the call.
This keeps internal calls on the same tenant authentication path as external gRPC clients. Cleanup of the temporary token and client prevents a proxy failure from leaving access state behind.
References: api/…/proxy.go• L13-23 api/…/proxy.go• L25-67 api/…/throttle.go• L11-29
Client surfaces
The service boundary supports applications, workers, the web console, generated SDK clients, and administrative clients. HTTP and gRPC expose the resource contract. The CLI uses the HTTP API for resource commands and a shared client for its connection to the instance, so operator actions use the same tenant and resource rules as other clients.
The public API contract has versioned families. The current versioned run, event, stream, webhook, serverless, and operational views are designed for clients that need stable resource behavior. The legacy Go admin client still supports workflow registration, scheduling, triggering, and run inspection, while new integrations should use the current Go SDK.
See Public API contracts for contract families and versioning. See Authorization and tenancy for the identity and permission model. See Operational command interfaces for the CLI and admin surface.
References: api/…/openapi.gen.go• L341-359 api/…/openapi.gen.go• L1165-1236 pkg/…/admin.go• L1-3 pkg/…/admin.go• L454-506 pkg/…/admin.go• L508-628 cmd/…/client.go• L20-62
Access control
Identity and credentials
Authentication establishes who or what is making a request before the service reads tenant-scoped state. Browser users use a session cookie. Programmatic clients use a bearer token. Trusted server-side flows can use an exchange token that represents a user and remains subject to that user's permissions.
Browser sign-in can use local credentials or configured OAuth providers. OAuth callbacks validate one-use session state and verified provider identity before creating or updating the local session. Tenant integrations use the same session context. Tenant API tokens are signed credentials with a tenant subject and token identity. The service checks both their claims and stored state, so expiration and revocation take effect. A token can be read-only, and its value is returned only once.
See Authorization and tenancy for the full identity, token, and permission model.
References: api/…/middleware.go• L65-142 api/…/oauth_callback.go• L17-99 api/…/openapi.gen.go• L368-379 api/…/openapi.gen.go• L423-439 pkg/…/token.go• L84-105 pkg/…/token.go• L120-188
Tenant scope
Tenant scope is the main boundary between customers and their resources. A tenant token must name the tenant selected by the request. A session-authenticated user must be a member of that tenant. The service carries the resolved tenant and membership through the request so downstream operations use one access decision.
Roles define the level of control. Viewers can inspect tenant resources but cannot change tenant state. Members can perform workflow and run changes. Admins and owners also manage members, invites, and API tokens. Owner rules protect membership administration: only an owner can grant or remove ownership, non-owners cannot change an owner, and users cannot change their own role or remove themselves through the member-delete operation.
Invites are part of the tenant boundary. They are tied to an email and tenant, remain pending until accepted or rejected, and create membership with the invited role and payload visibility setting. The create and update paths apply the same owner rule when an invite grants ownership.
References: api/…/middleware.go• L105-142 api/…/middleware.go• L176-242 api/…/rbac_test.go• L13-25 api/…/rbac_test.go• L27-84 api/…/rbac_test.go• L97-190 api/…/create_invite.go• L42-68 api/…/update_invite.go• L14-40 api/…/update_member.go• L14-52 api/…/delete_member.go• L13-37 api/…/user.go• L29-55
Payload and data visibility
Resource access and payload access are separate decisions. A caller can read a run, task, event, durable-task log, stream, or serverless event while lacking permission to see its input, output, message, or response excerpt. List and resource responses keep safe records and metadata while omitting protected fields. Direct payload reads return a permission error.
Owners and admins retain payload visibility. Other members use the membership payload flag. API tokens have no tenant-member record in the request context and therefore follow the token access path rather than a member payload flag. The handler and response transformation must apply the same decision so a new response path cannot expose protected data.
The same rule applies to durable-task user messages, webhook response event data, stream payload downloads, and serverless event excerpts. Tenant retention adds a separate time boundary for historical event, log, task, and run reads. It signals old data for usage and monitoring. It does not replace an access decision.
References: api/…/payloads.go• L10-24 api/…/payloads_test.go• L14-81 api/…/event_log.go• L46-80 api/…/list.go• L122-138 api/…/payload.go• L79-119 api/…/list.go• L343-377 api/…/serverless.go• L95-124 api/…/webhooks.go• L59-103
Unauthenticated and public routes
Not every route needs an authenticated identity. Route metadata can mark an operation as public or optionally secured. Public routes still receive the session handling needed for browser login and redirect behavior, while optional routes can continue without credentials.
This distinction lets login, health, metadata, webhook, and protected resource operations share one boundary without treating every request as a tenant request.
References: api/…/middleware.go• L51-61 api/…/openapi.gen.go• L28-31 api/…/receive.go• L36-67
Command-line access
CLI profiles
The CLI stores a named profile for each Hatchet environment. A profile binds an API token to a tenant, API and gRPC addresses, and the TLS choice needed to connect. Commands select an explicit profile, the default profile, or an interactive choice. This gives scripts and local operators a stable connection context.
When a profile is created or updated from a token, the CLI checks the connection and reads tenant details before saving it. Credentials use the system keyring when available. If the keyring is not available, the CLI warns that the token remains in the profile file. Profile export supports SDKs and shell scripts while guarding against printing credentials to an interactive terminal.
References: cmd/…/profile.go• L79-136 cmd/…/profile.go• L216-333 cmd/…/profile.go• L335-467 cmd/…/profile.go• L579-646 cmd/…/profile.go• L649-740 cmd/…/client.go• L20-62
Resource commands
The command set turns common operational actions into repeatable client calls. Workflow and worker commands inspect resources. Run commands list and inspect runs, filter results, and perform cancel or replay actions. Logs and events give operators a command-line view of run progress.
Interactive commands open a terminal view by default. JSON output writes API-shaped data for scripts. Destructive bulk actions ask for confirmation unless the caller selects a non-interactive mode.
See Operational command interfaces for the full command and admin surface.
References: cmd/…/workflows.go• L21-69 cmd/…/runs.go• L28-127 cmd/…/runs.go• L177-287 cmd/…/worker.go• L81-118
Initial access bootstrap
The admin seed path prepares a usable first tenant without changing normal request-time authorization. It can create a verified administrator, create the configured default tenant, assign the administrator as owner, and create the fixed internal token required by authentication-disabled mode. Existing records are reused, so startup seeding also supports an already initialized instance.
References: cmd/…/seed.go• L18-111 cmd/…/seed.go• L116-149
API service startup
The hatchet-api command is the process entry point for the service boundary. It loads configuration, applies process limits, requires a FIPS-capable build, and starts the API until an interrupt stops it. Optional metrics and stream usage aggregation follow the API lifecycle so operational data is flushed during shutdown.
The server assembles the resource handlers behind the OpenAPI contract. It starts request logging, recovery, route and webhook limits, telemetry, route population, authentication, authorization, and tenant task-stat limits as one request chain. Readiness and shutdown therefore affect both client traffic and operational accounting.
References: cmd/…/main.go• L20-63 api/…/run.go• L100-130 api/…/run.go• L188-220 api/…/run.go• L831-919 api/…/task_stats.go• L16-55
Worker development access
The CLI also connects local worker development to a selected Hatchet instance. The worker command uses the selected profile, runs preparation steps, and starts the worker with optional file reload. This is a developer workflow rather than a separate service boundary. The worker uses the platform's normal client and access path.
See Operational command interfaces for the command surface. See Workflow orchestration for how workers participate in execution.
References: cmd/…/worker.go• L47-78 cmd/…/worker.go• L202-276
Boundary relationships
Workflow coordination
The API does not execute workflow steps itself. It accepts control requests such as triggers, task cancellation, task replay, run cancellation, schedule changes, and pause changes. It passes those requests into workflow and runtime services, then exposes the durable result to clients.
Scheduled controls have a clear ownership boundary. The API can change or delete a schedule created through the API. A schedule created by a code definition remains owned by that definition. Bulk operations preserve this rule while returning item-level errors for ineligible schedules.
The versioned read path joins run state with task attempts, task events, workflow shape, and available definition data. It applies status and metadata filters before returning results. If a workflow or version was deleted, historical run or task data can still be returned when available. Status mapping keeps the public contract stable when internal data includes states such as evicted work.
See Workflow orchestration for definitions, scheduling, dispatch, and worker execution. See Data and runtime platform for the storage and messaging services that support the boundary.
References: api/…/delete_scheduled.go• L14-33 api/…/update_scheduled.go• L17-60 api/…/bulk_delete_scheduled.go• L40-172 api/…/list.go• L153-166 api/…/list.go• L168-271 api/…/list.go• L343-377 api/…/get-status.go• L11-19 api/…/workflow_runs.go• L133-177 api/…/workflow.go• L12-177 api/…/status_test.go• L9-18
Engine service assembly
The engine runtime hosts the internal services that make the boundary useful. It starts the services needed for health reporting, scheduling, task processing, worker dispatch, event ingestion, streams, and optional operators. These services share the configured storage and messaging resources, so an API command can move from control request to execution and back to observable state.
Startup and shutdown are part of the service contract. Readiness begins only after active services start. Long-lived sessions and worker-facing services stop before the dispatcher drains, which prevents new work from entering while existing work closes.
References: cmd/…/run.go• L87-171 cmd/…/run.go• L187-246 cmd/…/run.go• L428-665 cmd/…/run.go• L667-687 cmd/…/run.go• L690-749 cmd/…/run.go• L962-1217
Console and integration use
The web console uses browser sessions to manage resources through the protected service boundary. SDKs and external integrations use bearer or event-specific credentials to start work and read results. The access layer is therefore the shared contract between human interfaces, application clients, and the execution platform.
References: api/…/middleware.go• L79-142 api/…/create.go• L18-115 api/…/receive.go• L319-356 api/…/cel.go• L5-17
Change checklist
When these files or sections are changed, remember to consider these:
- Keep route security metadata, generated API models, and authorization behavior aligned. The access decision depends on the operation named by the API contract.
- Keep tenant identity consistent across HTTP route context, bearer-token claims, exchange-token claims, gRPC metadata, and the tenant loaded for the request.
- Keep role rules aligned across the RBAC policy and handler-level owner safeguards. Member updates, invite updates, and member deletion must not create a second path around owner rules.
- Keep payload visibility aligned across the authorization decision, handler reads, response transformers, and OpenAPI payload declarations. This includes event, task, durable-task, webhook, stream, and serverless responses.
- Keep public status values aligned across stored statuses, status filters, status responses, evicted-work markers, generated enums, and the enum consistency check.
- Keep webhook source parsing, credential validation, encrypted secret storage, challenge handling, static-data precedence, expression evaluation, and event ingestion aligned.
- Keep webhook source rules aligned with their authentication requirements. Slack and Stripe signed requests need their source-specific timestamp and signature checks, while form data rules differ by source.
- Keep schedule ownership aligned across single and bulk update or delete operations. API-created schedules are mutable through this surface; code-defined schedules are not.
- Keep task-stat limit identity and middleware order aligned. The tenant must be resolved and authorized before its bucket is charged.
- Keep stream payload entitlement, size and tenant limits, opaque references, read visibility, and completed-download usage accounting aligned.
- Keep serverless entitlement, endpoint validation, secret rotation, public response redaction, health state, and operator refresh behavior aligned.
- Keep tenant creation defaults aligned with the returned tenant context, owner membership, limits, retention, entitlements, and engine version.
- Keep invite expiry, pending status, duplicate checks, pending limits, role rules, payload visibility, membership creation, and email delivery aligned.
- Keep CLI profile fields aligned with API and gRPC client configuration, token scope, TLS mode, keyring fallback, shell export behavior, and tenant selection.
- Keep the generated OpenAPI contract aligned with shared enum values and the public response shapes used by transformers. Include new task-stat, schedule, workflow, tenant, user, and CEL shapes in this review.
- Preserve tenant and resource filters when changing event, run, worker, serverless, concurrency, or operational list responses. A filter that is accepted but not applied can silently cross an operator's intended view.
- Preserve the distinction between retryable throttling with retry information and non-retryable tenant quota errors across gRPC, proxy, and HTTP error handling.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| A tenant token names another tenant, is revoked, or is expired | The request is rejected before the resource operation runs | Validate signed claims and stored token state, then compare the token tenant with the resolved tenant |
| A session user is not a member of the requested tenant | The user cannot read or change that tenant's resources | Resolve membership before role checks |
| A viewer or restricted member attempts a write or payload read | The operation is denied, or the record is returned without protected data | Apply role and payload decisions before the handler reads or transforms protected fields |
| A non-owner grants ownership, changes an owner, changes their own role, or removes themselves | Tenant membership state is not changed | Enforce owner-only rules in invite and member handlers |
| An OAuth state value is missing, reused, or mismatched | The browser flow redirects with an error and does not link the account | Bind one-use state to the session and clear it after validation |
| A webhook source uses the wrong credential type or has an invalid signature, timestamp, body, or expression | No tenant event is created | Apply source-specific authentication and parsing before event ingestion |
| A webhook static field collides with an incoming field | The configured static value is lost if merge order is wrong | Apply static payload after request parsing |
| A stream payload is not entitled, empty, oversized, over quota, or read without payload access | Upload or download is rejected | Check entitlement, size, tenant limits, and payload permission before storage or read |
| A stream download ends before the full body is written | Delivered usage is overstated if it is counted as complete | Add usage only after the response body finishes successfully |
| A serverless endpoint is not entitled or has invalid endpoint data | Registration or update is rejected | Check entitlement and validate URLs, labels, and signing secret before storage |
| A public response includes a secret or internal placement value | Sensitive endpoint data crosses the service boundary | Transform stored endpoint data into a public shape that omits protected fields |
| Stored or database status values are not mapped to public status values | Clients cannot interpret run state or evicted work correctly | Keep status mapping total and verify every shared enum against the API specification |
| A task-stat request is charged before authorization or is keyed by client address | One tenant can consume another tenant's budget, or rejected callers can exhaust a budget | Resolve and authorize the tenant before applying the tenant bucket |
| A route limit refills once per second instead of across its configured window | Clients send more requests than the configured window allows | Convert the window limit to a refill rate and return Retry-After on denial |
| A schedule created by a code definition reaches an API update or delete path | Definition-owned schedule state changes outside its owner | Reject the operation and report the item as ineligible in bulk mode |
| A bulk schedule filter is combined with explicit IDs or has malformed metadata | The request is ambiguous or selects the wrong schedules | Require one selection mode and validate each metadata value as key:value |
| A workflow or task control request is accepted but runtime state is not updated | The API reports success while execution follows old behavior | Treat the API request and runtime handoff as one control flow |
| A CLI has no usable profile or selects the wrong TLS or tenant context | The command fails or reaches the wrong instance | Validate the profile connection before saving and preserve explicit transport settings |
| A profile lacks secure keyring storage or export is sent to a terminal | A token remains in a file or is exposed on screen | Warn on keyring fallback and block interactive credential output |
| The repository or task queue is not ready | Readiness fails and the instance should not receive normal traffic | Check required dependencies before accepting normal traffic |
Key files
| File | Why to read it |
|---|---|
| api/…/run.go | Shows how the API handlers, route population, authentication, authorization, throttling, telemetry, and lifecycle form one boundary. |
| api/…/middleware.go | Shows how authentication strategy becomes tenant membership and role-based access. |
| api/…/payloads.go | Defines the separate decision for viewing task and event payloads. |
| api/…/rbac_test.go | Shows the intended boundaries for owners, admins, members, viewers, and API tokens. |
| api/…/create.go | Shows tenant setup, default context, and owner assignment. |
| api/…/create_invite.go | Shows invite policy, expiry, role checks, payload visibility, and the email handoff. |
| api/…/update_member.go | Shows member role and payload-visibility changes with owner safeguards. |
| api/…/list.go | Shows the versioned run and task read model, filters, pagination, and payload choice. |
| api/…/list.go | Shows tenant-scoped event filters and payload-aware event responses. |
| api/…/create.go | Shows webhook source configuration, credential choices, encrypted secrets, and static payload setup. |
| api/…/receive.go | Shows source-specific request validation and conversion into tenant events. |
| api/…/update_scheduled.go | Shows the ownership and state rules for changing API-created schedules. |
| api/…/bulk_delete_scheduled.go | Shows filtered bulk deletion and per-item result reporting. |
| api/…/ratelimit.go | Shows route-aware request throttling and retry responses. |
| api/…/task_stats.go | Shows tenant-scoped throttling for the task-stat operational view. |
| api/…/tenant.go | Shows public tenant policy and task-stat response shaping. |
| api/…/user.go | Shows public user and tenant-member shapes, including owner and admin payload visibility. |
| api/…/workflow.go | Shows public workflow, version, trigger, and concurrency shapes. |
| api/…/cel.go | Shows the stable success and error shape for CEL evaluation responses. |
| api/…/openapi.gen.go | Shows generated public models, security schemes, enums, and response shapes. |
| api/…/enums_spec_test.go | Protects agreement between shared service values and the API specification. |
| cmd/…/profile.go | Shows how operators create, select, secure, and export environment profiles. |
| cmd/…/runs.go | Shows the main operational run actions exposed through the CLI. |
| cmd/…/seed.go | Shows how initial users, tenants, owner membership, and auth-disabled access are prepared. |
| cmd/…/main.go | Shows API process startup and lifecycle responsibilities. |
| cmd/…/run.go | Shows how runtime services assemble behind the boundary and stop safely. |
| pkg/…/admin.go | Shows the legacy Go client boundary for workflow control, run inspection, and bulk-trigger outcomes. |