๐Ÿ“Š Data Engineering

Dagster

Dagster

A data pipeline orchestrator. Software-defined assets.

Detailed Explanation

Dagster is a modern data pipeline orchestrator that innovates data engineering through the "Software-Defined Assets" paradigm. While traditional workflow orchestrators are designed around "tasks," Dagster defines pipelines around "assets," that is, data products.

The advantage of the asset-centric approach is that data lineage is tracked naturally. Because the code explicitly declares which upstream assets each asset depends on, change impact analysis, incremental runs, and backfills are supported automatically. The Asset Graph in the Dagster UI visually shows the structure of the entire data platform, which also helps with data discovery.

Dagster's core concepts include Assets, Resources, Sensors, and Schedules. Assets represent data products (tables, files, ML models, etc.), and Resources abstract connections to external systems (databases, cloud services). Sensors trigger pipelines in response to external events (a new file arriving, an API call), and Schedules manage time-based runs.

Dagster prioritizes developer experience. It validates data contracts through its type system, gives instant feedback with a local development server, and makes pipeline testing easy with pytest integration. It offers rich integrations with dbt, Spark, Snowflake, AWS, GCP, and more, so it is easy to introduce into an existing data stack.

Code Example

# Dagster Asset ๊ธฐ๋ฐ˜ ํŒŒ์ดํ”„๋ผ์ธ ์˜ˆ์ œ
from dagster import (
    asset, AssetIn, AssetKey, AssetExecutionContext,
    Definitions, ScheduleDefinition, define_asset_job,
    DailyPartitionsDefinition, MetadataValue, Output,
    ConfigurableResource, MaterializeResult
)
from dagster_dbt import DbtCliResource, dbt_assets
import pandas as pd
from datetime import datetime

# ============================================
# 1. ๊ธฐ๋ณธ Asset ์ •์˜
# ============================================

@asset(
    description="์™ธ๋ถ€ API์—์„œ ์›์‹œ ์‚ฌ์šฉ์ž ๋ฐ์ดํ„ฐ ์ˆ˜์ง‘",
    group_name="raw_data",
    compute_kind="python",
)
def raw_users(context: AssetExecutionContext) -> pd.DataFrame:
    """์‚ฌ์šฉ์ž ๋ฐ์ดํ„ฐ ์ˆ˜์ง‘ ์ž์‚ฐ"""
    # ์‹ค์ œ๋กœ๋Š” API ํ˜ธ์ถœ ๋˜๋Š” ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ์ฟผ๋ฆฌ
    users = pd.DataFrame({
        'user_id': [1, 2, 3, 4, 5],
        'name': ['Alice', 'Bob', 'Charlie', 'David', 'Eve'],
        'email': ['alice@example.com', 'bob@example.com',
                  'charlie@example.com', 'david@example.com', 'eve@example.com'],
        'signup_date': pd.to_datetime(['2024-01-01', '2024-01-02',
                                        '2024-01-03', '2024-01-04', '2024-01-05']),
        'country': ['US', 'UK', 'US', 'DE', 'FR']
    })

    context.log.info(f"์ˆ˜์ง‘๋œ ์‚ฌ์šฉ์ž ์ˆ˜: {len(users)}")

    # ๋ฉ”ํƒ€๋ฐ์ดํ„ฐ ๊ธฐ๋ก
    return Output(
        value=users,
        metadata={
            "row_count": len(users),
            "columns": list(users.columns),
            "preview": MetadataValue.md(users.head().to_markdown())
        }
    )

@asset(
    description="์™ธ๋ถ€ ์‹œ์Šคํ…œ์—์„œ ์ฃผ๋ฌธ ๋ฐ์ดํ„ฐ ์ˆ˜์ง‘",
    group_name="raw_data",
    compute_kind="python",
)
def raw_orders(context: AssetExecutionContext) -> pd.DataFrame:
    """์ฃผ๋ฌธ ๋ฐ์ดํ„ฐ ์ˆ˜์ง‘ ์ž์‚ฐ"""
    orders = pd.DataFrame({
        'order_id': range(1, 11),
        'user_id': [1, 2, 1, 3, 4, 2, 5, 1, 3, 4],
        'product_id': ['P001', 'P002', 'P001', 'P003', 'P001',
                       'P002', 'P003', 'P002', 'P001', 'P003'],
        'amount': [100, 200, 150, 300, 100, 250, 350, 200, 150, 400],
        'order_date': pd.date_range('2024-01-01', periods=10, freq='D')
    })

    return Output(
        value=orders,
        metadata={
            "row_count": len(orders),
            "total_revenue": float(orders['amount'].sum())
        }
    )

# ============================================
# 2. ์˜์กด์„ฑ์ด ์žˆ๋Š” Asset
# ============================================

