Workflow Orchestration and Scheduling Questions
Orchestrating multi-step data workflows with DAG schedulers (Airflow, Dagster, and similar tools): dependency management between tasks, scheduling strategies (cron-based, sensor and trigger patterns, event-driven runs), and backfills or catch-up runs for time-partitioned data. Covers task-level retries and idempotent task design, so a scheduler can safely re-run a failed step, plus SLA tracking and alerting when a run is late or missing. The core concern is coordination: given a set of dependent tasks that must run in some order on some schedule, how do you trigger, sequence, and re-run them reliably. This is distinct from whether the data itself stays correct across a failure (exactly-once processing, deduplication, checkpointing, and dead-letter handling for corrupted or poison messages, which is a data-consistency concern) and from how a specific compute engine executes a task internally (Spark or Hadoop mechanics). The operational glue of a data platform: getting the right task to run at the right time, in the right order, with visibility into failures.
Explain how to implement graceful task termination and cleanup for long-running jobs in orchestrators. Cover how to signal workers, checkpoint progress, handle partial outputs, and make sure resources are reclaimed in cloud environments.
Sample Answer
Direct answer
Graceful termination of a long-running orchestrated task means the task gets a real chance to leave things in a safe, resumable state before it dies, not an abrupt kill. That requires the orchestrator to send an actual termination signal, not just stop watching the task, the task's own code to handle that signal by checkpointing its current progress and cleaning up any partial output, and the underlying cloud resource to be reliably reclaimed afterward, so terminated work does not silently keep consuming budget.
Structured elaboration
Signaling workers. The orchestrator sends a SIGTERM first, not a SIGKILL, giving the task's process a defined grace period, sized against how long a safe checkpoint actually takes, typically 30 to 60 seconds, to react before escalating to SIGKILL if it has not exited cleanly by then. A task that is genuinely killed abruptly, an out-of-memory kill or a spot-instance reclamation with no warning, cannot perform any graceful cleanup at all, so a robust design also has to tolerate that harsher case through checkpoint-then-resume, not assume graceful signaling always succeeds.
Checkpointing progress. The task periodically persists enough state externally, not only in its own process memory, which vanishes on termination, to resume from roughly where it left off rather than from scratch: the last successfully processed batch, offset, or row range, written to a durable store on a defined cadence, not only at the very end. The SIGTERM handler's own job is to trigger one final checkpoint write immediately upon receiving the signal, capturing progress up to that exact moment, rather than relying on the last periodic checkpoint alone, which may already be somewhat stale.
Handling partial outputs. Any output the terminated task already wrote should either be deleted on termination if it is not safely resumable, or written to a staging location that a subsequent resumed run can pick up, validate, and complete, never left as an ambiguous, half-written artifact sitting directly where a downstream consumer might read it. This is the same staging discipline used for idempotent loads: the pattern that protects against a crash mid-write also protects against a deliberate termination mid-write.
Reclaiming resources in cloud environments. After a task terminates, gracefully or by force, the orchestrator needs to confirm the underlying compute resource, a Kubernetes pod or a cloud virtual machine, is actually torn down, not just that its own internal bookkeeping marked the task as done. A resource that fails to terminate cleanly and lingers keeps quietly consuming budget and, under resource quotas, can block a legitimately queued task from getting the capacity it needs. A periodic reconciliation sweep, comparing what the orchestrator believes is running against what cloud resources actually exist, catches this drift.
Worked example
A long-running data-export task processes 2,000,000 rows in batches of 50,000, checkpointing its current offset to a durable key-value store every 30 seconds. At 14 minutes into the run, having completed 1,350,000 rows (last periodic checkpoint: offset 1,350,000), the orchestrator sends SIGTERM, since a deploy is rolling out and needs to reclaim this worker.
The signal handler immediately writes one final checkpoint capturing whatever has actually completed by that instant, offset 1,352,000, a small amount of extra progress made in the second or two between the last periodic checkpoint and the signal's arrival, then exits cleanly within the grace period. On retry, the task reads that checkpoint and resumes from offset 1,352,000, reprocessing zero already-completed rows, rather than restarting the full run from scratch, saving:
20000001352000=67.6%
of the total work that would otherwise have been unnecessarily redone.
Trade-offs and pitfalls
Checkpointing too frequently adds real overhead: a write to a durable store every few seconds, for a task processing millions of small operations, competes with the actual work for the same input/output capacity. Checkpointing too infrequently means more redone work on the average termination. This is a direct trade to tune based on how expensive both the checkpoint write and the redone work actually are, not a setting with one universally correct value.
A SIGTERM handler that takes longer than the grace period to finish its final checkpoint write gets SIGKILLed mid-write anyway, so that final write needs to be fast and, ideally, atomic, a write to a temporary location followed by a rename, not a slow multi-step write that could itself be interrupted partway through.
Assuming graceful signaling always happens, and never designing for the abrupt SIGKILL or spot-reclamation case, leaves a real gap for exactly the termination scenarios most likely to occur without any warning at all.
Design an approach to prioritize reprocessing when a bug affects many datasets but resources are constrained. How would you score datasets by business impact, freshness, downstream fan-out, and cost to recompute, and use that score to schedule backfills?
Sample Answer
Direct answer
Under constrained resources, prioritize backfills with an explicit weighted score, not a first-come or alphabetical queue: score each affected dataset on business impact, staleness, downstream fan-out, and cost to recompute, combine those into a single priority number, and schedule the highest-scoring datasets first, throttled to whatever compute the environment can actually absorb without starving the live production pipelines running alongside the backfill.
Structured elaboration
The four scoring dimensions, and what each one actually measures.
- Business impact (I, 1-5): how directly the dataset feeds a decision or external commitment. A finance-facing or customer-facing table scores high; an internal debugging table scores low.
- Freshness / staleness (F, 1-5): how stale the current (wrong) data already is, and how much worse it will get if this dataset waits longer in the queue. A dataset feeding a daily report is more urgent than one feeding a quarterly one, independent of the bug's severity.
- Downstream fan-out (D, 1-5): how many other datasets or reports depend on this one. A root-level table many others build on should generally move earlier, since fixing it unblocks everything downstream of it too, whereas a leaf table's fix only helps that one output.
- Cost to recompute (C, 1-5, where 5 is cheapest): inverted so a higher score means cheaper, so it combines additively with the other three in the same "higher is more urgent to schedule" direction, rather than needing a separate subtraction step.
Combining into a single score. A simple weighted sum, score=wII+wFF+wDD+wCC, with weights reflecting the organization's actual priorities (a finance-heavy organization might weight I higher; a platform team enabling many downstream teams might weight D higher). A reasonable starting point, absent a strong reason to weight differently, is equal weights (wI=wF=wD=wC=1), which is what the worked example below uses, since it makes the arithmetic transparent and is easy to explain to stakeholders who will ask why one dataset was prioritized over another.
Using the score to schedule, not just to rank. A ranked list alone does not solve the resource-constraint problem; convert the ranking into an actual schedule by processing datasets in score order, but bounding how many run concurrently (a fixed pool size, or a percentage of total available compute reserved for backfill work specifically, separate from what live production pipelines need) so the highest-priority items are not competing with each other for the same limited slots and taking longer collectively than a more measured, sequenced rollout would.
Revisiting the ranking as work proceeds. Freshness in particular is not static: a dataset ranked mid-list can become more urgent purely by waiting longer (its staleness score should increase the longer it sits unprocessed), so a good design re-scores periodically (or on a fixed interval, like every few hours) rather than computing the ranking once at the start and executing it rigidly, so a dataset that was reasonably deprioritized at hour 0 does not silently stay at the bottom of the queue for days while newer, lower-impact-but-recently-discovered issues get inserted ahead of it without ever being compared on the same basis.
Worked example
Four datasets are affected by the same upstream bug, with limited backfill compute meaning only two can run concurrently. Scores (1-5 each dimension, equal weights, so score is the simple sum, maximum 20):
| Dataset | Impact I | Freshness F | Fan-out D | Cost (inverted) C | Score |
|---|---|---|---|---|---|
exec_revenue_summary | 5 | 5 | 4 | 2 | 5+5+4+2=16 |
regional_sales_detail | 3 | 4 | 5 | 3 | 3+4+5+3=15 |
marketing_attribution | 2 | 2 | 2 | 4 | 2+2+2+4=10 |
internal_debug_metrics | 1 | 1 | 1 | 5 | 1+1+1+5=8 |
Ranked by score: exec_revenue_summary (16), regional_sales_detail (15), marketing_attribution (10), internal_debug_metrics (8).
With a concurrency limit of 2, the backfill schedule runs exec_revenue_summary and regional_sales_detail first (the top two by score), not simply the two cheapest to recompute (which would have been internal_debug_metrics and marketing_attribution, the two highest C values) or the two most business-critical without regard to their actual recompute cost (which happens to be the same top two here, but would not always be). Once either of the first two finishes, the next-highest-scoring remaining dataset takes the freed slot, so marketing_attribution starts as soon as one of the top two completes, keeping the pool at its 2-concurrent cap throughout rather than sitting idle waiting for both top-priority jobs to finish together.
Note regional_sales_detail outranks exec_revenue_summary on fan-out (5 vs. 4) despite lower business impact (3 vs. 5); this is exactly the kind of trade-off a single combined score is meant to surface and make explicit, rather than leaving "which matters more, impact or fan-out" as an implicit, ad hoc judgment call made differently each time a real incident happens.
Trade-offs and pitfalls
A pure business-impact ranking with no cost or fan-out consideration systematically starves cheap, high-fan-out fixes that would unblock many downstream consumers quickly, in favor of expensive, singular high-impact fixes that take much longer to actually land; the combined score exists specifically to avoid this kind of single-dimension tunnel vision.
Weights chosen once and never revisited can drift out of alignment with actual organizational priorities over time; a quarterly review of the weighting scheme (not the individual scores, which should be assessed per-incident) keeps the framework honest as the business itself changes what actually matters most.
Scoring is inherently somewhat subjective, especially business impact and fan-out, which are not always precisely measurable; the mitigation is not to abandon scoring for pure gut-feel prioritization, but to make the scoring criteria explicit and documented (what does a 5 versus a 3 on business impact actually mean, concretely) so different people scoring different incidents produce comparable, defensible numbers rather than each person's own private intuition dressed up as an objective score.
Finally, a static one-time ranking that is not revisited as backfills complete and new information arrives (a dataset's actual recompute cost turning out higher than estimated once work starts, for example) can leave the schedule executing against stale assumptions; treating the score as a living input that gets recomputed on a cadence, not a one-time gate, is what keeps the prioritization honest under real, changing conditions.
Explain the difference between pipeline-level concurrency, DAG-level parallelism, and task-level parallelism. How do Airflow executors (LocalExecutor, CeleryExecutor, KubernetesExecutor) influence these types of parallelism, and what are trade-offs in resource isolation, scalability, and operational complexity?
Sample Answer
Direct answer
These three terms describe parallelism at three different grains, from coarsest to finest: pipeline-level concurrency is how many separate DAGs (or DAG runs across different DAGs) execute at once across the whole orchestrator; DAG-level parallelism is how many runs of the same DAG execute at once; task-level parallelism is how many individual task instances execute at once, whether from the same run or different runs. Each grain has its own limiting configuration, and the executor determines what actually enforces the limit at the task-level grain specifically, since that is where real compute gets consumed.
Structured elaboration
| Level | What it controls | Typical config | What limits it |
|---|---|---|---|
| Pipeline-level concurrency | How many DAGs, across the whole orchestrator, have runs executing simultaneously | Global scheduler/parallelism settings | The scheduler's own overall capacity and configuration |
| DAG-level parallelism | How many runs of one specific DAG execute simultaneously | max_active_runs (and concurrency/max_active_tasks for tasks within those runs) | Per-DAG configuration, independent of other DAGs |
| Task-level parallelism | How many individual task instances (from any run, any DAG) execute simultaneously | Pools, executor worker capacity | The executor's actual execution capacity |
Pipeline-level concurrency. The orchestrator-wide ceiling on total simultaneous activity: how many DAGs total have runs actively executing at once. This is largely a function of the scheduler's own overall settings (global parallelism limits) and, ultimately, of how much execution capacity the environment as a whole has, since pipeline-level concurrency is meaningless without task-level capacity to actually back it.
DAG-level parallelism. Controlled per DAG via max_active_runs (how many separate runs of this one DAG can be in progress at the same time, relevant when backfilling or when a DAG's schedule interval is tight enough that a new run can trigger before the last one finishes) and a per-DAG task concurrency setting (how many task instances within this DAG's own runs can execute simultaneously). This is scoped entirely to one DAG; it says nothing about how that DAG's activity interacts with any other DAG's.
Task-level parallelism. The finest grain: how many individual task instances, potentially spanning multiple DAGs and multiple runs, execute at the exact same moment. This is where pools become relevant (a pool can cap concurrent task instances across DAG boundaries, not just within one), and it is the level at which the executor's actual capacity is the real, physical constraint, since a task instance only "executing" means a worker (a process, a Celery worker, a Kubernetes pod) is actually running it right now.
How executors influence these levels. The executor is specifically what enforces (or fails to enforce) the task-level grain, since it is the layer that actually claims a worker slot and runs a task:
- LocalExecutor runs task subprocesses on the scheduler's own host, bounded by that single machine's CPU and memory; task-level parallelism across the whole environment is hard-capped by one machine's capacity, regardless of how generously pipeline-level or DAG-level settings are configured.
- CeleryExecutor distributes task execution across a worker fleet via a message broker; task-level parallelism scales with the size of that fleet, largely decoupled from the scheduler host's own capacity, which is what lets pipeline-level and DAG-level concurrency settings actually be realized at a meaningfully larger scale than LocalExecutor allows.
- KubernetesExecutor gives each task instance its own pod, so task-level parallelism is bounded by the Kubernetes cluster's total capacity, not a fixed worker count; it can, in principle, scale further than a fixed Celery worker fleet, at the cost of per-task pod-startup latency.
Trade-offs.
- Resource isolation. LocalExecutor offers the least: every concurrent task shares the same host's CPU, memory, and disk, so a resource-hungry task can degrade every other concurrently-running task on the same machine. CeleryExecutor offers isolation at the worker-process level, better but still shared within a given worker's own environment unless workers are specifically partitioned. KubernetesExecutor offers the strongest isolation, since each task gets its own pod with its own resource requests and limits, unaffected by any other task's resource use.
- Scalability. LocalExecutor does not scale horizontally at all; adding capacity means a bigger single machine, with a hard ceiling. CeleryExecutor scales by adding worker nodes to the fleet. KubernetesExecutor scales with the underlying cluster's own capacity, which is typically the most elastic of the three, especially when combined with cluster autoscaling.
- Operational complexity. LocalExecutor is the simplest to operate, nothing beyond the scheduler itself. CeleryExecutor adds a message broker and a worker fleet to provision, monitor, and keep healthy. KubernetesExecutor adds a Kubernetes cluster, image build and publish pipelines, and pod-template management, the most operational surface area of the three.
Worked example
An environment runs 50 DAGs. Pipeline-level concurrency is set so at most 20 DAGs have active runs at once (a global scheduler setting); one specific high-frequency DAG sets max_active_runs=3 (DAG-level, allowing up to 3 of its own runs to overlap if its schedule interval is tight) with max_active_tasks=10 (also DAG-level, bounding how many of its own tasks run concurrently within those overlapping runs); a shared heavy_compute pool caps task-level parallelism at 5 concurrent task instances specifically for tasks in that pool, regardless of which of the 50 DAGs they come from, since several different DAGs each have one or two tasks that are genuinely resource-heavy and need protecting from over-concurrency even though the DAGs themselves are otherwise unrelated.
Under LocalExecutor, all of this is still bounded by whatever the single scheduler host's CPU and memory can actually support concurrently; the heavy_compute pool's cap of 5 is only meaningful if the host can genuinely run 5 heavy tasks at once without degrading everything else sharing that machine. Migrating to CeleryExecutor with a 10-node worker fleet decouples task-level execution capacity from the scheduler host, so the same pipeline-level, DAG-level, and pool settings can now be realized without every concurrent task competing for one machine's resources; migrating further to KubernetesExecutor would give each of those 5 concurrent heavy-compute tasks its own pod with explicit memory and CPU requests, the strongest isolation of the three, at the added cost of operating the underlying cluster and its image pipeline.
Trade-offs and pitfalls
Configuring generous pipeline-level and DAG-level concurrency settings while running LocalExecutor is a common mismatch: the settings imply more parallelism than the executor can actually deliver, so tasks queue behind the scheduler host's real capacity regardless of what the configuration says is allowed, which can be confusing to diagnose since the configuration itself looks correctly generous.
Treating pools as redundant with max_active_tasks is a common misunderstanding: max_active_tasks bounds concurrency within one DAG's own runs, while a pool bounds concurrency across DAG boundaries for a specific category of task; a resource-heavy task type appearing in five different DAGs needs a shared pool to actually protect the resource it contends on, since five separate DAGs' own max_active_tasks settings have no visibility into each other.
Jumping to KubernetesExecutor purely for its stronger resource isolation, without the actual task-count and heterogeneity that justifies the added per-task pod overhead, trades a real, ongoing operational cost (cluster management, image pipelines) for an isolation benefit the workload may not need; LocalExecutor's simplicity, or CeleryExecutor's middle ground, are often the better fit until genuine per-task isolation requirements or elastic-scale needs actually appear.
Outline or implement an Airflow Sensor operator in Python that waits for S3 prefixes matching 's3://bucket/incoming/date=YYYY-MM-DD/' to appear. Requirements: poll with exponential backoff starting at 30s up to 10m, support soft_fail flag, and be compatible with Airflow 2. Describe how you'd test and scale this sensor.
Sample Answer
Direct answer
The sensor below waits for an S3 prefix to have at least one object, using Airflow's own built-in exponential-backoff mechanism (exponential_backoff=True plus mode="reschedule"), configured with poke_interval=30 and max_wait=timedelta(minutes=10) to match the required 30-second-to-10-minute range, with soft_fail passed straight through so a timeout can be a skip instead of a failure when the caller wants that. The key design choice is not hand-rolling a custom backoff loop: BaseSensorOperator already implements a correct, jittered exponential backoff internally, so the sensor only needs to configure it correctly, not reimplement it.
Structured elaboration
Airflow 2 compatibility. Subclassing airflow.sensors.base.BaseSensorOperator and implementing poke(self, context) returning a bool is the standard Airflow 2.x sensor contract; template_fields marks bucket and prefix_template as Jinja-templatable, so a caller can pass prefix_template="incoming/date={{ ds }}/" and have it rendered per logical date at run time.
Poll with exponential backoff, 30 seconds to 10 minutes. Rather than writing a custom sleep-and-retry loop, this uses Airflow's own exponential_backoff and max_wait parameters, which only take effect in mode="reschedule". poke_interval=30 sets the starting point; Airflow's internal _get_next_poke_interval computes each next delay by doubling from that base and applying a deterministic, hash-based jitter (so many parallel sensor instances polling different prefixes do not all re-poke at the exact same instant), capped by max_wait. This is verified directly in the worked example below by calling that internal method and printing the actual resulting delay sequence, not by trusting the parameter names alone.
soft_fail. Passed straight through to BaseSensorOperator.__init__, which owns the decision of what a timeout means: with soft_fail=True, a timeout raises AirflowSkipException (marking the task, and by extension anything gated on it, skipped rather than failed); with soft_fail=False (the default here), a timeout is a hard failure. The sensor does not re-implement this branch itself, since duplicating logic the base class already owns risks silently drifting from Airflow's actual behavior on a future Airflow upgrade.
Testing. Inject a fake S3 client via s3_client_factory (defaulting to a real boto3.client("s3") only when none is provided) so poke()'s logic can be tested against a deterministic in-memory object list, with no network calls or credentials, covering both the empty-prefix and populated-prefix cases directly. Separately, call the base class's own _get_next_poke_interval directly against a configured instance to confirm the actual delay sequence a production run would use, since a wrong poke_interval/max_wait pairing would be a config-level bug that a pure poke() unit test would never catch.
Scaling. For many prefixes watched concurrently (one sensor instance per source, for example), mode="reschedule" is what keeps this cheap at scale: each sensor releases its worker slot between pokes instead of holding one for the entire wait, so hundreds of concurrent sensors cost worker capacity only for the brief moments they are actually checking, not for the (much longer) time they spend waiting. The jitter built into Airflow's backoff calculation (visible in the worked example's non-monotonic-looking but internally consistent delay values) is also specifically what prevents many simultaneously-started sensors from synchronizing their poke timing and hammering S3's API in lockstep.
Worked example
from datetime import datetime, timedelta
from airflow import DAG
from airflow.sensors.base import BaseSensorOperator
from airflow.utils.context import Context
class S3PrefixSensor(BaseSensorOperator):
"""
Waits for at least one object under s3://{bucket}/{prefix_template}, where
prefix_template is formatted with the run's own logical date, e.g.
'incoming/date={{ ds }}/'. Airflow 2 compatible (subclasses BaseSensorOperator,
uses **context and the standard poke() contract).
Poll behavior: exponential_backoff=True + reschedule mode makes Airflow itself
compute the delay before each next poke, starting near poke_interval and capped
at max_wait, WITH jitter (so many parallel instances of this sensor watching
different prefixes don't all re-poke S3 in lockstep). We do not hand-roll our
own backoff loop: Airflow's BaseSensorOperator already implements this correctly
(_get_next_poke_interval), so we only need to pass the right parameters.
soft_fail: if True, a timeout marks this task (and its DAG run) SKIPPED instead
of FAILED, useful when a missing prefix is an expected, tolerable outcome for
some callers of this sensor (e.g. an optional enrichment source) rather than a
hard pipeline failure.
"""
template_fields = ("bucket", "prefix_template")
def __init__(
self,
*,
bucket,
prefix_template,
s3_client_factory=None,
poke_interval=30, # starting delay: 30s, per requirement
max_wait=timedelta(minutes=10), # cap: 10 minutes, per requirement
timeout=60 * 60 * 6, # give up entirely after 6 hours
soft_fail=False,
**kwargs,
):
super().__init__(
poke_interval=poke_interval,
timeout=timeout,
mode="reschedule", # required for exponential_backoff to take effect
exponential_backoff=True, # required: this IS the "poll with exponential backoff" mechanism
max_wait=max_wait,
soft_fail=soft_fail,
**kwargs,
)
self.bucket = bucket
self.prefix_template = prefix_template
# Injectable for testing; defaults to a real boto3 client in production.
self._s3_client_factory = s3_client_factory or (lambda: __import__("boto3").client("s3"))
def poke(self, context: Context) -> bool:
prefix = self.prefix_template
client = self._s3_client_factory()
keys = client.list_object_keys(self.bucket, prefix)
self.log.info("checked s3://%s/%s -> %d object(s)", self.bucket, prefix, len(keys))
return len(keys) > 0
demo_dag = DAG(
dag_id="demo_dag",
start_date=datetime(2026, 1, 1),
schedule=None,
catchup=False,
)
print("=== Case 1: sensor parameters are wired exactly as required ===")
sensor = S3PrefixSensor(
task_id="wait_for_incoming",
bucket="incoming-bucket",
prefix_template="incoming/date=2026-07-29/",
poke_interval=30,
max_wait=timedelta(minutes=10),
soft_fail=False,
dag=demo_dag,
)
print("poke_interval:", sensor.poke_interval)
print("max_wait:", sensor.max_wait)
print("mode:", sensor.mode)
print("exponential_backoff:", sensor.exponential_backoff)
print("soft_fail:", sensor.soft_fail)
assert sensor.poke_interval == 30
assert sensor.max_wait == timedelta(minutes=10)
assert sensor.mode == "reschedule"
assert sensor.exponential_backoff is True
assert sensor.soft_fail is False
print("PASS: sensor is configured with 30s starting interval, 10min cap, reschedule mode, backoff on")
class FakeS3Client:
def __init__(self, objects):
self._objects = objects
def list_object_keys(self, bucket, prefix):
return sorted(k for k in self._objects if k.startswith(prefix))
print()
print("=== Case 2: poke() correctly reports False when the prefix is empty, True once populated ===")
fake_empty = FakeS3Client({})
sensor_empty = S3PrefixSensor(
task_id="wait_for_incoming_2",
bucket="incoming-bucket",
prefix_template="incoming/date=2026-07-29/",
s3_client_factory=lambda: fake_empty,
)
result_empty = sensor_empty.poke(context={})
print("poke() with 0 objects present:", result_empty)
assert result_empty is False
fake_populated = FakeS3Client({"incoming/date=2026-07-29/part-0000.json": b"{}"})
sensor_populated = S3PrefixSensor(
task_id="wait_for_incoming_3",
bucket="incoming-bucket",
prefix_template="incoming/date=2026-07-29/",
s3_client_factory=lambda: fake_populated,
)
result_populated = sensor_populated.poke(context={})
print("poke() with 1 object present:", result_populated)
assert result_populated is True
print("PASS: poke() correctly distinguishes empty vs populated prefix")
print()
print("=== Case 3: the REAL Airflow backoff schedule this configuration produces ===")
started_at = 0.0
intervals = []
for poke_count in range(1, 12):
interval = sensor._get_next_poke_interval(
started_at=started_at,
run_duration=lambda: sum(intervals),
poke_count=poke_count,
)
intervals.append(interval)
print(f" poke_count={poke_count}: next interval = {interval:.1f}s")
print("first interval >= 15s (near the 30s starting point, jitter included):", intervals[0] >= 15)
print("max observed interval:", max(intervals), "s (must be <= max_wait=600s)")
assert intervals[0] < 60, "first interval should be close to poke_interval (30s), not already at the 10-min cap"
assert max(intervals) <= 600, "no interval should ever exceed max_wait (600s / 10 minutes)"
assert intervals[-1] >= intervals[1], "later intervals should trend upward toward the cap, not shrink"
print("PASS: backoff starts near 30s and is capped at 600s (10 minutes), exactly as required")
print()
print("=== Case 4: soft_fail is correctly wired through to the base sensor's failure behavior ===")
soft_sensor = S3PrefixSensor(
task_id="wait_for_optional_source",
bucket="incoming-bucket",
prefix_template="incoming/optional/date=2026-07-29/",
soft_fail=True,
)
print("soft_fail on soft_sensor:", soft_sensor.soft_fail)
assert soft_sensor.soft_fail is True
print("PASS: soft_fail=True is passed through to BaseSensorOperator, which owns the "
"skip-vs-fail decision on timeout")
print()
print("ALL CASES PASSED")
Output (actual, from running the block above under Airflow 2.11.2):
=== Case 1: sensor parameters are wired exactly as required ===
poke_interval: 30.0
max_wait: 0:10:00
mode: reschedule
exponential_backoff: True
soft_fail: False
PASS: sensor is configured with 30s starting interval, 10min cap, reschedule mode, backoff on
=== Case 2: poke() correctly reports False when the prefix is empty, True once populated ===
poke() with 0 objects present: False
poke() with 1 object present: True
PASS: poke() correctly distinguishes empty vs populated prefix
=== Case 3: the REAL Airflow backoff schedule this configuration produces ===
poke_count=1: next interval = 15.0s
poke_count=2: next interval = 41.0s
poke_count=3: next interval = 60.0s
poke_count=4: next interval = 159.0s
poke_count=5: next interval = 327.0s
poke_count=6: next interval = 600.0s
poke_count=7: next interval = 600.0s
poke_count=8: next interval = 600.0s
poke_count=9: next interval = 600.0s
poke_count=10: next interval = 600.0s
poke_count=11: next interval = 600.0s
first interval >= 15s (near the 30s starting point, jitter included): True
max observed interval: 600.0 s (must be <= max_wait=600s)
PASS: backoff starts near 30s and is capped at 600s (10 minutes), exactly as required
=== Case 4: soft_fail is correctly wired through to the base sensor's failure behavior ===
soft_fail on soft_sensor: True
PASS: soft_fail=True is passed through to BaseSensorOperator, which owns the skip-vs-fail decision on timeout
ALL CASES PASSED
Case 3 is the most important proof here: it does not merely assert the parameters were set, it calls Airflow's own internal _get_next_poke_interval (the exact method the real scheduler uses to decide when to re-poke a rescheduled sensor) and shows the actual sequence: starting at 15.0s (within the jittered range for a base of 30s, since Airflow's jitter can land anywhere in roughly half to just-under-double the deterministic backoff value for early pokes), growing through 41.0s, 60.0s, 159.0s, 327.0s, and reaching exactly the 600.0s cap (10 minutes) from the 6th poke onward, never exceeding it. This confirms the "30 seconds up to 10 minutes" requirement against Airflow's real behavior, not against a hand-written reimplementation that could silently diverge from it.
Key points, complexity, and edge cases
Key points: the backoff is delegated to Airflow's built-in mechanism rather than reimplemented, which is both less code and less risk of drifting from real scheduler behavior; the S3 client is injectable specifically so poke()'s logic is unit-testable without network access.
Complexity: each poke() call is O(k) where k is the number of objects under the prefix (one list-and-filter operation); the sensor's own overhead does not grow with how long it has been waiting, only with how many objects exist once something is finally there.
Edge cases: a prefix matching zero objects correctly returns False (Case 2), not an error, letting the sensor's own reschedule loop handle the wait; a soft_fail=True sensor's timeout still correctly reports as a distinct outcome from a poke() returning False repeatedly, since soft_fail only changes what happens once timeout is actually reached, not the meaning of any individual poke() result.
Trade-offs and pitfalls
Setting mode="poke" instead of mode="reschedule" would silently disable the exponential backoff entirely: exponential_backoff and max_wait only take effect in reschedule mode, so this is not just a resource-usage choice, it is required for the stated poll behavior to work at all, which is why the sensor hardcodes mode="reschedule" rather than leaving it as a caller-configurable parameter that could be set wrong.
Reimplementing backoff and jitter by hand, instead of using Airflow's own _get_next_poke_interval, is tempting for finer control but risks a subtle, hard-to-notice divergence from how the rest of the fleet's sensors behave, plus ongoing maintenance burden keeping a custom implementation in sync with any future Airflow scheduling changes; delegating to the base class trades a small amount of control for a large amount of correctness confidence.
A soft_fail=True sensor whose prefix never arrives will silently skip its downstream tasks rather than failing loudly; this is exactly the intended behavior for an optional source, but using soft_fail=True by default on a sensor that is actually required (not optional) would turn a genuine data-completeness problem into a silent skip nobody investigates, so the flag needs to be set deliberately per use case, not copied as a default across every instance of this sensor.
A scheduled hourly DAG frequently queues hundreds of small tasks and the scheduler itself becomes a bottleneck, delaying end-to-end freshness. What architectural or configuration changes would you propose to reduce scheduler pressure?
Sample Answer
Direct answer
Hundreds of small tasks queuing every hour is a symptom of the scheduler's own per-task overhead (parsing, dependency evaluation, database writes for state transitions) becoming the bottleneck rather than the actual work the tasks do. The fix is rarely "make the scheduler faster" in isolation; it is usually reducing the number of discrete task instances the scheduler has to manage per unit time, tuning the scheduler's own concurrency and parsing settings, and making sure the metadata database, which every task-state transition writes to, is not itself the hidden constraint.
Structured elaboration
Reduce the actual task count, first. The single highest-leverage fix is usually architectural, not a config tweak: if hundreds of small tasks are really doing conceptually similar work (processing many small files, checking many similar conditions), consolidate them into fewer, larger tasks that each handle a batch internally, rather than one orchestrator-managed task per unit of work. A task that loops over 200 small files inside a single Python callable produces the same business outcome as 200 separate tasks, at a fraction of the scheduler overhead, since the orchestrator now only has one task instance's state transitions to track instead of 200. Where per-item isolation is genuinely needed (so one bad item's failure does not block the rest), dynamic task mapping (fan out at runtime with a bounded map, not hundreds of independently-authored task definitions) is a middle ground: it keeps per-item retry isolation while still being a single logical task definition the scheduler manages more efficiently than hundreds of hand-authored ones.
Tune scheduler parsing and heartbeat settings. The scheduler periodically re-parses every DAG file to detect changes and evaluate what needs to run; a large number of DAG files, or DAGs whose top-level code is itself slow (heavy imports, network calls at parse time), directly increases this parsing overhead. Increasing parsing_processes (parallelizes DAG file parsing across more worker processes) and setting min_file_process_interval to a sensible value (not re-parsing every file every few seconds if DAGs do not change that often) reduces wasted scheduler cycles spent re-parsing rather than scheduling. Auditing DAG files for expensive top-level code (a database query or an API call executed at import time, outside any task) and moving that logic inside a task instead is a very common, high-impact fix, since that cost is paid on every single parse cycle for every file, not once per run.
Scale scheduler and executor capacity appropriately. If a single scheduler process is genuinely CPU-bound processing hundreds of tasks per hour, most modern orchestrator versions support running multiple scheduler replicas concurrently (leader-election or active-active depending on the version), which directly increases the system's task-processing throughput rather than tuning a single process harder. On the executor side, confirm the worker fleet (Celery workers, or the Kubernetes cluster's own capacity for KubernetesExecutor) is not itself capped below what the scheduler is now trying to dispatch; a scheduler that can keep up but hands work to a worker pool that cannot is a different bottleneck wearing the same symptom.
Check the metadata database. Every task-state transition (queued, running, success, failed) is a write to the shared metadata database; at high task-instance volume, this database's own connection pool size, query latency, and index health can become the actual bottleneck underneath what looks like "the scheduler is slow." Confirm the database has adequate connections configured for the scheduler and worker fleet's combined load, and check for slow queries or lock contention on the task-instance table specifically, since a database-side bottleneck presents identically to a scheduler-side one from the outside (things queue and are slow to start) but needs a completely different fix.
Use pools to shape contention, not just reduce it. If the hundreds of small tasks legitimately need to stay separate (per-item retry isolation matters), at minimum bound their concurrency with a dedicated pool sized to what the downstream systems they touch can actually absorb, so they queue in a controlled, visible way rather than all attempting to dispatch simultaneously and contending both for scheduler attention and for whatever external resource they touch.
Worked example
An hourly DAG discovers roughly 300 small files per run (a few KB each) and, as currently built, spawns one task per file (extract-file-1, extract-file-2, ..., extract-file-300), all fanning out from a single upstream discovery task. End-to-end freshness has degraded from a typical 8-minute run to over 40 minutes, and other, unrelated DAGs in the same environment have also started showing delayed starts.
Diagnosis: scheduler CPU utilization is consistently pegged near its limit during the hourly spike, and the metadata database shows a spike in write latency on the task-instance table correlated with the same window, confirming both the scheduler's own processing and the database write path are under pressure simultaneously, not just one or the other.
Fix, applied in order of impact: first, the 300 per-file tasks are consolidated into a single dynamically-mapped task that processes files in fixed-size batches of 25 (12 mapped task instances instead of 300 individually-scheduled ones), cutting the scheduler's per-hour task-instance count by roughly 25x for this DAG while keeping batch-level retry isolation (a failed batch of 25 retries independently, rather than one giant task retrying all 300 files on any single failure). Second, parsing_processes is increased from its default and a slow top-level API call discovered in the DAG file (used to fetch the file list at parse time, not at task-run time) is moved inside the discovery task instead, removing that cost from every scheduler parse cycle. After both changes, the hourly run returns to an 8-10 minute completion time, and the previously-affected unrelated DAGs also recover their normal start times, confirming the shared scheduler and database were the actual bottleneck, not anything specific to those other DAGs.
Trade-offs and pitfalls
Consolidating many small tasks into fewer, larger ones trades away per-item retry granularity: a single task processing a batch of 25 files that fails partway through either has to retry the whole batch (redoing already-successful work, assuming the batch's writes are idempotent) or needs its own internal checkpointing to resume only the unfinished items, which adds complexity the original many-small-tasks design got for free from the orchestrator's own per-task retry mechanism. Sizing the batch (25 in the example, not 1 and not 300) is the actual tuning decision, trading scheduler overhead against retry blast radius.
Throwing more scheduler replicas or worker capacity at the problem without first checking the metadata database is a common trap: if the database's own connection pool or query performance is the real constraint, adding more schedulers or workers just means more processes contending for the same already-saturated database writes, which can make effective throughput worse, not better, while looking on paper like more capacity was added.
Finally, moving expensive logic out of DAG top-level code and into a task is an easy fix to state but easy to miss in practice, since it often is not obviously "top-level code" to whoever wrote it, a helper function called at import time to build a list of tasks dynamically is just as costly per parse cycle as an explicit API call sitting directly in the file, and both need to be found by actually profiling DAG parse time, not just reading the code and guessing.
Unlock Full Question Bank
Get access to all Workflow Orchestration and Scheduling interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.