Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 5 of 6 · Worked example · 20 min · revision 2

The Asset-Centric Alternative: Dagster

Rebuild the orders pipeline as Dagster software-defined assets with daily partitions, materialize one day and a 14-day range from the command line, check the result with an asset check and a schedule test, and confirm it matches the Airflow backfill row for row. Then compare the two models and decide when each one fits.

Contentsand lesson path

What you will learn

  • Compare task-centric and asset-centric orchestration (Airflow and Dagster as examples) and run an orchestrator locally with containers.

Prerequisites: ETL/ELT Pipeline Design

01. The problem

In the Airflow labs you described the pipeline as tasks: extract, then transform, then load. The table it produced, region_revenue, never appeared in the graph; Airflow knew that load succeeded, not what it wrote. Dagster starts from the other end. You declare the data products, called assets, and how each one is computed from others, and Dagster works out what to run. This lesson rebuilds the same pipeline that way, with the same seeded orders, and checks that the result is identical to the Airflow backfill from the backfill lesson.

Use a separate folder and virtual environment, because Airflow and Dagster pin different versions of shared libraries. The lesson was tested with dagster 1.13.30, the dg command-line tool from dagster-dg-cli 1.13.30 and DuckDB 1.5.6 as the warehouse. DAGSTER_HOME is the folder where Dagster's instance keeps run history and the event log of every materialization; the empty dagster.yaml tells it to use the defaults, which store everything in SQLite files in that folder.

Terminal, inside orchestration-lab
mkdir dagster-lab && cd dagster-lab
uv venv --python 3.12 .venv
uv pip install --python .venv/bin/python \
  "dagster==1.13.30" "dagster-dg-cli==1.13.30" "duckdb==1.5.6"
Terminal, inside dagster-lab
source .venv/bin/activate
export DAGSTER_HOME="$PWD/dagster_home"     # run history and event log live here
mkdir -p "$DAGSTER_HOME" && touch "$DAGSTER_HOME/dagster.yaml"
dg --version
Expected output
dg, version 1.13.30

02. Step 1: Declare the assets

Save the definitions below as defs.py. Each @dg.asset function is a software-defined asset: the code that produces one data product, named after the function. deps=[raw_orders] says that region_revenue is computed from raw_orders; that is the only edge, and it is an edge between data, not between steps.

Python · defs.py
"""The orders pipeline as Dagster software-defined assets."""
import json
import random
from pathlib import Path

import dagster as dg
import duckdb

DATA = Path("data")
WAREHOUSE = "warehouse.duckdb"
REGIONS = ["north", "south", "west"]
daily = dg.DailyPartitionsDefinition(start_date="2026-11-01", end_date="2026-11-15")
one_run = dg.BackfillPolicy.single_run()  # a range of days runs as one run


@dg.asset(partitions_def=daily, backfill_policy=one_run)
def raw_orders(context: dg.AssetExecutionContext) -> dg.MaterializeResult:
    """One JSON Lines file per region and day, as the shop API returns it."""
    orders = 0
    for day in context.partition_keys:          # one key, or a whole range
        for region in REGIONS:
            rng = random.Random(f"{day}/{region}")  # the same seed as the Airflow lab
            rows = [{"order_id": f"{region[0]}{day[5:7]}{day[8:]}-{i}",
                     "amount": round(rng.uniform(5, 120), 2)}
                    for i in range(rng.randint(20, 40))]
            out = DATA / "raw" / f"day={day}" / f"{region}.jsonl"
            out.parent.mkdir(parents=True, exist_ok=True)
            out.write_text("".join(json.dumps(r) + "\n" for r in rows))
            orders += len(rows)
    return dg.MaterializeResult(metadata={"days": len(context.partition_keys),
                                          "orders": orders})


@dg.asset(partitions_def=daily, backfill_policy=one_run, deps=[raw_orders])
def region_revenue(context: dg.AssetExecutionContext) -> dg.MaterializeResult:
    """Orders and revenue per region and day; a run replaces exactly its own days."""
    start, end = context.partition_time_window
    window = [start.date(), end.date()]
    with duckdb.connect(WAREHOUSE) as con:
        con.execute("""CREATE TABLE IF NOT EXISTS region_revenue (
            day DATE, region TEXT, orders INT, revenue DECIMAL(10, 2))""")
        con.execute("BEGIN")
        con.execute("DELETE FROM region_revenue WHERE day >= ? AND day < ?", window)
        con.execute("""
            INSERT INTO region_revenue
            SELECT day, regexp_extract(filename, '(\\w+)\\.jsonl$', 1),
                   count(*), round(sum(amount), 2)
            FROM read_json('data/raw/*/*.jsonl', hive_partitioning = true,
                           filename = true)
            WHERE day >= ? AND day < ?
            GROUP BY ALL""", window)
        con.execute("COMMIT")
        rows = con.execute("SELECT count(*) FROM region_revenue "
                           "WHERE day >= ? AND day < ?", window).fetchone()[0]
    return dg.MaterializeResult(metadata={"rows_written": rows})


@dg.asset_check(asset=region_revenue)
def three_regions_per_day() -> dg.AssetCheckResult:
    """Every day in the table must have exactly one row per region."""
    with duckdb.connect(WAREHOUSE, read_only=True) as con:
        bad = con.execute("""SELECT count(*) FROM (SELECT day FROM region_revenue
                             GROUP BY day HAVING count(*) <> 3)""").fetchone()[0]
    return dg.AssetCheckResult(passed=bad == 0, metadata={"bad_days": bad})


daily_job = dg.define_asset_job("daily_orders", selection=[raw_orders, region_revenue])
defs = dg.Definitions(
    assets=[raw_orders, region_revenue],
    asset_checks=[three_regions_per_day],
    jobs=[daily_job],
    schedules=[dg.build_schedule_from_partitioned_job(daily_job)],  # daily at 00:00
)
  • Partitions replace data intervals. DailyPartitionsDefinition gives both assets one partition per day, keyed 2026-11-01 to 2026-11-14 (the end_date is exclusive). A run receives partition keys, never the clock, so the same rule as in Airflow holds: the code processes the days it is given.
  • A range can run as one run. By default a backfill of fourteen partitions launches fourteen runs. BackfillPolicy.single_run() asks for one run over the whole range, which suits engines that handle a range in one query. The code then reads context.partition_keys or context.partition_time_window instead of a single key. Dagster 1.13.30 marks this parameter as beta and prints a warning.
  • The write is idempotent. region_revenue deletes and reinserts exactly the days in its time window inside one transaction, like the Airflow load task.
  • The check is part of the asset. @dg.asset_check attaches a data test to region_revenue; it runs after the asset in the same run, and its result is stored next to the materialization.
  • The schedule comes from the partitions. build_schedule_from_partitioned_job creates a daily schedule that requests the most recent complete partition at each tick.

03. Step 2: Materialize one partition

To materialize an asset is to run its function and store the result. dg launch loads defs.py, starts a run for the selected assets and partition in this terminal, and records it in the instance. Then save the two helper scripts: status.py asks the instance what it knows, and query.py summarises the table with the same fingerprint as check.sql in the backfill lesson.

Python · status.py
"""What does Dagster know about each asset? Read it from the instance."""
import dagster as dg

instance = dg.DagsterInstance.get()  # the instance in $DAGSTER_HOME
for name in ["raw_orders", "region_revenue"]:
    records = instance.fetch_materializations(
        dg.AssetRecordsFilter(asset_key=dg.AssetKey(name)), limit=100).records
    days = sorted({r.partition_key for r in records})
    print(f"{name}: {len(records)} materializations, {len(days)} partitions "
          f"({days[0]} .. {days[-1]})")
check = instance.get_latest_asset_check_evaluation_record(
    dg.AssetCheckKey(dg.AssetKey("region_revenue"), "three_regions_per_day"))
passed = check.event.asset_check_evaluation.passed
print("latest check three_regions_per_day:", "passed" if passed else "failed")
Python · query.py
"""Summarise the warehouse table, with the same fingerprint as the Airflow lab."""
import duckdb

with duckdb.connect("warehouse.duckdb", read_only=True) as con:
    print(con.sql("""
        SELECT count(*) AS rows, count(DISTINCT day) AS days, sum(revenue) AS revenue,
               left(md5(string_agg(day || region || orders || revenue, ','
                                   ORDER BY day, region)), 12) AS fingerprint
        FROM region_revenue"""))
Terminal, inside dagster-lab
dg launch -f defs.py --assets raw_orders,region_revenue --partition 2026-11-02 \
  2>&1 | grep -o 'RUN_SUCCESS.*'
python -W ignore status.py
python query.py
Expected output
RUN_SUCCESS - Finished execution of run for "__ASSET_JOB".
raw_orders: 1 materializations, 1 partitions (2026-11-02 .. 2026-11-02)
region_revenue: 1 materializations, 1 partitions (2026-11-02 .. 2026-11-02)
latest check three_regions_per_day: passed
┌───────┬───────┬───────────────┬──────────────┐
│ rows  │ days  │    revenue    │ fingerprint  │
│ int64 │ int64 │ decimal(38,2) │   varchar    │
├───────┼───────┼───────────────┼──────────────┤
│     3 │     1 │       4749.05 │ 5b505e548911 │
└───────┴───────┴───────────────┴──────────────┘

The run materialized one partition of each asset, and the check passed. Dagster keeps this per partition, so it can show which days of region_revenue exist and which are missing.

04. Step 3: Backfill fourteen partitions in one run

Now fill 1 to 14 November. --partition-range takes the first and last key, both inclusive, and because both assets use the single-run policy the whole range is one run. 2 November is rewritten too, which is safe because the write is idempotent.

Terminal, inside dagster-lab
dg launch -f defs.py --assets raw_orders,region_revenue \
  --partition-range 2026-11-01...2026-11-14 2>&1 | grep -o 'RUN_SUCCESS.*'
python -W ignore status.py
python query.py
Expected output
RUN_SUCCESS - Finished execution of run for "__ASSET_JOB".
raw_orders: 15 materializations, 14 partitions (2026-11-01 .. 2026-11-14)
region_revenue: 15 materializations, 14 partitions (2026-11-01 .. 2026-11-14)
latest check three_regions_per_day: passed
┌───────┬───────┬───────────────┬──────────────┐
│ rows  │ days  │    revenue    │ fingerprint  │
│ int64 │ int64 │ decimal(38,2) │   varchar    │
├───────┼───────┼───────────────┼──────────────┤
│    42 │    14 │      78193.33 │ 7b0b3f2ea93d │
└───────┴───────┴───────────────┴──────────────┘

Fifteen materialization events (one from step 2, fourteen from this run) cover fourteen partitions. The row count, revenue and fingerprint 7b0b3f2ea93d are exactly what Airflow's backfill wrote to PostgreSQL in the backfill lesson: two orchestrators, two warehouses, the same data, because both take their dates from the run and replace whole partitions.

05. Step 4: Test the schedule and the check in-process

Dagster definitions are plain Python objects, so you can test them without any running service. test_defs.py asks the schedule which partition it would request at midnight on 15 November, then materializes one partition with dg.materialize, which uses a temporary in-memory instance, the usual way to write unit tests for assets.

Python · test_defs.py
"""Quick checks that run in-process, the way you would write unit tests."""
from datetime import datetime, timezone

import dagster as dg

from defs import defs, raw_orders, region_revenue, three_regions_per_day

# 1. Which partition does the schedule request at midnight on 15 November?
schedule = defs.get_schedule_def("daily_orders_schedule")
tick = datetime(2026, 11, 15, 0, 0, tzinfo=timezone.utc)
context = dg.build_schedule_context(scheduled_execution_time=tick)
requests = schedule.evaluate_tick(context).run_requests
print(schedule.cron_schedule, "->", [r.partition_key for r in requests])

# 2. Materialize one partition in-process (an ephemeral instance keeps no history).
result = dg.materialize([raw_orders, region_revenue, three_regions_per_day],
                        partition_key="2026-11-03")
print("success:", result.success)
for evaluation in result.get_asset_check_evaluations():
    print("check", evaluation.check_name, "passed:", evaluation.passed)
Terminal, inside dagster-lab
python -W ignore test_defs.py 2>/dev/null
Expected output
0 0 * * * -> ['2026-11-14']
success: True
check three_regions_per_day passed: True

At 00:00 on 15 November the schedule asks for 14 November, the last complete day: the same "run after the interval ends" rule as Airflow's data-interval timetable. To run the schedule for real you start Dagster's UI and its daemon, the process that evaluates schedules, sensors and automation conditions; dg dev starts both for local development, and the Dagster documentation describes a Docker Compose deployment with the webserver, the daemon and your code in separate containers. For downstream assets you can also set automation_condition=dg.AutomationCondition.eager(), which asks Dagster to materialize an asset soon after its upstream assets change.

06. Step 5: Compare the two models

Both tools ran the same pipeline, with the same idempotent writes and the same result. They differ in what the model puts first.

  • Unit of the graph. Airflow's nodes are tasks; Dagster's are assets. Because Dagster knows the assets, its UI shows lineage across pipelines, which partitions exist, when each was last materialized and whether upstream data is newer.
  • Dates. Airflow gives each run a data interval from its timetable. Dagster gives each run partition keys from the asset's partitions definition, and maps them between assets: a daily asset that depends on an hourly one depends on the 24 hourly partitions of its day, so the day is ready when all of them exist rather than at a fixed hour that may miss a late one. Both protect you from the wall-clock bug if you use them.
  • Backfills. Airflow creates one run per interval and lets the scheduler run them, with a concurrency limit and a reprocess behaviour. Dagster launches one run per partition by default, or one run for the whole range with a single-run policy.
  • Downstream triggers. Airflow 3 schedules a DAG on asset events with schedule=[asset], and its @asset decorator creates a one-task DAG that produces an asset. Dagster uses automation conditions and sensors on the asset graph.
  • Data tests. Dagster has asset checks built in; in Airflow a test is another task, or a call to a tool such as dbt tests or Great Expectations.

A task-centric model fits work whose result is an action rather than a dataset: calling partner APIs, sending emails, restarting services, coordinating systems you do not own. An asset-centric model fits platforms whose main output is many interdependent tables, where questions such as "which tables are stale, and why?" come up every day. Many teams use both, or start with one and adopt the other's ideas: Airflow's assets and Dagster's jobs are signs that the two models are converging.

07. Check your understanding

Practice check · 3 questions

Partitions, checks and the two models

Use defs.py and the comparison above.

Q1. You run `dg launch` with `--partition-range 2026-11-05...2026-11-07`. Which rows does the DELETE in `region_revenue` remove?
Q2. Someone inserts a second "south" row for 4 November by hand. You then materialize only the 6 November partition. What happens?
Q3. An Airflow 3 team wants a report DAG to start whenever their load task updates `region_revenue`. Which design is the closest match to a Dagster asset dependency?
Practice only: not graded, not saved, not evidence.

08. Apply it

The skill practice allows a Dagster job instead of an Airflow DAG. If you choose Dagster, add a third asset for your data test or report that depends on region_revenue and uses AutomationCondition.eager(), make the check blocking, start dg dev to see the asset graph and partitions in the UI, and run the 14-day backfill from there. If you stay with Airflow, write one paragraph on which of the five differences above would matter most for your team.

09. Review prompt

Without looking back, explain: what a software-defined asset is; how partition keys play the role of Airflow's data intervals; what a single-run backfill policy changes and what the code must do differently; why both orchestrators produced the same fingerprint; and two kinds of workflow where you would choose a task-centric tool.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check