Serverless endpoints and operator runtime
Serverless endpoints let a tenant run Hatchet tasks in an external HTTP or WebSocket runtime. The serverless operator discovers what each endpoint serves, presents that work to the engine as tenant workers, routes assigned tasks to a healthy endpoint, and reports the result back to the workflow engine. See Serverless execution platform for the wider platform model.
System boundary
The serverless path connects three actors: the tenant endpoint, the operator, and the Hatchet engine. The endpoint runs user code. The operator owns discovery and delivery. The engine remains the source of task state, retries, durable task state, and workflow progress.
Service flow
The service flow turns endpoint declarations into engine assignments and then into task results.
flowchart LR
A[Endpoint registration] --> B[Operator lease]
B --> C[Signed health check]
C --> D[Workflow and action catalog]
D --> E[Engine worker registration]
E --> F[Task assignment]
F --> G{Delivery mode}
G -->|HTTP| H[Signed trigger request]
G -->|WebSocket| I[Durable or stream relay]
H --> J[Task event]
I --> J
J --> K[Workflow state]
References: pkg/…/core.go• L1-15 pkg/…/registration.go• L426-479 pkg/…/protocol.go• L1-14
Endpoint resources
An endpoint resource belongs to one tenant and defines how the operator can find and call it. Its health status and registered action set are observed state, not input that the endpoint owner edits directly.
| Resource value | Purpose |
|---|---|
| Health check URL | Lets the operator discover the endpoint catalog and runtime details. |
| Trigger URL | Receives non-durable task calls and WebSocket upgrades. |
| Signing secret | Authenticates operator requests. It is stored encrypted and is not returned by the API. |
| Enabled flag | Controls whether the operator polls and delivers to the endpoint. |
| Status | Shows the last health result and the actions seen in the last accepted catalog. |
| Runtime and kind | Identifies the endpoint class and runtime for control-plane use. |
References: api-contracts/…/serverless_endpoint.yaml• L1-94 api-contracts/…/serverless_endpoint.yaml• L106-190 pkg/…/serverless_endpoint.go• L97-179
Endpoint lifecycle
The endpoint lifecycle starts when a tenant registers URLs and a signing secret. It ends when the endpoint is disabled or deleted, after the operator removes its actions from the tenant worker view and stops sending work to it.
Endpoint registration
The control plane creates or updates an endpoint inside the tenant boundary. Creation also creates the tenant's serverless lease unit and counts the endpoint in that unit, so later operator processes can claim the work as one schedulable resource.
Updates can change delivery URLs, timing, labels, enablement, endpoint kind, or the signing secret. Secret rotation changes what later requests must use without exposing the old or new plaintext secret in endpoint responses.
References: api-contracts/…/serverless_endpoint.yaml• L39-94 api-contracts/…/serverless_endpoint.yaml• L106-190 pkg/…/serverless_endpoint.go• L128-176 pkg/…/serverless_endpoint.go• L217-290
Health catalog
The endpoint health check is also a capability declaration. A successful response can declare workflow definitions, an exact action set or actions derived from those workflows, WebSocket task options, durable-task support, and runtime metadata.
The operator normalizes and validates that catalog before it reaches the engine. A listed action set is exact. An empty action list means all actions derived from the declared workflows. An endpoint that does not support durable tasks is not registered for its durable actions. The TypeScript serverless handler lists non-durable tasks with socket access as tasks: [{ action, streams: true }]; a task declared with hatchetClient: false is deliberately left out of that list and uses signed POST delivery.
References: api-contracts/…/serverless.proto• L22-75 pkg/…/healthcheck.go• L110-153 pkg/…/healthcheck.go• L168-272 sdks/…/healthcheck.ts• L24-51 sdks/…/declarations.ts• L33-42
Health state
The operator polls each enabled endpoint that belongs to a lease unit it owns. Three consecutive failed checks mark an endpoint unhealthy. One later success marks it healthy again and can update its action catalog.
Health changes affect routing and are written only when the observed state changes. The endpoint status therefore tells operators the last known result, while the action set tells the engine what the endpoint currently offers.
References: pkg/…/endpoint.go• L15-27 pkg/…/endpoint.go• L125-197 pkg/…/endpoint.go• L255-274 api-contracts/…/serverless_endpoint.yaml• L11-37
Tenant registration and routing
The operator represents each served tenant as one engine session with a worker action union. That union is the set of actions offered by the tenant's enabled endpoints, so the engine can assign a task without knowing which external endpoint will run it.
Tenant registration
When an operator gains a tenant unit, it opens a self-leased worker session with the current action union and separate default and durable capacity. Endpoint health checks add or remove workflow actions from that union. The operator then pushes only the change to the session.
The session is tenant-scoped and authenticated by the selected token source. A missing tenant token prevents polling and registration for that tenant. If a session ends because its host gives up, the operator closes the old registration and tries to open a new one while the tenant still has owned units.
References: pkg/…/registration.go• L140-200 pkg/…/registration.go• L203-247 pkg/…/registration.go• L617-702
Action routing
The routing view maps each action to the enabled endpoints that advertise it. A task normally goes to a randomly selected healthy endpoint. When no candidate is known healthy, an enabled endpoint can still receive work so a stale health view does not stop the tenant completely.
Two endpoints may advertise the same action. This shares task delivery in the same way that multiple workers share an action. A route miss means the worker view changed after assignment; the operator reports a retryable failure so the engine can assign the task again.
References: pkg/…/routing.go• L191-223 pkg/…/routing.go• L929-973 pkg/…/registration.go• L426-459
Tenant cache
The operator keeps a tenant routing cache that combines endpoint settings, health state, decrypted signing material, and the action union. Refreshes apply changed rows. Reconciliation also finds hard deletes or changes missed by an incremental refresh.
The cache publishes action-union revisions. Registrations use those revisions to catch up with small deltas and use a full difference only when they are too far behind. This keeps endpoint changes local while keeping every tenant worker aligned with the current union.
References: pkg/…/routing.go• L237-270 pkg/…/routing.go• L473-588 pkg/…/routing.go• L794-862
Lease and process coordination
The operator uses shared database leases so many operator processes can serve many tenants without sending the same task to competing processes. A lease unit is one tenant and one endpoint partition; its endpoint count gives the unit a weight for fair sharing.
Process membership
Each operator process keeps a process row alive with heartbeats. The row has a database-side time-to-live. Other processes treat an expired row as dead and can take its units. A periodic sweep removes old process rows and releases their units.
The operator can run the same core inside the engine or as a separate command. Both modes use the same lease and routing rules. The difference is how the core reaches the engine session: direct in the engine, or through the gRPC operator host out of process.
References: pkg/…/leaser.go• L1-5 pkg/…/leaser.go• L183-206 pkg/…/leaser.go• L261-328 pkg/…/core.go• L6-15
Unit ownership
Rebalancing claims unowned or dead-process units up to the process's fair share. An overloaded process sheds units with idle work first, then units with active deliveries when needed. Gaining a unit starts its tenant view and endpoint pollers. Losing a unit stops those pollers and drains its active deliveries.
Entitlement changes release units before the next claim pass. This prevents a process from reacquiring a tenant that no longer has access to serverless execution.
References: pkg/…/leaser.go• L331-497 pkg/…/leaser.go• L569-643 pkg/…/leaser.go• L646-671
Registration shutdown
A registration shuts down in a fixed order. It first pauses new assignments, waits for active deliveries up to the drain limit, and then closes the engine session. The process releases leases before it removes its process row.
This order lets the engine redirect new work before the old process stops, while unfinished work remains eligible for retry or reassignment instead of being silently lost.
References: pkg/…/registration.go• L790-843 pkg/…/core.go• L159-186
HTTP delivery
Non-durable tasks use a signed HTTP POST. The operator sends the registered action and workflow identity in a versioned trigger envelope, then converts the endpoint response into the engine's completed, failed, retryable, or cancelled task event.
Request authentication
Every signed POST carries the raw-body HMAC-SHA256 signature, endpoint ID, and Unix timestamp in headers. The same timestamp is in the body. An endpoint rejects a request whose timestamp is more than five minutes from its clock.
The signing secret authenticates the request but does not grant engine access. The endpoint receives task data only. For engine streams opened from a WebSocket, the operator uses its own engine credentials rather than passing a tenant token to the endpoint.
References: pkg/…/http.go• L18-68 pkg/…/signature.go• L11-35 pkg/…/healthcheck.go• L50-68
HTTP outcomes
The endpoint response controls task state through a small status contract.
| Endpoint result | Engine meaning |
|---|---|
2xx with valid JSON | Completed with that JSON output. Empty output becomes {}. |
204 | Completed with an empty output. |
Most 4xx responses | Permanent failure. |
408, 425, or 429 | Retryable failure. |
5xx responses | Retryable failure. |
| Non-2xx JSON error body | The error text replaces the default message. retry can replace the default retry choice. |
Transport timeouts are retryable. Unsafe destinations, invalid schemes or ports, oversized responses, invalid JSON, and redirects are permanent delivery errors.
References: pkg/…/delivery.go• L23-73 pkg/…/delivery.go• L87-152 pkg/…/delivery.go• L155-200
Durable stream relay
Durable tasks and tasks that request streaming use one operator-dialed WebSocket invocation. The socket carries the assigned action, durable requests and responses, task completion, and optional engine stream traffic.
Invocation protocol
The operator sends a first frame with the assigned action, invocation count, and inline wait budget. A durable endpoint can then send engine requests such as memo, wait, trigger, or eviction requests. The operator returns engine responses on the same socket.
The endpoint ends the invocation with one done frame. An output means completion. An error means failure and can request a retry. An evicted status has no terminal task event; the engine re-invokes the task when its awaited durable entry is ready. A later invocation starts again from the top while the engine replays the durable log.
References: api-contracts/…/serverless.proto• L102-142 pkg/…/relay.go• L97-142 pkg/…/relay.go• L553-601
Stream access
An endpoint can ask the operator to open an allowed engine stream by sending a stream_open frame. The operator relays messages in both directions and sends a stream_close frame when the stream ends.
The relay limits the number of open streams and the queued data for a slow endpoint. It also checks requests that name workflow runs or durable tasks against the task's tenant scope. The endpoint never receives the engine credentials used to open these streams.
The TypeScript SDK now exposes the generated engine stream contract used by this relay. It covers publishing single or batched messages, subscribing from a cursor, reading topic metadata, and resetting a topic. Stream entries can carry their data inline or through a payload reference, which lets the stream path handle larger data without changing the WebSocket frame contract.
Inside a task, clientFromContext(ctx) keeps the normal unary client and adds socket-backed streams.subscribe and runs.events iterators. These reads need an invocation WebSocket, so a task delivered over POST receives a clear serverless limitation error. A read can stop by breaking the iterator or aborting its signal. A non-normal close raises an error with the last cursor so the caller can resume; the task-side endpoint client does not fetch entries stored through an uploaded payload reference.
References: api-contracts/…/serverless.proto• L144-179 pkg/…/streams.go• L61-107 pkg/…/streams.go• L109-192 sdks/…/streams.ts• L13-94 sdks/…/streams.ts• L1206-1298 sdks/…/task-client.ts• L79-115 sdks/…/task-client.ts• L124-220 sdks/…/task-client.ts• L230-295
Socket protection
The WebSocket upgrade signs the endpoint ID, timestamp, nonce, task ID, and invocation. The endpoint can reject replayed upgrades by tracking the nonce. The relay uses frame, upgrade-header, queue, and stream limits, plus ping and pong checks, to bound memory and detect an endpoint that stops responding.
An unexpected socket close without a done frame is a retryable failure unless the engine has already cancelled, evicted, or ended the invocation. This preserves the difference between a task outcome and a transport failure.
References: pkg/…/http.go• L36-64 pkg/…/relay.go• L218-299 pkg/…/relay.go• L452-551 pkg/…/protocol.go• L17-47
Operator runtime
The operator runtime can run as a standalone process or inside each engine dispatcher. Both forms start the same serverless operator core. The runtime builds its database repository, encryption service, token exchange, safe outbound client, and engine host around that core.
Operator command
The hatchet-serverless-operator command is the out-of-process form. It reads and validates its database, encryption, token exchange, lease, health-check, WebSocket, and outbound HTTP settings before it opens connections.
Token exchange has two modes. Static exchange serves one tenant from HATCHET_CLIENT_TOKEN. Local exchange watches a token file and serves the tenants listed there. The configuration rejects a token source that does not match the selected mode, which avoids silently using the wrong tenant set.
References: cmd/…/main.go• L1-20 cmd/…/main.go• L29-104 pkg/…/serverlessoperator.go• L19-28 pkg/…/serverlessoperator.go• L161-208
Embedded runtime
When enabled in the engine, the core uses the dispatcher's in-process host and a worker name tied to the dispatcher. The engine supervises the core and restarts it with backoff after an unexpected stop. A normal engine shutdown releases leases, drains deliveries, closes registrations, and closes idle outbound connections.
The embedded core is not a separate readiness dependency for the engine. It initiates the connections it owns, so the engine does not route work to a replica only because the embedded process has started.
References: cmd/…/serverless.go• L30-48 cmd/…/serverless.go• L76-99 cmd/…/serverless.go• L109-165
Runtime health
The standalone operator exposes process health, readiness, and metrics on its health port. /healthz means the HTTP server is alive. /readyz becomes successful after the first lease rebalance, so readiness represents participation in serverless ownership rather than process start alone.
Endpoint health is separate from process readiness. An operator can be ready while individual endpoints are unhealthy, missing a token, or not yet polled.
References: pkg/…/health.go• L16-46 pkg/…/core.go• L109-147 pkg/…/endpoint.go• L376-387
SDK contract
The TypeScript serverless SDK surface is generated from the same serverless protobuf contract as the Go operator. It provides runtime-neutral task declarations, shared handler behavior, and adapters for Cloudflare Workers, Vercel, and Node. The adapters expose the same health check, trigger, signature, and task outcome rules while mapping each platform's HTTP and WebSocket APIs.
The generated TypeScript surface also includes the engine stream messages and client definitions used when an endpoint opens a stream through the operator. The generation script compiles the serverless contract together with its imported dispatcher, workflow, shared, and stream definitions. Changes to these contracts require regenerated Go and TypeScript bindings so endpoint and operator versions keep the same message names and fields. Both sides ignore unknown fields to allow compatible additions.
The SDK workspace keeps its dependency graph pinned and applies a minimum release age to new packages. It permits install scripts only for the build tools required by the SDK, so the package setup supports the generation and adapter toolchain without enabling unrelated package scripts.
References: sdks/…/README.md• L1-11 sdks/…/generate-proto.sh• L1-38 sdks/…/index.ts• L129-144 sdks/…/streams.ts• L13-94 sdks/…/streams.ts• L1206-1298 pkg/…/http.go• L82-126 api-contracts/…/serverless.proto• L13-20 sdks/…/pnpm-lock.yaml• L1-77 sdks/…/pnpm-workspace.yaml• L1-13
SDK runtime integration
The handler runtime gives each task a platform-neutral context. An optional Hatchet client handles unary engine calls such as child triggers, logs, cancellation, stream publishing, timeout refresh, and slot release. The same client can expose socket-backed reads for durable topic messages and workflow run events when the operator dialed the endpoint.
The context makes delivery limits explicit. A task declared with hatchetClient: false is a pure function and cannot use client-backed operations. A durable task must record child work through durable child operations rather than non-durable child waits. A non-durable task delivered over POST can use unary calls when configured with a client, but it cannot read engine streams because it has no invocation socket.
The endpoint package supports Cloudflare Workers, Vercel, and Node. It also provides an in-process operator for contract tests. That test operator signs requests and exercises the same POST or WebSocket choice, durable replay, child-run completion, stream limits, and response mapping as the production path.
References: sdks/…/context.ts• L137-183 sdks/…/context.ts• L187-243 sdks/…/context.ts• L253-328 sdks/…/context.ts• L332-355 sdks/…/task-client.ts• L98-115 sdks/…/task-client.ts• L298-395 sdks/…/index.ts• L120-160 sdks/…/durable-operator.ts• L1-9
Task modes
The Cloudflare Worker example shows how task declarations select the runtime contract. A pure task uses signed POST delivery. Tasks that use the client use the invocation socket. A durable task can be evicted and replayed while the engine waits for a durable event.
The same example publishes durable stream messages through unary client calls. A local Node consumer reads those messages from the engine after the task completes. A task that reads its own topic uses the invocation socket and needs an operator that relays the stream subscription.
References: examples/…/tasks.ts• L8-20 examples/…/tasks.ts• L22-47 examples/…/tasks.ts• L50-111 examples/…/README.md• L7-30 examples/…/consume-stream.ts• L1-13
Change checklist
When these files or sections are changed, remember to consider these:
- Keep api-contracts/…/serverless.proto, generated Go messages, and sdks/…/serverless.ts aligned. Keep v1/streams.proto and sdks/…/streams.ts aligned for endpoint-opened engine streams. Preserve protojson names and unknown-field behavior.
- Keep health catalog actions, stream actions, durable support, endpoint status, tenant action unions, and route selection consistent. A catalog change must update both the engine registration view and the endpoint's stored status.
- Keep signed POST fields and WebSocket upgrade fields aligned with endpoint verification. Changes must preserve timestamp age checks, endpoint binding, task binding, and nonce replay protection.
- Keep WebSocket done statuses, close codes, durable invocation replay, and engine task-event reporting aligned. An eviction must not become a terminal failure.
- Keep the allowed stream procedure list, stream request and response messages, tenant-scope checks, and the TypeScript stream bindings aligned. A stream contract change can fail only when an endpoint asks for that procedure.
- Keep the task client's socket-backed iterator behavior aligned with operator close codes, cursor handling, queue limits, and uploaded-payload support. POST delivery must continue to reject reads that need an invocation socket.
- Keep endpoint partition counts, lease endpoint counts, process heartbeats, and unit ownership changes in the same control-plane contract.
- Keep standalone and embedded runtime wiring equivalent for repository, encryption, token exchange, safe outbound requests, and shutdown order.
- Keep the SDK's edge-safe and Node-specific entry points aligned with adapter behavior. A runtime that cannot upgrade a socket must not advertise durable or stream-capable work.
- Keep the in-process testing operator's delivery selection and protocol checks aligned with the production operator, so contract tests do not accept a path the operator rejects.
- Keep sdks/…/pnpm-lock.yaml and sdks/…/pnpm-workspace.yaml aligned with the SDK generation and adapter toolchain. Required build tools must remain allowed while the workspace's package-age and install-script limits remain in force.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| The endpoint catalog lists an invalid or unsupported action | The catalog is rejected and the endpoint remains unhealthy for that catalog | Normalize and validate actions before updating the tenant union |
| Three health checks fail in a row | The endpoint is marked unhealthy and normal routing avoids it | Require a later successful health check before restoring healthy state |
| A tenant token is missing | The tenant is not polled or registered, and its endpoints show a token error | Use an explicit token exchange mode and mark the tenant unavailable until a token exists |
| A process heartbeat expires | Another process can claim the old process's tenant units | Use TTL heartbeats and release ownership on rebalance |
| A trigger request times out or returns a retryable status | The task is reported for retry | Apply the endpoint request timeout and preserve the response status mapping |
| A signed request has an old timestamp or wrong HMAC | The endpoint rejects the request | Verify the raw body, signature, endpoint ID, and timestamp before user code runs |
| A WebSocket closes without a done frame | The invocation becomes a retryable transport failure unless a prior engine state explains the close | Treat cancellation, eviction, shutdown, and normal completion as distinct relay outcomes |
| The endpoint cannot consume queued WebSocket frames | The relay closes for backpressure and the task does not retain unbounded data | Bound queued frames and bytes and report the relay outcome to the engine |
| A task reads a topic or run event stream over POST | The task fails with a serverless limitation instead of silently using an unavailable stream | Route stream-reading tasks over WebSocket and reject missing socket access clearly |
| A task reader falls behind its socket queue | The stream closes with RESOURCE_EXHAUSTED, and unread entries are lost after the last consumed cursor | Bound queued bytes and resume from the cursor in the close error |
| A task stream contains an uploaded payload reference | The serverless task client cannot decode the entry and the task fails | Read that topic with the Node client, which can fetch the uploaded payload |
| An endpoint opens an unsupported stream procedure or a stream request outside its task scope | The operator closes the stream before making an engine call | Allow only the listed procedures and enforce tenant and entitlement checks |
| An adapter advertises durable support without a working upgrade path | Durable tasks fail at delivery rather than being routed to a valid endpoint | Make health support depend on the adapter's actual WebSocket capability |
| The serverless client or stream binding uses a stale contract | Task-side engine calls or relayed streams fail at the wire boundary | Regenerate bindings from the shared contracts and keep the in-process protocol checks current |
| A required SDK build tool is blocked by workspace policy, or an install uses a package younger than the release-age limit | Dependency setup or contract generation stops before the SDK can build | Keep the lockfile and workspace policy aligned with the required toolchain |
Key files
| File | Why to read it |
|---|---|
| api-contracts/…/serverless.proto | Defines the health, trigger, durable, and stream message contract shared by the operator and endpoint SDK. |
| api-contracts/…/streams.proto | Defines the engine stream procedures and messages exposed through the serverless relay. |
| api-contracts/…/serverless_endpoint.yaml | Defines the tenant-facing endpoint resource and its configuration and status fields. |
| pkg/…/core.go | Shows the operator core lifecycle and its shared role in standalone and embedded modes. |
| pkg/…/healthcheck.go | Shows how endpoint catalogs become validated actions and capabilities. |
| pkg/…/routing.go | Shows the tenant action union and endpoint selection model. |
| pkg/…/registration.go | Shows worker registration, delivery choice, action sync, and shutdown drain. |
| pkg/…/delivery.go | Shows signed HTTP task delivery and response-to-task outcome mapping. |
| pkg/…/relay.go | Shows the WebSocket invocation lifecycle and durable message relay. |
| pkg/…/streams.go | Shows endpoint-requested engine stream access and stream limits. |
| pkg/…/leaser.go | Shows process heartbeats, fair-share unit ownership, and lease recovery. |
| cmd/…/main.go | Shows the standalone command wiring and runtime dependencies. |
| cmd/…/serverless.go | Shows the embedded operator mode and restart supervision. |
| sdks/…/index.ts | Shows the shared endpoint boundary and request routing. |
| sdks/…/healthcheck.ts | Shows the health catalog and delivery capability declaration. |
| sdks/…/registry.ts | Shows how task declarations become served actions and runners. |
| sdks/…/signature.ts | Shows POST and WebSocket signature verification and replay timing. |
| sdks/…/context.ts | Shows the task context limits and the split between unary client calls and socket-backed reads. |
| sdks/…/task-client.ts | Shows task-side topic and run-event reads, cursor errors, abort behavior, and queue bounds. |
| sdks/…/task-client.test.ts | Shows the contract guarantees for socket streams, POST limitations, and end-to-end operator relay. |
| sdks/…/invocation.ts | Shows the WebSocket invocation lifecycle and terminal outcomes. |
| sdks/…/streams.ts | Shows engine stream multiplexing and limits. |
| sdks/…/cloudflare.ts | Shows the Cloudflare runtime boundary. |
| sdks/…/vercel.ts | Shows the Vercel route and upgrade boundary. |
| sdks/…/node.ts | Shows the Node HTTP and WebSocket boundary. |
| sdks/…/index.ts | Shows the in-process operator used to verify delivery contracts. |
| sdks/…/generate-proto.sh | Shows the source contracts and generation boundary for the TypeScript endpoint SDK. |
| sdks/…/pnpm-lock.yaml | Pins the SDK dependency graph used by the runtime and contract-generation toolchain. |
| sdks/…/pnpm-workspace.yaml | Defines the package age and install-script policy for the SDK workspace. |
| examples/…/tasks.ts | Shows pure, client-backed, durable, and stream-reading task modes in one endpoint. |
| examples/…/consume-stream.ts | Shows a Node client consuming a durable topic after a serverless task publishes it. |
| examples/…/README.md | Explains the endpoint contract and the end-to-end Cloudflare Worker flow. |