Prefect

On this page 7

Prefect is an open-source workflow orchestration framework for Python that turns ordinary functions into observable, retryable and schedulable workflows. Among automation platforms it occupies the code-first, developer-oriented end of the spectrum: instead of drawing workflows in a visual canvas, engineers decorate Python code and let Prefect track every run, failure and retry.

Within the wider field of automation, Prefect is used mainly for data pipelines, machine learning jobs and backend automation, where the logic is too complex for a no-code tool but the team still needs scheduling, alerting and a central record of execution state. It is distributed under the Apache 2.0 license, with an optional managed service called Prefect Cloud.

How Prefect orchestrates Python code

Prefect orchestrates code by wrapping functions in two decorators, @flow and @task, and reporting each call to an orchestration API. A flow is the top-level unit of work, while a task is a smaller, individually tracked step inside a flow. When a decorated function runs, Prefect records a state transition such as Pending, Running, Completed or Failed, which makes every execution visible in the user interface.

A defining design choice is that workflows are dynamic rather than predeclared. Earlier orchestrators require a static directed acyclic graph to be defined before execution, whereas Prefect builds the run graph as the Python code executes. Loops, conditional branches and data-dependent fan-out therefore work with native Python control flow, without a separate templating language.

Prefect also follows a hybrid execution model. The orchestration layer stores metadata only, such as states, logs, schedules and parameters, while the actual code and data stay on infrastructure the team controls. This separation matters for data governance, because sensitive records never have to pass through the orchestration service.

The table below summarizes the core building blocks and the role each one plays.

ComponentWhat it isRole in orchestration
FlowDecorated Python functionTop-level unit that is scheduled and tracked
TaskDecorated step inside a flowRetries, caching and concurrency per step
DeploymentServer-side definition of a flowAdds schedule, parameters and infrastructure
Work poolQueue with infrastructure settingsRoutes runs to a type of compute
WorkerLong-running polling processPicks up runs and launches them
BlockStored configuration objectHolds credentials and connection settings
Core components of a Prefect setup

States, retries and caching in Prefect

Prefect treats state as a first-class object, which is the basis of its reliability features. Every flow run and task run moves through a defined lifecycle, and each state carries a timestamp, a message and optionally a persisted result. Because the orchestrator knows exactly where a run stopped, it can resume, retry or alert with precision.

Retries are configured per task or per flow with a count and a delay, and the delay can grow with exponential backoff for unreliable external APIs. Caching lets a task skip work when its inputs match an earlier run, based on a cache key that is usually derived from the task inputs and source code. Version 3 added transactional semantics, so a group of tasks can be committed or rolled back together.

The following table lists the most important run states and what normally causes each one.

StateTypical causeUsual follow-up
ScheduledDeployment schedule created a future runWorker picks it up at the due time
RunningCode is executing on infrastructureLogs stream to the interface
CompletedCode finished without an exceptionDownstream tasks proceed
FailedCode raised an exceptionRetry policy or alert applies
CrashedInfrastructure died or was killedInvestigate memory or node issues
PausedFlow waits for input or approvalResumes when a person or event responds
Common Prefect run states

The distinction between Failed and Crashed is easy to overlook but operationally important. A failure means the code itself raised an error, while a crash means the runtime environment disappeared, which points to resource limits, preempted spot instances or container eviction rather than a logic bug.

Prefect compared with other automation platforms

Prefect differs from neighboring tools mainly in who writes the workflow and how it is expressed. Visual integration services such as Zapier, Make or n8n target business users who connect applications through prebuilt connectors. Prefect assumes a Python developer and offers no drag-and-drop editor, in exchange for full programmatic control.

Among code-first orchestrators, the most frequent comparison is with Apache Airflow. Airflow is older, has a very large operator ecosystem and is widely offered as a managed service, but it was built around static DAG files parsed by a scheduler. Temporal, by contrast, focuses on durable execution of long-lived business processes with event-history replay, which is a different guarantee from Prefect’s state tracking.

ToolWorkflow definitionTypical strength
PrefectDecorated Python functionsDynamic data and ML pipelines
AirflowPython DAG filesMature batch scheduling, many operators
TemporalWorkflow code with replayDurable, long-running business processes
AWS Step FunctionsJSON state machineServerless orchestration within one cloud
n8nVisual node editorApplication integration with low code
Prefect and related orchestration tools

Deploying and running Prefect in production

Running Prefect in production means creating a deployment and pointing it at a work pool. A flow can run locally as a script, but scheduled or remotely triggered execution requires a deployment that stores the entry point, default parameters and schedule. Schedules support cron expressions, fixed intervals and calendar rules, and runs can also be triggered by events or API calls.

Teams choose between self-hosting the open-source server and using Prefect Cloud. The self-hosted server needs a database, typically PostgreSQL for production, while the managed service adds features such as role-based access control, audit logs and event-driven automations. Infrastructure options include local processes, Docker containers, Kubernetes jobs and serverless container services.

The decision table below shows how common situations map to an execution setup.

SituationRecommended setupReason
Single analyst, light jobsProcess work pool on one machineLowest operational overhead
Isolated dependencies per flowDocker work poolReproducible images per pipeline
Bursty, heavy workloadsKubernetes work poolElastic scaling of pods
No infrastructure teamManaged or serverless poolProvider runs the compute
Strict data residencySelf-hosted server and workersMetadata and data stay internal
Choosing a Prefect execution setup

Limitations and common mistakes with Prefect

Prefect is not a general integration platform, and its main limitation is that it requires Python skills. Teams without developers usually gain more from visual automation tools. The framework has also changed considerably between major versions 1, 2 and 3, so older tutorials and code samples often fail on current releases.

  • Passing large data between tasks in memory instead of writing it to object storage, which inflates memory and slows result persistence.
  • Overusing tiny tasks, which adds orchestration overhead for steps that need no separate tracking.
  • Forgetting idempotency, so a retried task writes duplicate rows into a database.
  • Storing secrets in code rather than in blocks or an external secret manager.
  • Running no worker for a work pool, which leaves scheduled runs stuck in a late state.

Most of these problems share one root cause: treating orchestration as a replacement for sound pipeline design. Prefect records and retries work reliably, but it cannot make a non-idempotent operation safe to repeat.

The idea in brief

Prefect is a tool that keeps watch over automated jobs written in Python. A developer marks pieces of code as steps, and Prefect then runs them on a schedule, repeats them when they fail and shows what happened.

Think of it as a control tower for computer jobs. The planes are the programs, and the tower does not fly them. It decides when each one departs, notices when one is in trouble and keeps a log of every trip, so nobody has to check each job by hand.

A practical scenario

A data team at a mid-sized online retailer must refresh its sales reports every night. The pipeline downloads orders from a payment provider API, cleans the records, loads them into a cloud data warehouse and rebuilds about 40 summary tables. Previously, a cron job ran one long script, and when the payment API timed out, nobody noticed until managers saw empty dashboards in the morning.

The team rewrote the script as a Prefect flow with separate tasks for extraction, cleaning and loading. The extraction task received three retries with exponential backoff, the load step was made idempotent with merge statements, and a Kubernetes work pool ran the deployment at 02:00 each night. A notification sends a message to the on-call channel whenever a run ends in a Failed or Crashed state.

Within the first month, several API timeouts were resolved automatically by retries, and the one real failure, a schema change at the provider, was reported within minutes instead of hours. The result was reliable morning reports and a clear run history for every table.