🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Prefect Flows: Dynamic Orchestration and Caching

Data Pipelines & OrchestrationPipeline EngineeringđŸŸĸ Free Lesson

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.

ConceptControlsCost of getting it wrong
FlowScheduling, state, parameters, UI groupingToo many flows means alert fatigue
TaskRetry, cache, timeout, loggingFine granularity floods the run history
SubflowReuse and independent stateDeep nesting obscures the parent run
ParameterRun-time inputs and defaultsUntyped parameters fail late and opaquely
ResultWhat is stored after a runLarge results bloat the state database
Cache policyWhether a task re-executesAggressive caching hides stale inputs
Work poolWhere work executesMisrouted 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.

python
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.

python
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.

ConcernPrefectAirflow
Workflow descriptionPython functions, discovered graphParsed DAG file, declared graph
Branching on dataNative control flowBranch operator plus join rules
Dynamic inputsSubmit per element at runtimeDynamic task mapping
Scheduler modelEvent-driven runsInterval-based scheduling with catchup
InfrastructureWork pools, any runnerExecutors: local, Celery, Kubernetes
BackfillsManual or parameterisedFirst-class, date range based
UI emphasisRun history and task statesDAG 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
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-13

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Data Engineering Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement