Quickback Docs

Workflows

Durable, versioned multi-step workflows on Cloudflare Workflows — persisted steps, sleeps and events, controls, and authority re-checked before every step.

A workflow is a persisted sequence of steps that can sleep for days, wait for an approval, and resume after a failure without re-running completed work. Quickback compiles each defineWorkflow version into a native Cloudflare Workflow and adds four things around it:

  • Durable starts and events. A start, event or control is a row in the run registry written in the same D1 batch as its durable effect intent. It exists if and only if its dispatch does.
  • Current authority. Before every step attempt, the initiating actor is reloaded from the auth database. A workflow never keeps acting with a role the actor has since lost.
  • Authorized controls. Start, status, events, cancel, pause, resume and retry routes check the caller's current role and the run's owner on every call.
  • Version pinning. Each version is its own native Workflow. A run finishes on the version it started on.

A workflow orchestrates work across resources. It is not a distributed SQL transaction, and it does not make external side effects happen exactly once.

Enable

Workflows need:

RequirementWhy
Cloudflare runtimeNative Cloudflare Workflows run the steps.
cloudflare-d1 features databaseThe run registry and event inbox commit with their intents in one native batch.
durableEffects: { enabled: true } and a queueStarts, events and controls are durable intents.
Better Auth organization pluginEvery run belongs to an organization actor.

With more than one queue, name the one that carries workflow intents:

database: defineDatabase("cloudflare-d1", {
  additionalQueues: [
    { name: "my-app-jobs", binding: "JOBS_QUEUE" },
    { name: "my-app-mail", binding: "MAIL_QUEUE" },
  ],
  durableEffects: { enabled: true, workflowQueue: "JOBS_QUEUE" },
}),

The compiler refuses each missing requirement. There is no degraded mode.

Define a workflow

Put one definition per file under quickback/services/workflows/:

quickback/services/workflows/onboarding-v1.ts
import { z } from "zod";
import { eq } from "drizzle-orm";
import { defineWorkflow } from "@quickback/compiler";
import { accounts } from "../../features/accounts/accounts";

export default defineWorkflow({
  name: "onboarding",
  version: 1,
  input: z.object({ accountId: z.string() }),
  result: z.object({ activated: z.boolean() }),
  events: { approval: z.object({ approved: z.boolean() }) },
  access: {
    start: { roles: ["admin"] },
    read: { roles: ["admin", "member"], scope: "organization" },
  },
  run: async ({ input, step }) => {
    await step.run("prepare", async ({ db }) => {
      await db.update(accounts).set({ status: "provisioning" }).where(eq(accounts.id, input.accountId));
    });
    const approval = await step.wait("approval", { timeout: "7 days" });
    await step.run("activate", async ({ db, idempotencyKey }) => {
      await db.update(accounts).set({ status: approval.approved ? "active" : "rejected" }).where(eq(accounts.id, input.accountId));
      // Pass idempotencyKey to external APIs: it is stable across retries.
    });
    return { activated: approval.approved };
  },
});

Everything that becomes a persisted identity is a literal the compiler checks: the name (camelCase), the version (a positive integer), event names and step names. Files starting with _ are helpers. Any other file in that directory must call defineWorkflow.

FieldMeaning
name, versionRequired. Each (name, version) is defined once.
input, resultZod schemas. Starts are validated against input. The return value is validated against result before it is stored.
eventsZod schema per event name.
accessRequired. See Routes and access.
retiredtrue stops new starts on this version. In-flight runs finish on it.
retentionHow long a finished run's registry row and result are kept (default "30 days", 1 hour to 365 days).
authorityOnly { mode: "actor" }, the default. See Authority.

Steps

run receives { input, step, runId }. It must destructure its parameter, and step may only be called directly. Passing, storing or destructuring step is a compile error, because steps are recorded only through those calls.

CallDoes
step.run(name, fn, options?)A persisted, side-effecting step. A completed step replays its stored result and never runs again.
step.sleep(name, duration) / step.sleepUntil(name, at)A durable sleep. Durations look like "30 seconds" or "7 days", or are milliseconds.
step.wait(event, { key?, timeout? })Waits for a declared event and returns its validated payload.
step.job(name, target, message)Calls a tenant result job in an organization or partition object.