@asset(
    ins={
        "raw_users": AssetIn(),
        "raw_orders": AssetIn()
    },
    description="์‚ฌ์šฉ์ž ์ฃผ๋ฌธ ํ†ต๊ณ„ ์ง‘๊ณ„",
    group_name="analytics",
    compute_kind="pandas",
)
def user_order_stats(
    context: AssetExecutionContext,
    raw_users: pd.DataFrame,
    raw_orders: pd.DataFrame
) -> pd.DataFrame:
    """์‚ฌ์šฉ์ž๋ณ„ ์ฃผ๋ฌธ ํ†ต๊ณ„"""

    # ์ฃผ๋ฌธ ์ง‘๊ณ„
    order_stats = raw_orders.groupby('user_id').agg({
        'order_id': 'count',
        'amount': ['sum', 'mean']
    }).reset_index()

    order_stats.columns = ['user_id', 'order_count', 'total_spent', 'avg_order_value']

    # ์‚ฌ์šฉ์ž ์ •๋ณด์™€ ์กฐ์ธ
    result = pd.merge(raw_users, order_stats, on='user_id', how='left')
    result = result.fillna(0)

    context.log.info(f"์ฒ˜๋ฆฌ๋œ ์‚ฌ์šฉ์ž ์ˆ˜: {len(result)}")

    return Output(
        value=result,
        metadata={
            "row_count": len(result),
            "users_with_orders": int((result['order_count'] > 0).sum()),
            "total_revenue": float(result['total_spent'].sum())
        }
    )

# ============================================
# 3. ํŒŒํ‹ฐ์…˜๋œ Asset
# ============================================

daily_partitions = DailyPartitionsDefinition(
    start_date="2024-01-01",
    end_date="2024-12-31"
)

@asset(
    partitions_def=daily_partitions,
    description="์ผ๋ณ„ ์ด๋ฒคํŠธ ๋ฐ์ดํ„ฐ",
    group_name="raw_data",
)
def daily_events(context: AssetExecutionContext) -> pd.DataFrame:
    """ํŒŒํ‹ฐ์…˜ ํ‚ค(๋‚ ์งœ)์— ํ•ด๋‹นํ•˜๋Š” ์ด๋ฒคํŠธ ์ˆ˜์ง‘"""
    partition_date = context.partition_key

    context.log.info(f"Processing partition: {partition_date}")

    # ์‹ค์ œ๋กœ๋Š” ํ•ด๋‹น ๋‚ ์งœ์˜ ๋ฐ์ดํ„ฐ๋งŒ ์กฐํšŒ
    events = pd.DataFrame({
        'event_id': range(100),
        'event_date': partition_date,
        'user_id': [i % 10 for i in range(100)],
        'event_type': ['click', 'view', 'purchase'] * 33 + ['click']
    })

    return events

@asset(
    partitions_def=daily_partitions,
    ins={"daily_events": AssetIn()},
    description="์ผ๋ณ„ ์ด๋ฒคํŠธ ์ง‘๊ณ„",
    group_name="analytics",
)
def daily_event_metrics(
    context: AssetExecutionContext,
    daily_events: pd.DataFrame
) -> pd.DataFrame:
    """์ผ๋ณ„ ์ด๋ฒคํŠธ ๋ฉ”ํŠธ๋ฆญ ๊ณ„์‚ฐ"""
    metrics = daily_events.groupby('event_type').size().reset_index(name='count')
    metrics['date'] = context.partition_key

    return metrics

# ============================================
# 4. Resource๋ฅผ ์‚ฌ์šฉํ•œ ์™ธ๋ถ€ ์‹œ์Šคํ…œ ์—ฐ๋™
# ============================================

class DatabaseResource(ConfigurableResource):
    """๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ์—ฐ๊ฒฐ ๋ฆฌ์†Œ์Šค"""
    host: str
    port: int = 5432
    database: str
    user: str
    password: str

    def get_connection(self):
        # ์‹ค์ œ๋กœ๋Š” psycopg2 ๋“ฑ์œผ๋กœ ์—ฐ๊ฒฐ
        return f"postgresql://{self.user}@{self.host}:{self.port}/{self.database}"

    def execute_query(self, query: str) -> pd.DataFrame:
        # ์‹ค์ œ๋กœ๋Š” ์ฟผ๋ฆฌ ์‹คํ–‰
        return pd.DataFrame()

@asset(
    description="๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์—์„œ ๊ณ ๊ฐ ์„ธ๊ทธ๋จผํŠธ ๋กœ๋“œ",
    group_name="segments",
)
def customer_segments(
    context: AssetExecutionContext,
    database: DatabaseResource
) -> pd.DataFrame:
    """๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์—์„œ ๊ณ ๊ฐ ์„ธ๊ทธ๋จผํŠธ ์ •๋ณด ๊ฐ€์ ธ์˜ค๊ธฐ"""
    conn_string = database.get_connection()
    context.log.info(f"Connecting to: {conn_string}")

    # ์‹ค์ œ๋กœ๋Š” ์ฟผ๋ฆฌ ์‹คํ–‰
    return pd.DataFrame({
        'user_id': [1, 2, 3],
        'segment': ['VIP', 'Regular', 'New']
    })

# ============================================
# 5. dbt ํ†ตํ•ฉ
# ============================================

"""
# dbt ํ”„๋กœ์ ํŠธ๊ฐ€ ์žˆ๋Š” ๊ฒฝ์šฐ
from pathlib import Path

dbt_project_dir = Path(__file__).parent / "dbt_project"

@dbt_assets(
    manifest=dbt_project_dir / "target" / "manifest.json",
)
def my_dbt_assets(context: AssetExecutionContext, dbt: DbtCliResource):
    yield from dbt.cli(["build"], context=context).stream()
"""

# ============================================
# 6. Sensor ์ •์˜
# ============================================

from dagster import sensor, RunRequest, SensorEvaluationContext

@sensor(
    job_name="process_new_files_job",
    minimum_interval_seconds=60
)
def new_file_sensor(context: SensorEvaluationContext):
    """์ƒˆ ํŒŒ์ผ์ด ๋„์ฐฉํ•˜๋ฉด ํŒŒ์ดํ”„๋ผ์ธ ํŠธ๋ฆฌ๊ฑฐ"""
    # ์‹ค์ œ๋กœ๋Š” S3, GCS ๋“ฑ ํ™•์ธ
    new_files = ["file1.csv", "file2.csv"]  # ์˜ˆ์‹œ

    for file in new_files:
        yield RunRequest(
            run_key=f"file_{file}",
            run_config={
                "ops": {
                    "process_file": {
                        "config": {"file_path": file}
                    }
                }
            }
        )

# ============================================
# 7. Job๊ณผ Schedule ์ •์˜
# ============================================

# Asset ๊ธฐ๋ฐ˜ Job
daily_analytics_job = define_asset_job(
    name="daily_analytics_job",
    selection=["raw_users", "raw_orders", "user_order_stats"],
    description="์ผ๋ณ„ ๋ถ„์„ ๋ฐ์ดํ„ฐ ๊ฐฑ์‹ "
)

# Schedule
daily_analytics_schedule = ScheduleDefinition(
    name="daily_analytics_schedule",
    job=daily_analytics_job,
    cron_schedule="0 6 * * *",  # ๋งค์ผ ์˜ค์ „ 6์‹œ
    execution_timezone="Asia/Seoul"
)

# ============================================
# 8. Definitions (ํ”„๋กœ์ ํŠธ ์ง„์ž…์ )
# ============================================

defs = Definitions(
    assets=[
        raw_users,
        raw_orders,
        user_order_stats,
        daily_events,
        daily_event_metrics,
        customer_segments,
    ],
    resources={
        "database": DatabaseResource(
            host="localhost",
            database="analytics",
            user="dagster",
            password="secret"
        )
    },
    schedules=[daily_analytics_schedule],
    sensors=[new_file_sensor],
    jobs=[daily_analytics_job]
)

How it is used in practice

Data engineer: "Our Airflow DAGs have become too complex and dependency management has gotten hard. The integration with dbt models isn't clean either."

Tech lead: "If we switch to Dagster, we can structure things around Assets. Each table becomes an Asset, and dependencies are declared explicitly in code, so lineage is tracked automatically too."

Data engineer: "How does it integrate with dbt?"

Tech lead: "With the dagster-dbt library, you can automatically convert dbt models into Dagster Assets. If you manage Python preprocessing and dbt transformations in a single Asset Graph, the whole pipeline is visible at a glance."

Interviewer: "How does Dagster's concept of Software-Defined Assets differ from traditional workflow orchestrators?"

Candidate: "Traditional orchestrators are designed around 'tasks' and focus on 'what to run.' Dagster's Software-Defined Assets, on the other hand, focus on 'what to produce.' Each Asset represents a data product (a table, file, or ML model), and dependencies are defined declaratively. As a result, data lineage is tracked automatically, and incremental runs and backfills are supported naturally. The Asset Catalog feature also enables data discovery."

Take a mock interview on this topic โ†’ WIA SOOM AI Interview ยท Start for free

Reviewer: "You're creating the DB connection directly in the Asset; it would be better to separate it into a Resource."

Developer: "Why should I use a Resource?"

Reviewer: "It's easy to swap with a mock when testing, and you can inject different configurations per environment. For example, you just change the Resource to use SQLite locally and PostgreSQL in production. It also improves code reusability."

Cautions

Related Terms

Learn More