Orchestration: how to make your data pipelines run reliably every day
TL;DR
Difficulty: Advanced
A daily data run is trustworthy when a handful of properties hold, whatever tool runs it:
- Every run is about a named business day, passed to every task, never computed from the clock.
- Every task replaces what it loads, so a retry, a rerun or a backfill never doubles a row.
- Passing failures get retries with growing, random waits. Real failures, such as an expired key or a half file, stop at once.
- Nothing waits forever and nothing guesses arrival times: sensors wait for data, timeouts end hangs, deadlines say what happens when data is late.
- A green run means complete data, because row counts are checked against normal, not just exit codes.
- Alerts are few and actionable, and a heartbeat catches the night the orchestrator itself is down.
- A cron script with a lock, a timeout and a heartbeat is enough for many small shops. Airflow, Dagster or Prefect earn their place with more steps, late data, regular backfills or more people.
Every piece of a data platform works when you run it by hand. The hard part is running all of them every night, in the right order, without you. This chapter walks from a fragile crontab to a proper orchestrator, with working Dagster, Airflow and shell examples from an invented homeware shop in Limerick.
A pipeline that someone starts by hand will one day not start
Every chapter so far has built a piece of the data platform: loads from the shop database and the APIs, cleaning rules, staging and clean layers, incremental loads. Each piece works when you run it. The question this chapter answers is the one that comes next: how do I make all of this run reliably every day, in the right order, without me?
The answer is orchestration. It sounds grand, but the idea is plain. Something has to start each step at the right moment, wait for the steps it depends on, try again when a step fails for a passing reason, stop when it fails for a real one, and tell a person when something needs a person. That something is the orchestrator.
A few terms first, so nobody is left behind:
- A job or task is one step of work, such as "load yesterday's Stripe payouts".
- A schedule says when work starts, for example every day at 3am.
- A dependency says what must finish before a task may start.
- A DAG (directed acyclic graph) is the map of all tasks and their dependencies. More on it below.
- A run is one execution of the whole map, for one period of data.
- A retry is a second (or third) attempt after a failure.
- Idempotent means running a task twice leaves the same result as running it once.
- A partition is a slice of data, usually one day, that a run processes on its own.
- A backfill is running the pipeline again for past partitions, for example after fixing a bug.
- A sensor is a task that waits until something exists, such as a file or a table.
This chapter builds on incremental loading and change data capture, which covered how to load only what changed. Here the topic is everything around those loads: the clock, the order, the waiting, the retries, the alerts and the reruns.
Example: how Shannonside Home's data gets in today
Shannonside Home is the invented homeware shop in Limerick that runs through this series (shannonsidehome.example). Niamh owns it. Callum builds the shop and its data platform. The shop runs on Ruby on Rails and Solidus with PostgreSQL, and the warehouse is BigQuery in a European region. Every figure for Shannonside in this chapter is invented for the example.
Right now, Callum's data platform is a list of lines in a crontab (the file that tells a Linux server what to run when) on one small server. Each line starts one script at a fixed time:
| Time | Script | What it does | Usual duration |
|---|---|---|---|
| 1.30am | load_shop | Copies changed rows from the shop's read replica | 6 minutes |
| 1.45am | load_payments | Downloads Stripe and PayPal settlement files | 2 minutes |
| 2.00am | load_ad_costs | Pulls yesterday's Google Ads and Meta costs | 4 minutes |
| 2.15am | load_3pl | Fetches the warehouse partner's CSV of shipments and returns | 3 minutes |
| 2.30am | load_suppliers | Reads the supplier feeds | 5 minutes |
| 2.45am | load_sheets | Reads the newsletter export and the marketing cost sheet | 1 minute |
| 5.00am | dbt_build | Builds every model, including the GA4 models | 31 minutes |
The gaps between the lines are guesses. Callum chose them because the scripts "usually" finish in time and the GA4 export "usually" lands before 5am. Niamh opens her dashboard at 8am. Most mornings it is grand. This chapter is about the other mornings.
Cron is a clock, not an orchestrator
Cron is the scheduler built into Linux and macOS. It wakes up every minute, compares the time with each line of the crontab and starts every command whose time matches1. A line has five time fields (minute, hour, day of month, month, day of week) followed by the command:
# minute hour day-of-month month day-of-week command
30 1 * * * /opt/shannonside/bin/load_shop
That is all cron does, and it does it very reliably. What it does not do is everything this chapter is about:
- It knows nothing about dependencies. If
load_shopruns late,dbt_buildstill starts at 5am. - It does not retry. A failed command stays failed until tomorrow.
- It keeps no history beyond what your scripts write to a log file.
- It cannot rerun last Tuesday. There is no notion of "the day this run is about".
- It does not stop a second copy of a job from starting while the first is still running.
- Its only built in alert is email to the crontab's owner, and only if the server can send mail1.
Cron also has two traps that catch almost everyone once. The first is the % character: in a crontab command, an unescaped % is turned into a new line, and everything after it is passed to the command as input1. A command such as date +%F silently breaks unless the % is written as \%. The second is daylight saving time. The cron manual says it plainly: times that do not exist because the clocks jump forward never match, so those jobs do not run, and times that happen twice when the clocks go back run twice1.
Example: the night the clocks go forward
Irish law looks at this the other way round from its neighbours. Irish Standard Time is the summer time, and the Standard Time (Amendment) Act 1971 created a "period of winter time" during which the State runs on Greenwich mean time2. Under the Winter Time Order 2001, winter time begins at 1am Greenwich mean time on the last Sunday in October and ends at 1am Greenwich mean time on the last Sunday in March3. On the clock on the wall, the clocks go forward at 1am in March and back at 2am in October. In 2027 that is 28 March and 31 October.
Callum's server runs on Irish local time. On 28 March 2027 the clock jumps from 12.59am straight to 2.00am. The line 30 1 * * * asks for 1.30am, a time that does not exist that night. So load_shop never runs. At 5am dbt_build runs happily on Saturday's shop data. Niamh's Monday report shows Sunday with almost no orders and nobody gets an error.
On 31 October 2027 the opposite happens. The hour from 1am to 2am happens twice, so load_shop runs twice. If the script appends rows instead of replacing them, Sunday's orders are in the warehouse twice.
The minimum fix keeps cron but removes both traps and the overlap:
# crontab for the user "etl" (cronie): one line, one entry point
CRON_TZ=UTC
# 03:00 UTC every day; flock stops a second copy, timeout stops a hung run
0 3 * * * flock -n /run/lock/shannonside-daily.lock timeout 3h /opt/shannonside/bin/daily-run.sh >> /var/log/shannonside/daily.log 2>&1
CRON_TZ=UTC makes cronie read the times in UTC, which has no daylight saving time1. flock -n takes a lock file and fails at once instead of waiting if another copy already holds it4. timeout 3h kills the run if it hangs. One line now starts one script that runs the steps in order, which already removes the guessed gaps. It is still not an orchestrator, but it is a far safer clock.
A DAG is the map of what waits for what
A directed acyclic graph sounds like mathematics, and it is, but the idea is everyday. "Graph" means dots and arrows. "Directed" means each arrow points one way: from the task that must finish first to the task that waits for it. "Acyclic" means you can never follow the arrows in a circle back to where you started, because a task that waits for itself would wait forever.
Orchestrators read this map and do two things with it. They start each task as soon as everything it depends on has finished, and they run tasks that do not depend on each other at the same time. That second point changes how long a run takes. A run is no longer the sum of all its tasks. It is the length of the longest chain of tasks that must happen one after another, called the critical path.
- is the time the whole run takes when tasks run in parallel wherever the map allows.
- is the set of all paths through the DAG from the first task to the last.
- is one of those paths, and is a task on it.
- is the duration of task .
In words: add up the durations along every path and take the longest. The basics of sums and maxima are in Foundations: ratios and rates.
Example: Shannonside's run as a DAG
Callum draws the map. The six loads depend on nothing and can run side by side. The dbt staging models need all six loads. The GA4 staging model needs only the GA4 export, which Google writes straight into BigQuery. The marts (the clean tables Niamh's reports read) need staging and GA4 staging. A reconciliation check needs the marts, and a final step publishes the day and sends a heartbeat (more on that later).
The durations, measured over a normal week, are: loads 6, 2, 4, 3, 5 and 1 minutes, GA4 staging 9 minutes, dbt staging 8 minutes, marts 14 minutes, reconciliation 2 minutes, publish 1 minute.
Run one after another, as the crontab does in effect, the total is minutes.
As a DAG, there are two kinds of path to the marts. Through the loads, the longest is the shop load (6 minutes) and then dbt staging (8 minutes), so 14 minutes. Through GA4, it is GA4 staging alone, 9 minutes. The marts can start when both are done, after minutes. Then the marts (14), the reconciliation (2) and the publish step (1) follow one after another, so minutes.
The same work takes 31 minutes instead of 55, and the critical path tells Callum where speed matters: making the supplier load faster saves nothing, because it is not on the critical path. Making the shop load or the marts faster shortens every run.
Tasks or assets: two ways to describe the same pipeline
Orchestrators differ less in what they can do than in how they ask you to think. There are two main ways.
Task based. You describe the steps and their order. "Run the shop load, then dbt, then the check." The orchestrator's world is made of tasks, and the tables they produce are a side effect. Apache Airflow grew up this way: a Dag in Airflow is "a model that encapsulates everything needed to execute a workflow", with its schedule, its tasks and their dependencies5. (Airflow 3 writes "Dag", not "DAG", in its documentation.) Since version 2.4, Airflow can also start a Dag when another task updates an asset, a named piece of data, and Airflow 3 calls these assets6.
Asset based. You describe the data you want to exist and how each piece is made from other pieces. "The table fct_orders is built from stg_orders and stg_payments." The orchestrator works out which steps to run from that. Dagster is built around this idea. Its documentation defines an asset as "an object in persistent storage, such as a table, file, or persisted machine learning model", and an asset definition as a description in code of an asset that should exist and how to produce it7.
Python first flows. Prefect sits slightly apart. You decorate ordinary Python functions as flows and tasks. Flows can call tasks and other flows, and behave much like normal Python functions with added run history, retries and scheduling8.
| Question | Airflow 3 | Dagster | Prefect 3 |
|---|---|---|---|
| Main unit you write | Dags made of tasks (operators, sensors, Python tasks) | Assets (tables, files, models) and checks on them | Flows and tasks as decorated Python functions |
| How a day of data is named | Data interval and logical date of a Dag run | Partition key of a partitioned asset | Parameters you pass to a flow run |
| Waiting for something | Sensors, deferrable operators, asset triggers | Sensors, schedules, declarative automation | Triggers and events, or waiting inside a flow |
| dbt | Usually one task that calls dbt, or a community package | Each dbt model becomes an asset with its own history | Usually a task that calls dbt |
| Feels most natural for | Teams with many kinds of jobs, not only data | Teams whose work is mostly tables and models | Teams who want to stay close to plain Python |
None of these is better in general. The useful question is which mental model matches the work. Shannonside's work is almost entirely "keep these tables correct", which leans towards assets. A business whose jobs are mostly "call this API, send that file, trigger that system" may find tasks more natural.
Example: one table, described both ways
Niamh asks a simple question: "Why is yesterday's revenue missing from the dashboard?"
In a task based setup, Callum looks at the run for 4 February and finds the failed task, say load_payments. He then has to know that fct_orders depends on it to answer Niamh.
In an asset based setup, he opens fct_orders itself. He sees that its partition for 4 February is missing, that it was not built because its upstream raw/stripe_payouts failed, and when each upstream table was last updated. The question Niamh asked is about a table, and the tool answers it in the same terms.
Both setups contain the same information. The difference is which question is one click away.
Every run is about a day, and that day is not today
The most important idea in orchestration is also the most often missed. A run that starts at 3am on 5 February is not "today's run". It is the run for the business day 4 February. Every task in it should load, build and check 4 February, and nothing else, no matter when it actually runs.
Airflow calls this the data interval. Each Dag run has a data interval that represents the time range it operates in9. In Airflow 3 a plain cron schedule such as @daily uses a trigger timetable by default, where the interval start and end are both the trigger time. If you want each run to cover a whole day from midnight to midnight, you use a data interval timetable such as CronDataIntervalTimetable, and the run for 1 January then starts only after 2 January 00:009. Dagster expresses the same idea with partitions: a daily partitioned asset has one partition per day, and a run materialises one named partition, such as 2027-02-0410.
Airflow's own best practice page says it bluntly: never read "the latest available data" in a task, read a specific partition, and never use the current time from now() for critical computation, because each rerun would give a different result11.
Time zones make this sharper. Airflow stores all times in UTC and its templates hand you time zone aware times that are still in UTC. Converting them to local time "is left up to the Dag"12. Google Analytics writes each daily GA4 table for a day in the property's own time zone13. So "the day" has to be defined once, explicitly, and used everywhere.
Example: the rerun that loaded the wrong day
On Tuesday 9 February, Callum reruns the payments load for 4 February after Stripe corrects a settlement file. The script contains this line:
day = date.today() - timedelta(days=1) # "yesterday"
On 9 February, "yesterday" is 8 February. The rerun reloads 8 February, which was already correct, and 4 February stays wrong. Nothing fails. The fix is to pass the day into every task instead of computing it inside:
def load_payments(day: date) -> int:
"""Load the settlement files for one business day. The caller decides the day."""
...
Then Callum meets the second trap. His Airflow template uses {{ data_interval_start | ds }} to get the day. In winter, midnight in Limerick is midnight UTC, so it works. From 28 March, Ireland is one hour ahead of UTC, the interval for 15 June starts at 11pm UTC on 14 June, and ds formats that as 14 June. Every summer run would load the previous day. The template must convert first: {{ data_interval_start.in_timezone('Europe/Dublin') | ds }}. The cleaner choice, and the one Airflow's documentation recommends where possible, is to define the business day in UTC and schedule in UTC12. Callum keeps the business day in Irish time, because that is how Niamh thinks about sales, but converts in one place only.
Idempotent tasks: run it twice, get the same result
Orchestrators retry. People rerun. Backfills replay weeks. All three are only safe if every task is idempotent: running it twice for the same day leaves exactly the same data as running it once.
Airflow's best practice page compares a task to a database transaction: it should never leave incomplete results, and because it may be retried, it should produce the same outcome on every rerun. It names the classic cause of duplicates: a plain INSERT during a rerun adds the rows a second time11.
Three patterns make loads idempotent:
- Replace the partition. Delete everything for the day and insert it again, inside one transaction, so a reader never sees the table half done. BigQuery supports multi statement transactions that commit or roll back as one unit14, and its partition decorators (
table$20270204) let a load job write one day's partition directly15. - Merge on a key. Update rows whose key exists and insert the rest, as covered in incremental loading and change data capture.
- Append only raw, deduplicate later. Raw tables keep every delivery with a load id, and the staging model keeps one row per business key. The raw layer may hold duplicates by design, as the chapter on raw, staging and clean layers explains, but nothing downstream ever counts them twice.
In dbt, the insert_overwrite incremental strategy on BigQuery replaces whole partitions instead of appending, which makes a rerun of a day harmless16.
Example: the payments load that ran twice
On the morning of 5 February the Stripe load inserts 66 payment rows for 4 February into raw.stripe_payouts. Just after the insert commits, the network drops before the script hears back. The orchestrator sees a failure and retries. The retry inserts the same 66 rows again.
Shannonside's average order value is €84, so 66 orders are of revenue. With the duplicate rows, the warehouse shows €11,088 for 4 February. For the month, with of real revenue, the report is €5,544 too high, an overstatement of , or 3.3% (see Foundations: percentages).
That is enough to change a decision about ad budget, and no test on the load itself would fail. Callum rewrites the load to replace the day in one transaction (BigQuery dialect):
-- BigQuery: replace one business day of Stripe payouts atomically
BEGIN TRANSACTION;
DELETE FROM raw.stripe_payouts
WHERE business_day = DATE '2027-02-04';
INSERT INTO raw.stripe_payouts (business_day, payout_id, charge_id, amount_minor, currency, loaded_at, load_id)
SELECT DATE '2027-02-04', payout_id, charge_id, amount_minor, currency, CURRENT_TIMESTAMP(), @load_id
FROM landing.stripe_payouts_20270204;
COMMIT TRANSACTION;
Now the retry deletes the 66 rows the first attempt wrote and inserts the same 66 again. The day holds 66 rows whether the task runs once or five times. In his own code the date is a parameter, never typed in, and @load_id records which attempt wrote the rows.
Retries: another go for passing failures, and only for those
Some failures pass on their own: a network blip, an API that is briefly overloaded, a database that restarted. Others never will: an expired password, a renamed column, a file in the wrong format. A good retry setup retries the first kind and fails fast on the second.
Retrying immediately is the wrong reflex. If an API is overloaded and every client retries at once, the retries arrive together and overload it again. The standard answer is exponential backoff with jitter: wait longer after each failure, and add randomness so clients spread out. Marc Brooker's simulations for AWS showed that adding jitter substantially reduced the work clients and servers had to do compared with backoff alone, and that full jitter, a random wait between zero and the backoff value, used the least work of the variants he tested17.
Dagster documents its exponential backoff exactly18. Each wait roughly doubles, the same growth as in Foundations: compounding:
- is the wait before retry number , in seconds.
- is the attempt number of the retry, starting at 1.
- is the base delay you configure.
With full jitter, the actual wait is a random value between 0 and 18. Airflow uses a multiplier instead: with retry_exponential_backoff=2.0 the delay doubles after each retry, and max_retry_delay caps it19. Prefect accepts a list of delays or an exponential_backoff helper, plus a retry_jitter_factor20.
Retries also need a way to say "do not bother". Airflow has AirflowFailException, which fails a task at once and ignores remaining retries, meant for cases such as an invalid API key21. Dagster's Failure takes allow_retries=False for the same purpose18.
Example: Meta's API at 3am
Callum's ad cost load calls Meta's API, which occasionally answers with a temporary error in the early morning. Over the last 100 nights it failed on the first attempt 4 times, so he estimates a first attempt failure rate of .
He sets max_retries = 4 and seconds. The maximum waits are:
| Retry | Maximum wait | |
|---|---|---|
| 1 | 1 | 30 seconds |
| 2 | 3 | 90 seconds |
| 3 | 7 | 210 seconds |
| 4 | 15 | 450 seconds |
| Total | 780 seconds, 13 minutes |
With full jitter, each wait is on average half its maximum, so the expected total wait if all four retries happen is 390 seconds, six and a half minutes.
If failures were independent, the chance that all five attempts fail would be
where is the number of retries, so five attempts in all. That is about one night in 27,000 years. See Foundations: probability for why independent chances multiply.
That number is wrong in an instructive way. Failures are not independent. If Meta has a 40 minute incident, all five attempts fall inside the same 13 minutes and all fail. Retries only cover failures shorter than the retry window. Callum therefore does two more things. He makes the load fetch the last three days every night and replace them, so a missed night is repaired by the next one. And he marks an expired access token as a non retryable failure, so it reaches him at 3am instead of after 13 pointless minutes.
Timeouts stop the task that never ends
A failure is easy to notice. A task that simply never finishes is not. An SFTP download that stalls without closing the connection can sit for hours. Meanwhile it holds its slot, its lock, and everything downstream waits.
Every task needs a maximum run time. In Airflow this is execution_timeout, and when it is breached the task fails with AirflowTaskTimeout and can be retried like any other failure. Sensors have a separate timeout for how long they may wait in total, which retries do not reset21. A good starting point is a few times the task's normal duration: long enough that a slow night does not trip it, short enough that a hang is caught well before the morning.
Example: the 3PL download that hung
The 3PL load usually takes 3 minutes. Over the last 60 runs, 95% finished within 4 minutes, so the 95th percentile is 4 minutes. Callum sets the timeout at three times that, 12 minutes.
On 18 January the 3PL's SFTP server accepts the connection and then sends nothing. Without a timeout, the old crontab version waited until Callum noticed at 9.40am. With the timeout, the task fails at 3.12am, retries after a short wait, connects properly on the second attempt and finishes at 3.17am. Niamh's report is ready on time and the only trace is one retry in the run history.
Wait for the data instead of guessing when it arrives
Callum's crontab assumed the GA4 export would land before 5am. Google does not promise a time. Its help page says the daily table events_YYYYMMDD is created after Analytics has collected all the events for the day, and that Analytics may keep updating a daily table for up to two calendar days plus today with late events13. The 3PL file also has no fixed time.
Instead of guessing, an orchestrator waits. A sensor checks a condition again and again, such as "does the table exist", and succeeds as soon as it is true, or fails when its timeout runs out22. Waiting costs resources if done naively, so Airflow offers a reschedule mode, where the sensor only takes a worker slot while it checks22, and deferrable operators, which hand the waiting to a separate lightweight process called the triggerer so no worker slot is used at all23. The Google provider for Airflow includes BigQueryTableExistenceSensor, which can run deferred24. Dagster sensors run on an interval you set, can keep a cursor so they remember what they have already seen, and request a run when their condition is met25. A run_key on the request makes sure the same day only starts one run, however many times the sensor fires26.
Every wait needs an end. If the data has not arrived by a deadline, the pipeline should do something defined: build what it can, mark the rest as stale, and tell a person.
Example: when the GA4 table lands
Callum records when events_YYYYMMDD appeared in BigQuery for each day of January. These are invented example times:
The old 5am start found the table on days. On the other 15 days, 50% of the month, the GA4 models ran against a missing table. dbt did not fail, because the staging model read the newest existing table, so the reports quietly showed the previous day's sessions next to today's orders.
The new setup waits. A sensor checks for the table every 10 minutes from 3am. As soon as it exists, the GA4 models run. The latest arrival in January was 6.25am, so the GA4 numbers are ready by about 6.40am on the worst day, well before Niamh's 8am. If the table is still missing at 8am, the run builds every shop model anyway, marks the GA4 tiles on the dashboard as stale with the date of their last good day, and sends Callum a message. Nothing is silently mixed.
Dependencies across systems and people
The hardest dependencies are not between two tasks in the same pipeline. They are on systems and people outside it: the GA4 export, the 3PL's file, a spreadsheet Niamh's marketing assistant fills in by hand every Monday. The orchestrator cannot control those. It can only check them before trusting them.
dbt has a built in way to check sources: freshness. You tell dbt which column says when a row was loaded and how old the newest row may be before dbt warns or errors27. Running dbt source freshness before the build turns "the marketing sheet was not updated" from a silent wrong number into a visible message. In Airflow, a Dag can also be scheduled on assets that another Dag updates, which links pipelines owned by different people without guessing at times6.
Example: the Monday marketing sheet
Niamh's assistant enters influencer and print costs into a Google Sheet every Monday by 11am. The weekly marketing efficiency report reads it. One Monday she is ill, the sheet is not updated, and the report shows a week with no influencer spend and a much better return on ad spend than reality.
Callum adds a freshness rule to the source (dbt YAML):
# models/sources.yml (dbt Core)
sources:
- name: sheets
tables:
- name: marketing_costs
loaded_at_field: entered_at
config:
freshness:
warn_after: {count: 8, period: day}
error_after: {count: 10, period: day}
On a normal Monday the newest row is a few hours old. On the Monday the sheet is missed, the newest row is 7 days old by the evening and 8 days old on Tuesday, so dbt warns. Callum's pipeline treats a warning on this source as "build the report, but print a banner saying the costs end on the previous Monday". A two day delay would turn into an error, and the weekly report would not be published at all.
Partitions make backfills routine
A backfill is running the pipeline again for past days. It is not an emergency procedure. It happens every time a cleaning rule changes, a bug is fixed, or a source corrects old data. If tasks are partitioned by day and idempotent, a backfill is simply many normal runs, one per day.
Airflow 3 has backfills built in: you give a Dag, a start date and an end date, and Airflow creates the runs. You choose whether to create only missing runs, missing and failed runs, or all runs, and max_active_runs limits how many run at once, independently of the Dag's own limit28. A dry run prints the dates first. Catchup, which runs every missed interval when a Dag is switched on, is off by default in Airflow 39. Dagster launches backfills over a range of partitions from its interface, either as one run per partition or, with a backfill policy, as a single run over the range29.
Two limits matter in practice. The source systems: a backfill that calls the Google Ads API for 200 days at once will hit its rate limits. And the warehouse: every partition rebuilt is a query you pay for. Pools in Airflow30 and concurrency pools in Dagster31 cap how many tasks touch one system at a time.
Example: the VAT bug
On 5 February Callum finds that a change to the VAT logic on 1 December treated gift cards as standard rated. Every partition of the order marts from 1 December 2026 to 4 February 2027 is wrong. That is days.
One partition of the marts takes 2.5 minutes. Run one at a time, the backfill takes minutes. With three at a time, it runs in waves: minutes. The brackets mean "round up": 66 partitions in groups of three make 22 groups. Callum uses three, not ten, because the backfill must not slow down the normal nightly run, and Airflow's documentation points to max_active_runs as the main lever for exactly that28:
# Apache Airflow 3: rebuild the order marts for the affected days, three at a time
airflow backfill create --dag-id shannonside_daily \
--from-date 2026-12-01 \
--to-date 2027-02-04 \
--reprocess-behavior completed \
--max-active-runs 3
completed reprocesses every day in the range, including days that succeeded, because they succeeded with the wrong rule. Because every task replaces its partition, each day ends up correct whether it ran once or three times. The restatement itself, telling Niamh that December's figures changed and by how much, is the subject of the chapter on reporting on cleaned data.
Running dbt inside the orchestrator
dbt already has its own DAG: it reads the ref() calls in every model and builds models in dependency order. dbt build runs models, tests, snapshots and seeds in that order, and when a test on a model fails, the models downstream of it are skipped32. That is exactly the behaviour you want: a failed uniqueness test on stg_orders should stop fct_orders from being built on top of duplicates.
The question is how much of dbt's DAG the orchestrator should see. There are two common answers:
- One task for all of dbt. The orchestrator calls
dbt buildonce. Simple, and dbt handles the order. The orchestrator only knows "dbt failed", and you read dbt's log to find out where. - Every model as its own node. Dagster's dbt integration reads dbt's
manifest.jsonand turns each model into an asset with its own history, so you can run subsets and see failures per model33. In Airflow this usually needs a community package.
Either way, two dbt commands help when things go wrong. dbt retry reruns the last invocation from the point of failure, using the results file dbt wrote, instead of rebuilding everything34. And dbt's selection syntax can pick models by state, such as everything modified compared with a previous run and everything downstream of it35.
Example: the duplicate that stopped the marts
On 22 January a guest checkout and an account with the same email, differing only in a trailing space, slip past the customer merge rule from the chapter on duplicates. The unique test on dim_customers.customer_key fails.
dbt build stops at that point. dim_customers exists with the failing rows, but fct_orders, which joins to it, is skipped, and so is everything after it. Niamh's dashboard still shows the previous day's complete, correct figures, with the "data as of 21 January" date visible on every tile. Callum fixes the trimming in the merge rule, runs the model's unit test, and then runs dbt retry. It picks up from dim_customers and builds only what was skipped, 11 minutes instead of 31.
The alternative, a pipeline that builds the marts anyway and reports the failed test afterwards, would have counted one customer twice in every repeat purchase metric for that day.
Secrets: what the pipeline may know and nobody else
A daily run touches almost every system the business has. It needs a read only login for the shop database replica, API keys for Stripe, PayPal, Google Ads and Meta, an SFTP key for the 3PL, a service account for BigQuery, and a webhook for alerts. Those are the keys to customer data and to money.
The rules are simple to state:
- Never in code, never in the repository, never in a log line.
- Each credential with the least access it needs: the shop login reads the replica and nothing else, the BigQuery account writes to the raw datasets and nothing else.
- Stored in one place built for secrets, and read at run time. Airflow reads connections from environment variables, its metadata database or a secrets backend such as a cloud secret manager36. Dagster's
EnvVarreads a value at run time and keeps it out of the interface37. Google Cloud's Secret Manager stores, versions and audits secrets for services running in Google Cloud38. - Rotated on a schedule, and immediately when someone leaves.
This is also a legal duty. Under Article 32 of the GDPR, a business must put appropriate technical and organisational measures in place to secure personal data. If a leaked key exposes customer data, that can be a personal data breach, which under Article 33 must usually be reported to the supervisory authority within 72 hours of becoming aware of it39. In Ireland that is the Data Protection Commission, whose guidance covers both data security40 and breach notification41. This is general information, not legal advice. The deeper topic, personal data inside pipelines, has its own chapter later in this series on privacy engineering.
Example: Callum's secrets inventory
Callum lists every credential the daily run uses, where it lives and what it can do:
| Credential | Stored in | Can do | Rotated |
|---|---|---|---|
| Shop replica login | Secret manager | Read the replica only | Every 90 days |
| Stripe restricted key | Secret manager | Read balance transactions and payouts only | Every 90 days |
| PayPal API client | Secret manager | Read transaction reports only | Every 90 days |
| Google Ads and Meta tokens | Secret manager | Read reports only | When they expire |
| 3PL SFTP key | Secret manager | Read one folder only | Yearly |
| BigQuery service account | Workload identity, no key file | Write raw datasets, run dbt | Not needed |
| Alert webhook | Secret manager | Post to one channel | Yearly |
Writing the list finds two problems. The old crontab script had the Stripe key in a shell file with read access for every user on the server, and the dbt logs printed full email addresses when a customer test failed. He moves the key and changes the test to report customer ids only.
Failures that look like success
The most dangerous runs are the green ones that are wrong. Three patterns cause most of them:
- The silent success. Every task succeeds, but one loaded nothing: the 3PL dropped an empty file, an API returned an empty page with status 200, a query filtered on the wrong day.
- The partial load. Half a file was read before the connection dropped, and the script treated end of stream as end of file.
- The run that reports success despite a failure. Airflow's documentation warns that a leaf task with the trigger rule
all_doneruns whatever happened before it, and if it succeeds the whole Dag run is marked as success, even if something in the middle failed9.
The defence is to check results, not just exit codes. A volume check compares each load with what is normal for that day of the week:
- is the number of rows loaded for the day.
- are the row counts for the same weekday in the four previous weeks.
- is the middle value, which a single unusual week cannot drag far. See Foundations: median and mode.
- is the share of normal you accept, for example 0.5 for half.
Weekdays matter because a Monday and a Sunday are different businesses. This simple rule catches empty and half files. A full chapter on data observability later in this series goes much further, with freshness, schema and anomaly monitoring.
Example: the empty 3PL file
The 3PL's shipment counts for the last four Tuesdays were 84, 79, 81 and 88. Sorted, they are 79, 81, 84, 88. The median of four values is the average of the middle two:
With , the threshold is rows.
On Tuesday 26 January the 3PL's system writes the file before its own export has finished. The file has a header and 37 rows. , so the check fails. Because a rerun would read the same half file, Callum marks this failure as not retryable, and it reaches him straight away. He asks the 3PL to resend, reruns that one partition, and the next check sees 83 rows. Without the check, 46 shipped orders would have shown as "not yet shipped" on the fulfilment report for a week, until someone asked why.
Alerts a team of one can live with
An alert is only useful if a person acts on it. Google's site reliability engineering book puts it well: every page should be actionable, every page response should require intelligence, and a person can only react with urgency a few times a day before fatigue sets in42. For a business where the data team is one person, or one person plus an outside developer, that rule is not a nicety. It is the difference between alerts that are read and alerts that are muted.
Useful alerts for a small data platform come in four kinds:
- Failure. A task has failed after all its retries. Airflow calls an
on_failure_callback43, and Dagster has a run failure sensor that fires when a job fails26. - Lateness. The run has not finished by the time people need it. Airflow 3 has deadline alerts, still marked experimental, which call a function when a run misses a deadline measured from a reference point such as when it was queued44.
- Silence. The orchestrator itself is down, so nothing runs and nothing fails. Only an outside check catches this: the last step of the run sends a heartbeat to an external service, and that service alerts when no heartbeat arrives by a set time. This pattern is often called a dead man's switch.
- Data. A check such as the volume rule above fails.
Everything else, such as a retry that succeeded or a warning on a low priority source, goes into a daily summary, not an alert.
Example: Callum's alert plan
| Situation | Who hears | How | When |
|---|---|---|---|
| Load or dbt failure after retries | Callum | Message to his phone | At once from 6am, overnight failures wait until then |
| Run not finished by 7.30am | Callum and Niamh | Message | 7.30am |
| No heartbeat by 8am | Callum | Message from the external monitor | 8am |
| Volume or reconciliation check fails | Callum | Message with the numbers | At once, from 6am |
| Retries that succeeded, warnings | Callum | Daily summary | 9am |
| Stale data on a dashboard tile | Niamh and anyone reading | "Data as of" date on the tile | Always |
Two choices here are deliberate. Overnight failures wait until 6am, because nothing Callum could do at 3am would change what Niamh sees at 8am, and he needs to sleep to fix things well. And Niamh is told about lateness directly, so she never makes a decision on a report she does not know is stale. A runbook, one page per alert with "what it means, how to check, how to fix", lives next to the pipeline code. When someone else covers for Callum on holiday, the runbook is what they have.
Run times creep up before they fail
Most pipelines do not break suddenly. They slow down a little every day, because data grows, until one morning they are not done in time. A run time chart catches this weeks before it hurts.
Example: a month of dbt run times
Callum plots the duration of the nightly dbt build for January, after moving to the orchestrator:
Nothing failed in January, so no alert fired. But the build went from 22 to 40 minutes. Callum fits a straight line to the 31 points with ordinary least squares (see Foundations: regression):
- is the fitted build time in minutes on day .
- is the day number, 1 for 1 January.
- is the intercept, the fitted time on day 0.
- is the slope, how many minutes the build grows each day.
The fit gives and . On day 90, 31 March, the fitted build time is minutes.
The GA4 table landed as late as 6.25am in January. With a 75 minute build, a late morning in March finishes at 7.40am, past the 7.30am lateness alert, and by early May past Niamh's 8am. The cause is easy to find once Callum looks: the GA4 staging model is still a full rebuild of every event since 2022, so it grows with every day of history. He turns it into an incremental model with a lookback, as described in the chapter on incremental loading, and the build drops to 24 minutes and stays flat. He also adds a rule to the daily summary: flag any model whose run time over the last 14 days grows by more than 20%.
What a small business really needs
Not every business needs Airflow or Dagster. An orchestrator is another system to run, update, secure and understand. For a shop with a handful of sources and one person looking after them, the honest answer is often a single scheduled script with a lock, a timeout, an explicit business day, idempotent steps, an alert on failure and a heartbeat on success. That covers most of what this chapter has asked for.
An orchestrator earns its place when one or more of these become true:
- More than about ten steps with real dependencies between them.
- Sources that arrive at unpredictable times.
- Regular backfills.
- More than one person changing the pipelines.
- A need to see the history of each table, not just of each run. Managed services, from cloud providers and from the companies behind Airflow, Dagster and Prefect, remove the work of running the orchestrator itself, at a monthly price worth comparing with the time it saves.
Example: what Shannonside chooses, and the script it starts with
Shannonside has seven sources, two of which arrive at unpredictable times, a backfill every few weeks, and Callum alone changing the pipelines. That is past the single script line, but only just. Callum first hardens the cron version for a month, then moves to Dagster because Shannonside's work is about tables, and the per model history answers Niamh's questions directly.
The single script he uses in the meantime shows that the principles come before any tool:
#!/usr/bin/env bash
# /opt/shannonside/bin/daily-run.sh: the whole daily run, in order, for one business day
set -euo pipefail
source /etc/shannonside/run.env # ALERT_URL and HEARTBEAT_URL, readable by the etl user only
# The business day is fixed once, at the start, and passed to every step.
DAY="${1:-$(TZ=Europe/Dublin date -d 'yesterday' +%F)}"
trap 'curl -fsS -m 10 --retry 3 --data "Daily run for $DAY failed at line $LINENO" "$ALERT_URL"' ERR
for source in shop payments ad_costs tpl suppliers sheets; do
/opt/shannonside/bin/load "$source" --day "$DAY" # each load replaces its day and checks volume
done
/opt/shannonside/bin/wait-for-table "analytics_123456789.events_${DAY//-/}" --until 08:00
cd /opt/shannonside/dbt
dbt source freshness
dbt build --vars "{\"min_date\": \"$DAY\"}"
curl -fsS -m 10 --retry 3 "$HEARTBEAT_URL" # silence after 8am means something is wrong
set -euo pipefail stops the script at the first failed command, unset variable or failed pipe. The trap sends an alert with the failing line. The day can be passed as an argument, which makes a rerun for 4 February as simple as daily-run.sh 2027-02-04. The load and wait-for-table commands are Callum's own small programs.
The daily run in Dagster
Here is the core of Shannonside's daily run in Dagster, written against the current documentation10182645. The loaders and alerts modules are Callum's own code: they run the replace by day loads from the idempotency section, the volume check, and send messages.
# shannonside_data/definitions.py (Dagster 1.13 with dagster-dbt)
import json
from datetime import datetime, timedelta
from pathlib import Path
from zoneinfo import ZoneInfo
import dagster as dg
from dagster_dbt import DbtCliResource, DbtProject, dbt_assets
from shannonside_data import alerts, loaders # Callum's own code
DUBLIN = "Europe/Dublin"
daily = dg.DailyPartitionsDefinition(start_date="2022-02-01", timezone=DUBLIN)
api_retry = dg.RetryPolicy(
max_retries=4,
delay=30, # seconds
backoff=dg.Backoff.EXPONENTIAL, # (2^n - 1) x 30: 30, 90, 210, 450 seconds
jitter=dg.Jitter.FULL, # a random wait between 0 and that value
)
def raw_load(table: str) -> dg.AssetsDefinition:
@dg.asset(key=["raw", table], partitions_def=daily, retry_policy=api_retry, group_name="raw")
def _load(context: dg.AssetExecutionContext) -> dg.MaterializeResult:
day = context.partition_key # e.g. "2027-02-04", never "today"
rows = loaders.replace_day(table, day) # delete and insert in one transaction
expected = loaders.median_same_weekday(table, day, weeks=4)
if expected and rows < 0.5 * expected:
raise dg.Failure(
description=f"{table}: {rows} rows for {day}, normal is about {expected}",
metadata={"rows": rows, "expected": expected},
allow_retries=False, # a rerun would read the same file
)
return dg.MaterializeResult(metadata={"rows": rows, "expected": expected})
return _load
raw_assets = [raw_load(t) for t in ["spree_orders", "spree_line_items", "spree_payments",
"stripe_payouts", "paypal_settlements", "ad_costs", "tpl_shipments"]]
dbt_project = DbtProject(project_dir=Path(__file__).parent.parent / "dbt")
dbt_project.prepare_if_dev()
def day_vars(context: dg.AssetExecutionContext) -> list[str]:
start, end = context.partition_time_window
return ["--vars", json.dumps({"min_date": start.strftime("%Y-%m-%d"),
"max_date": end.strftime("%Y-%m-%d")})]
@dbt_assets(manifest=dbt_project.manifest_path, exclude="tag:ga4", partitions_def=daily)
def shop_models(context: dg.AssetExecutionContext, dbt: DbtCliResource):
yield from dbt.cli(["build", *day_vars(context)], context=context).stream()
@dbt_assets(manifest=dbt_project.manifest_path, select="tag:ga4", partitions_def=daily)
def ga4_models(context: dg.AssetExecutionContext, dbt: DbtCliResource):
yield from dbt.cli(["build", *day_vars(context)], context=context).stream()
shop_job = dg.define_asset_job("shop_daily", selection=[*raw_assets, shop_models])
ga4_job = dg.define_asset_job("ga4_daily", selection=[ga4_models])
@dg.schedule(job=shop_job, cron_schedule="0 3 * * *", execution_timezone=DUBLIN)
def shop_at_three(context: dg.ScheduleEvaluationContext):
day = (context.scheduled_execution_time.date() - timedelta(days=1)).isoformat()
return dg.RunRequest(run_key=day, partition_key=day)
@dg.sensor(job=ga4_job, minimum_interval_seconds=600)
def ga4_export_landed(context: dg.SensorEvaluationContext):
day = (datetime.now(ZoneInfo(DUBLIN)).date() - timedelta(days=1)).isoformat()
table = f"analytics_123456789.events_{day.replace('-', '')}"
if not loaders.table_exists(table):
return dg.SkipReason(f"{table} has not landed yet")
if not loaders.day_published("marts.fct_orders", day):
return dg.SkipReason(f"shop models for {day} are not finished yet")
return dg.RunRequest(run_key=f"ga4-{day}", partition_key=day)
@dg.run_failure_sensor(monitored_jobs=[shop_job, ga4_job])
def tell_callum(context: dg.RunFailureSensorContext):
alerts.send(f"{context.dagster_run.job_name} failed: {context.failure_event.message}")
defs = dg.Definitions(
assets=[*raw_assets, shop_models, ga4_models],
jobs=[shop_job, ga4_job],
schedules=[shop_at_three],
sensors=[ga4_export_landed, tell_callum],
resources={"dbt": DbtCliResource(project_dir=dbt_project)},
)
Read from the top, the file says everything this chapter has argued for:
DailyPartitionsDefinitionwithtimezonedefines the business day once, in Irish time46. Every asset receives its day ascontext.partition_keyand never asks the clock.RetryPolicygives every load four retries with exponential backoff and full jitter. The volume check raisesFailurewithallow_retries=False, because retrying a half file is pointless18.@dbt_assetsturns every dbt model into an asset, split by a dbt tag into shop models and GA4 models. Each run passes its day to dbt as variables, following the partitioned example in Dagster's dbt reference4547. dbt's raw sources map to theraw/...asset keys, so Dagster knows the loads come first.- The schedule starts the shop run at 3am Irish time for yesterday's partition. The
run_keymeans one run per day, even if the scheduler restarts26. 3am is outside the hour that is skipped or repeated when the Irish clocks change. - The sensor checks every 10 minutes whether the GA4 table exists and the shop models for that day are published, and only then starts the GA4 run, once per day thanks to its
run_key. - The failure sensor sends Callum a message when either job fails. The heartbeat and the 8am deadline live in the external monitor, because a check inside Dagster cannot report that Dagster itself is down.
The same run in Airflow 3, for comparison
The same daily run as an Airflow 3 Dag, shorter because it calls the same load commands as the shell script:
# dags/shannonside_daily.py (Apache Airflow 3)
from datetime import timedelta
import pendulum
from airflow.sdk import CronDataIntervalTimetable, dag
from airflow.providers.google.cloud.sensors.bigquery import BigQueryTableExistenceSensor
from airflow.providers.standard.operators.bash import BashOperator
DAY = "{{ data_interval_start.in_timezone('Europe/Dublin') | ds }}"
DAY_NODASH = "{{ data_interval_start.in_timezone('Europe/Dublin') | ds_nodash }}"
@dag(
schedule=CronDataIntervalTimetable("0 0 * * *", timezone="Europe/Dublin"),
start_date=pendulum.datetime(2027, 1, 1, tz="Europe/Dublin"),
catchup=False,
max_active_runs=1,
default_args={
"retries": 4,
"retry_delay": timedelta(seconds=30),
"retry_exponential_backoff": 2.0, # 30 s, 60 s, 120 s, 240 s
"max_retry_delay": timedelta(minutes=10),
"execution_timeout": timedelta(minutes=30),
},
)
def shannonside_daily():
loads = [
BashOperator(task_id=f"load_{source}", bash_command=f"/opt/shannonside/bin/load {source} --day {DAY}")
for source in ["shop", "payments", "ad_costs", "tpl", "suppliers", "sheets"]
]
ga4_landed = BigQueryTableExistenceSensor(
task_id="ga4_landed",
project_id="shannonside-analytics",
dataset_id="analytics_123456789",
table_id=f"events_{DAY_NODASH}",
deferrable=True, # waits in the triggerer, not in a worker slot
poke_interval=600,
timeout=8 * 3600,
)
dbt_build = BashOperator(
task_id="dbt_build",
bash_command=f"cd /opt/shannonside/dbt && dbt source freshness && dbt build --vars '{{\"min_date\": \"{DAY}\"}}'",
)
loads >> dbt_build
ga4_landed >> dbt_build
shannonside_daily()
CronDataIntervalTimetable gives each run a whole Irish day as its data interval, so the run for 4 February starts just after midnight on 5 February48. The templates convert data_interval_start to Irish time before formatting, which avoids the summer trap described earlier4912. The retry settings follow the Task SDK reference, where retry_exponential_backoff is a multiplier and 2.0 doubles the wait each time19. The GA4 sensor is deferrable, so its hours of waiting cost no worker2423. In this simpler version, dbt waits for GA4 before building anything. The Dagster version above builds the shop models first and the GA4 models when their table lands, which is one reason Callum prefers it.
Conclusion
Orchestration is not about a tool. It is about a handful of properties that make a daily run trustworthy. Each run is about a named day, not about whenever it happens to run. Every task can run twice without changing the result. Passing failures are retried with growing, randomised waits, and real failures stop at once. Nothing waits forever, and nothing guesses when data will arrive. A green run means the data is complete, because volumes are checked, not just exit codes. And a person hears about a problem before the person reading the report does, without being woken for things that can wait.
A crontab with a lock, a timeout, an explicit day and a heartbeat gets a small business most of the way. Airflow, Dagster and Prefect add dependencies, partitions, sensors, backfills and history when the work outgrows one script, and the choice between them is mostly a choice between thinking in tasks and thinking in tables. Whichever you choose, write the day into every task, make every load replace what it loads, and watch the run times as well as the failures. The next chapter in this series is about testing pipelines, so that what runs reliably every day is also right.
