The transforms in a batch pipeline are rarely what goes wrong. What goes wrong is everything around them: a retry that double-counts, a schedule whose window silently changed width, a skewed key that turns a 20-minute job into a 4-hour one, a lookback that fixes one table and quietly desynchronises the three downstream of it, and a test suite that fires after the CFO has already seen the number. This chapter is about those mechanisms, and about the single property that makes most of them tractable: every task is a pure, idempotent function of an interval.
You know what an orchestrator does: dependency ordering, parallel branches, retries, SLAs, run history, lineage. The part worth being deliberate about is the mental model. A daily pipeline is not "the revenue job"; it is "produce dt=2026-03-03 of fct_daily_revenue", and every hard problem in this chapter — reruns, backfills, late data — reduces to producing that partition correctly any number of times. Once the partition is the unit, retries, backfills and disaster recovery become the same operation with different date ranges.
Each box is a rerun, retry and alerting boundary — and should be an atomicity boundary: a task either publishes its whole output or leaves the previous version untouched. Lineage across the edges is what turns "why is this dashboard number wrong?" into a backwards graph walk.
The design decision people get wrong is task granularity. Task boundaries are your rerun, retry and alerting boundaries — and, crucially, your atomicity boundaries. Too coarse (one task that extracts, transforms and publishes) and a failure in the last step forces a rerun of the first, and a mid-task crash can leave a half-written table visible. Too fine (one task per SQL statement) and you pay scheduler overhead — seconds of queueing and process start per task in Airflow — plus cross-task state passed through intermediate tables nobody cleans up. A workable rule: one task per durable, independently meaningful output, where each output is written atomically. If two steps must succeed or fail together, they belong in one task.
The retry setting also interacts with idempotency in a way that is easy to miss. retries=3 on a task that is not idempotent does not make it reliable; it makes it wrong up to four times. And retries are indiscriminate: an OOM or a bad SQL statement will burn through its retries before paging anyone, delaying the alert by the full backoff schedule. Retry budgets belong on tasks whose failures are plausibly transient (network, warehouse queueing, API rate limits), not blanket defaults.
The number to manage is slack: the SLA minus the pipeline's critical-path duration, measured from when the last upstream lands, not from the cron time. Parallelism shortens nothing off the critical path, so adding workers to a DAG whose longest chain is extract → stg → fct → dq does not move the finish time. What consumes slack is late upstreams (usually the largest and least controllable term), queueing for warehouse or executor capacity when everyone's 02:00 jobs collide, and retries. The worst of these is a retry of a deterministic failure: each attempt costs a full task duration plus backoff and cannot succeed.
Neither failure alone misses the SLA: a 2h late upstream still leaves ~1h25 of slack, and one OOM costs 70 minutes. Together with a blanket retry policy they miss it by more than an hour, and the page arrives after the deadline, when nothing can be done. Fail-fast on deterministic errors turns the same morning into a near-miss.
Two practices follow. First, classify failures and retry only the transient ones: an OOM, a schema mismatch, a failed assertion or a SQL error should fail immediately and page. Second, alert on projected lateness, not on the deadline passing: when the upstream has not landed by SLA − p95(critical path) − margin, page then, while someone can still act, for example by chasing the upstream or publishing yesterday's data with a stale banner. An SLA alert that fires at 06:00 is only a record of the miss.
In the classic Airflow model a daily run covers [Mar 3 00:00, Mar 4 00:00) and is triggered after that interval closes; its logical date (the old execution_date) is the interval start, so the run labelled "Mar 3" executes early on Mar 4. SQL filters on {{ data_interval_start }} / {{ data_interval_end }}, never on now(), which is what lets a rerun next month produce last Tuesday's answer.
The classic interval timetable: a run covers a closed window and starts only after it ends. Filter on data_interval_start / data_interval_end, never now(). Under a trigger timetable (the Airflow 3 default for cron strings) this window has zero width unless you configure one — see below.
The trap for anyone upgrading: Airflow 3 changed what a cron schedule means. With the create_cron_data_intervals setting now defaulting to off, cron strings are interpreted by CronTriggerTimetable, where the run's logical date is the trigger time and the data interval has zero width unless you configure one. A task that filters created_at >= data_interval_start AND created_at < data_interval_end then selects nothing, succeeds, and overwrites yesterday's partition with an empty one — a green run that deletes data. Same code, different semantics. Pin the timetable explicitly (CronDataIntervalTimetable, or a trigger timetable with an explicit interval) rather than inheriting a default, and add a volume check that treats zero rows as a failure. The same release also turned catchup off by default, which is the safer direction but means a newly deployed DAG no longer backfills unless asked.
Sensors bridge "the interval closed" and "the upstream data actually landed". Two failure modes matter more than the familiar advice about reschedule mode and deferrable operators. First, sensing the wrong condition: a sensor on "any file exists under s3://exports/dt=2026-03-03/" fires when the first of forty part-files lands, and the downstream task reads a partial export. S3 has been strongly read-after-write consistent since late 2020, but consistency of a single object says nothing about completeness of a multi-file export. Sense a completion marker (_SUCCESS, a manifest with expected file count and row count) that the producer writes last. Second, sensor timeouts as silent SLA: a sensor that times out after 24 hours marks the run failed at a time nobody is looking. The timeout should be set from the downstream SLA, not from how long you are willing to wait.
Asset-oriented orchestration (Dagster's software-defined assets, Airflow's assets, formerly Datasets) inverts the model: you declare the tables that should exist and their upstreams, and runs are derived. The decision criterion is where your freshness requirements live. If most consumers care about "is this table current and correct", and many tables have multiple upstreams on different cadences, assets win: data-triggered runs replace sensor chains and fragile schedule offsets ("run at 02:30 because the upstream usually finishes by 02:15"). If your work is largely side-effectful operations — API calls, exports, ML training jobs — task-oriented DAGs are the more honest model.
Spark parallelism is partition count: a 2 TB input read as 128 MB splits is ~16,000 map tasks. Narrow operations pipeline inside a task; wide ones (join, groupBy, window, distinct) force a shuffle, where each map task writes its output bucketed by hash(key) to local disk and each reduce task fetches its bucket from every map task. That is serialisation, disk, and network on the full post-filter dataset, and it is usually the dominant cost.
Every shuffle is a stage boundary: map tasks serialize and write their output partitioned by key, and reduce tasks pull those blocks over the network — M × R fetches in total. For a join or window, the reducer that owns the hot key (here, US; illustrative share) does most of the work alone, and the stage finishes only when its slowest task does. For a decomposable aggregate, map-side partial aggregation shrinks that bar to one row per map task.
Three things about the shuffle are less widely understood than they should be. First, it is an M × R problem, not just a volume problem. 16,000 map tasks feeding 2,000 reducers produce 32 million shuffle blocks averaging a few tens of KB each (illustrative arithmetic), and the reduce side becomes a storm of small random reads; fetch failures under that load cause map-stage recomputation, which is how a job that "usually takes 40 minutes" occasionally takes three hours. Push-based shuffle (Spark 3.2+, on YARN) exists precisely to merge those blocks. Second, the default spark.sql.shuffle.partitions = 200 is wrong in both directions: on a 2 TB shuffle it means ~10 GB per reducer and heavy spilling; on a 2 GB shuffle it means 200 tiny tasks. With AQE on, the robust pattern is to start high (spark.sql.adaptive.coalescePartitions.initialPartitionNum) and let AQE coalesce toward advisoryPartitionSizeInBytes (64 MB default) — AQE merges small partitions but, outside skewed joins and explicit REBALANCE hints, does not split large ones.
Third, skew in an aggregation is often not the problem you think. For decomposable aggregates (sum, count, min, max) Spark runs a partial aggregation on the map side, so the reducer for the hot key receives one pre-aggregated row per map task, not 61% of the raw rows. Salting a SUM … GROUP BY country is usually wasted effort. Skew bites hard in three places: joins (every row of the hot key on both sides meets in one task), window functions partitioned by the hot key (a window partition cannot be split; the whole partition is sorted and buffered in one task), and non-decomposable aggregates like collect_list or exact count(distinct). AQE's skew-join handling splits an oversized partition of a sort-merge join and replicates the matching side, but it does nothing for windows or aggregations. The NULL join key that half the rows share is the most common skew in practice and the cheapest to fix: filter it out and union it back.
Broadcast joins avoid the shuffle entirely (autoBroadcastJoinThreshold, 10 MB by default), but they have their own failure mode. The build side is collected to the driver and then shipped to every executor, and the threshold is checked against estimated size. A "small" dimension whose statistics are stale, or whose compressed Parquet footprint is a fraction of its in-memory size, can blow the driver heap or hit spark.sql.broadcastTimeout (300 s). A forced broadcast() hint is a promise about data size that nobody re-checks as the table grows. Note also that when AQE converts a sort-merge join to broadcast at runtime, the map-side shuffle has already been written; you save the sort and reduce-side work, not the shuffle write.
200
Default shuffle partitions
10 MB
Default broadcast threshold
64 MB
AQE advisory partition size
M × R
Shuffle blocks fetched
Architect's note
dbt's value is well known: ref()-derived DAGs, per-environment schema resolution, tests beside models, and dbt build running models and tests in graph order. The operationally interesting part is where its defaults leave gaps.
sources →
raw.orders
source()
raw.payments
source()
raw.fx_rates
source()
staging →
stg_orders
view
stg_payments
view
stg_fx_rates
view
intermediate →
int_payments_usd
ephemeral
marts
fct_daily_revenue
incremental
dim_customers
table
Tests attach to the same graph, so a failed test on a node skips its descendants. The node itself has already been materialised by the time its tests run — if fct_daily_revenue fails unique(order_id), the duplicated table is already what dashboards read.
A failing test does not unpublish the model it tests. In dbt build, a model is materialised into its target relation and then its tests run. A failure skips everything downstream, but the model itself — say a mart that dashboards read directly — has already been replaced with the bad data. Tests protect descendants, not the node under test. For any model that consumers read directly, you need build-into-staging-then-swap (section 3.7), not just tests. Unit tests (dbt 1.8+) and model contracts do run before materialisation, but they test logic and shape, not the contents of today's data.
Incremental models drift silently. on_schema_change defaults to ignore: add a column to the model and the existing incremental table simply does not get it, with no error, until someone runs a full refresh. The merge strategy on a large target scans the target to match keys unless you constrain it with incremental_predicates — which is how an incremental model ends up costing more per run than the full rebuild it replaced.
illustrative: 5 TB target clustered by dt · 20 GB/day new source rows · 3-day lookback
full rebuild (table)
re-read all source · rewrite 5 TB
merge, no predicate
scan whole target to match keys
merge + incremental_predicates
target pruned to last 3 days of dt
insert_overwrite / microbatch, 3 days
rewrite 3 partitions from source
The predicate only saves anything if it lines up with the target's physical layout. incremental_predicates on dt prunes a table partitioned or clustered by dt; on a table clustered by customer_id it prunes almost nothing, and the merge is back on the pink row. And the green rows are only correct if every late row lands inside the 3-day window, which is the 3.6 problem.
The decision rule is about the ratio of change to table size and where the changes land. If a run touches a bounded, recent range of a date-organised table, use partition overwrite or microbatch; they need no key matching at all. Use a keyed merge when updates are scattered across the table's history (entity tables, SCD-style dimensions), and then accept that the target scan is the cost of the design, and cluster on the merge key rather than on date. When the daily delta passes something like 10–20% of the table (an illustrative threshold that depends on the engine), a full rebuild is often both cheaper and simpler, and it removes drift. And because an incremental table is the accumulation of every past run's logic, it can hold rows no current version of the code would produce; the only proof it does not is a periodic --full-refresh diffed against the incremental result.
Pitfall
Worked example. A daily revenue job appends yesterday's revenue by currency. On Mar 4 the INSERT succeeds, a downstream notification task times out, and on-call clears and reruns the whole DAG. Mar 3 revenue now reads $96,420 instead of $48,210, and nobody notices until finance does. The fix is familiar; the subtleties are in what "idempotent" has to cover.
Before — two bugs, both invisible on the happy path
-- Bug 1: INSERT INTO appends. A rerun adds a second copy of the day.
-- Bug 2: CURRENT_DATE makes the result depend on WHEN it runs, so a
-- backfill for Mar 3 run on Apr 10 computes Apr 9 instead.
INSERT INTO analytics.fct_daily_revenue
SELECT DATE(o.created_at) AS dt,
o.currency,
SUM(p.amount) AS revenue
FROM stg_orders o JOIN stg_payments p ON p.order_id = o.order_id
WHERE DATE(o.created_at) = CURRENT_DATE - 1
GROUP BY 1, 2;After — parameterised by the interval, overwrites exactly one partition
-- '{{ ds }}' is the run's logical date, supplied by the orchestrator.
-- An explicit PARTITION (dt='...') spec replaces only that partition. The
-- trap is df.write.mode("overwrite").partitionBy("dt"): under Spark's
-- default partitionOverwriteMode=static it deletes EVERY partition.
INSERT OVERWRITE TABLE analytics.fct_daily_revenue
PARTITION (dt = '{{ ds }}')
SELECT o.currency,
SUM(p.amount) AS revenue
FROM stg_orders o JOIN stg_payments p ON p.order_id = o.order_id
WHERE o.created_at >= '{{ data_interval_start }}'
AND o.created_at < '{{ data_interval_end }}'
GROUP BY o.currency;The orchestrator will run your task more than once for the same interval — retries, clears, backfills — so a non-idempotent write is a latent double-count waiting for its first transient failure. Both green rows also assume the write is atomic; see below.
Overwrite is only idempotent if it is atomic. On a plain Hive-style table in object storage, INSERT OVERWRITE deletes the partition's files and then writes new ones. A reader in between sees an empty day; a job killed in between leaves an empty day that no retry will notice if the task is marked failed and nobody reruns it. That is the concrete reason to run overwrites through a table format (Iceberg, Delta, Hudi) or a warehouse transaction: the new files are committed in one metadata swap, and a failed write leaves the old partition intact. On a warehouse, DELETE WHERE dt = … ; INSERT must be in the same transaction for the same reason.
Idempotent is not the same as reproducible. The "after" query is idempotent — running it twice in a row gives the same table — but rerunning it next week may give a different Mar 3, because stg_payments has since absorbed refunds and late settlements. Usually that is what you want: a rerun should incorporate corrections. It is not what you want for a closed financial period, an audit, or a debugging session trying to reproduce last Tuesday's bad number. For those, pin inputs: read upstream tables as of a snapshot (Iceberg/Delta time travel, Snowflake AT) and record the snapshot IDs a run consumed alongside its output. Decide per table which of the two properties you are promising, and write it down; most arguments about "why did the number change" are two teams assuming different ones.
MERGE suits entity tables that change in place, with one condition that bites: the source key must be unique per batch. Snowflake (with its default nondeterministic-merge setting), BigQuery, and Delta error when multiple source rows match one target row; engines configured otherwise pick an arbitrary winner, which is worse. Deduplicate the source with an explicit ordering rule (latest updated_at, then a tiebreaker) inside the task, not in a hopeful upstream.
Architect's note
With interval-parameterised tasks a backfill is "run these 730 logical dates." The operational problems are second-order. Resource contention: 730 runs at default concurrency will saturate the warehouse and starve the daily jobs the business is actually waiting on — cap max_active_runs and, where possible, give backfills a separate warehouse or queue. Logic changes: backfill into a shadow table and diff it against the old one before swapping, so you learn whether the change moved the numbers you expected it to and no others. Downstream propagation: rewriting two years of a fact table means every derived model over that range is now stale, and incremental downstream models will not notice, because they only look at recent partitions.
Do the capacity arithmetic before you click "clear". Say one logical date takes 12 minutes on the production warehouse (illustrative). 730 dates is ~146 hours serially; at max_active_runs=8 that is ~18 hours of wall clock, assuming the warehouse scales linearly, which it will not once eight runs contend for the same slots. If the backfill shares a warehouse with the nightly critical path, those 18 hours cover a night, and the SLA from 3.1 absorbs the queueing. The alternative is usually cheaper than it looks: rewrite the model as one set-based statement over the whole range, INSERT OVERWRITE … WHERE dt BETWEEN …, which pays one scan of the source instead of 730 overlapping ones and lets the engine parallelise internally. The per-date loop exists for operational convenience, not efficiency. Use it when individual dates must be retryable, and set-based rebuilds when the range is large and the logic is stable.
Late-arriving data is the everyday version of the same problem. If you partition by event time — which you should, because that is what the business asks about — some rows will always belong to a day already published: offline mobile clients, partner files that land two days late, payments that settle after the order.
A fixed lookback recomputes the last N partitions on every run whether or not anything landed in them, and still misses the 0.2% that fell outside the window (Mar 2, dimmed). Change-driven reprocessing, below, overwrites exactly the partitions that received rows.
The standard answer is a lookback window: each run overwrites the last N partitions. Its cost is easy to underestimate. A 3-day lookback is roughly 3× the daily compute for that model; a 30-day lookback, which late partner feeds can push you toward, is 30×, to pick up what may be well under 1% of rows. And the lookback has to propagate: if fct_daily_revenue rewrites the last 3 days but the weekly rollup downstream only processes "yesterday," the two now disagree, and the discrepancy surfaces as a reconciliation ticket weeks later. Every downstream consumer of a lookback table needs a lookback at least as wide.
Past the knee, every extra day of lookback buys a smaller slice of correctness at the same marginal cost. That tail is usually one or two named sources: give them their own reprocessing path, or book them as adjustments, rather than widening N for every row in the table.
Lookbacks also stack in a way nobody plans. If each of four chained models independently takes a 3-day lookback, a row arriving 3 days late reaches the first model on day 3 but only reaches the fourth if every intermediate run re-reads the window after its parent rewrote it, which depends on run order within the day. The failure is a mart that is correct most days and wrong on days when an upstream ran late and a downstream ran on schedule. The fix is to key each model's reprocessing set on its parent's changed partitions rather than on the calendar, which leads to the next design.
The better design at scale is two timestamps and change-driven reprocessing. Land raw data partitioned by ingest date and carry event_time as a column. Each run reads only the newly ingested partition, computes SELECT DISTINCT event_date over it, and overwrites exactly those event-date partitions downstream — plus emits that list so downstream models know which partitions changed. Compute now scales with the number of affected days rather than a fixed N, arbitrarily late data is handled correctly, and the "which partitions moved" signal is exactly what downstream incrementals and cache invalidation need. The price is a slightly more complex task contract (a list of partitions rather than one date); asset-partition orchestration and dbt microbatch both move in this direction.
Either way, pair it with a finality policy: a documented date after which numbers are frozen, with anything later booked as an adjustment in the current period rather than restating history. Finance almost always wants this, and it bounds the blast radius of a late file. Choose the window from the measured arrival-delay distribution — plot ingest_date minus event_date per row for a month — rather than from intuition; the tail is usually dominated by one or two specific sources, which are better handled individually. Streaming systems formalise the same trade-off with watermarks, covered in chapter 5.
A pipeline that runs green and publishes wrong numbers is worse than one that fails, because people act on it. The check taxonomy (schema, nulls, uniqueness, referential integrity, freshness, volume, business rules) is familiar; the practical questions are which checks catch real incidents and where they run. Volume is the best single catch-all for broken upstreams, but a naive "within ±30% of the trailing 7-day median" (illustrative threshold) pages every Monday for a B2B product and every holiday for a consumer one. Compare against the same weekday over the last several weeks, and alert on both tails: a sudden doubling is usually a duplicate load, which is exactly the idempotency failure from 3.5. Treat zero rows as a hard failure, never a warning.
Write
build into staging / a branch — invisible to readers
Audit
schema · nulls · uniqueness · volume · freshness · business rules
Publish
atomic swap / branch fast-forward — readers see all or nothing
✗ audit fails
halt · page owner · keep yesterday's good data live · quarantine the batch for debugging
✓ audit passes
Snowflake SWAP WITH · Iceberg branch → main · view repoint
Testing after publishing only tells you how long the wrong numbers were visible. Write-audit-publish moves the checks before the moment of visibility, and the atomic publish means a consumer never reads a half-written table.
Write-audit-publish is the answer to the dbt gap in 3.4: build into a relation readers cannot see, run the checks there, and make visibility an atomic metadata operation. The decision it forces is a policy one: when an audit fails at 05:30 and the SLA is 06:00, do you publish stale-but-correct data or fresh-but-suspect data? Decide per table in advance. For finance and anything feeding automated decisions (pricing, reverse-ETL into a CRM), stale-but-correct is almost always right. For an operational dashboard someone watches hourly, a published-with-warning flag may be better than a silent stale page. What you should not do is leave the choice to whoever is on call.
Data contracts move the checks upstream to the only place a breaking change can be stopped cheaply: the producer's CI. Most breakages begin with a product team renaming a column or adding an enum value in their service database with no idea a revenue pipeline depends on it. A contract that fails their build converts a 6 a.m. incident for you into a review comment for them. The hard part is organisational, not technical; the contract only holds if the producer owns it.
Finally, cost and complexity. A single large machine running DuckDB or Polars handles datasets in the tens to low hundreds of gigabytes, and a warehouse can run most transformations with no Spark at all. Six SQL jobs against one warehouse can be a cron entry running idempotent, interval-parameterised scripts with failure alerts and a row-count check. Adopt an orchestrator when cross-task dependencies, retries, backfills and lineage across dozens of tasks become real pain; reach for Spark when the data genuinely will not fit. The principles — partition as unit, atomic idempotent writes, explicit lookback and finality, audit before publish — apply at every scale.
Questions to ask in a design review
Partition
The unit of work
Atomic
Or overwrite isn't idempotent
Lookback
Must propagate downstream
WAP
Audit before visible
Where next