πŸ“Š Data Engineering

Prefect

Prefect

Modern workflow orchestration. Python-native.

Detailed Explanation

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.

Code Example

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 μ„œλ²„ μ‹œμž‘

How It's Said in Practice

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()."

Cautions

Learn More