Orchestration without a static DAG file
Prefect's central claim is that a workflow should be ordinary Python. You decorate functions, call them, and the runtime records the resulting task graph as it executes â which means branching on real data, looping over whatever a previous step returned, and composing subflows at run time are all native control flow rather than special operators. The graph is discovered, not declared.
That inversion has a consequence worth stating early: because the graph is discovered during execution, you cannot inspect a complete plan without running it. Airflow parses a file and shows you the whole DAG before anything happens; Prefect shows you what actually ran, when, and with which inputs. Teams with deeply branching, data-dependent logic usually prefer the former's simplicity, and teams whose workflows are scripts with retries usually prefer the latter.
By the end of this lesson you should be able to structure a flow with sensible task granularity, choose cache policies that prevent redundant work without hiding staleness, and decide how concurrency limits and tags map onto your infrastructure.
Flows, tasks, and where the boundaries belong
A flow is the unit of scheduling, state, and observability; a task is a unit of retry, caching, and logging. Getting the boundary right matters more than any configuration: tasks that are too fine-grained drown the run engine in state transitions, while tasks that are too coarse lose retry granularity, because one failure inside a two-hour task throws away all the work before it.
| Concept | Controls | Cost of getting it wrong |
|---|---|---|
| Flow | Scheduling, state, parameters, UI grouping | Too many flows means alert fatigue |
| Task | Retry, cache, timeout, logging | Fine granularity floods the run history |
| Subflow | Reuse and independent state | Deep nesting obscures the parent run |
| Parameter | Run-time inputs and defaults | Untyped parameters fail late and opaquely |
| Result | What is stored after a run | Large results bloat the state database |
| Cache policy | Whether a task re-executes | Aggressive caching hides stale inputs |
| Work pool | Where work executes | Misrouted work queues behind the wrong runner |
Two practical guidelines cover most situations. Make each task a step you would be willing to re-run alone, with inputs and outputs small enough to store. And keep I/O and compute in different tasks, so a slow network call can retry without re-running the expensive computation that preceded it.
A flow with retries, caching, and explicit results
The flow below pulls three sources, validates each, loads the merged result, and reports. Retries live on tasks, not on the flow, so a single flaky source does not restart the entire run; caching is keyed on the inputs, so re-running with unchanged upstream data skips the expensive extract.
from datetime import datetime, timedelta
from prefect import flow, task, get_run_logger
from prefect.tasks import task_input_hash
from prefect.cache_policies import TASK_CACHE_KEY
import pandas as pd
@task(retries=3, retry_delay_seconds=30, cache_key_fn=task_input_hash,
cache_expiration=timedelta(hours=6))
def extract(source: str, since: str) -> pd.DataFrame:
logger = get_run_logger()
frame = read_from_source(source, since)
logger.info("extracted %s rows from %s", len(frame), source)
return frame
@task(retries=2, retry_delay_seconds=10)
def validate(name: str, frame: pd.DataFrame) -> pd.DataFrame:
if frame.empty:
raise ValueError(f"{name} returned no rows")
null_rate = frame["amount"].isna().mean()
if null_rate > 0.05:
raise ValueError(f"{name} amount null rate {null_rate:.1%} exceeds 5%")
if (frame["amount"] < 0).any():
raise ValueError(f"{name} contains negative amounts")
return frame
@task
def merge(frames: list[pd.DataFrame]) -> pd.DataFrame:
merged = pd.concat(frames, ignore_index=True)
return merged.drop_duplicates(subset=["order_id"])
@task(log_prints=True)
def load(frame: pd.DataFrame, target: str) -> dict:
write_upsert(frame, target)
return {"rows": len(frame), "target": target}
@flow(name="daily-orders", log_prints=True)
def daily_orders(dt: str | None = None) -> dict:
day = dt or (datetime.utcnow() - timedelta(days=1)).date().isoformat()
frames = [extract(s, day) for s in ("erp", "shop", "pos")]
clean = [validate(s, f) for s, f in zip(("erp", "shop", "pos"), frames)]
result = load(merge(clean), target=f"orders_fact/{day}")
print(f"loaded {result['rows']} rows for {day}")
return result
if __name__ == "__main__":
daily_orders(dt="2026-01-12")
Read the configuration choices, not just the body. cache_expiration prevents a cache from becoming a permanent lie: hash-based keys make an identical call free, but a six-hour expiry ensures yesterday's extract does not still answer for today. Raising inside validate rather than returning a sentinel means the failure is a task state with a traceback in the UI, which is what you want at 03:00.
Mapping over whatever the data contains
Dynamic work is where the runtime graph pays for itself. Instead of computing a partition list in the DAG and hoping it matches reality, a flow reads the list from the source and maps over it, creating one child run per element with its own state, retries, and concurrency accounting.
from prefect import flow, task
from prefect.futures import wait
@task(retries=2)
def process_partition(partition: str) -> int:
frame = read_partition(partition)
transformed = apply_transform(frame)
write_partition(transformed, partition)
return len(transformed)
@task
def summarise(counts: list[int]) -> dict:
return {"partitions": len(counts), "total_rows": sum(counts)}
@flow(name="repartition-warehouse")
def repartition(source: str = "lake/raw/events") -> dict:
partitions = list_partitions(source) # discovered at run time
futures = [process_partition.submit(p) for p in partitions]
counts = [f.result() for f in futures] # raises on first hard failure
summary = summarise(counts)
print(summary)
return summary
@flow
def repartition_with_threshold(source: str, min_rows: int = 10_000) -> dict:
"""Skip empty partitions instead of paying the write cost."""
partitions = [p for p in list_partitions(source) if p.row_count > 0]
futures = [process_partition.submit(p.path) for p in partitions]
done, not_done = wait(futures, timeout=3600)
if not_done:
raise TimeoutError(f"{len(not_done)} partitions still running after an hour")
return summarise([f.result() for f in done])
The second version shows two habits worth copying. Filtering the work list before submitting avoids paying write cost for empty partitions, and wait with an explicit timeout converts an unbounded hang into a defined failure. Both are ordinary Python, which is the entire argument for this style of orchestration.
Concurrency, tags, and where work runs
Concurrency in Prefect is layered. A deployment carries a global limit, tags can carry per-tag limits, and the work pool decides which infrastructure receives the run at all. The design question is which resource you are actually protecting: a database connection pool, a licence, an API rate limit, or a cluster's memory.
Tags are the tool for expressing that. Tag a task set with warehouse and give the tag a limit of four, and no matter how many flows run, four warehouse operations happen at once â including across flows that never knew about each other. This is the correct place to protect a fragile dependency, because the constraint survives changes to individual flows.
Work pools separate intent from infrastructure. A flow deployed to a kubernetes-pool runs on cluster jobs, the same flow pointed at a process-pool runs as a local process, and switching is a deployment setting rather than a code change. That separation is what makes promoting from a laptop to staging to production a configuration edit.
Prefect or Airflow?
Neither is universally right, and the honest comparison is about where you want the control plane. Airflow keeps a declarative, parseable description of every future run, which suits organisations that need to review planned work, backfill on a schedule, and enforce structure across many teams. Prefect keeps the result of work that actually happened, which suits teams whose workflows are Python programs that need branching, dynamic inputs, and minimal infrastructure.
| Concern | Prefect | Airflow |
|---|---|---|
| Workflow description | Python functions, discovered graph | Parsed DAG file, declared graph |
| Branching on data | Native control flow | Branch operator plus join rules |
| Dynamic inputs | Submit per element at runtime | Dynamic task mapping |
| Scheduler model | Event-driven runs | Interval-based scheduling with catchup |
| Infrastructure | Work pools, any runner | Executors: local, Celery, Kubernetes |
| Backfills | Manual or parameterised | First-class, date range based |
| UI emphasis | Run history and task states | DAG plan, grid, and calendar |
The migration signal is usually one of two sentences. If your team says "we keep fighting the parser" or "our DAG is mostly Python logic with operator wrappers", Prefect will feel like relief. If you say "we need auditable plans and date-based backfills across fifty pipelines", Airflow's rigidity is the feature.
Deploying flows that survive restarts
A flow that only runs from a developer laptop is a demo. Production means a deployment with a stored definition, parameters, a work pool, and a trigger â either a schedule, an event, or an API call. Keep the flow code in version control, register deployments through CI so the running definition matches a commit, and store results in a database rather than on the runner's disk.
Failure handling closes the loop. Retries at the task level cover transient faults; flow-level state tells you whether the run succeeded, failed, or crashed mid-flight; and a notification hook on terminal failure routes to the team that owns the flow. Test the restart path deliberately: kill a worker mid-run and confirm the flow lands in a clear state rather than half-finished and silent.
đĄStart with fewer tasks than you think
A flow with four well-chosen tasks is easier to operate than one with forty micro-tasks. Split further only when you need independent retry or caching behaviour â granularity is a tool for failure isolation, not a style preference.
Common Mistakes
Creating a task for every line of work, flooding the run history
Fix: Split only where retry, cache, or timeout behaviour genuinely differs
Caching with no expiration, so a task answers from stale inputs forever
Fix: Set a cache expiration alongside the hash key so freshness has a bounded cost
Retrying at flow level and restarting the whole run on one flaky call
Fix: Put retries on the task that can actually succeed on a second attempt
Leaving concurrency protection in a single flow's code
Fix: Express shared limits as tag-based limits so every flow respects them
Best Practices
- Keep flow code in version control and register deployments from CI
- Return small, serialisable results and push large frames to storage by reference
- Use parameters with defaults so manual runs are one command
- Set tag-based concurrency limits on the dependencies that are actually fragile
- Rehearse worker failure and confirm the run ends in a clear, visible state
Interview Questions
Q1: How does Prefect discover a workflow graph?
At runtime, as decorated tasks are called; the executed call structure becomes the run graph rather than a pre-parsed declaration.
Q2: When is caching dangerous?
When the cache key does not capture every input that affects the output, or when there is no expiration, so stale results answer indefinitely.
Q3: Where should concurrency limits live?
On the shared resource, expressed as a tag or pool limit, so independent flows cannot exceed the constraint.
Q4: Prefect or Airflow for date-based backfills across many teams?
Airflow, because interval scheduling, catchup, and backfill ranges are first-class and auditable.
Key Takeaways
- Prefect runs ordinary Python and derives the graph from execution, enabling native branching and dynamic loops
- Task granularity is a failure-isolation decision: split where retry or caching behaviour differs
- Hash-based cache keys with an expiration prevent redundant work without hiding staleness
- Tag-based concurrency limits protect shared dependencies across all flows at once
- Deployments, work pools, and version-controlled registration are what separate a demo from a production workflow