Available state change hooks
Type | Flow | Task | Description |
---|---|---|---|
on_completion | ✓ | ✓ | Executes when a flow or task run enters a Completed state. |
on_failure | ✓ | ✓ | Executes when a flow or task run enters a Failed state. |
on_cancellation | ✓ | - | Executes when a flow run enters a Cancelling state. |
on_crashed | ✓ | - | Executes when a flow run enters a Crashed state. |
on_running | ✓ | - | Executes when a flow run enters a Running state. |
Flow run state change hooks
Task run state change hooks
Use multiple state change hooks
State change hooks are versatile, allowing you to specify multiple state change hooks for the same state transition, or to use the same state change hook for different transitions:Pass kwargs
to state change hooks
The Prefect engine will call your hooks for you upon the state change, passing in the flow, flow run, and state objects.
However, you can define your hook to have additional default arguments:
Common uses of state change hooks
Below are two common real-world applications of state change hooks.Send a notification when a flow run fails
State change hooks enable you to customize messages sent when tasks transition between states, such as sending notifications containing sensitive information when tasks enter aFailed
state.
Here’s an example of running a client-side hook upon a flow run entering a Failed
state:
on_failure
hook does not run until all retries
have completed when the flow run enters a Failed
state.
Delete a Cloud Run job when a flow run crashes
State change hooks help manage infrastructure cleanup in scenarios where tasks spin up individual infrastructure resources independently of Prefect. When a flow run crashes, tasks may exit abruptly and result in the potential omission of cleanup logic within the tasks. Use state change hooks to ensure infrastructure is properly cleaned up, even when a flow run enters aCrashed
state.
Here’s how to create a hook that deletes a Cloud Run job if the flow run crashes: