Prefect
Prefect
Modern workflow orchestration. Python-native.
Prefect
Modern workflow orchestration. Python-native.
Prefect is a modern workflow orchestration tool developed by the company of the same name, founded in 2018. Under the philosophy of minimizing "Negative Engineering," it automates error handling, retries, and logging so that data engineers can focus on business logic.
The @flow and @task decorators are the core. Adding a decorator to a regular Python function turns it into a workflow. A Flow represents the entire workflow and a Task represents an individual unit of work, and dependencies between Tasks are automatically inferred from the order of function calls.
Prefect 2.0 (the current version) is greatly simplified compared to Prefect 1.x. You do not need to define a DAG explicitly; you write it like regular Python code. The cloud UI lets you monitor workflows, set up scheduling, and configure alerts, and local execution works without a server as well.
Retries (retries), caching (cache_key_fn), timeouts (timeout_seconds), and concurrency control (concurrency_limits) are configured at the Task level. Parallel processing is possible through Dask and Ray integration, and you can deploy to various environments such as Docker, Kubernetes, and AWS ECS.
from prefect import flow, task, get_run_logger
from prefect.tasks import task_input_hash
from datetime import timedelta
import httpx
import pandas as pd
# Task μ μ - μ¬μλ, μΊμ± μ€μ
@task(
retries=3,
retry_delay_seconds=60,
cache_key_fn=task_input_hash,
cache_expiration=timedelta(hours=1)
)
def extract_data(url: str) -> dict:
"""APIμμ λ°μ΄ν° μΆμΆ"""
logger = get_run_logger()
logger.info(f"Fetching data from {url}")
response = httpx.get(url, timeout=30)
response.raise_for_status()
return response.json()
@task
def transform_data(raw_data: dict) -> pd.DataFrame:
"""λ°μ΄ν° λ³ν"""
logger = get_run_logger()
df = pd.DataFrame(raw_data['results'])
# λ°μ΄ν° μ μ
df['created_at'] = pd.to_datetime(df['created_at'])
df['value'] = df['value'].fillna(0)
logger.info(f"Transformed {len(df)} rows")
return df
@task(timeout_seconds=300)
def load_data(df: pd.DataFrame, destination: str) -> int:
"""λ°μ΄ν° μ μ¬"""
logger = get_run_logger()
# μ€μ λ‘λ DB, S3 λ±μ μ μ₯
df.to_parquet(destination)
logger.info(f"Saved {len(df)} rows to {destination}")
return len(df)
# Flow μ μ
@flow(
name="ETL Pipeline",
description="Daily data extraction and loading",
version="1.0.0"
)
def etl_pipeline(
api_url: str = "https://api.example.com/data",
output_path: str = "data/output.parquet"
):
"""λ©μΈ ETL μν¬νλ‘μ°"""
logger = get_run_logger()
logger.info("Starting ETL pipeline")
# Task μ€ν - μμ‘΄μ± μλ μΆλ‘
raw_data = extract_data(api_url)
transformed_df = transform_data(raw_data)
rows_loaded = load_data(transformed_df, output_path)
logger.info(f"Pipeline completed: {rows_loaded} rows processed")
return rows_loaded
# λ‘컬 μ€ν
if __name__ == "__main__":
etl_pipeline()
# μ€μΌμ€λ§ μ€μ (λ°°ν¬ μ)
# from prefect.deployments import Deployment
# from prefect.server.schemas.schedules import CronSchedule
#
# deployment = Deployment.build_from_flow(
# flow=etl_pipeline,
# name="daily-etl",
# schedule=CronSchedule(cron="0 2 * * *"), # λ§€μΌ μλ²½ 2μ
# work_queue_name="default"
# )
# deployment.apply()
# λ³λ ¬ μ²λ¦¬ (μ¬λ¬ μμ€ λμ μΆμΆ)
@flow
def parallel_etl():
sources = ["https://api1.example.com", "https://api2.example.com"]
# λ³λ ¬ μ€ν
futures = [extract_data.submit(url) for url in sources]
results = [f.result() for f in futures]
return results
# CLI μ€ν
# prefect deployment run "ETL Pipeline/daily-etl"
# prefect server start # UI μλ² μμ
Senior: "If you use Prefect instead of Airflow, you can use Python functions as they are, without defining a DAG. The learning curve is much lower."
Junior: "How do I do scheduling?"
Senior: "When you create a Deployment, just attach a CronSchedule or IntervalSchedule. You can monitor in the Prefect Cloud UI, and manual triggers are possible too."
Interviewer: "Do you have experience with data pipeline orchestration?"
Candidate: "I managed more than 100 ETL Jobs per day with Prefect. I implemented failure recovery and duplicate-execution prevention with @task's retries and cache_key_fn, and I integrated failure alerts from Prefect Cloud into Slack. Visibility and error handling improved significantly compared to the previous Cron scripts."
Take a mock interview on this topic β WIA SOOM AI Interview Β· Start for free
Reviewer: "Please add timeout_seconds to the Task. If an API call waits indefinitely, the entire pipeline stalls."
Developer: "Yes, I'll set retries=3 and timeout_seconds=60. I'll also switch the logging to get_run_logger()."