Durable Workflows

A durable workflow is a function that takes many steps, sleeps for days or waits for an event, and still finishes after a crash, a restart or a deploy. Temps stores the result of every step, so a run that is interrupted continues where it stopped instead of starting over.

Typical uses are onboarding sequences, payment reminders, webhook processing that must not run twice, chunked imports, and approvals that wait for a person. Without it these jobs usually live in a queue library or a setTimeout that dies with the container.


What is available today

Durable workflows are new in v0.1.0-beta.62. Read this before you plan around them:

PartStatus in v0.1.0-beta.62
Server: engine, scheduler, API, console tabIncluded. There is no switch to enable: the scheduler starts with temps serve, and each environment has its own settings.
@temps-sdk/workflows (the SDK your app uses)Not published yet. The npm package of that name is a placeholder. The SDK is in the Temps repository under sdks/node/packages/workflows, and you build and install it from there.
temps workflows CLI commandsIn the repository source, but not in the published @temps-sdk/cli (0.1.38 does not have them). Build the CLI from the repository to use them.
Maturity labelNone. Durable workflows have no entry in the feature maturity registry in this release, so no badge is shown. Treat the feature as new: names, limits and the protocol can still change.

The examples below use the SDK and CLI as they exist in the repository, so they work once you have built them.


How it works

Temps orchestrates and your app executes. Temps stores each run's history and decides what runs next. The code runs in your own container, through the SDK. Temps never runs your code.

  1. Your app serves two endpoints under /.well-known/temps/workflows/: manifest, which lists your workflows, and invoke, which runs one.
  2. A run starts from the console, the API, the CLI or your app's code.
  3. Temps calls invoke on a healthy replica of your app. Your function runs, and each ctx.step result is recorded on Temps before the function continues.
  4. When the function sleeps or waits for an event, the invocation ends and no connection or container is held. Temps wakes the run later and calls invoke again.
  5. The function runs again from the top. Steps that already finished return their recorded result without running again, and execution continues from the first step that is not recorded.

That replay is why a workflow has three rules:

  • Step bodies run at least once. A step that was interrupted can run again, so make it idempotent.
  • Step names must stay stable. Temps matches recorded results to steps by name.
  • Use await ctx.now() and await ctx.random() instead of the clock and Math.random(). Their values are recorded once and replayed.

Temps verifies every invoke call before your code runs: it signs each request with an Ed25519 key and checks the request body, so a forged invocation is rejected. The SDK fetches the public key from Temps with your workflow credential.


Write a workflow

import { defineWorkflow } from '@temps-sdk/workflows'

export const sendInvoice = defineWorkflow<{ orderId: string }>(
  'send-invoice',
  async (ctx) => {
    // Recorded on Temps. If the container dies after this, the invoice is not created again.
    const invoice = await ctx.step('create-invoice', () => billing.create(ctx.input.orderId))

    // Sleeps for three days without holding a connection or a container.
    await ctx.sleep('grace-period', '3d')

    // Waits up to seven days for an event with this name and key.
    const paid = await ctx.waitForEvent('payment', {
      event: 'invoice.paid',
      key: invoice.id,
      timeout: '7d',
    })

    if (!paid.received) {
      await ctx.step('send-reminder', () => mail.remind(invoice.id), { retries: 5, timeout: '30s' })
    }
  },
  { version: '2026-11-01', concurrency: 10 },
)

The context gives you these durable operations:

MethodWhat it does
ctx.step(name, fn, options?)Runs fn and records the result. A failed attempt is retried.
ctx.sleep(name, duration) and ctx.sleepUntil(name, date)Suspends the run. Durations are milliseconds or strings such as "30s", "5m", "2h", "1d".
ctx.waitForEvent(name, { event, key?, timeout? })Suspends until an event arrives. The result has received: false if the timeout passes first.
ctx.sendEvent(name, event, { key?, payload? })Sends an event to other runs in the environment.
ctx.child(name, workflow, input?)Starts a child run and waits for it. The child starts exactly once however often this run replays, and cancelling the parent cancels the child.
await ctx.now() and await ctx.random()A time and a number in [0, 1), recorded once and replayed.

Step options, with their defaults:

OptionDefaultMeaning
retries3Retries after the first attempt, so four attempts in all
initialBackoff1sWait before the first retry
maxBackoff5mLongest wait between retries
factor2How much the wait grows each attempt
timeoutnoneAbort an attempt after this long. The attempt fails and is retried.

Workflow and step names use 1–128 letters, digits and . _ - : /. The concurrency option caps how many runs of that workflow execute at once in the environment.

An event is stored first and delivered to every run waiting on its name and key. A run that starts waiting for an event that already arrived picks it up straight away.


Serve and deploy it

Create a handler from your workflows and mount it in your web framework. The SDK ships adapters for Node http and Express, the Next.js App Router and Hono.

import express from 'express'
import { createWorkflowHandler, toNodeListener } from '@temps-sdk/workflows'
import { sendInvoice } from './workflows'

const handler = createWorkflowHandler({ workflows: [sendInvoice] })

const app = express()
app.use(toNodeListener(handler))
app.get('/health', (_req, res) => res.send('ok'))
app.listen(3000)

For Next.js, export nextRouteHandlers(handler) as GET and POST from app/.well-known/temps/workflows/[action]/route.ts. For Hono, use app.all('/.well-known/temps/workflows/*', honoHandler(handler)).

Your app needs two environment variables:

VariableValue
TEMPS_API_URLThe root of your Temps API
TEMPS_WORKFLOWS_TOKENThe environment's workflow credential (a twf_ token)

Create the credential in the console: open the project, go to the Durable workflows tab, choose the environment, and create the workflow credential. Store it as a runtime secret in the app. Rotating it stops the old credential immediately, so update the app at once. The tab also shows Executor not ready with the reason when Temps cannot find a deployment that serves the handler.

The CLI can scaffold a worker for you:

temps workflows init my-worker --sdk-package ./temps-sdk-workflows.tgz

--sdk-package takes a tarball you built with npm pack from the repository, which is needed while the SDK is unpublished. The scaffold is a small Node app with a sample workflow, a test, and a Dockerfile. Deploy it with the Durable workflow worker preset (workflow-worker) on port 3000 with health path /health.

Temps reads the manifest again for each new deployment (and otherwise caches it for ten minutes), so a new workflow appears after you deploy. By default the handler is expected in the environment's main service; for a Docker Compose project, the host_service setting names the Compose service that hosts it.


Start runs and send events

From your app, with the client (it reads TEMPS_API_URL and TEMPS_WORKFLOWS_TOKEN):

import { WorkflowsClient } from '@temps-sdk/workflows'

const workflows = new WorkflowsClient()

// Starting twice with the same key returns the first run.
const { run, created } = await workflows.start(
  'send-invoice',
  { orderId: 'ord_123' },
  { idempotencyKey: 'invoice-ord_123' },
)

await workflows.sendEvent('invoice.paid', { key: invoice.id, payload: { amount: 4200 } })

const finished = await workflows.waitForRun(run.id, { timeoutMs: 60_000 })

From the console, use the Durable workflows tab of the project: start a run with a workflow name and an input JSON, and open a run to see its steps.

From the CLI (source build only; every command needs --project-id and --environment-id):

CommandWhat it does
temps workflows listLists detected workflows and onboarding status
temps workflows runsLists a page of runs, optionally for one --workflow
temps workflows get <run-id>Shows run metadata. Add --reveal input (or output, error, step_result, step_error) to decrypt one payload. A step payload also needs --sequence <n>
temps workflows diagnose <run-id>Explains the run's state without decrypting payloads
temps workflows start <workflow> --idempotency-key <key> --input <json>Starts a run
temps workflows cancel, resume, retry, delete <run-id> --yesChanges a run. retry also takes --from-step <n> to replay from that step
temps workflows send-event <name> --key <key> --payload <json>Sends an event to matching waits
temps workflows watch <run-id>Polls until the run finishes, for at most --timeout seconds (default 300, maximum 3600)

From the API, the management routes sit under /projects/{project_id}/environments/{environment_id}/workflows and accept a session or an API key:

RoutePurpose
GET on the base pathOverview of the environment's workflows
GET, POST on /runsList or start runs
GET, DELETE on /runs/{run_id}Read or delete a run
GET on /runs/{run_id}/steps and /diagnoseSteps, and an explanation of the state
POST on /runs/{run_id}/reveal, /cancel, /retry, /resumeReveal a payload, cancel, retry, resume
POST on /eventsSend an event
GET, PUT on /settingsRead or change settings
GET, POST, DELETE on /credentialRead, issue or revoke the workflow credential

Apps use a smaller set with the workflow credential: POST /workflows/v1/runs, GET /workflows/v1/runs/{run_id} and POST /workflows/v1/events.

Across projects: an app can start a workflow or send an event in another project only if that environment has created an explicit, revocable grant for it. Grants are created and revoked with workflows:write and are audited.


Run states

StateMeaning
queuedDue now, waiting for a free invoker or under a concurrency limit
runningLeased to an invocation
sleepingSuspended in sleep until its wake time
waitingSuspended in waitForEvent. Its wake time is the timeout, if one was set.
retryingA step failed and will be retried at its wake time
completed, failed, cancelledFinished
stuckRepeated invocation failures or expired leases. An operator resumes it.

A run becomes stuck after 8 consecutive invocation failures by default. Use diagnose to see why, fix the app, then resume or retry the run.


Settings and limits

Each environment has its own settings, with these defaults. Change them with PUT on /settings or from the settings page of the environment's workflows.

SettingDefaultMeaning
host_servicethe main serviceCompose service that hosts the handler
invocation_deadline_secs900Longest a single invocation may run
lease_secs120How long an invocation holds a run before it can be reclaimed
max_concurrent_runs50Runs executing at once in the environment
max_active_runs10000Runs that are not finished
max_steps_per_run1000Steps recorded for one run
max_journal_bytes_per_run64 MiBTotal journal size of one run
inline_payload_limit_bytes256 KiBPayloads up to this size are stored in the database row
max_payload_bytes4 MiBLargest single payload
retention_days30How long finished runs are kept
stuck_after_failures8Failures before a run becomes stuck
drain_timeout_secs0 (off)Pause new invocations during a deploy and wait for running attempts. Suspended runs resume on the new deployment.
managed_store_service_idnoneStore the journal of new runs in a managed PostgreSQL service instead of the Temps database

Security and permissions

  • Payloads are always encrypted. Run inputs, outputs, errors, step results and event payloads use AES-256-GCM, bound to their project, environment, run and field. There is no plaintext option. A payload larger than the inline limit goes to the project's blob storage under .temps/workflows when blob storage is available, and is rejected otherwise.
  • Revealing a payload is audited. The console and the API never show decrypted payloads unless someone with workflow_payloads:read asks for one with reveal, and the request is recorded in the audit log. Treat revealed content as untrusted input.
  • Per-project keys, with shredding. Each project has its own data key. The project's Encryption keys page lists them, and shredding a key makes the payloads encrypted under it permanently unrecoverable. Use it for data you must be able to destroy.
  • Optional client-side encryption. The SDK accepts a codec (it ships aesGcmCodec) so that Temps only ever stores payloads you encrypted yourself.
  • Credentials: the workflow credential is stored hashed. Invocation tokens are signed by Temps and valid only for one run and lease.
PermissionWhat it allows
workflows:readView the overview, runs, steps, settings and credential status
workflows:writeChange settings, issue or revoke the credential, manage grants and encryption keys
workflow_runs:createStart runs
workflow_runs:writeCancel, retry and resume runs
workflow_runs:deleteDelete runs
workflow_events:createSend events
workflow_payloads:readReveal decrypted payloads

The Admin role has all seven. The User role has workflows:read, workflow_runs:create, workflow_runs:write and workflow_events:create. The Reader and Platform Admin roles have workflows:read. See Authorization for roles and custom roles.


Develop locally

  • In-memory tests. @temps-sdk/workflows/testing runs workflows against an in-memory engine, and the scaffold includes a sample test.
  • temps workflows dev forwards invocations from a preview environment to a server on your machine, so you can run and debug a workflow locally against a real Temps instance:
temps workflows dev --project-id 12 --environment-id 34 --port 3000

The environment must be an undeployed, unprotected preview environment. The command stays running and forwards each invocation until you stop it.


  • Cron jobs run a command on a schedule. A durable workflow keeps state across many steps and waits, and you start it yourself.
  • Temporal and Restate starters. The templates temporal-workflow-engine and restate-workflow-engine deploy those engines with persistent storage. They are separate from Temps durable workflows and use their own upstream SDKs.
  • Agent workflows. The temps workflow command (singular, alias wf) triggers and inspects agent and workflow runs for a project. It is a different feature from the durable workflows described here, which use temps workflows (plural).
  • Webhooks notify other systems when something happens in Temps. To react to your own events inside a workflow, use waitForEvent.

Last updated

Was this page helpful?