DAGs, tasks and schedules
Part of the free LogicWiz Data Engineering course, Module 9: Orchestration. The SQL and Python run in the app, on real Postgres and real Python in the browser.
It is 9:05 on Wednesday. Tess opens the sales dashboard and Tuesday shows half a day of sales. Nothing failed overnight: three cron jobs ran at 01:00, 01:30 and 02:00, as they do every night. Nora asks one question: "How long did the first one take?" It took 45 minutes.
You'll learn to
- Draw a pipeline as tasks that wait for each other
- Read a cron schedule and the data interval each run covers
- Write tasks that use the run's interval, never the clock
- Predict what Airflow 3 and daylight saving do to a daily schedule
Learn
Three alarm clocks, nobody watching
SwiftKart's pipeline is three commands on one server. The first extracts last night's orders into a file at 01:00. The second transforms that file at 01:30. The third loads the dashboard at 02:00.
The tool that starts them is cron, the classic Unix scheduler. Think of three alarm clocks. Each one rings at its time, whatever the others are doing.
Cron does not know that the transform needs the extract to finish first. It does not retry, it does not remember which days worked, it does not tell anyone, and it cannot rerun last Tuesday. Most nights the extract is done well before 01:30, so the gaps hide the problem. On Tuesday it took 45 minutes.
Tuesday night, three ways
A timeline of the three nightly jobs: on a normal night each finishes before the next starts, on Tuesday the transform starts while the extract is still writing, and as a DAG each task starts only when the one before it has finished.
A normal night. The extract takes 20 minutes (a number made up for the picture). It is done before the 01:30 alarm rings, so the transform reads a whole file.
Tuesday, with cron. The extract runs for 45 minutes. At 01:30 the transform starts anyway and reads the half of the file that exists. At 02:00 the dashboard loads half a day. Every job exits without an error.
Tuesday, with tasks that wait. The same slow extract. The transform starts at 01:45, when the extract has succeeded, and the dashboard load follows it. Everything is done by 02:00, with the right numbers.
Read each row left to right: minutes after 01:00, one row per job. The two lines are the times cron rings the second and third alarm.
A pipeline where each step waits
You want a tool that knows the order. It starts the transform when the extract has succeeded, not when a clock says so. That tool is an orchestrator: Apache Airflow, Dagster, Prefect, Databricks Jobs, Azure Data Factory.
An orchestrator does not do the heavy work: the warehouse, Spark or dbt still do that. It decides what runs, when, in which order, and what to do when something fails.
You describe the pipeline as steps and arrows:
- A task is one step: "extract orders".
- A dependency is an arrow:
extract >> transformmeans transform starts only after extract succeeds. - The whole drawing is a DAG, a directed acyclic graph: the arrows point one way and never loop back. It is the same idea as dbt's graph in Module 8.
Your first DAG: three tasks, two arrows
import miniflow as mf
dag = mf.DAG('daily_orders', start_date='2025-06-01', schedule='@daily')
@dag.task()
def extract(ctx):
print(' extract orders for', ctx['ds'])
@dag.task()
def transform(ctx):
print(' transform', ctx['ds'])
@dag.task()
def load(ctx):
print(' load', ctx['ds'])
extract >> transform >> load # the dependencies
dag.run_until('2025-06-02') # the simulated clock reaches 2 June, 00:00
dag.run_until('2025-06-03') # and then 3 June, 00:00
dag.grid()
miniflow is a small scheduler written for this course (open miniflow.py to read it). Its clock is simulated: run_until() moves time forward and the scheduler starts everything that is due. @daily is the schedule: once a day. Each column of the grid is one run, the whole DAG executed for one day. Now look at the dates. The clock is at 3 June, yet there is no run for 3 June.
The run for 1 June started on 2 June
Look at the output again. The clock reached 2 June, and the run that started is dated 1 June. That is not a delay. It is the idea that confuses most newcomers.
A daily run for 1 June processes the orders of 1 June. Those orders are only all there once the day is over. So the run starts at 2 June 00:00, the moment its day ends.
The period a run covers is called its data interval: here, 1 June 00:00 to 2 June 00:00. Airflow names the run after the start of that interval. That name is the logical date, and tasks receive it as ds (2025-06-01).
One task inside one run is a task instance, with its own state and its own tries.
Each run covers a day that has already ended
A timeline over three days: each daily run reads a 24-hour data interval and starts only at the moment that interval closes, at the next midnight.
Read each row left to right: the blue bar is the day the run reads, the green bar is the run. Hours count from 1 June 00:00 UTC, and each run is drawn two hours long as an example. While the first run executes, the data of 2 June is already arriving.
One minute before midnight, nothing runs
import miniflow as mf
dag = mf.DAG('daily_revenue', start_date='2025-06-01', schedule='@daily')
@dag.task()
def show(ctx):
print(' ds:', ctx['ds'])
print(' interval:', ctx['data_interval_start'], 'to', ctx['data_interval_end'])
print(dag.run_until('2025-06-01 23:59')) # 1 June is not over: nothing runs
print(dag.run_until('2025-06-02 00:00')) # now it is: the run for 1 June starts
Every task gets ctx, the run's context, like the context Airflow passes to a task: ds, data_interval_start, data_interval_end, try_number and more. run_until() returns the logical dates it started: none at 23:59, one a minute later.
Three schedules, read the same way
| Schedule | Logical date (ds) | Data interval | The run starts at |
|---|---|---|---|
| @daily | 2025-06-01 | 06-01 00:00 to 06-02 00:00 | 2025-06-02 00:00 |
| @daily | 2025-06-02 | 06-02 00:00 to 06-03 00:00 | 2025-06-03 00:00 |
| 0 6 | 2025-06-01 | 06-01 06:00 to 06-02 06:00 | 2025-06-02 06:00 |
| @weekly | 2025-06-01 | Sunday 06-01 to Sunday 06-08 | 2025-06-08 00:00 |
The start of one interval is the end of the one before, so the intervals cover time with no gaps and no overlaps.
Remember: a run is named after the period it covers, and it starts when that period ends. The run dated 1 June starts on 2 June.
A week on the run grid
A grid of daily runs as columns and tasks as rows, showing each run start only after its day has ended, with retries, catchup on and off, and backfilling a range of dates.
Press Next day and watch the grid: each column is one logical date, and it fills only after that day is over. The retries, the outage and the backfill you will see are the next two lessons.
Ask the run, not the clock
Now the habit that makes the rest of this module work. A task should process its run's interval, and nothing else:
where order_ts >= data_interval_start and order_ts < data_interval_end
Not "today". Not "yesterday" from the server clock. Not "the latest day in the table".
Then the run for 3 June always processes 3 June: on time, retried an hour later, or rerun next month after a bug fix. The answer depends on which run it is, never on when it runs.
A task that reads its own interval
import duckdb
import miniflow as mf
dag = mf.DAG('daily_orders', start_date='2025-06-01', schedule='@daily')
@dag.task()
def count_orders(ctx):
n = duckdb.sql(f"""
select count(*) from 'data/orders.csv'
where order_ts >= '{ctx['data_interval_start']}'
and order_ts < '{ctx['data_interval_end']}'
""").fetchone()[0]
print(f" {ctx['ds']}: {n} orders")
return n
dag.run_until('2025-06-04')
The query never names a date of its own: both bounds come from ctx. In Airflow you write the same filter with the template variables {{ data_interval_start }} and {{ data_interval_end }}.
An order at exactly midnight
Two daily runs side by side with three orders: when the interval is closed with less-than-or-equal, the order placed at exactly midnight is counted by both runs; closed with less-than, it is counted once.
The end closed with
<=. Order B was placed at exactly 2 June 00:00:00. The run for 1 June takes it (<=its end) and the run for 2 June takes it too (>=its start). Three orders, four rows.The end closed with
<. Now the run for 1 June stops just before midnight, so Order B belongs to 2 June only. Three orders, three rows.
Read the two boxes as two runs, each with the filter it uses. >= the start and < the end is called a half-open interval: every moment belongs to exactly one run.
Two classic bugs. Using the clock (datetime.now(), CURRENT_DATE) inside a task: a retry after midnight or a rerun next month processes the wrong day. And closing the interval with <= the end: an order at exactly 00:00 is counted on two days. Always >= the start and < the end, both taken from the run.
Five fields say when
How does the scheduler know "once a day"? The schedule is written in cron's old notation: five fields, read left to right. Minute, hour, day of the month, month, day of the week. A * means "any".
So 0 6 * * * is minute 0 of hour 6, on any day: 06:00 every day. @daily is a short name for 0 0 * * *, midnight.
Cron in five fields
| Schedule | Fields: minute hour day month weekday | Means |
|---|---|---|
| 0 6 | minute 0, hour 6, any day | 06:00 every day |
| 30 1 1 | minute 30, hour 1, weekday 1 | 01:30 every Monday (0 is Sunday) |
| 0 | minute 0 of every hour | hourly, on the hour |
| 0 0 1 | midnight on day 1 | monthly |
| @daily, @weekly, @monthly | presets | 0 0 , 0 0 0, 0 0 1 |
Read each row left to right. Airflow reads schedules in UTC unless you give the DAG a time zone, so 06:00 in the schedule is not 06:00 in Toronto.
Midnight is not every 24 hours
SwiftKart's UK team wants a sales DAG that runs at midnight in London. Airflow stores every timestamp in UTC and reads a schedule in the DAG's time zone: UTC unless you give the timetable one, as in CronDataIntervalTimetable("0 0 * * *", timezone="Europe/London").
London has daylight saving, so "every day at midnight" is not "every 24 hours". On the two nights the clocks change, the daily interval is 23 or 25 hours long.
A task that filters on data_interval_start and data_interval_end stays right with no extra code, because the interval already follows the local calendar. A task that computes ds + 24 hours, or a report that divides a day's events by 24 to get an hourly rate, is wrong twice a year.
A London midnight schedule when the clocks change (2025)
Three bars of interval length for a daily London schedule: 24 hours on 29 March, 23 hours on 30 March when clocks go forward, and 25 hours on 26 October when clocks go back.
Each bar is one run's data interval, named by its logical date. UK clocks change at 01:00 UTC on the last Sunday of March and of October. Local midnight on 31 March is already 23:00 UTC on 30 March, so that day is an hour short.
Airflow 3 reads the same line differently
One more surprise, and it bites on upgrade day. Airflow turns a schedule into runs with a timetable, and there are two ways to read 0 0 * * *.
CronDataIntervalTimetable: each run covers the span between two ticks and starts when the span ends. That is everything you have seen so far.CronTriggerTimetable: each tick is a point. The run starts at the tick, its logical date is the tick, and its data interval has zero length (data_interval_startequalsdata_interval_end) unless you passinterval=.
Airflow 2 gave a bare cron string or @daily the first one. Airflow 3 gives it the second. An upgraded DAG still runs at 00:00 and stays green, but a task that filters on its interval selects nothing.
The run that starts at 2 June 00:00
| CronDataIntervalTimetable (Airflow 2 default) | CronTriggerTimetable (Airflow 3 default) |
|---|---|
| Logical date (ds): 2025-06-01 | Logical date (ds): 2025-06-02 |
| Interval: 1 June 00:00 to 2 June 00:00 | Interval: 2 June 00:00 to 2 June 00:00, zero length |
| An interval filter finds 1 June's orders | The same filter finds nothing |
| In Airflow 3: pass the class, or set createcrondataintervals = True before upgrading | In Airflow 3: what schedule="0 0 " and @daily get |
| Switching an existing DAG to it skips one scheduled run | Switching an existing DAG to it skips nothing |
The same DAG in a real Airflow file
Runs in Airflow:
from datetime import datetime
from airflow.sdk import dag, task
from airflow.providers.common.sql.operators.sql import SQLExecuteQueryOperator
from airflow.timetables.interval import CronDataIntervalTimetable
@dag(
dag_id="daily_revenue",
# midnight UTC; each run covers the day that just ended
schedule=CronDataIntervalTimetable("0 0 * * *", timezone="UTC"),
start_date=datetime(2025, 6, 1),
catchup=False,
tags=["swiftkart"],
)
def daily_revenue():
@task
def extract(data_interval_start=None, data_interval_end=None):
print(f"orders from {data_interval_start} to {data_interval_end}")
load = SQLExecuteQueryOperator(
task_id="load",
conn_id="warehouse",
sql="""
DELETE FROM daily_revenue WHERE day = '{{ ds }}';
INSERT INTO daily_revenue
SELECT DATE(o.order_ts), SUM(i.qty * i.unit_price)
FROM orders AS o JOIN order_items AS i ON i.order_id = o.order_id
WHERE o.status IN ('placed', 'shipped', 'delivered')
AND o.order_ts >= '{{ data_interval_start }}'
AND o.order_ts < '{{ data_interval_end }}'
GROUP BY 1;
""",
)
extract() >> load
daily_revenue()
Airflow fills the {{ ... }} templates (Jinja again, as in dbt) for each run. Naming CronDataIntervalTimetable makes the file behave the same on Airflow 2 and 3. Airflow 3 imports the decorators from the Task SDK, airflow.sdk; Airflow 2 used airflow.decorators. Lesson 9.4 reads a bigger DAG file line by line.
Numbers to remember
| What | Value | Note |
|---|---|---|
| A bare cron string on Airflow 2 | CronDataIntervalTimetable | the run covers the span between two ticks |
| A bare cron string on Airflow 3 | CronTriggerTimetable | [scheduler] createcrondataintervals now defaults to False |
| Keeping data intervals on Airflow 3 | name CronDataIntervalTimetable in the DAG | or set createcrondataintervals = True before upgrading: switching an existing DAG later skips one scheduled run |
| catchup default | False on Airflow 3 | it was True on Airflow 2 (Lesson 9.3) |
| Gone from the task context in Airflow 3 | executiondate, prevds, nextds, yesterdayds, tomorrowds | a template that uses them breaks the DAG |
| Decorator imports | airflow.sdk on Airflow 3 | airflow.decorators on Airflow 2 |
| Schedule time zone | UTC | unless you give the timetable a timezone |
| Weekday numbers in cron | 0 is Sunday, 1 is Monday | @weekly is 0 0 0 |
What changed at SwiftKart
The three cron lines are gone. In their place is one DAG, extract >> transform >> load, on a daily schedule with data intervals. On a slow night the transform waits for the extract, and the dashboard still shows a whole day.
Each task asks its run for the interval, so the run for Tuesday always processes Tuesday, on time or a month later. Tess has not seen half a day since.
But waiting is the easy part. In Lesson 9.2 the warehouse drops its connection in the middle of a load, the task retries, and the retry makes the numbers worse.
In one line
A DAG runs once per data interval, after the interval ends; the run is named by the interval's start, and its tasks filter on >= start and < end from the run, never on the clock.
Interview corner
Why use an orchestrator like Airflow instead of cron?
cron only starts commands at times. An orchestrator models dependencies between tasks, retries failures, keeps the history and state of every run, alerts on failure, and can rerun or backfill past intervals. It also gives a UI and logs, so you can see what ran, what failed and why.
What is the logical date in Airflow, and when does a daily run start?
With a data-interval schedule, the logical date is the start of the data interval the run processes. The daily run for 1 June covers 1 June 00:00 to 2 June 00:00, so it starts at 2 June 00:00 when that data is complete. Tasks should use data_interval_start and data_interval_end, not the wall clock. That was the default for cron schedules in Airflow 2; in Airflow 3 you choose it with CronDataIntervalTimetable, because a plain cron string now runs at the tick with no interval.
How do you make a task process the right day?
Filter on the run's interval with a half-open range, >= data_interval_start and < data_interval_end, and never on now() or the latest date in the table. That way a retry, a manual rerun or a backfill of that date processes exactly the same data. In a time zone with daylight saving the interval is 23 or 25 hours twice a year, and the interval filter handles it with no special code.
You are upgrading from Airflow 2 to Airflow 3. What can silently change in a daily DAG?
A bare cron string or @daily now gets CronTriggerTimetable, so the run at midnight is dated at the tick with a zero-length interval: interval filters return nothing while every run stays green. catchup now defaults to False, so history after a gap is no longer filled. execution_date, prev_ds and next_ds are gone from the context, and imports move to airflow.sdk. I would pin CronDataIntervalTimetable (or set create_cron_data_intervals = True before upgrading, since switching later skips a run), set catchup explicitly, and compare row counts for a few days on both versions.