---
title: "Run a durable workflow"
description: "Run work of several steps over minutes or days, each step retried and the whole surviving restarts and deploys, and follow a run's status live from Vue."
canonical_url: "https://nuxt-backend.dev/docs/build/data/jobs/workflows"
---
# Run a durable workflow

> Run work of several steps over minutes or days, each step retried and the whole surviving restarts and deploys, and follow a run's status live from Vue.

Version: nuxt-backend 0.6.x · Tab: Build · Kind: how-to · Status: stable

Every page: [llms.txt](https://nuxt-backend.dev/llms.txt) · Skill for coding agents: [nuxt-backend](https://nuxt-backend.dev/.well-known/skills/nuxt-backend/SKILL.md)

Commands use npm; use your project's package manager.

- [API reference](https://nuxt-backend.dev/docs/reference/api/workflows)
- [Source](https://github.com/qruto/nuxt-backend/blob/main/src/convex/integrations/workflows.ts)

Some work has several steps that must all happen, with waits between them: provision an account, then email the person, then follow up three days later. A workflow runs such work durably, on the workflow component the scaffold mounts: each step that finished is remembered, an action step can be retried on its own, a sleep of days costs nothing while it waits, and a restart or a deploy picks the run up where it was.

## Set it up

The scaffold's `backend/workflows.ts` creates the manager every workflow is defined on:

```ts [backend/workflows.ts]
import { setupWorkflows } from 'nuxt-backend/workflows'
import { components } from './_generated/api'

export const workflow = setupWorkflows(components)
```

`setupWorkflows(components, options?)` from `nuxt-backend/workflows` returns the component's `WorkflowManager` with these defaults, each overridable through `options.workpoolOptions`:

<table>
<thead>
  <tr>
    <th>
      Option
    </th>
    
    <th>
      Default
    </th>
    
    <th>
      Effect
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        maxParallelism
      </code>
    </td>
    
    <td>
      <code>
        10
      </code>
    </td>
    
    <td>
      Steps running at once, across every workflow
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        defaultRetryBehavior
      </code>
    </td>
    
    <td>
      <code>
        { maxAttempts: 3, initialBackoffMs: 250, base: 2 }
      </code>
    </td>
    
    <td>
      How an action step that asks for retries is retried: three attempts in all, 250 ms before the second, doubling after
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        retryActionsByDefault
      </code>
    </td>
    
    <td>
      <code>
        false
      </code>
    </td>
    
    <td>
      Retry every action step without <code>
        { retry: true }
      </code>
      
       on each. Turn it on only when every action step is safe to run twice
    </td>
  </tr>
</tbody>
</table>

## Define a workflow

`workflow.define({ args, handler })` defines one. The handler's `step` runs your queries, mutations and actions, each as a step of its own, and sleeps:

```ts [backend/workflows.ts]
// Below the `workflow` defined above; merge these imports with the file's.
import { v } from 'convex/values'
import { internal } from './_generated/api'

export const provisionAccount = workflow.define({
  args: { userId: v.string(), email: v.string() },
  handler: async (step, { userId, email }): Promise<void> => {
    await step.runAction(internal.accounts.createSandbox, { userId }, { retry: true })
    await step.runMutation(components.backend.email.send, {
      to: email,
      subject: 'Your account is ready',
      text: 'Everything is set up.',
    })
    await step.sleep(24 * 60 * 60 * 1000)
    await step.runMutation(internal.accounts.markOnboarded, { userId })
  },
})
```

- **Each step runs once and is remembered.** On a retry or after a restart, the handler replays from the start, and the steps that already finished return what they returned the first time without running again. Keep the handler itself free of side effects: put each one in a step.
- **A mutation step** runs exactly once, in a transaction of its own. **An action step** that fails raises its error in the handler, which ends the run as `failed` unless it catches it. It is tried again first only when it asks for retries: `{ retry: true }` for the `defaultRetryBehavior`, or a `{ maxAttempts, initialBackoffMs, base }` of its own. Ask only for an action that is safe to run twice: one that charged a card or sent an email must not.
- **Annotate the handler's return type**, as above, when it refers to `internal` of its own file: TypeScript cannot infer it through the cycle.

## Start and stop a run

Start a run from a mutation or an action with `workflow.start(ctx, internal.<file>.<name>, args)`, which returns its `WorkflowId` at once. Store the id where a page can find it, then read the run with `workflow.status(ctx, id)` or stop it with `workflow.cancel(ctx, id)`.

```ts [backend/onboarding.ts]
import { internal } from './_generated/api'
import { authed } from './functions'
import { workflow } from './workflows'

export const start = authed.mutation({
  args: {},
  handler: (ctx): Promise<string> => workflow.start(ctx, internal.workflows.provisionAccount, {
    userId: ctx.user.id,
    email: ctx.user.email,
  }),
})
```

`workflow.start` also takes `{ onComplete, context }`, a mutation of yours called once the run ends, with how it ended, the way a [workpool's](https://nuxt-backend.dev/docs/build/data/jobs/workpool#hear-back-when-an-item-ends) `onComplete` is.

## Email sequences

A sequence of delayed emails is a workflow built with `defineEmailSequence`: see [Send an email sequence](https://nuxt-backend.dev/docs/build/growth/engage/lifecycle-emails), which also shows how the scaffold starts one on sign-up.

## Reactive status

`useWorkflowStatus(query, { workflowId })` subscribes to a query that takes `{ workflowId }` and wraps `workflow.status`. The scaffold doesn't ship one, so add it next to your workflows. `WorkflowId` is a branded string, so cast the validated argument back:

```ts [backend/workflows.ts]
// Below the `workflow` defined above; merge these imports with the file's.
import { type WorkflowId } from 'nuxt-backend/workflows'
import { authed } from './functions'

export const getWorkflowStatus = authed.query({
  args: { workflowId: v.string() },
  handler: (ctx, { workflowId }) => workflow.status(ctx, workflowId as WorkflowId),
})
```

The subscription pauses while the id is `null`, `undefined` or blank. It returns `data`, `isLoading` and `error`, and a failed read never throws. `data` is the component's `WorkflowStatus`: `type` is `'inProgress'` (with the `running` steps), `'completed'` (with `result`), `'failed'` (with `error`) or `'canceled'`:

```vue
<script setup lang="ts">
import { api } from '#backend/api'

const startOnboarding = useMutation(api.onboarding.start)
const workflowId = ref<string | null>(null)
const { data: status } = useWorkflowStatus(api.workflows.getWorkflowStatus, { workflowId })

async function begin() {
  workflowId.value = await startOnboarding({})
}
// status.value?.type: 'inProgress' | 'completed' | 'failed' | 'canceled'
</script>
```

<note>

`useWorkflowStatus` is in the [experimental tier](https://nuxt-backend.dev/docs/ship/releases/stability#the-experimental-tier): it follows the upstream workflow component's status shape, which is still before its 1.0 and may change in a minor release.

</note>

## Related

- [Background work](https://nuxt-backend.dev/docs/build/data/jobs): when to reach for a workflow, a workpool, a cron or the scheduler.
- [Queue work](https://nuxt-backend.dev/docs/build/data/jobs/workpool): many of the same job, a few at a time.
- [Send an email sequence](https://nuxt-backend.dev/docs/build/growth/engage/lifecycle-emails): onboarding and drip email as workflows.
- [`nuxt-backend/workflows`](https://nuxt-backend.dev/docs/reference/api/workflows) and [`useWorkflowStatus`](https://nuxt-backend.dev/docs/reference/api/use-workflow): the API reference.


## Sitemap

See the full [sitemap](https://nuxt-backend.dev/sitemap.md) for all pages.
