Vercel Workflows tutorial: build a durable background job
By Flavio
Tagged: Services
Build a durable Vercel Workflow with use workflow, use step, sleep, automatic retries, local inspection, and deployment-safe execution.
Vercel Workflows lets an async function keep running across failures, long waits, and new deployments. You still write normal TypeScript, except the runtime records completed work as it goes so a failed step can pick up where it left off instead of starting from scratch.
In this tutorial we’ll build a small customer onboarding workflow.
Why a normal background function is not enough
Say you want to send a new customer a welcome message right away and follow up three days later. Putting a timer inside a regular handler won’t work:
await sendWelcomeMessage(customerId)
setTimeout(async () => {
await sendFollowUpMessage(customerId)
}, 3 * 24 * 60 * 60 * 1000)
A serverless Function doesn’t stay alive for three days, and any deployment or runtime restart wipes out in-memory timers anyway. A workflow solves this by saving its progress along the way. It can sleep without holding compute, then wake up and continue later.
Create the Next.js app
Start by creating a new Next.js app:
npx create-next-app@latest workflow-demo
cd workflow-demo
Next, install the Workflow SDK along with its Next.js integration:
npm install workflow @workflow/next
Wrap your Next.js config in next.config.ts so the build can find functions marked with the workflow directives:
import type { NextConfig } from 'next'
import { withWorkflow } from 'workflow/next'
const nextConfig: NextConfig = {}
export default withWorkflow(nextConfig)
Create the workflow
Create workflows/onboard-customer.ts with the workflow and its steps:
import { sleep } from 'workflow'
export async function onboardCustomer(customerId: string) {
'use workflow'
const customer = await loadCustomer(customerId)
await sendWelcomeMessage(customer)
await sleep('10s')
await sendFollowUpMessage(customer)
return {
customerId,
status: 'completed',
}
}
async function loadCustomer(customerId: string) {
'use step'
return {
id: customerId,
name: 'Ada',
email: 'ada@example.net',
}
}
async function sendWelcomeMessage(customer: {
name: string
email: string
}) {
'use step'
console.log(`Welcome sent to ${customer.name} at ${customer.email}`)
}
async function sendFollowUpMessage(customer: {
name: string
email: string
}) {
'use step'
console.log(`Follow-up sent to ${customer.name} at ${customer.email}`)
}
Two string directives control how this runs:
'use workflow'marks the durable coordinator'use step'marks work that runs and retries on its own
The ten-second sleep keeps local testing fast. Once you’re ready for the real feature, change it to 3d or 3 days.
Workflow code and step code have different jobs
The workflow function coordinates the process, while all side effects live inside steps. Put database queries, API calls, email delivery, and file writes in functions marked with 'use step'.
Step boundaries matter because the workflow records every step’s inputs and outputs. When a workflow replays, it reuses the recorded result instead of repeating the side effect. My advice is to make each step do one clear job, because small steps are much easier to retry and inspect.
Start the workflow from an API route
Create app/api/onboard/route.ts to trigger the workflow:
import { start } from 'workflow/api'
import { onboardCustomer } from '@/workflows/onboard-customer'
export async function POST(request: Request) {
const { customerId } = await request.json()
if (typeof customerId !== 'string' || !customerId) {
return Response.json(
{ error: 'customerId is required' },
{ status: 400 },
)
}
const run = await start(onboardCustomer, [customerId])
return Response.json({
runId: run.runId,
status: 'started',
})
}
Calling start() queues the workflow and hands back a handle immediately. The route doesn’t wait for the welcome message, the sleep, or the follow-up; it just returns the run ID.
Start the development server:
npm run dev
Now trigger the workflow:
curl -X POST http://localhost:3000/api/onboard \
-H 'content-type: application/json' \
-d '{"customerId":"customer_42"}'
Here’s what the route returns:
{
"runId": "wrun_...",
"status": "started"
}
Keep an eye on the development terminal. The welcome message prints right away, followed by a ten-second pause, and then the follow-up message.
Inspect the run locally
Open the local Workflow inspector to look at the run:
npx workflow web
The inspector lists the workflow alongside each step, including:
- inputs
- outputs
- current status
- step duration
- failures and retries
That beats trying to piece together a three-day job from unrelated Function logs.
See automatic retries
Let’s make the follow-up fail once so we can watch retries work. Replace sendFollowUpMessage() with a temporary failure:
async function sendFollowUpMessage(customer: {
name: string
email: string
}) {
'use step'
if (Math.random() < 0.7) {
throw new Error('Temporary email provider error')
}
console.log(`Follow-up sent to ${customer.email}`)
}
When a step throws, Workflow retries it while leaving the completed loadCustomer() and sendWelcomeMessage() steps alone. Remove that random failure once you’ve tested it (a real step throws when a database query or external API request fails).
Make side effects idempotent
Because retries can run a step more than once, your side effects need to handle repeats safely. For an email step, create a stable idempotency key:
const idempotencyKey = `onboarding-welcome-${customer.id}`
Pass that key to an email provider that supports idempotency, and use a unique constraint or an upsert for database writes. Never assume a Function returning an error means the side effect didn’t happen, since the provider might accept the request right before the connection drops.
Stop retrying permanent failures
Some failures won’t get better on a second try. If an email address is invalid, retrying forever won’t fix it, so throw FatalError:
import { FatalError } from 'workflow'
async function sendWelcomeMessage(customer: {
name: string
email: string
}) {
'use step'
if (!customer.email.includes('@')) {
throw new FatalError('Customer email is invalid')
}
console.log(`Welcome sent to ${customer.email}`)
}
Use normal errors for temporary failures, and reach for FatalError when retrying can’t fix the input.
Deploy to Vercel
Deploy the app to Vercel:
npx vercel
Vercel picks its managed Workflow backend automatically, giving you storage, queues, authentication, and the Workflows dashboard. Make sure Fluid compute is enabled for the project, since Workflows use it when suspending and resuming steps.
Open the project in Vercel, go to Workflows, trigger the preview URL, and inspect the run. Deployed runs appear in that dashboard, while local runs stay in the local inspector. If you want the full details on preview deployments, production promotion, logs, and rollbacks, check the Vercel deployment documentation.
Prove it survives a deployment
Change the sleep duration to two minutes:
await sleep('2m')
Deploy the app and start a workflow. While it’s sleeping, change the follow-up log message and deploy again.
The running workflow stays attached to the deployment that started it and finishes with the old code, while new runs pick up the new deployment. That protects long-running work from code changes made halfway through the run.
When to use a Workflow
Reach for a Workflow when a job has state and several ordered steps:
- customer onboarding
- order fulfillment
- document processing
- AI agent runs
- approval flows
- delayed follow-ups
If you need lower-level message delivery, fan-out consumers, and direct control over acknowledgment, use Vercel Queues instead. We’ll cover that difference in the next tutorial.
For an agent example, Vercel eve combines Workflows with Sandbox and AI Gateway. I also compared this runtime with Pi Durable and Cloudflare Workflows in Pi Durable, Cloudflare Workflows, or Vercel Workflow?.
Want me to talk about your product? You can sponsor this site.
Related posts about services: