Skip to content
Tech Interview Prep
Technical interview guide

Data Pipeline Orchestration

Scheduling and sequencing interdependent pipeline steps as a DAG, with retries and backfills.

Minutes to read
3
Practice MCQs
25
Interview Q&A
25
Edition
v5
Editorial status
Reviewed

Scope: Apache Airflow 3.3.x, Prefect 3, Kubernetes 1.36, and OpenLineage 1.53 documentation current 2026-08-31.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-1

Design orchestration for a daily source-to-warehouse data product.

Answer

The 90-second answer

Before drawing a DAG I pin three things: what the consumer does with the data and by when, which logical interval a run represents, and where the source's authoritative cut sits for that interval. Everything else follows.

Assume a daily product. Source is an OLTP Postgres plus an events table. Airflow 2.9 orchestrates, dbt transforms, Snowflake stores. Two consumers: a finance mart that must be correct by 09:00 UTC, and a feature job that must have the table by 07:00 UTC. Missing the feature deadline yields a stale model; missing finance yields a wrong number. That asymmetry sets the design: publish a version early, gate correctness on its own, never let DAG success stand in for data correctness.

The graph is one chain per source (readiness sensor, extract to immutable landing, validate, transform, reconcile) meeting at a publish task that also notifies consumers. Independent sources fan out in parallel and converge only at publish.

Why landing is immutable

Write raw bytes to object storage under a stable key, e.g. landing/orders/ingest_date=2024-03-10/extract_ts=20240310T0512Z/part-000.parquet. A transform is now a pure function of (raw partition, code version, data_interval). Re-running it after a bug fix reproduces the same output, so you can diff the new result against the old one. If the extract instead overwrites a landing table or re-queries the source, replay is gone: the source has moved on and last Tuesday's wrong number can never be reconstructed. Replay then costs a warehouse scan: an X-Small Snowflake warehouse bills 1 credit per hour, 60-second minimum per resume: instead of a re-extraction against production, which is the expensive and sometimes impossible half.

Choices, and what decides them

DecisionUse thisInstead ofDeciding criterion
Source arrivalAirflow sensor, poke_interval=60, mode="reschedule", timeout=3hAirflow 2.4+ datasets (assets in 3.0), Dagster asset sensorsArrival predictable within a window: sensor, keep it simple. Unpredictable: event-driven, because a polling sensor holds a worker slot
Incremental strategyMERGE on (partition, natural_key)INSERT OVERWRITE on the partitionOverwrite is cheaper and atomic when the model is a full rebuild of one day; merge when you receive deltas only or must keep history
PublicationStage, then ALTER TABLE staging SWAP WITH live (Snowflake, metadata-only)DELETE + INSERT into the live tableConsumers must never read a half-published day

Failure modes and what you alert on

FailureSignalResponse
Late sourceSensor times out at 06:00 UTCFail that interval, do not publish, auto-trigger on arrival
Partial inputExtracted max(event_time) < data_interval_endMark partition incomplete and refuse publish; row count alone misses truncation at a page boundary
Duplicate triggerTwo runs for the same intervalIdempotent key means the second merge is a no-op; alert on attempt count, not on rows
Worker lost after commit, before ackTask retriesSafe only because the write is keyed; a non-idempotent publish here is a real corruption path, so set retries=0 on publish
DST boundary23-hour or 25-hour logical dayStore UTC, compute the interval in the source's business timezone. 2024-03-10 US/Eastern is [05:00Z, 2024-03-11T04:00Z), 23 hours; 2024-11-03 is 25
Schema changeValidation compares against the previous landing schemaQuarantine that partition, page the owner, keep the prior version live

Numbers to bake in

Airflow defaults are retries=0 and no execution_timeout, so set them: extract and transform retries=3, retry_delay=5min, retry_exponential_backoff=True, max_retry_delay=20min. Bound concurrency rather than hoping: a source_api pool of 4 slots holds you under a 10 rps vendor limit, and a snowflake_load pool of 8 matches dbt threads: 8 (default is 1) plus the warehouse's active statements. Set max_active_runs=1 on the daily DAG (default is 16) so a slow run cannot overlap the next interval. Backfills run as a bounded date range into a dedicated pool, on separate capacity, so a 30-day replay cannot starve the 06:00 job.

Monitor scheduler and queue delay, event-time freshness (max(event_time) versus now, not task status), retry counts, pool saturation, and consumer delivery. Test source outage, sink outage, partial publish, duplicate trigger and the DST day; a green leaf task is not acceptance evidence.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Migrate a collection of cron jobs to a workflow orchestrator.

Answer

Clarify first. How many jobs, what do they touch, and what is forcing the move? If the driver is "we can't see failures" or "we need backfills," an orchestrator earns its cost. If it is "cron is old," it does not. I'll assume ~400 jobs, mostly Python and shell on a mix of VMs, a handful of real cross-job dependencies, and Airflow 2.x as the target: the same reasoning applies to Dagster or Temporal.

Core answer. Don't port cron lines. Re-derive each job as a function of a named interval, then let the orchestrator own scheduling, retries and identity.

  1. Inventory. For each job record owner, the actual schedule (not the comment), timezone, whether it reads now()/date, inputs and outputs with paths, credentials, retry behavior, locks, side effects, and any undocumented ordering. The undocumented ordering is where migrations break.
  2. Define the interval. Replace "yesterday" with a half-open interval [start, end). This is the change that makes everything else possible.
  3. Refactor for idempotency. Write to a staging path keyed by the interval, then atomically swap. For external APIs, pass an idempotency key derived from the interval so a retry is a no-op.
  4. Model dependencies. Only real ones. Keep parallelism; use pools for shared systems (say a database pool of 8 connections).
  5. Cut over. Shadow-run, compare, then flip.

Why interval identity works. A cron job running date -d yesterday is a function of wall-clock time, not of the data. If the box is down at 02:00 and the job runs at 09:00, "yesterday" is still yesterday. Fine. But if it runs at 00:30 after a DST fall-back, or is retried, it can process the same day twice or skip one. An interval-keyed job is a pure function of [start, end): a retry recomputes the same interval, and the idempotency key makes the second write a no-op.

DST, concretely. TZ=America/New_York with 0 2 * * *: on the second Sunday in March, 02:00 local does not exist, so Vixie cron runs the job at the next valid time (03:00); on the first Sunday in November, 01:00–02:00 happens twice, so a 30 1 * * * job runs twice. In Airflow the interval boundaries are computed in the DAG's timezone, so the interval is 23 or 25 hours long on those days but is still a single named interval: no double run, no skip.

Python
from airflow.decorators import dag, task
from datetime import datetime

@dag(schedule="0 2 * * *", start_date=datetime(2024, 1, 1),
     catchup=True, max_active_runs=1, default_args={"retries": 3})
def daily_rollup():

    @task
    def rollup(data_interval_start=None, data_interval_end=None):
        # half-open interval; key derived from the interval, not from now()
        run_rollup(start=data_interval_start, end=data_interval_end,
                   idempotency_key=f"daily_rollup:{data_interval_start.isoformat()}")

    rollup()

daily_rollup()

Note the Airflow gotcha: the run whose data_interval_end is 2024-03-09T02:00 covers [2024-03-08T02:00, 2024-03-09T02:00). The run for day X processes day X−1. Get this wrong and every downstream consumer is off by one.

Trade-offs.

OptionUse whenDon't use when
AirflowBatch Python jobs, backfills, a UI, existing Python teamSub-second latency, hour-long tasks, event-driven
TemporalLong-running, stateful, signal-driven workflowsSimple nightly batch; the Cassandra/MySQL + Elasticsearch stack is heavy
DagsterAsset-centric data products with lineage and partitionsYou just need a scheduler
Stay on cronIndependent single-node jobs, no backfills, no dependenciesYou need retries, lineage, or cross-job ordering

Roughly 60% of a typical cron fleet is the last row. Migrating those buys nothing and adds a scheduler, a metadata DB, and a new failure domain. Migrate the 25% with real dependencies first; delete the 15% that are dead.

Failure modes.

  • Double-write at cutover: cron and the DAG both fire. Disable the crontab entry before enabling the DAG; idempotency keys are the backstop.
  • Backfill storm: catchup=True with a year-old start_date queues 365 runs. Cap with max_active_runs and pools.
  • Timezone drift: DAGs default to UTC; a job that was TZ=America/New_York now fires five hours off.
  • Zombie tasks: a hung task holds a pool slot forever without execution_timeout.

Cutover. Shadow-run each job for a week, diff outputs and timing, then flip in waves of ~20 jobs. Decommission the crontab only after freshness, recovery and owner sign-off.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

Choose schedule-, sensor-, or event-triggered orchestration.

Answer

Clarify first. What decision does the output drive, and how stale can it be? Then: does the source emit a completeness signal, or only a presence signal?

Assume this: hourly Parquet files land under s3://landing/orders/dt=.../, a Kafka topic carries order-status CDC, and a dashboard refreshes every 15 minutes. Files can arrive up to 40 minutes late; Kafka events are at-least-once.

Answer. Use all three, per source, not one globally. Schedule the file ingestion, hourly at :05 with a readiness check, because the producer contract is "a file per hour" and a schedule is the only mode that can express "run for interval 14:00 even though it is now 15:20." Put an event trigger on the Kafka topic to start the fast path within seconds. Use a sensor only where you must wait on an external system you do not control and cannot get a callback from.

Why deferrable sensors matter. A classic Airflow sensor in mode="poke" holds a worker slot for the entire wait; with the default poke_interval=60, 200 concurrent sensors occupy 200 slots and starve real tasks. mode="reschedule" releases the slot between pokes but still wakes the scheduler every minute. Deferrable operators (Airflow 2.2+, run by the triggerer) hand the wait to an asyncio event loop and free the worker entirely: that is the difference between a 20-slot pool surviving 200 waits and not.

Why receipt time breaks backfills. Bind every run to a logical interval, not wall clock. Airflow's data_interval_start/data_interval_end (2.2+) with catchup=True let you re-run 14:00 next week and land in the same partition. Key on now() and a backfill writes today's date into yesterday's partition, silently double-counting.

Event failure modes. S3 event notifications and EventBridge are at-least-once: expect duplicates and no ordering guarantee. Kafka orders per partition only, and consumers are at-least-once unless you set enable.idempotence=true and use transactions. So dedupe on a stable key (S3 object key + versionId, or topic-partition-offset), make the write idempotent (MERGE on the natural key), and reconcile with a scheduled sweep counting expected vs. landed objects. EventBridge retries a failed target for up to 24 hours by default; attach a DLQ or the failure disappears.

Quiet periods and storms. A sensor with no timeout waits forever on a quiet day: set timeout and exponential_backoff=True. A source-side bulk backfill fires thousands of triggers; cap with max_active_runs and a pool, and debounce by aggregating events into a 60-second window before starting a run.

ModeLatency to startFails whenCost
Scheduleup to one interval (1 h)source late or emptycheap, auditable
Sensorpoll interval (60 s default)no timeout hangs; poke mode burns slotsworker or triggerer slots
Eventsecondsduplicate, lost, out-of-orderneeds dedupe and a DLQ

Detection. Alert on event-to-run p99 (target under 30 s), sensor age, runs per interval (expect exactly 1), and output freshness against the 15-minute SLA. A missing trigger shows up as a gap in runs-per-interval, not as an error.

Test: duplicate event, out-of-order event, file arriving 40 minutes late, a quiet day with zero events, scheduler down for an hour, replay of yesterday.

Pick: schedule for interval data with a completeness contract, event for latency-sensitive CDC, sensor only for external waits you cannot instrument. Combine an event-triggered start with a scheduled completeness sweep.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-2

Make an orchestration task safe for retries and task clearing.

Answer

The 90-second answer. A retry or a clear must re-run the same logical unit and converge on one result. So derive identity from the schedule, not the attempt: (dag_id, logical_date, partition, code_version). In Airflow 2.2+ that is data_interval_start/data_interval_end (the old execution_date is now logical_date); try_number is a counter, not identity. Then order the effects: read versioned inputs → write to attempt-scoped staging → atomically publish → commit progress last. If the process dies anywhere, the next attempt redoes work that is already idempotent, and the only thing lost is progress, which you re-derive.

Airflow defaults worth knowing. retries=0, retry_delay=300s, retry_exponential_backoff=False, max_retry_delay=86400s, execution_timeout=None, catchup=True, max_active_runs=16, trigger_rule='all_success', depends_on_past=False. Clearing a task instance sets it back to None and it re-runs; airflow tasks clear -t load -s 2024-01-01 -e 2024-01-02 my_dag does it in bulk. None of that machinery knows your business key: you supply it.

Make the write idempotent. Two shapes work.

Deterministic upsert. Postgres 9.5+:

SQL
INSERT INTO fact_orders (order_id, amount, updated_at)
VALUES (%(order_id)s, %(amount)s, %(updated_at)s)
ON CONFLICT (order_id) DO UPDATE
  SET amount = EXCLUDED.amount, updated_at = EXCLUDED.updated_at
  WHERE fact_orders.updated_at < EXCLUDED.updated_at;

Trace: attempt 1 inserts order 42, amount 10, updated_at 100. Attempt 2 replays the same row → conflict → 100 < 100 is false → 0 rows updated, no duplicate, no clobber. A late-arriving older attempt also loses. Delta Lake MERGE INTO ... WHEN MATCHED THEN UPDATE and Iceberg MERGE give the same guarantee on a deterministic key. Snowflake MERGE does too, but fails with "duplicate row detected" if the source has duplicate keys, so dedupe upstream.

Staging plus atomic swap. Write to s3://bucket/staging/orders/dt=2024-01-01/run=<run_id>/, then publish with a partition overwrite (spark.sql.sources.partitionOverwriteMode=dynamic, Delta replaceWhere, Iceberg overwritePartitions()). Readers see the old partition until the swap commits.

Commit progress last. For Kafka, set enable.auto.commit=false and commit offsets only after the sink commits; Kafka Streams processing.guarantee=exactly_once_v2 (3.0+) does this for you. In Airflow the task's success state is the progress marker, so the durable write must happen before the task returns.

External APIs. Send an Idempotency-Key; Stripe retains keys for 24 hours and replays the original response with Idempotency-Replayed: true. If the vendor has no key, write a transactional outbox row in the same DB transaction as your state change, or record a queryable operation ID and reconcile before repeating. Never blind-retry a POST that charges money.

Clearing and orphans. Clearing a task does not delete its staging. Give staging a TTL: an S3 lifecycle AbortIncompleteMultipartUpload rule after 7 days, or a partition-drop job keyed on run_id values absent from the completion manifest. Never delete by "everything under dt=": that is how you delete committed work.

Failure modes and detection.

failuresymptomdetection
crash before writeno rows, task failedtask state plus row count
crash after sink commit, before successduplicate on retryunique-key violation or upsert no-op
lost API responsedouble chargeidempotency-key replay, outbox row
concurrent duplicate attempttwo writers, one winsmax_active_runs, advisory lock, ON CONFLICT
old code bundle re-runwrong schema writtencode_version in the manifest

Test matrix. Kill the process before write, mid-write, and after sink commit but before the success callback; drop the API response; run two attempts concurrently; clear and re-run with the previous code bundle; roll the DAG back. Each case must end with exactly one logical result.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-3

Design a retry, timeout, and failure-classification policy.

Answer

Assumptions I'd state before answering. A request-serving service calling a dependency it doesn't control; the write can carry an idempotency key; a user is waiting, so there's a latency budget. Change any of those (batch job, no key, no user) and the numbers below move, which I'll flag as I go.

Core answer, the first 90 seconds. Classify the failure, then decide. Retry only faults that are plausibly transient, and only when the operation is idempotent or reconcilable. Bound every retry with three numbers: max attempts, per-attempt timeout, overall deadline. Back off exponentially with full jitter, and let the dependency's own hint override your computed delay. A timeout is not evidence the remote work stopped: treat it as an uncertain commit and reconcile before retrying. Deterministic failures fail fast into an owned path.

Concretely: 5 attempts max, 200 ms base, 5 s cap, full jitter (sleep = random(0, min(cap, base × 2^attempt))), 2 s per attempt, 30 s overall deadline for a background job or 5 s for a user-facing call. Circuit breaker opens after 5 consecutive failures or >50% failures over a 20-request window, half-open after 10 s. For reference points: AWS SDKs' standard retry mode defaults to 3 attempts with jitter; gRPC exposes retry policy through the service config and google.rpc.RetryInfo in status details; HTTP Retry-After (RFC 9110) is the hint to honor on 429 and 503.

Classification.

SignalClassAction
503 + Retry-Aftertransient, provider-pacedretry after the hint
429transient, ratebackoff, shed load
connection reset, 408, 504transient, commit unknownretry only if idempotent or reconciled
400, 422 schema/validationdeterministicfail fast, quarantine payload
401, 403config/authfail fast, page the owner
409 conflictambiguousreconcile, never blind-retry
gRPC UNAVAILABLE, RESOURCE_EXHAUSTEDtransientretry; INVALID_ARGUMENT does not

Worked trace (base 200 ms, cap 5 s, full jitter, 2 s per attempt, 5 s deadline):

  • t=0.00 attempt 1 → 503 with Retry-After: 1 → sleep 1.00 s (hint beats computed backoff)
  • t=1.00 attempt 2 → connection reset at t=1.20 → computed min(5, 0.2×2¹)=0.40 s, jitter draws 0.27 s
  • t=1.47 attempt 3 → 503, no hint, fails t=1.70 → min(5, 0.2×2²)=0.80 s, jitter draws 0.61 s
  • t=2.31 attempt 4 → 503, fails t=2.50 → min(5, 0.2×2³)=1.60 s, jitter draws 1.42 s
  • t=3.92 attempt 5 would need 2.00 s but only 1.08 s of budget remains → don't start it; return DEADLINE_EXCEEDED after 4 attempts

The last line is the rule that matters: never start an attempt you can't finish inside the deadline.

Trade-offs and when not to retry. In-process retry is cheap and keeps the caller's context; queue-based retry (visibility timeout plus a dead-letter queue) survives process death and gives you replay, at the cost of a second delivery path. Fixed backoff is simpler but synchronizes clients into a thundering herd; full jitter is the fix. A circuit breaker protects the dependency, a bulkhead or concurrency limit protects you: you usually want both. Don't retry when the fault is deterministic, when the write has no idempotency key and no reconciliation path, or when the dependency is already failing broadly: retries then are an amplifier, not a remedy. Stripe documents 24-hour idempotency-key retention, so a retry after that window is a new write.

Failure modes and detection. Retry storms across mapped tasks: detect as a rising attempt count with flat success rate. Poison payloads looping forever: detect as one key hitting max attempts repeatedly; quarantine and alert. Lost response after commit: detect as duplicate-key rejections or reconciliation mismatches. Cancellation races: a cancelled orchestration timeout does not prove the remote job stopped, so fence with a token the worker checks. Watch success-after-retry and exhausted-retry rates; a chronic fault showing up as routine retries should be fixed, not normalized.

Decision criteria, in order: is the fault plausibly transient, is the operation idempotent or reconcilable, is there budget left, and does retrying risk amplifying an outage? Any "no" ends the retry.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

A task has shown as running for six hours against a 12-minute p99. Walk me through how you'd decide whether it's slow, dead, or hung, and how you'd recover it safely.

Answer

Three cases hide behind "running for six hours": a slow task still making progress, a task whose worker died (Airflow marks it zombie), and a live process that is hung. Heartbeat fine, no progress. Only the third needs a human to kill something, so classify before touching anything.

Assumptions: Airflow 2.x on KubernetesExecutor or Celery, the task writes to object storage or a warehouse table, and at least one step calls a non-transactional external API.

signalslowdead workerhung process
last task heartbeatfresholder than scheduler_zombie_task_threshold (default 300 s)fresh
worker / podalivepod gone, Celery worker heartbeat stalealive
progress (log lines, rows written, external job status)advancingfrozenfrozen
processR/S, CPU movingno PIDD state, or blocked on a socket or DB lock

Heartbeat alone cannot catch a hung process: the process is alive and heartbeating, it just never finishes. That is what execution_timeout is for, and it is unset by default: a task with no timeout runs until someone notices. dagrun_timeout bounds the whole run, task_queued_timeout (default 600 s) fails tasks that never leave queued, and sla only alerts; it never kills anything. The KubernetesExecutor applies execution_timeout as the pod's activeDeadlineSeconds; the task gets SIGTERM, then SIGKILL after terminationGracePeriodSeconds (default 30 s). on_kill is where cleanup goes.

Budget it from data: p99 is 12 minutes, so execution_timeout=30m and retries=2 with backoff give a ~95-minute worst case, with dagrun_timeout=4h. Zombie detection adds up to 5 minutes of lag after the last heartbeat, so alert on heartbeat age at 2x the threshold instead of waiting for the scheduler to act.

Recovery order matters: kill the producer before you change the state. Clearing a task while its process still runs gives you two writers and duplicate side effects.

  1. Kill and confirm. Delete the pod, or revoke the Celery task with terminate=True; verify the PID or pod is actually gone.
  2. Quarantine partial output. If the write was atomic (temp path plus rename, or a partition swap), nothing to do. If not, delete or rename the partial partition so no consumer reads it.
  3. Choose the state. Mark failed when retries are configured: the retry policy applies and you keep attempt history. Clear when you want a fresh run and the task is idempotent. If downstream already ran on partial data, airflow tasks clear --downstream, or the DAG shows success on stale inputs.
  4. Re-run and verify. Row counts and checksums against the source, plus an idempotency-key lookup on the external API to prove the first attempt did not land twice.

Failure modes worth naming: clearing before killing (duplicate API calls); clearing without downstream (green DAG, stale table); treating sla as enforcement; misreading a deferred deferrable operator or an up_for_reschedule sensor as stuck. Neither holds a worker slot. Prefect has the same shape: run state lives in the API, so a dead worker leaves the flow run Running until work pool health checks or a human intervene.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

Design a safe sensor for an external dataset or API condition.

Answer

The 90-second answer

Assume a daily batch producer drops a partition into object storage and a downstream job must not start until that partition is complete. My orchestrator is Airflow 2.9, the store is S3-compatible, and the producer is another team I can page but not deploy.

The sensor answers one question: is this exact partition complete and fresh?: without burning a worker slot or hammering the source. Existence is the weakest predicate available, so I make it three conditions: the marker dt=2024-06-01/_SUCCESS exists, the data object's ContentLength matches the byte count in the producer's manifest, and its LastModified falls within six hours of the scheduled 03:00 run. Each failure gets its own name, because "timed out" tells the on-call nothing.

If the producer can publish an event (an S3 EventBridge notification into SQS, or an SNS topic) I subscribe and skip polling entirely. When I have to poll, I poll deferrably so the worker slot is released between pokes, and I revalidate the predicate immediately before the downstream read rather than trusting the sensor's verdict.

Python
# Airflow 2.9, apache-airflow-providers-amazon 8.x
wait = S3KeySensor(
    task_id="wait_for_partition",
    bucket_name="raw-events",
    bucket_key="dt={{ ds }}/_SUCCESS",
    deferrable=True,              # triggerer polls; worker slot released
    poke_interval=30,             # default is 60
    timeout=timedelta(hours=2),   # default is 7 days - far too long here
    soft_fail=False,              # hard timeout fails the run, does not skip
)

@task(retries=0)
def validate(ds):
    head = s3.head_object(Bucket="raw-events", Key=f"dt={ds}/part-00000.parquet")
    manifest = read_json(s3, f"dt={ds}/manifest.json")
    assert head["ContentLength"] == manifest["bytes"], "partial upload"
    assert head["LastModified"] > scheduled_at(ds) - timedelta(hours=6), "stale"
    return {"etag": head["ETag"], "version": head.get("VersionId")}

Trace: producer crashes mid-upload. It writes two of three multipart parts and dies before _SUCCESS. The sensor pokes at 03:00:00, 03:00:30, 03:01:00, backing off to a 60-second cap, and at 05:00:00 raises AirflowSensorTimeout. The run fails, the alert routes to the producer's on-call, and downstream never started. Correct outcome.

Trace: marker written before the data. An ordering bug publishes _SUCCESS first. The sensor fires at 03:00:30, validate heads the parquet, gets a 404, and fails in about 200 ms. The sensor's predicate was satisfied; the revalidation is what caught it. That is why the check runs immediately before use.

Trace: object replaced. The producer re-uploads the same key at 04:00 with corrected data. The ETag changes. If downstream already read the 03:00 bytes, two consumers now hold different data. Recording VersionId at read time is what makes that detectable after the fact.

One gotcha worth knowing: for multipart uploads the ETag is <md5-of-part-md5s>-<partcount>, not the object's MD5, so never compare it against a locally computed digest.

FailureAction
Not readyKeep waiting until the 2h hard timeout
403 / permission lossFail now; retrying for two hours hides a credential bug
Marker present, bytes wrongFail and quarantine the partition
Producer confirms partition droppedSkip, with the reason recorded on the run
S3 5xxRetry with exponential backoff and jitter

Poll cost is rarely the constraint on S3: it absorbs 5,500 GET/HEAD per second per prefix, so a 30-second poke is noise. A GitHub API source is a different story: 5,000 requests per hour authenticated, so three DAGs polling every 30 seconds would exhaust it. There you back off to five minutes and share a cursor across consumers.

Monitor p99 wait age, timeout rate, poll request count, and downstream freshness lag. Alert when wait age exceeds 45 minutes, which is three times the producer's normal 15-minute landing time.

What would change the decision: an event source replaces polling outright; a source with no completion marker needs a watermark or cursor instead of a marker file; an SLA under a minute makes 30-second polling too coarse and forces the event path.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

Use dynamic task mapping for partitioned work safely.

Answer

Assumptions I'd state before answering: Airflow 2.x (dynamic task mapping landed in 2.3), a nightly job over tenant × date partitions (say 4,000 of them) writing to a shared warehouse and calling a rate-limited vendor API. If the unit is millions of uniform records, mapping is the wrong tool; that's a Spark or SQL job, not 4,000 orchestration tasks.

The answer in 90 seconds. Expand over a manifest you computed and stored, not over raw query results. Every element carries its own identity (tenant, date, input version) because map_index is positional and positional identity drifts. Cap the fanout before it happens, run the mapped tasks in a dedicated pool so they can't starve the rest of the DAG, make each task idempotent and scoped to one item, and have the reducer compare what it received against the manifest instead of summing whatever arrived.

Why identity lives in the payload. map_index is assigned by position in the list returned at expand time. Clear a mapped task and Airflow re-expands from the upstream XCom; if that upstream re-ran and returned a reordered list, index 7 is now a different tenant. Nothing errors: you just process the wrong partition. So the task logs and writes under tenant/date/version taken from its own argument, and map_index is never used as a key.

Python
# Airflow 2.9, Python 3.11
@task
def plan(ds=None):
    rows = query("select tenant, version from partitions where date = %s", ds)
    return [{"tenant": r.tenant, "date": ds, "version": r.version} for r in rows]

@task(pool="warehouse_etl", pool_slots=1, retries=3,
      retry_delay=timedelta(seconds=30), retry_exponential_backoff=True,
      max_active_tis_per_dagrun=8, execution_timeout=timedelta(minutes=20))
def load(item: dict):
    key = f"{item['tenant']}/{item['date']}/{item['version']}"
    if exists(f"s3://stage/{key}/_SUCCESS"):
        return {"key": key, "status": "skipped"}
    write_staged(key, fetch(item["tenant"], item["date"]))
    return {"key": key, "status": "ok"}

@task(trigger_rule="all_done")
def reduce(results: list[dict], manifest: list[dict]):
    expected = {f"{m['tenant']}/{m['date']}/{m['version']}" for m in manifest}
    got = {r["key"] for r in results}
    missing = expected - got
    if missing:
        raise AirflowException(f"{len(missing)} partitions missing: {sorted(missing)[:5]}")
    publish()

manifest = plan()
reduce(load.expand(item=manifest), manifest)

What the trace shows. plan returns 4,000 dicts. load.expand checks the length against [core] max_map_length, default 1024: 4,000 raises rather than truncating, so you either raise that setting deliberately or shard into four chunks of 1,000. With the default all_success trigger rule, one failed partition blocks the reducer entirely: safe, but no partial progress. Setting all_done lets the reducer run with a short list, and now the manifest diff is the only thing between you and a publish that is quietly missing three tenants.

Retry storms. Airflow's default is retries=0, so the storm is self-inflicted: set retries=5, retry_delay=timedelta(minutes=5) on all 4,000 tasks and a 429 at t=0 produces 4,000 retries at t=300s and another 4,000 at t=600s. Exponential backoff with jitter plus a pool spreads the wave. With 16 pool slots and ~2s of API time per item, the floor is 4,000 × 2 / 16 ≈ 500s; max_active_tis_per_dagrun=8 caps it further.

Failure modes to name. Cardinality spike: a bad partition query returns 2M rows; alert on manifest count against the 7-day median. Pool starvation: mapped tasks holding every slot block the DAG's other work; use a dedicated pool. XCom bloat: 4,000 keys at ~200 bytes is ~800 KB, fine; 4,000 payloads at 50 KB is 200 MB in the metadata DB, so keep the manifest to keys and fetch bodies inside the task. Positional drift, as above, is caught by logging the key, not by the manifest diff: a swapped key is present, just wrong.

When not to use it: uniform bulk records, sub-second items, or anything where the per-task overhead exceeds the work.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Orchestrate a task that calls a non-transactional external API.

Answer

Assumption that decides the design: the external API can commit and then lose the response, and it does not join our database transaction. No distributed transaction exists here, so the target is not exactly-once delivery. It is at most one effect per logical operation, plus a known state when we cannot prove one.

Three moves get you there.

Derive the key from the run, never from the attempt. sha256(tenant_id | run_id | step_name), stored on the run row and reused by every retry for the life of that operation. An attempt-scoped key tells the provider each retry is a brand-new operation, which is the most common way this orchestration bills someone twice.

Write an outbox row instead of calling inside the transaction. The dual-write race is concrete: commit-then-call loses the call if the process dies in between, and call-then-commit loses the record of it, so a different worker retries. Committing the state change and the outbox intent in one local transaction shrinks the crash space to two cases - nothing committed (no call was ever wanted), or intent committed (a durable record exists to retry). That is why the outbox works: it makes the intent to call atomic with the state change and leaves the call itself safely retryable.

Reconcile on timeout rather than re-deciding. A lost response leaves two unknowns: did the provider commit, and under what ID. Re-sending the same key with a byte-identical body resolves both, because the provider replays the stored response instead of creating a second object. A lookup or status endpoint does the same job and is preferable when the call is expensive.

Worked trace - order 8842, $19.99, client read timeout 3 s, provider honours an idempotency key (timings hypothetical, jitter omitted):

t (s)local ledger (Postgres)provider
0.000one commit: orders.state='charging'; outbox row idem_key='run-4711:charge', body_sha='a91f', status='pending'-
0.010sender claims it FOR UPDATE SKIP LOCKED -> status='sending', attempt=1-
0.020POST /v1/charges, Idempotency-Key: run-4711:chargerequest queued at ingress
3.000read timeout, no responsenot processed yet
3.040row -> status='unknown_after_send', next_at=3.500commits ch_3Qx, stores key -> response, 24 h TTL
3.500attempt=2, same key, byte-identical bodykey matches, replays stored 200 ch_3Qx
3.560orders.state='charged'; outbox done; provider_ref='ch_3Qx'-

One charge. Had the key been run-4711:charge:attempt2, the 3.500 POST creates ch_3Qy and the customer pays twice.

Settings I would ship: 3 s client read timeout (below the provider's observed p99), 5 attempts maximum, backoff min(0.5 * 2^(attempt-1), 30) s with 20 percent jitter, one in-flight attempt per key enforced by a partial unique index on idem_key where status in ('sending','unknown'), and an alarm on rows sitting in sending past 60 s. Postgres SKIP LOCKED (9.5+) lets several senders share the table without double-claiming. Durable-execution engines - Temporal, Step Functions - give you the retries and the execution history, but no external exactly-once; the key is still yours to own.

Failure modes and what detects them:

  • Same key, different body -> 400 idempotency_error. That is a code bug; alert, do not retry.
  • Key expiry. Stripe evicts idempotency keys after 24 hours, so dedupe is bounded by that window and a retry at +25 h is a fresh charge. Reconcile inside the window.
  • Vendor offers neither idempotency nor lookup: you cannot distinguish the cases. Fall back to a single-writer ledger (one process owns the vendor account, serialized per key) or manual reconciliation, and say plainly that a duplicate effect is possible.
  • Compensation (refund, void) is a new idempotent action with its own key; it never erases the original effect.
  • 401 and 422 are terminal for the intent; only 5xx and timeouts are transport-transient.

Counters to watch: age of sending, unknown_after_send count, duplicate-key rejections, compensation count, provider error rate. Tests: crash before send; crash after the provider commits but before the response is read; duplicate attempt with same key and same body; same key with different body; response delayed past the timeout; provider 503 for 10 minutes; compensation failure. Then reconcile the vendor's records against the ledger and against downstream consumers - a duplicate charge usually surfaces there first.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

Design data-quality gating inside an orchestrated pipeline: where checks sit, how a failed check halts or quarantines downstream work, and how quarantined data is reprocessed?

Answer

Clarify three things before designing: what "bad" means for this data (a null join key and a 3% drop in row count are different failures), whether the pipeline is partition-scoped and idempotent on a business key, and whether publishing late is cheaper than publishing wrong. Assume a daily partitioned batch pipeline that merges into the warehouse on a business key, where wrong data is worse than late data.

The design is gates at four points, with severity decided per check, not per pipeline.

StageCheckSeverityOn failure
Extract → stagingSource contract: schema, source partition exists, row count vs previous run ±X%hard if schema or partition missing; soft if count drifthard: fail task, no transform; soft: metric + warn
Staging → transformRow-level: null or duplicate business key, negative amounts, referential integrity to dimensionshardreject rows to quarantine; fail the partition if reject ratio exceeds threshold
Transform → pre-loadReconciliation: sum(amount) and row count conserved between staging and transform outputhardfail, do not load
Post-loadPublished table: uniqueness on key, freshness, row count vs staginghardfail the run, alert, do not mark the DAG run successful

Two rules make this work. First, a gate must write its evidence before it fails: quarantine rows and the check result are committed, then the task raises. Raise first and the rejected rows are gone, leaving re-extraction from a source that may have moved on as the only recovery. Second, severity belongs to the check: hard checks fail the task and block downstream through the default all_success trigger rule; soft checks record a metric and let the run continue. Turning every anomaly into a full stop is how teams end up disabling their own gates.

python from airflow.decorators import task from airflow.exceptions import AirflowException

@task def validate(partition: str) -> dict: rows = read_staging(partition) bad = [r for r in rows if r["order_id"] is None or r["amount"] < 0] if bad: write_quarantine(partition, bad, check="order_integrity") # committed first ratio = len(bad) / max(len(rows), 1) if ratio > 0.01: # hard gate raise AirflowException(f"order_integrity failed: {ratio:.2%} of {partition}") return {"partition": partition, "rejected": len(bad), "ratio": ratio}

The gate is idempotent because quarantine rows are keyed on (run_id, partition, row_key), so a task retry overwrites rather than duplicates.

Fail-fast versus fail-soft is a question of granularity. Fail fast within a partition: one bad partition must not publish. Fail soft across partitions: with dynamic task mapping, partition 2024-06-08 failing does not block 2024-06-09. That gives a hard gate where correctness matters and a partial run you can reason about.

Quarantine is a table, not a log line: quarantine(run_id, task_id, check_name, partition, row_key, raw_payload, reason, quarantined_at). Downstream reads only the clean partition. Reprocessing has two paths: if the bug is in the parser, fix the code and backfill the affected dates (airflow dags backfill --start-date 2024-06-08 --end-date 2024-06-08 --task-regex 'extract|validate|load'); if the source has moved on, run a dedicated reprocess DAG that reads the quarantine table, applies the fix, and merges on the business key. Both must be idempotent: the merge is what makes a re-run safe.

Reporting: every check writes (check_name, severity, rows_evaluated, rows_failed, threshold, status) to a results table and emits the check name as an OpenLineage facet on the task, so lineage answers "which gate rejected this partition". Hard failures page; soft breaches go to a digest. One alert per anomalous row is alert fatigue.

Worked trace (figures illustrative): 12 daily partitions, 1.2M rows. 2024-06-07 rejected 4,318 rows (0.36%): under the 1% threshold, clean rows loaded, quarantine held the rest. 2024-06-08 rejected 61,204 (5.1%): hard fail, load skipped, run marked failed. Cause: upstream changed a date format. Parser patched, backfill re-ran the day, merge on order_id produced 0 duplicate rows.

Failure modes to name: a gate placed after load publishes the bad data it was meant to stop; a flaky check halts the pipeline (track its false-positive rate, test checks against known-bad fixtures); quarantine grows unbounded (alert on row count and on oldest row age); quarantine not partitioned by run or date turns reprocessing into a full scan.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

Run a production backfill without harming live freshness or correctness.

Answer

Clarify first. Two questions decide whether this is a backfill at all: can the source still replay the window, and have consumers already read the wrong data? If retention has expired, there is no backfill: you document the gap and move on. Assume the source can replay and consumers can absorb a restatement.

The shape. A backfill is a bounded set of interval-pure tasks, run in a pool the live schedule does not share, writing to staging, published by atomic partition swap, with live processing resumed from a recorded source position. Everything else is detail.

Why interval-pure. A task keyed only on its interval (not on wall-clock time, not on "now") produces the same partition however many times it runs. That is what makes retries and duplicate runs safe. In Airflow 2.x that means deriving output paths from data_interval_start/data_interval_end. Idempotency then comes free: the write is a partition overwrite, not an append.

Isolation. Give the backfill its own pool with a fixed slot count and cap the DAG:

Python
# Airflow 2.7
@task(pool="backfill", max_active_tis_per_dag=4, retries=2)
def backfill_interval(interval_start: str, interval_end: str): ...
# pool "backfill": 8 slots; DAG: max_active_runs=1

The live DAG keeps its own pool and slots, so a 90-interval backfill cannot starve the hourly schedule. Without this, backfill tasks queue ahead of live tasks and freshness dies: that is the failure you are actually preventing.

Order. Chronological if consumers read forward and you want partial results usable early; reverse if the newest partition is the wrong one and you want it fixed first. The deciding criterion is which end of the window a consumer reads. Neither is free: reverse order leaves the oldest data wrong longest.

Arithmetic. 90 daily intervals, 6 minutes per interval, 4 concurrent tasks: 90/4 × 6 ≈ 135 minutes wall clock, plus validation. If that exceeds the freshness SLO, shrink the window before raising concurrency: raising concurrency is what breaks the live schedule.

Validate before publish. Compare grain counts, control totals (row count and sum of the measure per partition) and the old/new metric diff. Classify each difference as expected (late-arriving source rows now included) or a defect. Publish only coherent partitions: a partition is fully old or fully new, never half.

Resume live. Record the source position (Kafka offset, binlog position, Postgres LSN) at the moment the backfill window ends, and restart live processing from there. Restart from "now" and you drop everything in between; restart from before the window and you double-count. This is the most common way a backfill corrupts live data.

Failure modes and detection.

  • Duplicate run: two runs write the same partition. A uniqueness constraint on (dataset, interval) in the run ledger makes the second fail loudly.
  • Source expiry mid-run: retention deletes the tail of the window. Check the source's oldest available position before each interval and abort rather than emit a green partial.
  • Schema drift: source adds a column mid-window. Compare a schema hash per interval; fail the interval, do not coerce.
  • Worker loss: task dies mid-write. Safe, because the write is a partition overwrite: rerun the interval.
  • Cancellation: leaves staging garbage. Sweep staging by age.

When not to run. If nobody owns the restatement, if consumers cannot tolerate corrected numbers, or if the correction is smaller than the metric's noise floor, don't. A backfill that moves a dashboard 0.1% and pages three teams is a net loss.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Coordinate dependencies between independently owned workflows.

Answer

Assumptions. Two teams, one Airflow deployment (2.9 or 3.0), producer writes hourly partitions to a warehouse table or object store, consumer needs each partition once it is complete. Neither team can block the other's deploy.

Core answer. Don't wire the consumer to the producer's task. Publish a data contract, a stable identifier for the output plus a readiness signal, and let the consumer schedule on that signal. The producer owns "the data is complete and correct"; the consumer owns "I ran on the version I was told about."

Mechanism. In Airflow 2.4+ the native version is a Dataset (renamed Asset in Airflow 3.0). The producer declares an outlet on the task that finishes the data; the consumer's DAG schedules on it.

Python
from airflow import DAG, Dataset
from airflow.operators.python import PythonOperator
from datetime import datetime

orders = Dataset("s3://lake/orders/")

with DAG("producer_orders", start_date=datetime(2024, 1, 1),
         schedule="0 * * * *", catchup=False) as producer:
    write = PythonOperator(task_id="write", python_callable=write_parquet)
    validate = PythonOperator(task_id="validate", python_callable=check_row_count,
                              outlets=[orders])   # marker only after validation
    write >> validate

with DAG("consumer_revenue", start_date=datetime(2024, 1, 1),
         schedule=[orders], catchup=False) as consumer:
    ...

The outlet sits on validate, not write. Airflow emits the dataset event when the task succeeds, so putting it on write marks the partition ready before the row-count check runs: the single most common way this pattern fails.

Alternatives, and when not to use them.

MechanismCouples consumer toFails when
ExternalTaskSensorupstream dag_id, task_id, scheduletask renamed, schedules drift, sensor times out
TriggerDagRunOperatorproducer DAG codeproducer deploy blocks consumer
Airflow Dataset / Assetdata URImarker emitted before validation
_SUCCESS / manifest in object storestorage pathS3 rename is copy+delete, not atomic
Catalog + event (OpenLineage, Kafka)contractevent lost, nothing reconciles

ExternalTaskSensor is the one to avoid at scale. Defaults: poke_interval=60, timeout=60*60*24*7 (7 days), mode='poke'. In poke mode the sensor holds a worker slot for the entire wait. Thirty consumer DAGs each waiting ~40 minutes on an hourly producer block 30 slots continuously; mode='reschedule' releases the slot between pokes and cuts that to seconds per poke. It also matches on logical date by default, so an hourly producer feeding a daily consumer needs execution_date_fn or execution_delta: otherwise the sensor waits for a date that never arrives and burns the 7-day timeout.

Failure modes and detection.

  • Marker before validation: consumer reads a partial partition. Detect with a row-count or not null check in the consumer's first task, alerting on empty or short partitions.
  • Producer rerun or late correction: the same partition is published twice. Dedupe on (dataset, partition, producer_version); the consumer must be idempotent on partition, not append.
  • Lost event: dataset events are not replayed. Reconcile with a scheduled sweep that lists partitions in the catalog and compares to consumer run history; alert on partitions older than 2× the producer interval with no consumer run.
  • Ownership spoofing: in Airflow 2.x a dataset URI has no ownership ACL. Any DAG can declare an outlet for another team's URI and trigger your consumers. Gate it in CI, or route readiness through a catalog that authenticates the writer.
  • Schedule drift: producer moves from hourly to 15-minute; consumers silently run 4× or miss partitions. Version the contract and treat a cadence change as a breaking change.

Testing. Producer rerun, empty partition, schema change, consumer outage spanning two partitions, duplicate event, and a backfill that republishes a week of partitions.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

Design concurrency, pools, priorities, and fairness for shared orchestration.

Answer

Assumptions first. One Airflow 2.x cluster, CeleryExecutor, three workers, a shared Postgres metadata DB, two tenants: A runs 40 SLA DAGs, B wants a 90-day backfill. Everything below is sized for that; the shape generalizes.

The core answer. Concurrency, pools, priorities and fairness are four different knobs, and conflating them is the bug. Concurrency caps how many task instances run at once. Pools cap how many of them may touch a named resource. Priority orders what the scheduler hands out next. Fairness decides who gets a slot when demand exceeds supply. Airflow gives you the first three; it does not give you the fourth, so you build fairness out of pools.

Sizing. Worker slots are the real ceiling: 3 workers × worker_concurrency 16 = 48. Set parallelism to 48 rather than the default 32, and make pool slots sum to 48. The default_pool ships with 128 slots, larger than the cluster, so leaving tasks there just moves the queue from the scheduler into Celery. A working split:

poolslotswho
warehouse_load12anything writing the warehouse
tenant_a20SLA DAGs
tenant_b8backfill
default_pool8everything else

Sum 48. warehouse_load is the one that matters: it's the shared dependency, and 12 concurrent writers is what the warehouse absorbs before load time doubles.

Mechanism. The scheduler only moves a task instance from scheduled to queued when its pool has a free slot; the worker then picks it up. Pool wait is a scheduler-side gate, worker wait is a Celery-side gate: two queues, two metrics. priority_weight (default 1) with weight_rule (default downstream) only reorders the scheduler's queue, and it is static per task: Airflow has no aging. That's the limitation that decides the design: a continuous stream of priority_weight=100 SLA tasks starves a priority_weight=1 backfill forever. You don't fix that with priority; you fix it with reservation. tenant_b's 8 slots are backfill's guarantee, and max_active_runs_per_dag (default 16) plus per-task max_active_tis_per_dag stop one DAG from eating its own pool.

Collisions. Backfill and live run hitting the same table: pick per semantics, not per preference. Idempotent overwrite → supersede (newer run cancels older). Append-only → enqueue behind a pool of 1 on that table. SLA-critical → cancel the backfill when the SLA DAG starts. Coalesce only when duplicate runs are genuinely equivalent. This design is wrong when the warehouse is the bottleneck and you've given it 12 slots anyway, then no scheduling policy saves you and you shard the load instead.

Failure modes and detection. Pool starvation: pool.queued_slots climbing while pool.running_slots sits at the cap. Blast radius is every SLA DAG sharing that pool. Scheduler backlog: scheduler_heartbeat age and dag_processing.last_duration rising. DAGs stop being scheduled at all. Metadata DB exhaustion: sql_alchemy_pool_size 5 plus sql_alchemy_max_overflow 10 per process, and scheduler, workers and webserver all connect. The symptom is scheduler hangs, not task failures. Worker loss: with Celery's default task_acks_late=False the task is lost on worker death; set it true with worker_prefetch_multiplier=1 so redelivery is bounded. Hot tenant: one tenant's max_active_tasks floods a shared pool. Detection is that tenant's queue time diverging from cluster queue time.

What I'd say in the room: reserve, don't prioritize; cap the shared dependency, not the cluster; and measure pool wait, not just task duration, because pool wait is where starvation shows up first.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

How do you orchestrate a pipeline that combines batch and streaming stages, ensuring consistency between batch reprocessing and live stream processing, and how does the orchestrator detect and restart a stalled stream consumer?

Answer

Assume Kafka 3.x as the log, a Flink or Kafka Streams consumer writing to Iceberg/Delta on S3, Airflow 2.x orchestrating, and the consumer running as a Kubernetes Deployment. The orchestrator owns lifecycle and reconciliation, not execution: Airflow never runs the stream job as a task, it starts it, watches a health signal, and restarts it. Consistency comes from both paths writing idempotently on the same partition key, and from never letting a backfill and the live stream write the same partition concurrently.

ResponsibilityBatchStreaming
TriggerCron schedule or dataset sensorOrchestrator starts/stops a Deployment
ExecutionFinite task, retriesLong-running, owned by Kubernetes
ConsistencyIdempotent partition overwriteCheckpointed, idempotent sink writes
BackfillSeparate DAG run with an intervalPause the partition, or run the same job in batch mode
MonitoringTask success/failureConsumer lag, committed-offset progress, checkpoint age

Consistency. Both paths write to the same sink keyed by event_id. Iceberg's overwritePartitions() and Delta's REPLACE WHERE are atomic at partition granularity, so a backfill of dt=2025-06-01 either fully lands or not at all. Before a backfill starts, stop the consumer for the affected partitions and let the group rebalance; restart it after the DAG's final task. If you want one code path, Flink 1.12+ runs the same job graph as a bounded source with execution.runtime-mode: BATCH, which gives you the batch semantics without a second codebase.

Detecting a stall. Lag magnitude alone is the wrong signal: a caught-up consumer that has died reports zero lag, and a slow-but-progressing consumer reports growing lag. Detect a stall on committed-offset progress, not on lag.

Python
# kafka-python 2.0.2
from kafka import KafkaConsumer, KafkaAdminClient

def group_lag(bootstrap, group_id, topic):
    admin = KafkaAdminClient(bootstrap_servers=bootstrap)
    committed = admin.list_consumer_group_offsets(group_id)  # {TopicPartition: OffsetAndMetadata}
    tps = [tp for tp in committed if tp.topic == topic]
    if not tps:
        return None
    c = KafkaConsumer(bootstrap_servers=bootstrap, group_id=None)
    c.partitions_for_topic(topic)      # force metadata fetch
    end = c.end_offsets(tps)           # {TopicPartition: log_end_offset}
    c.close(); admin.close()
    return sum(end[tp] - committed[tp].offset for tp in tps)

Trace for group agg-writer, topic events (3 partitions):

  1. list_consumer_group_offsets returns {(events,0): 1000, (events,1): 2500, (events,2): 900}.
  2. tps keeps all three; partitions_for_topic returns {0,1,2}.
  3. end_offsets returns {(events,0): 1000, (events,1): 3000, (events,2): 1200}.
  4. Sum: (1000-1000) + (3000-2500) + (1200-900) = 0 + 500 + 300 = 800. Returns 800.

An Airflow sensor polls this every 60s with mode="reschedule" (frees the worker slot between pokes) and timeout=600. It also tracks sum(committed offsets): 4400 in the trace above. Three consecutive readings of 4400 at t, t+60, t+120 while end offsets climb 5200 → 5600 → 6000 means the consumer is stalled, and the sensor times out. A downstream task then runs kubectl rollout restart deployment/agg-writer with execution_timeout=timedelta(minutes=2); the Deployment recreates the pod and the group rebalances.

Kafka already covers one stall class itself: max.poll.interval.ms defaults to 300000 (5 minutes), so a consumer whose poll loop is stuck is evicted from the group and its partitions reassigned. session.timeout.ms defaults to 45000 in Kafka 3.0+ (10000 before 3.0), with heartbeat.interval.ms at 3000. What Kafka cannot cover is a process that is gone entirely: check kafka-consumer-groups.sh --describe --group agg-writer --state; Empty or Dead for more than 5 minutes means nothing is consuming, and that is the orchestrator's restart trigger. Kubernetes liveness probes do not help here: a stalled consumer is alive and passing its probe.

Alternatives. Kappa (one Flink job for both) removes reconciliation but makes a 30-day backfill compete with live traffic for the same slots. Lambda keeps two codebases and needs a reconciliation job. Running the stream job as a long-running Airflow task is an anti-pattern: Airflow has no mechanism to restart a task that is alive but wedged.

Failure modes. Backfill overwrites stream data written after the interval: detect with a row-count and max(event_id) diff per partition after the DAG finishes. Non-idempotent sink writes duplicate on restart: detect with a count(distinct event_id) vs count(*) check. Flink checkpoint age exceeding 3× execution.checkpointing.interval (unset by default; set it to 30s, alert at 90s) means the job is not making progress even though the process is up.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Design multi-tenant orchestration for many product teams.

Answer

Assumptions I'd state first: ~30 product teams, three trust tiers (trusted internal, regulated. PCI/PHI, and semi-trusted code from vendors or data scientists running arbitrary Python), one cloud, Kubernetes underneath. If it's 5 teams and all trusted, the answer collapses to namespaces plus quotas. If any team runs untrusted code, it's separate node pools with a sandboxed runtime.

Core answer. Two tiers of boundary, decided by trust, not by team count.

Tier 1: hard boundary: a separate cluster, or at minimum a separate control plane and node pool, per trust domain. Regulated data and untrusted code each get their own. The reason is blast radius: a CVE in the shared scheduler, a cluster-admin RBAC mistake, or a container escape stays inside one domain. Cost: each Airflow/Temporal/Argo control plane is its own scheduler, metadata DB and upgrade cadence, roughly 3x the platform toil for 3 domains, and cross-team dependency visibility disappears, because a DAG in domain 1 can't see a dataset in domain 2.

Tier 2: soft boundary inside a domain: one namespace per team with RBAC, ResourceQuota, LimitRange, default-deny NetworkPolicy (needs a CNI that enforces it. Calico or Cilium), and Pod Security Admission set to restricted. Example quota for a mid-size team: requests.cpu: 40, limits.memory: 160Gi, count/pods: 200, count/jobs.batch: 50. Airflow pools cap per-team concurrency; Temporal namespaces give per-tenant retention and rate limits; PriorityClass plus preemption stops a batch backfill from starving interactive runs.

SignalBoundary
untrusted code, regulated dataseparate cluster + sandboxed runtime (gVisor, Kata)
trusted, shared datanamespace + quota + RBAC
cross-team dependencyshared read-only lineage/metadata service

Identity is the part teams get wrong. Bind tenant at the authenticated ingress: the OIDC token's sub/groups claim, the service account, the trigger's authenticated principal, and write it as an immutable label onto the workflow, run, task, artifact, secret path, pool and log stream. Never accept tenant_id as a workflow parameter: a parameter is attacker-controlled, so team A passes team B's ID and reads their XComs. The platform sets the label; the DAG author cannot.

Failure modes, each with a detection:

  • DAG name collision in a shared scheduler: assert the run's tenant label matches the caller.
  • Result/XCom leak: team A reads team B's result by ID. Fix: scope result lookups by tenant label in the metadata query, not by ID alone.
  • Secret mount: a shared worker with a projected service-account token can call the API as another tenant. Fix: per-tenant workload identity (EKS Pod Identity/IRSA, GKE Workload Identity, or SPIFFE/SPIRE), never a cluster-wide token.
  • Queue starvation: one team submits 10k tasks. Alert on per-tenant queue depth at ~5x steady state.
  • Log leakage: a shared log store query that forgets the tenant filter. Fix: tenant label as a mandatory index dimension, plus per-tenant buckets.

Platform-only administration; support impersonation is time-boxed and audited. Teams get scoped pause, containment and deletion of their own runs.

When not to split: if every team is trusted, share the control plane and spend the effort on quotas and identity propagation instead. Separate clusters buy isolation you don't need and cost you the cross-team lineage graph.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

Deploy an orchestration workflow change safely.

Answer

Core answer (first 90 seconds)

Treat a workflow change as a state migration, not a code push. The scheduler holds run state keyed by (dag_id, run_id, task_id); workers execute whatever definition they last parsed. So the safe deploy has two phases: make the new definition immutable and addressable, then move triggers to it while in-flight runs finish on the old one.

Assumptions I'd state up front: an Airflow 3.x-style scheduler with DAG versioning (or Temporal-style durable execution); runs lasting hours to days; backfills spanning months; workers pulling definitions from a shared store.

Why pinning is the whole game

In Airflow 2.x the scheduler re-parses DAG files on a loop (dag_dir_list_interval defaults to 300s) and workers import the same file. Edit a task's callable between parse and execution and a running run executes new code against old state. Airflow 3.0 addressed this by serializing each DAG into a version row and pinning dag_run.dag_version_id, so a run keeps its definition after you deploy. Not on 3.0? Emulate it: a new DAG ID per version, or ship the DAG as an immutable bundle/image.

changewhat breaksmechanism
add a tasknothingnew task_id, no history to orphan
rename/remove taskhistory orphaned, backfill re-runstask instance rows keyed by task_id
dependency/trigger editskipped or duplicated intervalsdata_interval_start sequence
interval/grain shiftdouble-counted or gapped partitionsschedule + catchup
schema/state changeresume fails on old statedeserialization of XCom/pickled state

In-place patching when you can't fork the definition

Temporal's patched is the alternative:

Python
@workflow.run
async def run(self, order_id: str) -> str:
    if workflow.patched("add-idempotency-key"):
        key = f"{order_id}:charge"
    else:
        key = order_id
    return await workflow.execute_activity(
        charge, key, start_to_close_timeout=timedelta(seconds=30)
    )

Trace: a workflow started before the deploy replays its history, finds no add-idempotency-key marker, so patched returns False and it takes the old branch. Deterministic replay preserved. A workflow started after the deploy returns True and writes the marker into history. Keep both branches until every pre-patch execution has left the retention window, then call deprecate_patch. Delete the branch early and replay raises a non-determinism error.

Arithmetic on the rename cost (hypothetical): a 90-day backfill, 12 tasks, 4 minutes each = 90 × 12 × 4 = 4,320 task-minutes, about 72 hours of compute re-executed, because the new task_id has no completed instances to skip.

Failure modes and detection

  • Mixed-version execution: worker on the old image, scheduler on the new definition → ModuleNotFoundError in worker logs and a spike in upstream_failed.
  • Orphaned history after a rename: task instance count for the DAG jumps on the next backfill and run duration roughly doubles.
  • Interval shift: a gap or overlap in data_interval_start; the freshness alert fires on the skipped partition.
  • Irreversible rollback: the new task wrote an output partition the old code can't read, so downstream freshness stalls after rollback. Catch it by diffing output paths before cutover.

Trade-offs

Versioned DAG ID works on any Airflow, but doubles the DAG list and confuses backfill. Native DAG versioning is clean, needs 3.0+, and old versions still consume parse budget. In-place patching adds no new IDs, but the branch is debt you must retire on a schedule. If nothing is in flight and no backfill history matters, a dev DAG, deploy in place; the machinery costs more than it saves.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

Build a test strategy for workflow definitions and orchestration behavior.

Answer

Assumptions first. I'll assume an Airflow 2.x-style scheduler on a Kubernetes executor, batch data pipelines, and DAGs written by several teams. On Temporal or Argo the layers are the same; the knobs differ. The question is what to test at each layer and where to stop.

The answer. Four layers, cheapest first. You stop adding layers when the bugs found per engineer-hour drop below the flakiness you're introducing.

  1. Static validation: CI, seconds, no cluster.
  2. Unit: task logic with clock, filesystem and HTTP client faked.
  3. Integration with fault injection: real scheduler, real queue, real object store, injected failures.
  4. Production-shaped load: backfill and burst, measuring lag and cost.

Most teams over-invest in layer 4's happy path and under-invest in layer 3. A DAG that imports cleanly proves nothing about whether a worker dying mid-commit duplicates a partition.

Layer 1, with real defaults. Airflow's defaults are permissive in exactly the wrong places: retries=0, retry_delay=300s, catchup=True, max_active_runs=16, execution_timeout=None. So the static test is an assertion that your DAGs override them.

Python
# pytest, apache-airflow 2.9
from airflow.models import DagBag

def test_dag_contract():
    bag = DagBag(dag_folder="dags/", include_examples=False)
    assert bag.import_errors == {}
    for dag_id, dag in bag.dags.items():
        assert dag.catchup is False, dag_id
        assert dag.max_active_runs <= 4, dag_id
        for task in dag.tasks:
            assert task.retries >= 1, (dag_id, task.task_id)
            assert task.execution_timeout is not None, (dag_id, task.task_id)
            assert task.retry_delay.total_seconds() >= 60

Trace: DagBag imports every file under dags/; import_errors is non-empty if any file raises at parse time. Then per DAG, catchup is False fails anything that left the default True: the setting that silently backfills three years of partitions on first deploy. task.retries >= 1 fails on the default 0. execution_timeout is not None fails on the default None, which is how a hung sensor holds a worker slot until someone notices.

Layer 3, fault injection. The failures worth injecting, and what each should produce:

  • Worker killed after the task commits to the sink but before it acks the scheduler. Airflow marks the task a zombie after scheduler_zombie_task_threshold (default 300s) and re-runs it. If the sink isn't idempotent on a natural key, you get a duplicate partition. Detect by asserting row counts and a unique key after the re-run.
  • Duplicate trigger for the same logical date. The scheduler's uniqueness on (dag_id, logical_date) should reject it, not luck.
  • Lost API response from an external system. The retry must be safe; assert the external system saw exactly one write.
  • Queue delay: hold a pool at zero slots for 10 minutes and confirm the SLA miss fires rather than the run stalling silently.

Arithmetic for layer 4. 200 queued runs, max_active_runs=16, each run 10 minutes → drain time is 200/16 × 10 ≈ 125 minutes. If your freshness SLA is 60 minutes, the config is already wrong before you run the test. That number is what you take to the capacity conversation.

Trade-offs, and when each choice is wrong.

  • Canary with versioned outputs versus differential checks: version the outputs when a downstream consumer can't tolerate mixed data in one table; run differential (old and new on the same input, compare) when the sink is idempotent by key and you want the comparison. Differential against a non-idempotent sink writes garbage twice.
  • Human review: keep it for business dependency meaning, which upstream dataset is authoritative for a metric, because no linter knows that. Don't spend it on schema shape; contract tests do that better and don't get tired.
  • Full end-to-end on every commit is wrong once the pipeline takes 40 minutes. Run it nightly and on the DAG's own changes.

Failure modes to name. A sensor that never times out holds a slot forever. A retry storm, retries=5 with retry_delay=300s on a task that fails fast, turns one bad deploy into 6× the load. Detect both from scheduler metrics: queued task count and task duration p99, not from a green CI badge.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

Define orchestration observability and service objectives.

Answer

The 90-second answer. Orchestration observability is the ability to answer, from outside the scheduler, one question: did logical interval I produce a correct, complete, fresh output that consumers actually received? A task exiting 0 is not that answer: it only says the process ended. A service objective is a target on a measurable indicator over a stated window, plus the error budget that follows from it. Two I would commit to in a real review: freshness. 95% of hourly partitions land within 15 minutes of interval close, measured over 28 days; scheduler health. scheduler_loop_duration p99 under 5 seconds over 7 days. If you cannot name the percentile and the window, you have a dashboard, not an objective.

Why queued and running time diverge. Airflow's StatsD metrics separate executor.queued_tasks from executor.running_tasks, and pool.queued_slots from pool.open_slots. Queued time is the gap between the scheduler creating a task instance and an executor slot picking it up; running time is the task's own execution. When queued p99 climbs while running p99 stays flat, you have a capacity problem (pool slots exhausted, workers saturated, or scheduler.tasks.starving rising) not slow code. That distinction is the whole reason to instrument both. dagrun.schedule_delay and dag_processing.total_parse_time cover the other two stalls: a DAG file that got expensive to parse delays every run in the file, and a scheduler loop that slows delays every DAG at once. Dagster and Prefect expose the same shape, a run queue with depth and a daemon or work-pool heartbeat, under different names.

Aggregates hide the failure you care about. Take 200 tenants on an hourly DAG. Mean freshness is 4 minutes, p99 is 6 minutes, and tenant 47 has been stuck for 6 hours. That one tenant contributes 360/200 = 1.8 minutes to the mean, so the mean reads 5.8 minutes and the alert never fires. Segment by tenant and partition, and alert on max and on count-of-breaches, not on the average.

Failure modes and how each is detected.

FailureDetection signal
Silent success: task exits 0, writes 0 rowsRow-count reconciliation against source; freshness sensor on the output table; canary DAG writing a known row
Scheduler heartbeat lostAbsence alert: no scheduler_loop_duration sample for 2× the loop interval
Zombie task: killed but marked runningRunning duration above 3× p99 with a stale worker heartbeat
Backfill storm starving productionpool.queued_slots rising while pool.open_slots sits at 0
Source not ready, DAG greenSensor age and source-readiness check correlated to the run, not to the task

Trade-offs. Per-run lineage correlation (input and output versions, code and config bundle, quality results) is the expensive part, and on a pipeline with thousands of runs an hour you sample it rather than store it all. A single-team, single-DAG pipeline does not need tenant segmentation or a canary; task-level alerts plus a freshness check on the final table are enough, and adding the rest costs more in storage and on-call attention than it returns. The point of the objective is to decide which of those you can afford to skip, and to say out loud what freshness you are buying with the on-call burden you are paying.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-23

Manage secrets and connections for orchestrated tasks.

Answer

Clarify first. I'd ask two things: where the workers run (managed Kubernetes on AWS/GCP, or bare VMs), and the longest single task runtime. Those decide whether I can use federated identity with hour-scale tokens or need a secret backend with lease renewal. I'll assume Airflow 2.x on Kubernetes, batch tasks, one task that runs ~4 hours, and Postgres plus S3 as the data stores.

The answer in one line: the orchestrator should hold references to credentials, never credentials, and every task should authenticate as a short-lived identity scoped to the one resource it touches.

Three layers, in order of how much they buy you.

1. Identity. Give each task class its own Kubernetes service account, annotated for IRSA (eks.amazonaws.com/role-arn) or GCP Workload Identity. The pod then gets an STS token with a 1-hour default lifetime (12-hour max) or a Google access token with a 1-hour default, with no long-lived key anywhere on disk. This is the layer that survives a worker compromise: an attacker who reads process memory gets a token that expires before they can exfiltrate much.

2. Retrieval. For anything federation can't cover (an on-prem Postgres, a third-party API key) point Airflow at a secret backend instead of the metadata DB:

INI
# airflow.cfg
[secrets]
backend = airflow.providers.amazon.aws.secrets.secrets_manager.SecretsManagerBackend
backend_kwargs = {"connections_prefix": "airflow/connections", "variables_prefix": "airflow/variables"}
Python
from airflow.providers.postgres.hooks.postgres import PostgresHook

hook = PostgresHook(postgres_conn_id="warehouse_ro")  # resolved from Secrets Manager, not the DB
hook.run("select count(*) from orders")

The conn_id resolves against the backend before the metadata DB, so the DB row can be a stub. Never call Variable.get() at module top level: the scheduler re-parses files every min_file_process_interval (default 30s), so a top-level fetch hits the backend on every parse and leaks the value into the parse-time namespace.

3. Containment. AIRFLOW__CORE__HIDE_SENSITIVE_VAR_CONN_FIELDS defaults to True and the SecretsMasker scrubs connection and variable values from logs, but it does not scrub XComs, which land in the metadata DB in plaintext, nor rendered_task_instance_fields, which stores rendered templates since 2.1. Both are readable in the UI by anyone with DAG read access. Keep tokens out of op_kwargs that get templated, and pass data between tasks by reference (an S3 key), not by value.

Trade-offs.

OptionCredential lifetimeBlast radius on worker compromiseWrong when
Static connection in metadata DBUntil rotatedFull, and it's in every backupAlmost always
Secret backend lookup at task startRotation window (e.g. 30d)Full for the task's durationYou can federate instead
Cloud identity federation1h defaultBounded to ~1hOn-prem resources with no IAM
Vault dynamic DB credsRole default_ttl, e.g. 1hBounded, per-task userTask outlives the lease

That last row is the trap. A 4-hour Spark job holding a 1-hour Vault lease fails at minute 61 with an auth error, and the retry gets a new credential, which is correct for the retry but means the job must be written to reconnect, not to hold a connection object across the whole run.

Failure modes and how you'd catch them.

  • Backfill picks up today's credential. A 2023 backfill runs with current prod write permissions. Detect by joining credential-issuance audit logs to run_id and alerting when a run's credential is newer than the run's logical date.
  • Rotation mid-run. The connection pool holds the old password; you see a spike in auth failures across many tasks at once. Alert on that shape, not on individual task failures.
  • Leak through metadata. Scan the XCom and rendered_task_instance_fields tables for high-entropy strings on a schedule.
  • Break-glass. A named role with an expiry and a review ticket; log the retrieval, not the value.

Decision rule: pick the shortest-lived credential the task can finish inside, make the orchestrator store only the reference, and treat any value that reaches the metadata DB as already leaked.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

Secure an orchestration control plane and its task execution.

Answer

Assumptions: Airflow 2.x scheduler/webserver/workers on Kubernetes, metadata in Postgres, DAGs in Git, secrets in Vault or a cloud secret manager. Argo or Temporal change the nouns, not the shape.

The answer, first 90 seconds. Three trust planes, one hard boundary between them.

  • Control plane: scheduler, webserver/REST API, DAG store, metadata DB. Decides what runs.
  • Execution plane: worker pods. Does the work, touches target systems.
  • Authoring plane: Git, CI, image registry. Decides what code exists.

The fact that drives the whole design: Airflow's scheduler parses DAGs by importing them as Python. Parsing is arbitrary code execution with the scheduler's identity, its network position, and its access to the metadata DB. So "who can merge a DAG" is a control-plane privilege. Treat DAG authoring like deploying code to production, because it is.

From there: the control plane holds no target-system credentials at all. Workers get short-lived, per-task identity: Kubernetes projected service account tokens, IRSA/Workload Identity, or SPIFFE SVIDs, and fetch secrets at runtime. RBAC is split by role (author, deploy, trigger, clear/backfill, connection admin, platform admin), not by one admin group.

Trade-offs.

Per-task identity vs shared worker credentials. Minting a token costs a round trip to STS or Vault: tens of milliseconds, and you must handle expiry mid-task. Shared static credentials skip that and are simpler. The deciding question: can this worker reach more than one target system, or more than one team's data? If yes, per-task identity; the blast radius of one compromised pod is then one task, not the fleet. Single-tenant cluster, one target, reviewed code: static credentials scoped to that target are defensible.

Parse isolation. In-process parsing is free. A separate DAG-processor deployment costs another service and a serialization hop, but the scheduler never imports untrusted code. Multi-tenant authoring → isolate. One team with reviewed DAGs → in-process is fine.

Secrets in the metadata DB (Fernet-encrypted) vs an external manager. The DB is one dependency, but the Fernet key lives in the same deployment config as the ciphertext. An external manager gives rotation and audit, at the cost of task startup depending on Vault: cache with a TTL shorter than the lease.

Failure modes and how you see them.

  • Malicious DAG import exfiltrating env or hitting the metadata DB. Detect: egress from the scheduler namespace, unexpected DNS, and import timeouts. dagbag_import_timeout defaults to 30s, dag_file_processor_timeout to 50s.
  • Task outliving its token. Projected service account tokens default to 1h; a 3-hour task gets 401s mid-run. Detect: auth failures clustered at task duration > token TTL.
  • Parameter injection reaching a shell or SQL. Detect: user params appearing in rendered commands.
  • Unauthorized clear/backfill saturating the pool. Detect: max_active_runs_per_dag (default 16) hit, queue depth climbing.

Artefact: the worker pod.

YAML
# Kubernetes 1.29
spec:
  serviceAccountName: etl-runner
  automountServiceAccountToken: false   # drop the legacy, non-expiring token
  containers:
    - name: task
      volumeMounts:
        - {name: token, mountPath: /var/run/secrets/tokens}
  volumes:
    - name: token
      projected:
        sources:
          - serviceAccountToken:
              path: token
              audience: vault          # only Vault will accept this token
              expirationSeconds: 600   # kubelet refreshes at 80% of TTL

Arithmetic on blast radius. A static credential with a 12-hour STS session across 40 workers: one compromised pod buys 12 hours against everything that credential reaches. A 10-minute audience-scoped token buys 10 minutes against one audience: 72× less time, and no lateral reach. That ratio is the argument you make to whoever owns the credential.

Closing criterion. If you can't name the audience and TTL of every credential a worker holds, you haven't secured the execution plane yet.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Control orchestration cost without hiding failure or weakening recovery.

Answer

The 90-second answer

Assume Airflow 2.x on the Celery or Kubernetes executor, and that "cost" means the fully-loaded bill: scheduler and triggerer nodes, metadata Postgres, broker, worker slot-hours, log and lineage storage, and the downstream compute the DAG triggers. The orchestration software is rarely the line item that matters. Worker slot-hours spent waiting, and metadata writes, are.

So three moves, in order. Attribute first: tag every task with workflow, tenant and run type, and emit slot-hours, DB writes and downstream spend per tag. Then kill the two dominant drivers: sensors holding worker slots, and task-instance churn in the metadata DB. Then put guardrails on so the savings don't come out of recovery.

Why the drivers behave that way

A sensor in the default poke mode occupies a worker slot for the entire wait. poke_interval defaults to 60s, but the slot is held between pokes. Fifty sensors each waiting six hours is 300 slot-hours a day; on a 4-slot worker node at $0.20/hr that's 75 node-hours, roughly $450/month, for doing nothing. mode='reschedule' releases the slot between pokes. A deferrable operator releases it entirely and parks the wait on the triggerer's event loop, where one process multiplexes thousands of triggers. Same reasoning applies to TimeDeltaSensor and ExternalTaskSensor.

The metadata DB is the second ceiling. Every task instance writes state transitions into task_instance and task_instance_history. A 10,000-task DAG on a 5-minute cadence is 2.88M task-instance rows a day. Postgres absorbs that for a while, then the scheduler loop slows, dag_processing.total_parse_time climbs, and DAGs start appearing late. airflow db clean with a retention window is the fix, not a bigger instance.

Scheduler parse cost is the third. min_file_process_interval defaults to 30s and parsing_processes to 2. Two thousand DAG files at 200ms each is 400s of parse work per pass, split across two processes: the scheduler never idles. Fewer, larger DAGs and a longer parse interval fix it.

What I would not do

I would not cut cost by shortening log retention below what an incident review needs, dropping historical intervals, removing reconciliation tasks, or lowering max_active_runs so far that backfill catchup misses its freshness SLA. Those convert a cost problem into a correctness problem. Retry storms and hot pools get fixed, not budgeted around.

Failure modes and how they show up

FailureDetect
Sensor slot starvationCelery queue depth, queued task count
Scheduler parse backlogdag_processing.total_parse_time, DAG visibility lag
Metadata DB bloattask_instance table size, scheduler loop duration
Retry storm masking a bad sinkretry counter, duplicate downstream rows
Cost cut hiding failurereconciliation task skipped, freshness gap

Guardrails

Budgets and quotas per tenant with a named owner, plus anomaly alerts on slot-hours and DB writes. Load-test any change against p95/p99 freshness, queue fairness and recovery catchup. Report cost per trusted interval, not cost per run: a cheap run that produces an untrusted interval is the expensive one.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Design highly available scheduling and execution for critical workflows.

Answer

Assumptions I'd state first. An hourly settlement workflow, ~400 tasks, p99 task 90 s, must finish inside a 30-minute window. RTO 15 min, RPO 0 for schedule and run state: losing the schedule means a missed settlement or a double payment. At-least-once dispatch is acceptable because every task writes to the sink under a business key. If any of those are wrong, the design below changes; I'll say where at the end.

The answer: three planes, three different availability mechanisms.

Control plane: scheduler/dispatcher, DAG parser, API, trigger service. Run two or more replicas, but only one may dispatch a given schedule. Enforce that with a lease, not with hope: a Kubernetes Lease using client-go defaults (leaseDuration 15 s, renewDeadline 10 s, retryPeriod 2 s), or Airflow 2.x's row locks in the metadata DB, which is why Airflow 2.x supports multiple schedulers at all. SQLite is not an HA metadata store.

Metadata store: PostgreSQL with synchronous replication (synchronous_commit=on plus synchronous_standby_names) to a standby in a second AZ, Patroni + etcd driving failover. RPO 0; RTO typically 30–60 s. This component sets your RPO. Everything else is stateless and can be replaced.

Data plane: workers and queues. Stateless workers across three AZs, each AZ sized to carry the full load alone. Queue depth bounded so a backlog cannot exhaust memory.

Duplicate prevention. Assume at-least-once. Every task upserts on a natural key, INSERT ... ON CONFLICT (workflow_id, task_id) DO NOTHING, so a duplicate dispatch is a no-op rather than a second payment.

ComponentHA mechanismFailure it does not fix
SchedulerLeader lease + fencing tokenTwo leaders during a partition
Metadata DBSync replication + PatroniRegion loss if standby is co-located
Workers3 AZs, each sized for full loadA poison task looping forever
QueueReplicated broker, bounded depthBacklog exceeding the window
ArtifactsImmutable, content-addressedRegistry outage blocking new starts

Capacity arithmetic. 400 tasks × 90 s = 36,000 task-seconds. Window is 1,800 s, so 20 concurrent slots minimum. Each AZ must carry 20 alone, so 3 × 20 = 60 slots = 15 workers × 4 slots. Add 25% for retries: 75 slots.

Failover trace. t=0 the leader pod dies. The lease expires within 15 s; the new leader acquires at roughly t=17 s, reads in-flight task states from the DB, and resumes dispatch. Tasks already running on workers keep running: they never needed the scheduler. A task whose worker died is not requeued until the zombie threshold (Airflow 2.x default scheduler_zombie_task_threshold = 300 s). Worst-case added latency for one lost task is therefore ~5 min. A 30-minute window absorbs that; a 5-minute window would not, and you would need a shorter zombie threshold or a heartbeat-based requeue.

Failure modes and how you detect them.

  • Split brain: two schedulers dispatch the same run. Detect with a duplicate-run counter keyed on (workflow_id, task_id); alert on any non-zero value.
  • Zombie tasks: requeued by the threshold above; idempotency makes the requeue safe.
  • Missed intervals after failover: catch up deliberately under a concurrency cap. Replaying six missed hours at full width saturates the sink.
  • Metadata DB failover: workers retry state writes with backoff; the scheduler must not re-dispatch until the DB is writable again.

Health checks. Liveness is process-up. Readiness is a synthetic DAG every 60 s that writes a row and validates the output. Alert on schedule lag, the gap between expected and actual run start, not on replica count.

What would change the decision. If the workflow is long-running stateful orchestration (Temporal-style activities running for hours), lean on the engine's own sharded durability instead of a leader-elected scheduler. If RPO 0 is not required, async replication with a 5-minute RTO is far cheaper.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

Recover orchestration after loss or corruption of its metadata database.

Answer

What I'd say first. Before touching anything: which orchestrator, which store, and is the scheduler still running? I'll assume Airflow 2.9 on Postgres 15, the metadata DB is corrupt, and the external systems (S3, Kafka, the payment API) still hold the real effects. The DB is a record of intent; the external systems are the truth. So the order is freeze, fence, restore, reconcile, resume, and nothing runs until reconciliation finishes.

Freeze and fence. Pause every DAG (airflow dags pause <dag_id>), stop all schedulers, workers and the triggerer. Airflow 2's HA schedulers coordinate through the DB, so a restored DB plus a live scheduler is two writers on one row set. Bring up exactly one scheduler after restore.

Restore. Postgres PITR: base backup plus WAL archive, recovery_target_time just before the corruption, recovery_target_action = 'promote'. Then airflow db migrate to bring the schema to the running Airflow version: a 2.7 backup restored under 2.9 will not start otherwise. Example figures: WAL shipped every 60 s gives RPO ≤ 60 s; a 200 GB DB restoring at 150 MB/s is ~22 min plus WAL replay, so RTO ~35 min. Those are the numbers you record, not the words "RPO/RTO".

Reconcile before resuming. The restored DB's task states are a claim, not a fact. List runs active at the recovery point:

airflow dags list-runs --state running --output table
airflow tasks states-for-dag-run <dag_id> <run_id>

For each task the DB calls succeeded or running, check the external effect by its stable logical identity: the idempotency key you passed, the S3 object key, the Kafka offset, the remote operation ID. Then decide:

DB saysExternal saysAction
successeffect presentmark success, no re-run
successeffect absentre-run (state write landed, effect didn't)
runningeffect presentmark success, do not re-run
runningeffect absentre-run
failedeffect presentmark success, skip retry

The "running + effect present" row is the one that bites: the task committed externally and died before writing state. Re-running it double-charges. That is why every task touching an external system needs an idempotency key, charge_id = f"{dag_id}-{run_id}-{task_id}", so a re-run is a no-op.

Zombie tasks: Airflow marks a task a zombie when its heartbeat is older than scheduler_zombie_task_threshold (default 300 s). After a restore, stale heartbeats from pre-crash workers look like zombies; clear them with airflow tasks clear only after the table above is filled in.

Missed schedules. The scheduler was down, so time-based runs never fired. Backfill only after checking source retention, if Kafka retention is 7 days and the gap is 9, the data is gone and backfill is theatre. airflow dags backfill --start-date ... --end-date ... with max_active_runs bounded so you don't stampede the pool.

Trade-offs. Full re-run wins when tasks are cheap and idempotent. Compensate (saga rollback) wins when the effect is expensive or irreversible and you can name the inverse operation. Mark-success wins when the effect is confirmed present and re-running is unsafe. Never pick mark-success from the DB alone.

Failure modes and detection. Restore during an external commit: the effect exists, the DB doesn't know. Caught by the reconciliation table, symptom is a duplicate charge. Stale worker rejoins: it heartbeats into the restored DB and the scheduler re-queues its task. Caught by fencing, symptom is two workers on one task. Backup incompatible with the running Airflow version: airflow db migrate fails at startup. Caught before you promote. Event retention expired: backfill produces empty runs. Caught by comparing source offsets to the gap.

Drills. Quarterly: PITR to a point mid-commit, kill a worker mid-task and let it rejoin, restore a backup one minor version behind. Record achieved RPO/RTO and any gap you could not prove.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Respond to an orchestration incident causing stale or partial data.

Answer

The 90-second answer

First thing I ask: is the data wrong, or just late? Stale-but-complete means the pipeline stopped and the last published version is still correct. Partial means something published a subset and consumers may already be reading it. Those need different responses.

Assumptions I'd state: an orchestrator (Airflow, Dagster) with per-partition tasks, a warehouse or lakehouse that supports snapshot reads (Iceberg, Delta, Snowflake AT), and consumers reading a published table or topic rather than raw task output.

My posture: contain, classify, reconcile, republish. Never clear task instances first: the dag_run state and logs are the only record of which partitions were attempted and what was written.

Contain

Pause the schedule (airflow dags pause), set max_active_runs=1, and stop backfills and duplicate workers. Fencing matters because two writers on the same partition key interleave or duplicate output: a backfill racing the live run is how a partial partition becomes a corrupt one. Preserve the evidence: task logs, run metadata, source offsets, external operation IDs.

Classify

ClassDetection signalCost if missed
Control planescheduler heartbeat gap, DAG not scheduled, run stuck running past SLAsilent staleness, no alert fires
Code/schematask fails on schema mismatch; null rate spikes while row count looks finewrong values pass row-count checks
Sourceupstream freshness lag, source row count flatbackfill recomputes nothing
WorkerOOMKilled, same exit code on every retryretry loop burns the recovery window
Resourcepool slots exhausted, queue depth climbinglive work starves behind backfill
Sinkcommit latency, deadlock, partition written partiallypartial data looks complete
Externalcall timed out after sendunknown whether it landed

Repair, and how to choose

  • Idempotent retry when the fault was transient and the task is genuinely idempotent: it writes with INSERT OVERWRITE on the partition or a MERGE keyed on event_id, so re-running yields the same rows. If the task appends, retry duplicates and you've made it worse.
  • Bounded backfill when source retention still covers the gap and the volume won't starve the live schedule.
  • Compensation when the source is gone, retention expired, and you must correct downstream effects instead of recomputing.
  • Rollback beats repair when the fault is in code or schema (retry reproduces the bug), when the blast radius is unknown, or when consumers have already acted on the bad data. Point them at the last coherent version (Delta VERSION AS OF, Iceberg TIMESTAMP AS OF, Snowflake AT) and mark the bad interval stale.

Worked trace (hypothetical figures)

Hourly table, partitions 00:00–06:00. At 06:40 the freshness check fires: partition 04:00 holds 1.2M rows against an expected ~4M. Last coherent version is 03:00. Cause: worker OOM at 04:12; the retry appended a partial batch because the sink commit wasn't per-partition atomic. Action: pause, roll consumers to 03:00, backfill 04:00–05:00 through the overwrite path, verify row counts and null rates against 03:00, then resume from 06:00.

Validate and resume

Check populations, quality, and downstream delivery before republishing. Resume from an exact boundary, not "now". Monitor catchup without starving current work.

Failure modes to watch

Retry storms that duplicate rows; backfills that starve live tasks; a "fixed" partition that's still short because the source retention gap was never stated. Say the irrecoverable gaps out loud.

After

Root-cause the detection and control gaps, update runbooks and tests, blameless review, rotate credentials if exposure is possible, keep incident artifacts privacy-safe.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

Capacity-test an orchestration platform and its critical dependencies.

Answer

Assume Airflow 2.x with the Celery executor on Kubernetes, Postgres for metadata, RabbitMQ as broker. Swap the names for your stack; the shape holds. The deliverable is one number: the load at which the platform still meets its SLOs and can absorb a single component failure and drain the backlog inside the recovery window. The crash maximum is not a capacity plan.

Why it degrades where it does. The scheduler is a loop: parse DAG files, create DagRuns, emit TaskInstances. Parsing is CPU-bound and gated by min_file_process_interval (30s default), so a synchronized 00:00 burst across 2,000 DAGs makes one loop pass emit tens of thousands of TIs before any worker pulls. Workers then drain at parallelism (32 default) per worker, capped by pool slots (default_pool is 128). Queue-to-start is roughly queue depth ÷ (workers × concurrency). The metadata DB is the ceiling underneath both: every TI state change is a row update, and Postgres write throughput saturates before scheduler CPU does.

Worked burst (hypothetical figures). 2,000 DAGs, 10 tasks each, all scheduled at 00:00 → 20,000 TIs. Scheduler emits at ~500 TIs/s → 40s to fill the queue. 20 workers × 32 = 640 concurrent slots, 5s per task → 20,000 ÷ 640 = 31 waves × 5s ≈ 156s to drain. The last task starts ~196s after the burst, so p99 queue-to-start ≈ 3.3 min against a 90s SLO: a fail. The fix is not more workers if Postgres write p99 is already climbing; it is staggering schedules or raising pool slots.

What to measure.

SignalHypothetical SLOWhat it catches
event/schedule → DagRun createdp99 < 60sscheduler parse + emit loop
queue → task startp99 < 90sworker pull rate vs depth
task completion tailp99 < 15 minretries, long tasks
metadata DB write p99< 20 msTI state churn
tenant share of slots< 3× its DAG sharepool starvation

Trade-offs. Three levers raise throughput and each has a wall. More workers add broker consumers and Postgres connections: the DB connection limit becomes the wall, and adding workers when writes are the bottleneck just moves the queue into the DB and worsens lock contention. Bigger pools raise concurrency but widen the blast radius of one bad DAG. Queue partitioning by pool or tenant isolates a hot tenant but makes fairness accounting harder. Pick based on which signal saturates first, not on which is easiest.

Failure modes. Kill the scheduler mid-burst: TIs sit in running until scheduler_zombie_task_threshold (300s default) clears them, and any task that already ran gets re-executed. Silent duplicates unless tasks are idempotent. Detect with output canaries and row-count reconciliation, not throughput graphs. Broker ack loss redelivers the same way. A slow metadata DB makes the scheduler miss its heartbeat and a second scheduler takes over: split brain.

Recovery and growth. Restore metadata from backup and measure catch-up to get real RPO/RTO. Version the workload and results so a re-run is comparable. Set growth triggers (queue depth, DB write p99) and define load-shedding semantics: reject unbounded queues as a capacity plan.

Curated: · Written: · Reviewed:

Difficulty: Hard