Pipeline Orchestration: DAG Design, Idempotency, Retries
Difficulty: Senior Level | Companies: Netflix, Uber, Airbnb, Lyft, DoorDash
Most pipeline bugs are not logic bugs. The transformation computes the correct number; the failure is that the job was re-run after a partial write, or that a retry hammered a rate-limited API until it banned the account, or that a backfill quietly skipped a day because an upstream partition had not landed yet. Orchestration patterns exist to make those operational failures impossible or at least harmless.
Prerequisites
- !Airflow DAGs, tasks and dependencies
- !Atomic file operations and transactional table formats
- !How parallel workers share state
What You'll Learn
- 1Compose fan-out, fan-in and branching DAG shapes deliberately
- 2Design writes that produce identical output when re-run
- 3Choose retry, backoff and circuit breaker settings per failure type
- 4Run backfills that respect upstream readiness
Shapes a DAG can take
The four shapes cover nearly every pipeline you will write. A linear chain expresses a strict sequence where each step consumes the previous output. Fan-out splits work into independent units, usually by date, region or tenant, so they run in parallel; fan-in merges them into a single downstream result and must wait for every branch. Branching selects exactly one path at runtime based on a computed condition, typically a data quality verdict. A sensor-driven shape waits for an external condition, such as an upstream file appearing, rather than doing work itself.
Two discipline rules keep these shapes readable. First, keep branching shallow: a DAG with nested branches three levels deep is impossible to reason about at three in the morning, so push the decision into a single task that returns a path. Second, make fan-out units independent in both data and state. If two parallel branches append to the same partition, you have moved a race condition into your orchestrator, and reruns will produce duplicates that no amount of retry tuning will fix.
| Shape | Use when | Main risk | Rerun behaviour |
|---|---|---|---|
| Linear chain | Steps are strictly ordered | One slow step serializes everything | Safe if each step is idempotent |
| Fan-out and fan-in | Partitions or tenants are independent | Partial branches after a failure | Safe only if merge deduplicates |
| Branching | Exactly one path should execute | Skipped tasks look like successes | Safe if each branch is idempotent |
| Sensor wait | Upstream readiness is external | Sensor timeouts during backlogs | Safe, no write happens |
Making every write safe to re-run
Idempotency means running the same task twice produces the same final state as running it once. Three techniques achieve it. Overwrite the whole partition, so a rerun replaces rather than appends. Deduplicate on a natural key before writing, so replayed input collapses. Or write to a temporary location and atomically publish, so readers only ever see a complete result.
import uuid
class IdempotentWriter:
def __init__(self, target_path: str, spark):
self.target_path = target_path
self.spark = spark
def write_partition(self, df, partition_date: str, key_columns: list) -> None:
deduped = df.dropDuplicates(key_columns)
staging = f"{self.target_path}/_staging/{uuid.uuid4().hex}"
(
deduped.write.format("delta")
.mode("overwrite")
.option("replaceWhere", f"date = '{partition_date}'")
.save(staging)
)
self._publish(staging, partition_date)
def _publish(self, staging: str, partition_date: str) -> None:
self.spark.sql(
f"MERGE INTO delta.`{self.target_path}` t "
f"USING delta.`{staging}` s "
f"ON t.date = s.date "
f"WHEN MATCHED THEN REPLACE * "
f"WHEN NOT MATCHED THEN INSERT *"
)
Note the replace predicate on the staging write. Without it, a partial rerun can leave rows from a wider previous run sitting beside the new ones, which is exactly the double-counting that makes finance distrust a table for months.
Retry policy and the circuit breaker
Not every failure deserves a retry. Transient network errors, throttling and brief lock contention are retryable; a schema violation, a null constraint failure and an authentication error are not, and retrying them only delays the real diagnosis while consuming quota. Classify first, then set backoff per class.
Exponential backoff with a cap prevents the thundering herd that follows a shared dependency recovery: when a warehouse comes back, every queued task must not hit it in the same second. A circuit breaker goes further by refusing to call a dependency that has already failed repeatedly, which converts a cascading outage into a fast, visible failure at one boundary.
import random
import time
from functools import wraps
class ThrottlingError(Exception):
pass
class CircuitOpenError(Exception):
pass
RETRYABLE = (TimeoutError, ConnectionError, ThrottlingError)
def retry(max_attempts=3, base_delay=1.0, cap=60.0):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
last_error = None
for attempt in range(max_attempts):
try:
return func(*args, **kwargs)
except RETRYABLE as exc:
last_error = exc
if attempt == max_attempts - 1:
raise
delay = min(base_delay * (2 ** attempt), cap)
time.sleep(delay + random.uniform(0, 0.5 * delay))
raise last_error
return wrapper
return decorator
class CircuitBreaker:
def __init__(self, failure_threshold=5, recovery_seconds=60):
self.failure_threshold = failure_threshold
self.recovery_seconds = recovery_seconds
self.failures = 0
self.opened_at = None
def call(self, func, *args, **kwargs):
if self.opened_at is not None:
if time.time() - self.opened_at < self.recovery_seconds:
raise CircuitOpenError("dependency unavailable, failing fast")
self.opened_at = None
self.failures = 0
try:
result = func(*args, **kwargs)
except Exception:
self.failures += 1
if self.failures >= self.failure_threshold:
self.opened_at = time.time()
raise
self.failures = 0
return result
Wire the breaker to the dependency, not to the task. A single pool of breakers shared across a cluster is what lets one degraded upstream throttle the entire platform.
Quality gates that stop bad data early
A quality gate is a task whose failure legitimately blocks downstream publication. The distinction matters: failing a pipeline on a cosmetic warning trains engineers to ignore red, while publishing unvalidated data trains analysts to distrust the table. Gate on the properties consumers actually depend on: required columns present and non-null, primary keys unique, and row volume inside an expected band.
class QualityGate:
def __init__(self, checks):
self.checks = checks
def evaluate(self, df) -> dict:
results = {}
for check in self.checks:
results[check.name] = check.run(df)
failed = [name for name, ok in results.items() if not ok]
return {"passed": not failed, "failed": failed, "results": results}
class NotNullCheck:
def __init__(self, columns):
self.columns = columns
self.name = "not_null"
def run(self, df) -> bool:
return all(df.filter(F.col(c).isNull()).count() == 0 for c in self.columns)
class VolumeCheck:
def __init__(self, min_rows, max_rows):
self.min_rows = min_rows
self.max_rows = max_rows
self.name = "volume"
def run(self, df) -> bool:
count = df.count()
return self.min_rows <= count <= self.max_rows
gate = QualityGate([
NotNullCheck(["order_id", "user_id"]),
VolumeCheck(min_rows=1000, max_rows=10_000_000),
])
Route a failed gate to a quarantine path rather than deleting the data. Keeping the rejected rows means you can repair and reload them after a fix instead of re-extracting from the source, which is often impossible for events that only stream past once.
Backfills that respect dependencies
A backfill is a normal run with a different date parameter, so the first requirement is that the normal run is idempotent. Beyond that, a backfill manager must record which dates completed, skip them on rerun, bound concurrency so it does not starve production schedules, and check upstream readiness before processing each date.
from concurrent.futures import ThreadPoolExecutor, as_completed
from datetime import date, timedelta
class BackfillManager:
def __init__(self, process_date, upstream_ready, state_store, parallelism=4):
self.process_date = process_date
self.upstream_ready = upstream_ready
self.state = state_store
self.parallelism = parallelism
def run_one(self, day: date, force: bool = False) -> str:
if self.state.get(day) == "completed" and not force:
return f"skipped {day}"
if not self.upstream_ready(day):
return f"blocked {day}"
self.state.set(day, "in_progress")
try:
self.process_date(day)
self.state.set(day, "completed")
return f"done {day}"
except Exception as exc:
self.state.set(day, f"failed {exc}")
raise
def run_range(self, start: date, end: date) -> dict:
days = [start + timedelta(days=i) for i in range((end - start).days + 1)]
outcome = {"done": 0, "skipped": 0, "blocked": 0, "failed": 0}
with ThreadPoolExecutor(max_workers=self.parallelism) as pool:
futures = {pool.submit(self.run_one, d): d for d in days}
for future in as_completed(futures):
message = future.result()
outcome[message.split()[0]] += 1
return outcome
Bound the parallelism deliberately. A backfill that runs at full width will happily consume every worker slot and delay the scheduled production run, which turns a data fix into a new outage. Publish the plan before it runs, including the date range, the estimated slot usage and the expected finish time, so the on-call rotation is never surprised when half the cluster is busy at midnight. When the backfill ends, emit a summary line with how many dates completed, skipped, blocked and failed, because that is the sentence you will paste into the incident channel when someone asks whether their dashboard is current yet.
Failure modes interviewers probe
Expect questions about re-running a partially failed task, handling a dependency that is permanently down, and recovering a backfill that produced wrong results. The strongest answers name the mechanism rather than the hope: replace-where semantics for partition rewrites, a circuit breaker plus a dead-letter path for permanent failures, and checkpointed backfill state so a bad run can be invalidated and repeated without touching healthy dates.
Equally important is the human side. Every retry, gate and skip should emit a structured log line with the run identifier, the date and the reason, because the question you will actually face is not how the pipeline failed but what you can prove about which partitions are trustworthy right now.
đĄRerun drill
Once a quarter, deliberately fail a production task after its first write, then rerun it and compare the output against a known-good snapshot. Teams that skip this drill discover their non-idempotent writes during a real incident.
Common Mistakes
Appending on every run instead of overwriting a partition
Fix: Use replace-where or merge semantics so reruns converge on the same state
Retrying every exception with a fixed delay
Fix: Classify failures, retry only transient ones, and back off with jitter
Failing the pipeline on cosmetic warnings
Fix: Reserve hard gates for properties consumers depend on and quarantine the rest
Running backfills at unrestricted concurrency
Fix: Cap parallelism and yield worker slots to scheduled production tasks
Best Practices
- Keep branching shallow and push decisions into one task that returns a path
- Make fan-out units independent in both data and state before parallelizing
- Store backfill checkpoints so completed dates are skipped on rerun
- Emit a structured log line for every skip, gate failure and retry
- Place circuit breakers per dependency rather than one shared global breaker
Interview Questions
Q1: What makes a pipeline idempotent?
Running it again yields the same final state as running it once. In practice that means overwriting a partition, deduplicating on a natural key, or writing to staging and publishing atomically.
Q2: How do you decide what to retry?
Classify failures first. Retry timeouts, throttling and transient connection errors with exponential backoff and jitter; fail fast on schema, constraint and authentication errors because retrying only hides the real cause.
Q3: Design a DAG for a multi-region ETL with cross-region dependencies.
Fan out per region with independent partitions, gate each branch on its own quality checks, fan in through a merge that deduplicates on region and date, and model cross-region ordering explicitly with sensors rather than implicit task ordering.
Q4: How would you handle out-of-order arriving data?
Land raw events keyed by event time, process with watermarks or micro-batches that allow a lateness window, and make the final table merge on event time so late arrivals update rather than duplicate.
Q5: What does a self-healing pipeline look like?
Idempotent tasks, classified retries with backoff, a circuit breaker around flaky dependencies, quarantine paths for bad records, checkpointed backfills, and alerts only when automatic recovery has already been exhausted.
Key Takeaways
- Four DAG shapes cover almost everything; keep branches shallow and fan-out units independent
- Idempotency comes from overwrite, deduplication or staging plus atomic publish
- Retry only transient failures and back off with jitter to avoid thundering herds
- Circuit breakers convert cascading outages into a fast failure at one boundary
- Quality gates should block publication and quarantine rather than discard bad rows
- Bound backfill concurrency so fixes never starve scheduled production runs