Cookbook: Handle workflows when referenced content is deleted
Apply an application-owned policy when a document that a workflow instance references is deleted.
Early access
Workflows is in early access, built in public. Read How early access works before you rely on it.
When someone deletes a document that a workflow instance references, the instance stays in place, with its history. If the instance needs that document to move on, the engine stops advancing it and blocks its actions and transitions until the document is readable again. You decide what happens next: keep the instance so someone can repair it, or abort it.
This recipe implements the abort policy. A Sanity Function runs when a document is deleted. It finds the in-flight instances that reference the document, confirms that no version of the document remains, and aborts those instances through the engine. The aborted instance documents stay in the dataset as an audit record.
The diagram shows the abort path after the Function has confirmed the deletion. The Function finds the affected instances and aborts each one through the engine. It skips the abort when a draft or release version still exists, when the document was restored, or when the availability check can’t tell.
Choose the policy first
Choose one of these policies for your application:
- Keep the instance for repair: the instance can’t advance while a required reference is missing. To unblock it, restore the document, restore access to it, or select a different document in the reference field, if the field is editable. The engine unblocks the instance in its next call after the referenced document is readable again.
- Abort after confirmed deletion: call
abortInstance. The engine cancels the instance’s pending effects, records your reason in history, removes the instance’s document guards, and tells any parent workflow that the instance ended. An abort is final. Restoring the document later doesn’t resume the instance.
To see which references are missing, call engine.evaluate and read the result:
missingDocumentslists every missing reference, with the field it belongs to.blockingMissingDocumentslists only the missing references that stop the instance from advancing.
A missing optional reference can leave other actions available. A completed instance stays completed. For the full evaluation fields, see Evaluation insights.
Don’t delete or patch workflow instance documents directly. Change an instance only through engine methods such as abortInstance.
Find instances watching the deleted document
instancesForDocument returns the in-flight instances that reference a document. You pass the document as a global document reference (GDR), which names the dataset as well as the document ID. So two documents with the same ID in different datasets never match each other. The method reads with a GROQ query, so it can miss an instance change made in the last second or so. See commit visibility.
Create functions/engine.ts and export an engine from it. Configure it for your workflow resource, and give it clients for any other datasets your instances reference. Run the engine from your own code shows the client and engine setup. Then install @sanity/id-utils with npm install @sanity/id-utils.
The Function receives the deleted document in event.data. The handler does three things:
- It converts the deleted ID to the published ID, so a deleted draft and a deleted published document both map to the same GDR.
- It finds the in-flight instances that reference that GDR.
- For each instance, it evaluates the instance and aborts it only if the reference has
availability: 'not-found'. That value means no version of the document exists.
not-found alone can’t tell a deleted document from one that never existed. The delete event is what tells the handler that the document was deleted:
import {documentEventHandler} from '@sanity/functions'
import {DocumentId, getPublishedId} from '@sanity/id-utils'
import {gdrFromResource} from '@sanity/workflows'
import {engine} from '../engine'
interface DeletedDocument {
_id: string
}
export const handler = documentEventHandler<DeletedDocument>(
async ({context, event}) => {
const {projectId, dataset} = context.clientOptions
const contentResource = {
type: 'dataset',
id: `${projectId}.${dataset}`,
} as const
const documentId = getPublishedId(DocumentId(event.data._id))
const document = gdrFromResource(contentResource, documentId)
const instances = await engine.instancesForDocument({document})
for (const instance of instances) {
const evaluation = await engine.evaluate({instanceId: instance._id})
const deleted = evaluation.missingDocuments?.some(
({reference, availability}) =>
reference.id === document && availability === 'not-found',
)
if (!deleted) continue
await engine.abortInstance({
instanceId: instance._id,
idempotencyKey: `subject-delete:${document}`,
reason: `Referenced document deleted: ${document}`,
})
}
},
)The engine needs a client for the workflow resource and a client for the content dataset. The token behind them must be able to read every version of the document, update instances, and update document guards. If the availability check fails or isn’t supported, availability is unreadable, and this handler keeps the instance.
Trigger only on relevant deletions
Add this delete trigger to your sanity.blueprint.ts, the project stack that Generate Functions from your workflow definitions deploys the generated drains and start watchers from. Bind it to the generated robot token, and narrow the filter to document types that can be workflow subjects:
// Add this resource to sanity.blueprint.ts.
defineDocumentFunction({
name: 'handle-deleted-subject',
src: './functions/handle-deleted-subject',
project: projectId,
robotToken: '$.resources.wf-prod-runtime.token',
event: {
on: ['delete'],
filter: '_type in ["article", "post"]',
resource: {type: 'dataset', id: `${projectId}.production`},
},
})The generated runtime declares that robot token, named after the deployment: wf-prod-runtime for a deployment named prod. This recipe adds the deletion trigger and lifecycle policy.
Retries and partial failures
Sanity Functions can deliver the same event more than once, and service calls can be retried. The example passes the same idempotencyKey for the same deletion on each instance. So a retry of an abort that already succeeded does nothing. On a later delivery, instancesForDocument doesn’t return the aborted instance, because it isn’t in flight.
The handler aborts instances one at a time. If an evaluation or abort fails, the Function fails. When it runs again, instancesForDocument returns only the instances that are still in flight. An unreadable availability doesn’t throw. The handler keeps that instance so you can investigate it.
If the referenced document is in a different dataset from your workflow instances, run the delete trigger in the document’s dataset. Keep the dataset in the GDR, as the example does. Give the engine resource clients and token permissions for the workflow resource and for every content dataset whose document guards the abort may remove.
Audit and retention
abortInstance marks the instance as aborted and completed. It cancels pending effects and records them in history, records your reason, and tells any parent workflow that the instance ended. The stored instance stays as the audit record.
The availability check and the abort are separate calls. If someone restores the document between them, the instance is still aborted. If a restored document should keep its workflow going, choose the repair policy instead.
Next steps
- Fields for document-reference field behavior.
- Engine for
instancesForDocumentandabortInstance. - Cookbook for other runtime patterns.
Visiting agent?
Workflows has MCP tools that let an agent inspect, operate, author, validate, and deploy workflows. An agent host embeds these tools. Ask the person you work for whether your host includes the Workflows tools.
Was this page helpful?
Feedback submitted, thanks for helping us improve the docs. Have you tried these alternatives?