Step names are unique within a version. Repeated work, such as a loop or a map callback, needs a stable item key: step.run("charge", fn, { key: invoiceId }). A run or wait inside a loop without a key is a compile error.

fn receives fresh handles for each attempt. Nothing persists between attempts except the step's JSON result:

HandleIs
dbA scoped database for the actor, built exactly like an action's: the same firewall, audit stamps and atomic db.batch, including effects.
ctx{ authMethod: "workflow", userId, activeOrgId, roles, orgRole, userRole, workflowRunId }, reloaded for this attempt.
env, servicesThe Worker bindings and services.
idempotencyKey<runId>:run:<name>[#key], stable across attempts.
attemptThe 1-based attempt number.

A step's result must be JSON and at most 128 KiB. undefined comes back as undefined.

Retries and timeouts

Native Workflows retries are the only retry layer for steps. Quickback adds no retry loop of its own.

OptionDefaultBounds
retries.limit30–10
retries.delay"10 seconds"1 second – 1 hour
retries.backoff"exponential"constant, linear, exponential
timeout"5 minutes"1 second – 30 minutes

A step can run more than once: after a crash, a timeout, or a lost acknowledgement. Make writes idempotent, and pass idempotencyKey to external APIs. An external request that was already running when a run was cancelled or blocked may still complete.

Authority

A run stores its actor: the user ID and the organization of the caller who started it. It stores no token, session, role snapshot or database handle.

Before every attempt of a run or job step, the engine:

  1. checks the run is still runnable. A cancelled run, or one being cancelled, stops here;
  2. reloads the user. The user must exist and not be banned;
  3. reloads the user's membership in the run's organization;
  4. expands the membership role through auth.roleHierarchy, the same way a request does;
  5. evaluates access.execute.roles (default: access.start.roles) with the project's access evaluator.

If any check fails, the run becomes blocked with error AUTHORITY_REVOKED, and the step does not run. The block is durable and does not retry. The run never continues as a system identity or as anyone else. A run that loses authority while sleeping or waiting blocks at its next run or job step. Sleeps and waits have no side effects, so they are not checked.

Retry resumes a blocked run only when the original actor holds the execute roles again.

Subscription tier roles (tier_*) are not re-resolved for steps. A rule that names one fails closed. Service authority (authority: { mode: "service" }, a named, revocable service grant) is not supported yet and is a compile error.

Routes and access

Routes live under the API prefix:

RouteOperationResponse
POST /api/v1/workflows/<name>/runsstart202 + run status. Needs Idempotency-Key.
GET /api/v1/workflows/<name>/runs/<runId>read200 + run status.
POST …/runs/<runId>/events/<event>signal202. Idempotency-Key is the event ID.
POST …/runs/<runId>/cancelcancel202 + status.
POST …/runs/<runId>/pause · resume · retrycontrol202 + status.

Each access rule is { roles, scope? }. start is required. read, signal and cancel default to start, and control defaults to cancel. PUBLIC is not allowed.

scopeWho can act on a run
"actor" (default)Only the run's actor, while holding the roles.
"organization"Any member of the run's organization holding the roles.

Every call reloads the caller's membership from the auth database. A cached JWT role is not enough. Only a signed-in user with an active organization can call these routes. Delegated principals, scope-only principals and share links get 403 WORKFLOW_ACTOR_REQUIRED. A caller without the operation's role on any version gets 403. A run in another organization, a run owned by another actor under "actor" scope, or an unknown run ID all return the same 404. Knowing a run ID grants nothing.

The routes are listed in the generated OpenAPI spec under the Workflows tag.

Durable starts and events

Start. The route validates the input and derives an opaque run ID from the project, workflow, organization, actor and Idempotency-Key. In one D1 batch it writes the registry row and a qb.workflow.start intent. The global idempotency layer replays a repeated request with the same key. A key reused with a different input is refused.

Dispatch. The generated queue consumer admits the intent, like every durable effect, then creates the native instance with the run ID as its instance ID. If an earlier create succeeded but its reply was lost, the dispatcher finds the instance and does not create a second one. If the Worker dies after the commit and before dispatch, the effects sweep delivers the intent later.

Events go to the run's inbox: one row per (runId, eventId), written in the same batch as a qb.workflow.event intent. The native sendEvent is only a wakeup. A wait first claims the oldest pending matching event from the inbox, so an event sent before the run reaches its wait is not lost. Unknown events (400 WORKFLOW_EVENT_UNKNOWN), invalid payloads, payloads over 64 KiB, events for a finished run (409 WORKFLOW_TERMINAL) and more than 1,000 unconsumed events (429 WORKFLOW_INBOX_FULL) are refused.

Idempotency-Key values are scoped to the caller across the whole API. Use a fresh key for every start and every event.

Status and errors

Status responses contain registry facts only: { runId, workflow, version, status, createdAt, updatedAt, result?, error? }. They never include the persisted input or native internals.

StatusMeaning
startingRecorded. The native instance may not exist yet.
runningThe instance exists.
pausedPaused on request.
blockedStopped for review. See error.code.
cancelling → cancelledCancellation recorded, then the native instance terminated.
completedFinished. result is the validated return value, at most 64 KiB.
failedA step exhausted its retries, a wait timed out, or validation failed.

error.code is a stored code: an error's code property, or its message when that looks like a code (CARD_DECLINED). Anything else becomes WORKFLOW_FAILED, so error messages with user data are never stored.

CodeStatusCause
AUTHORITY_REVOKEDblockedThe actor lost the execute roles or the membership.
VERSION_MISMATCH / VERSION_UNAVAILABLEblockedThe run's version is not the code or binding asked to run it.
TENANT_*blockedA tenant object is permanently unavailable to a step.job: purged, archived, restore pending or not provisioned.
WORKFLOW_RESULT_TOO_LARGE, WORKFLOW_STEP_OUTPUT_TOO_LARGEfailedSize limits.

Controls

  • Cancel records cancelling and a revision fence before it asks the platform to terminate the instance. Every new step checks the fence. A step already in flight may finish, so the status stays cancelling until the dispatcher records cancelled. Nothing is compensated automatically. Write explicit, idempotent cleanup steps when you need them.
  • Pause and resume apply to running and paused runs. You can call them back to back: each records its status at once, and the dispatcher drives the native instance to the latest recorded status, so a pause still in flight never undoes the resume that followed it. A paused run keeps its completed steps; resume continues from where it stopped.
  • Retry applies to blocked and failed runs. It restarts the native instance from the step that blocked or failed. Earlier completed steps keep their results and do not run again. A run that did not stop at a step, such as a version mismatch or a failed result validation, returns 409 WORKFLOW_NOT_RETRYABLE: a restart from the beginning would run completed steps again. Start a new run instead.

Each control increments the run's revision in the same batch as its intent. The dispatcher applies only the latest revision, so a stale or duplicate control does nothing.

Versions

Versions are immutable. onboarding version 2 is a new file with version: 2. Each version compiles to its own class, binding and native Workflow: QbWorkflowOnboardingV2, QB_WF_ONBOARDING_V2 and <app>-onboarding-v2. New starts use the highest version that is not retired. A run always executes the version recorded in its registry row.

Immutable is your contract, not the platform's. Cloudflare does not pin a native instance to the Worker deployment it started on. If you edit a deployed version's file in place and deploy, its in-flight runs execute the edited code from their next step: a sleeping or waiting run wakes on the new deployment. An invocation already running may finish on the old code for a short grace period first, so one run can mix both. To change steps, add a new version.

To retire a version:

  1. Set retired: true on it and deploy. It accepts no new starts.

  2. Wait until no run references it:

    wrangler d1 execute <features-db> --remote --command \
      "SELECT count(*) FROM _quickback_workflow_runs WHERE workflow = 'onboarding' AND version = 1 AND status NOT IN ('completed','failed','cancelled')"
  3. Delete the file.

The compiler reads the deployed wrangler.toml and refuses to remove a version that was deployed without retired: true (WORKFLOW_VERSION_REMOVED). It cannot see the registry, so step 2 is yours to check. A run whose version binding is gone is marked blocked (VERSION_UNAVAILABLE). It never runs on another version.

Tenant and partition steps

step.job calls a tenant result job using the partition-job destination contract (Partition jobs):

const summary = await step.job("summarize", {
  kind: "partition", organizationId: input.organizationId, partition: "conversation", key: input.conversationId,
}, { type: "conversation.summary" });

The step first passes the authority check. target.organizationId must be the run's organization. The job's run ID is wf:<runId>:job:<name>, so a retried step replays the job's recorded result in that same object. A purged, archived, restore-pending or unprovisioned object blocks the run instead of retrying. The edge's registry fences apply to workflows exactly as they apply to everything else. step.job needs tenancy.isolation: 'durable-object'.

Named environments

Wrangler does not inherit Workflows into environments. Each environment target declares its own native Workflows under environment-qualified names (<app>-<env>-onboarding-v2), and keeps its registry in its own features database. Runs never cross targets.

Data and retention

StoredWhereKept
Run identity, version, organization, actor, status, revision, input, result, error code_quickback_workflow_runs (features D1)Until retention after a run finishes. Unfinished runs are never pruned.
Events_quickback_workflow_eventsDeleted with their run.
Step results, sleeps, waitsNative Workflow instance stateCloudflare's instance retention.

The effects sweep cron also deletes expired runs, in batches of 200.

Limits and guarantees

  • Delivery is at least once at every boundary: intents, dispatch, events and steps.
  • Nothing is exactly once, and nothing is compensated automatically.
  • Each start, event and control costs one D1 batch, one durable effect and one queue message. Each step attempt adds two auth-database reads and one registry read.
  • Native Workflows limits apply: step count, payload sizes, concurrency and pricing. See Cloudflare Workflows limits.

The generated runtime is tested under Miniflare's local Workflows engine: durable starts, the inbox, registry and step state across a process restart, pause and resume, revocation and retry, cancellation, and two versions running at once. The local engine keeps sleep timers in memory, so after a restart it does not wake a sleeping run by itself; the test re-invokes the run through pause and resume and checks that completed steps replay. On a deployed account (2026-11-19): a run sleeping across a redeploy woke and completed; pause, back-to-back pause and resume, cancel, revocation to blocked, restart-from-step retry, idempotent start and event delivery behaved as described here.

Compile errors

CodeWhen
WORKFLOW_RUNTIME / WORKFLOW_DATABASEThe runtime is not Cloudflare, or the features database is not D1.
WORKFLOW_DURABLE_EFFECTS_REQUIREDdurableEffects is not enabled.
WORKFLOW_ORGANIZATIONS_REQUIREDThe organization plugin is off.
WORKFLOW_QUEUESeveral queues and no workflowQueue, or an unknown workflowQueue.
WORKFLOW_TENANT_JOB_UNAVAILABLEstep.job without durable-object tenancy.
WORKFLOW_NAME / WORKFLOW_VERSION / WORKFLOW_DUPLICATE_VERSIONInvalid or repeated identity.
WORKFLOW_ACCESS / WORKFLOW_AUTHORITY / WORKFLOW_AUTHORITY_SERVICE_UNSUPPORTEDInvalid policy or authority mode.
WORKFLOW_STEP_NAME_LITERAL / WORKFLOW_STEP_DUPLICATE / WORKFLOW_STEP_LOOP_KEYA step name that is not a literal, is repeated, or runs in a loop without a key.
WORKFLOW_STEP_ESCAPES / WORKFLOW_STEP_HANDLE / WORKFLOW_STEP_EVENT / WORKFLOW_STEP_OPTIONSMisuse of step, an undeclared event, or out-of-bounds options.
WORKFLOW_NATIVE_NAMEA native name longer than 64 characters.
WORKFLOW_VERSION_REMOVEDA deployed, unretired version was deleted.

On this page