When you define a workflow endpoint, you can attach a failure function to the workflow that allows you to execute custom logic when a workflow run fails after exhausting all retry attempts.This feature ensures that you can perform cleanup operations, logging, alerting, or any other custom error handling logic before the failed workflow run is moved to the Dead Letter Queue (DLQ).
Failure function is executed automatically when worklow run fails
The failure function automatically receives the workflow run context and the reason for the failure, so you can decide how to handle it.
Copy
Ask AI
import { serve } from "@upstash/workflow/nextjs";export const { POST } = serve<string>( async (context) => { // Your workflow logic... }, { failureFunction: async ({ context, failStatus, failResponse, failHeaders, }) => { // 👇 Log error to monitoring system await logToSentry(...); // 👇 Send alert to team await sendSlackAlert(...); // 👇 Perform cleanup operations await cleanupWorkflowResources(...); }, }
You cannot create new workflow steps inside the failureFunction using context.
The context provided here is only meant to expose workflow run properties (like URL, payload, and headers).
Think of the failure function as an individual context.run step. It executes once with the provided context but cannot define further steps.
If you use a custom authorization method to secure your workflow endpoint, add authorization to the failureFunction too.
Otherwise, anyone could invoke your failure function with a request.Read more here: securing your workflow endpoint.
You can enable failure function for a workflow run when starting it:
Configure Retry Attempt Count
Copy
Ask AI
import { Client } from "@upstash/workflow";const client = new Client({ token: "<QSTASH_TOKEN>" })const { workflowRunId } = await client.trigger({ url: "https://<YOUR_WORKFLOW_ENDPOINT>/<YOUR-WORKFLOW-ROUTE>", // 👇 Activates the failure function execution if it is defined useFailureFunction: true, applyConfiguration: true,})