Skip to main content
State change hooks execute code in response to changes in flow or task run states, enabling you to define actions for specific state transitions in a workflow.

Available state change hooks

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:
… or define your hook to accept arbitrary keyword 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 a Failed state. Here’s an example of running a client-side hook upon a flow run entering a Failed state:
Note that retries are configured in this example. This means the 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 a Crashed state. Here’s how to create a hook that deletes a Cloud Run job if the flow run crashes: