ETL and ELT Design Patterns Questions
Trade-offs between extract-transform-load and extract-load-transform strategies, where transformation logic should live, and when to push compute into the warehouse. Covers incremental vs full loads, change-data-capture, slowly changing dimensions handling in the load path, and tooling (dbt-style transformation layers). Focuses on the processing-strategy decision rather than a specific vendor.
Describe how you would author an Airflow DAG for a daily incremental load that must be idempotent. Include task granularity, use of staging tables and run identifiers, pre-checks, deduplication steps, atomic swaps or MERGE, and metadata recording to prevent double-processing when a DAG is retried or a task restarts.
Sample Answer
Direct answer
An idempotent daily incremental-load DAG needs four things working together: staging-first writes that never touch the production table directly, an explicit run identifier scoping every write to exactly one logical attempt, deduplication before the final promotion, and a metadata record of what was actually committed. Together these mean retrying the same logical day, whether from a single task retry or a full DAG rerun, converges to the same final state instead of duplicating or losing rows.
Structured elaboration
Task granularity. Split the load into distinct tasks along natural idempotency boundaries: extract-to-staging, pre-checks, deduplicate-within-staging, atomic-swap-or-merge-into-target, and record-metadata. Splitting this finely, rather than one monolithic load task, means a failure at, say, the pre-check step can retry just that step without re-extracting, and it gives a clear per-step audit trail of exactly what happened on a given run.
Staging tables. The extract task writes to a staging table scoped by run identifier, either a uniquely named table per run or a shared staging table with a run_id column, never directly to the production table. A retried or even duplicated extract simply produces another (or overwrites the same) staging row set, with zero risk to the already-correct production table until the swap step deliberately promotes it.
Run identifiers. Every staged row carries an explicit run identifier, typically the DAG run's logical date combined with a monotonic attempt number, rather than relying on wall-clock insert time. This is what lets deduplication and metadata recording answer "which specific attempt produced this data" unambiguously, instead of inferring it from timing, which breaks under retries and backfills.
Pre-checks. Before promoting staged data, validate the row count against an expected historical range, validate that the expected columns are present, and validate that no key column has an unexpected null rate. A pre-check failure should halt before the swap, not attempt to promote suspect data and hope a downstream consumer catches it later.
Deduplication. Within staging, deduplicate on the row's natural business key, not a surrogate row identifier that would not survive a retried extract, keeping the most recent version when duplicates exist from overlapping incremental windows.
Atomic swap or MERGE. Promote staging into production either through an atomic rename or swap (the staging table becomes the new partition instantaneously) or a MERGE (or INSERT ... ON CONFLICT DO UPDATE) keyed on the business key, so a retry of this exact step, even after a partial completion, converges to the same end state rather than duplicating already-promoted rows.
Metadata recording. After a successful promotion, write a row to a metadata table (run_id, logical_date, row_count, status='committed', committed_at) that acts as the definitive record of what has actually been committed for that logical date. A subsequent run for the same date checks this metadata first, so an accidental double-trigger, two DAG runs for the same date somehow both firing, can detect the prior commit and skip redundant work rather than blindly reprocessing.
Transactional writes to the warehouse. Where the target warehouse supports it, wrap the final swap or merge and the metadata-recording insert in a single database transaction, so a crash between "data promoted" and "metadata recorded" cannot happen: either both commit, or neither does. This closes the small window that staging, run identifiers, and deduplication alone leave open, where data has landed in production but the metadata table does not yet know it, which could otherwise let a naive check-metadata-first design re-promote data that already landed.
Handling partial DAG failure explicitly. If the DAG fails partway, for example after the swap but before metadata recording, in a warehouse where the two cannot share one transaction, the retry logic must re-check the actual target-table state rather than re-run blindly. The metadata-recording task itself, on retry, should verify whether its own prior attempt already landed, an idempotent metadata write keyed on run_id such as INSERT ... ON CONFLICT DO NOTHING, rather than assuming a clean slate every time it runs.
Worked example
A daily incremental load of an orders table runs with run_id = 20260720_020000_attempt1. The extract lands 48,213 rows into staging_orders. The pre-check's expected row-count range is 40,000 to 60,000 based on historical daily volume, so 48,213 passes.
Deduplication finds 312 duplicate business keys from an overlapping incremental window with yesterday's late-arriving data, and keeps the most recent occurrence of each, leaving:
48213−312=47901 unique rows
The MERGE into the orders production table affects all 47,901 rows, each either updating an existing row or inserting a new one depending on whether its business key already exists. The metadata table then records run_id=20260720_020000_attempt1, row_count=47901, status=committed.
Later that same day, the DAG is manually retried after a downstream consumer flags something and asks for a rerun. The metadata-check-first step queries the metadata table, finds logical_date=2026-07-20 already has a committed row with row_count=47901, and either skips straight to a no-op success if the retry was accidental, or, if the source data genuinely changed since the last run, proceeds through the same extract, deduplicate, merge, and metadata sequence again under a new run_id, landing whatever the currently correct row count is through the same idempotent MERGE, converging to the correct final state regardless of how many times it is repeated.
Trade-offs and pitfalls
Over-fragmenting task granularity, a separate task for every tiny sub-step, adds scheduling overhead and dependency-graph visual complexity that may not be worth it for a small pipeline; granularity should track genuine retry and audit boundaries, not be maximized for its own sake.
The metadata-check-first pattern only actually prevents double-processing if every code path that can trigger a run, including a human manually running the DAG from the orchestrator's own user interface, goes through it. A common gap is a manual "clear and rerun" action that bypasses the intended metadata check entirely.
Deduplication that blindly keeps the latest occurrence can silently mask a genuine data-quality bug: if a business key should never legitimately appear twice in a correct extract, always deduplicating instead of alerting on the first unexpected duplicate trades away a real correctness signal for a smoother-looking run.
Architect how you would run dbt transformations within Airflow for multiple environments (dev, staging, prod). Explain how to handle environment-specific variables, concurrent runs, dependency management between dbt models and non-dbt tasks (e.g., file ingestion), and schema migrations that require coordination with data producers.
Sample Answer
Direct answer
Running dbt transformations inside Airflow across dev, staging, and prod comes down to three coordination problems: making the same DAG definition behave differently per environment without duplicating it, keeping concurrent runs (a scheduled prod run and a developer's manual staging run, say) from stepping on each other, and sequencing dbt models correctly alongside the non-dbt tasks (file ingestion, for example) and schema migrations they actually depend on, since dbt's own internal dependency graph only covers dbt models, not the ingestion step that has to land raw data before dbt can transform it.
Structured elaboration
Environment-specific variables. Parameterize the DAG with an environment identifier (dev, staging, prod) passed at the Airflow connection or Airflow Variable level, not hardcoded into the DAG file, and have the dbt invocation select its target (dbt run --target {env}) from dbt's own profiles.yml, which maps each named target to its own connection details. One DAG definition then serves all three environments; only the resolved variables differ per run, which avoids maintaining three near-duplicate DAG files that inevitably drift apart.
Concurrent runs. Give each environment its own Airflow pool (or its own dedicated set of dbt-invoking tasks with environment-scoped concurrency limits), so a long-running prod run and a developer's ad hoc staging run never compete for the same worker slots, and, more importantly, so dbt's own internal state (its manifest, its run results written to the target schema) for one environment is never overwritten mid-run by a concurrent run against a different environment's schema.
Dependency management between dbt models and non-dbt tasks. dbt's own dependency graph (built from ref() calls between models) only covers dbt models; it has no visibility into an upstream file-ingestion task that has to land raw source data before any dbt model can read it. Model that ingestion step as its own Airflow task, upstream of the dbt run task, with an explicit Airflow dependency edge (ingest_files >> dbt_run), so Airflow's dependency graph is the one true source of truth for "must happen before," spanning both dbt and non-dbt work, rather than expecting dbt's own graph to somehow know about a task outside of it.
Schema migrations requiring coordination with data producers. A schema change on an upstream source table (a data producer team adding or renaming a column) can break a dbt model that references it. Coordinate this the same way any cross-team contract needs coordinating: a data producer proposing a schema change signals it in advance (a pull request against the dbt project's source definitions, for instance, or a shared schema-registry entry), dbt's own source freshness and schema tests catch a mismatch as a failing test run rather than a silent wrong result, and the DAG's own failure-handling routes that test failure to an alert naming the specific model and the specific upstream source, not a generic "dbt run failed."
Worked example
The DAG uses an Airflow Variable target_env resolved per run. For a scheduled prod run, target_env=prod; the dbt task executes dbt run --target prod --profiles-dir /opt/dbt, referencing a prod target block in profiles.yml that points at the production warehouse schema. For a developer's manual staging run of the same DAG, triggered with a run configuration overriding target_env=staging, the exact same DAG and the exact same dbt project run instead against the staging target block, writing to a separate staging schema, with no code change required, only the run configuration differs.
The DAG's dependency chain is ingest_raw_files >> dbt_run (which internally sequences staging models, then mart models, per dbt's own ref() graph) >> dbt_test >> notify_on_failure (only if dbt_test fails). If a data producer renames a source column without warning, dbt_test catches it as a failing schema test for the specific downstream model that referenced the old column name, and notify_on_failure pages the owning team with that model's name in the message, rather than a downstream business-intelligence dashboard silently rendering a null column with no alert at all.
Trade-offs and pitfalls
Parameterizing environments through a single DAG definition is more maintainable long-term, but it means a bug in the shared DAG logic affects all three environments at once; a genuinely risky change to the DAG itself, not the dbt models it invokes, deserves its own staged rollout discipline, the same as any other shared infrastructure change.
Environment-scoped pools prevent concurrent runs from clobbering each other's dbt state, but they do not by themselves prevent a developer's staging run from reading stale upstream data if the staging environment's own ingestion has not run recently; staging environments commonly lag production data freshness, and that gap should be visible, not silently assumed away.
Relying solely on dbt's own tests to catch upstream schema drift means the failure is only caught after the fact, when the scheduled run actually executes; a producer team that wants earlier warning needs a separate, proactive schema-change-review process, since dbt tests are a safety net for this specific pipeline, not a substitute for the upstream coordination itself.
What does an in-warehouse transformation tool like dbt actually give you that hand-written SQL scripts scheduled by cron don't? Ground your answer in specific capabilities (not just 'it's more organized').
Sample Answer
An in-warehouse transformation tool like dbt gives you three things a scheduled cron script does not: version-controlled, testable SQL; a dependency graph the tool builds and executes for you; and documentation that stays attached to the code instead of living in a separate wiki.
Concretely, what you get
- Modularity and dependency management. Each model is a
.sqlfile that references other models withref(). dbt parses those references into a DAG (directed acyclic graph) and runs models in the right order automatically, so you never hand-maintain "run script B after script A finished." - Testing as a first-class citizen. You declare assertions in YAML next to the model (uniqueness, not-null, accepted values, referential integrity to another model) and dbt runs them as part of the pipeline, not as an afterthought someone has to remember to write.
- Documentation and lineage for free. dbt generates a browsable docs site from your model definitions and column descriptions, and a lineage graph showing exactly what feeds what. A cron-scheduled SQL script has none of this unless someone builds it by hand and keeps it in sync.
- Git-native change management. Because everything is plain text SQL and YAML, you get code review, branching, and CI the same way you would for application code, which a stored procedure buried in a scheduler typically does not.
Where this actually helps day to day
A change to an upstream source column shows up as a broken test or a documented lineage edge before it silently corrupts three downstream marts. Onboarding a new analyst is "clone the repo and read the docs site" instead of "ask around for who owns which script." A bad model can be reverted with git revert instead of hand-reconstructing what the SQL used to say.
What it does not replace
dbt only transforms; it does not extract or load data (you still need a connector or CDC (Change Data Capture) tool to get data into the warehouse), and it does not orchestrate anything outside the warehouse (you still need something like Airflow to trigger dbt run on a schedule and coordinate it with non-dbt tasks).
A team currently schedules reports with simple cron jobs and is considering adopting a full orchestrator (Airflow/Prefect). What are the real trade-offs? Cover dependency management, retries, backfills, SLA monitoring, visibility for non-engineers, and operational overhead.
Sample Answer
Direct answer
Moving from simple cron jobs to a full orchestrator is worth it once a team has more than a handful of jobs with real dependencies between them. The honest trade-off is real, ongoing operational overhead, a new system to run, monitor, and learn, traded for capabilities cron structurally cannot provide on its own: dependency-aware sequencing, consistent retries, real backfill tooling, and visibility that a crontab file never gives anyone outside the team that wrote it.
Structured elaboration
| Axis | Simple cron | Full orchestrator (Airflow/Prefect) |
|---|---|---|
| Dependency management | None natively; a job scheduled at a fixed time simply assumes its input finished by then, with no actual check | First-class: a job starts only once its declared upstream has actually succeeded |
| Retries | Hand-rolled inside each script, inconsistent from job to job | Declarative and consistent across the whole platform (a retries setting on any task) |
| Backfills | Manually re-run a script once per missed date, no built-in tooling | A deliberate, built-in capability: re-run a date range with one command or user-interface action |
| SLA monitoring | Nothing beyond an email if a cron job happens to fail and someone wired that up | First-class dashboard and alerting surface built into the platform |
| Visibility for non-engineers | Essentially none; a crontab is not readable by anyone outside the team that wrote it | Real: a rendered dependency graph and run history a non-engineer can open and understand without reading code |
| Operational overhead | Minimal; cron is already running, nothing new to deploy or learn | Real and ongoing: someone runs the scheduler (or pays for a managed version), the team learns the platform's concepts, and DAG code becomes a real software artifact to maintain |
Worked example
A team runs 15 cron jobs, 4 of which have a real dependency: job B needs job A's output, enforced only by "job B is scheduled 20 minutes after job A, and that has always been enough time." One month, job A runs 25 minutes late because of an unusually large input file. Job B still fires at its normal fixed offset and processes a stale, incomplete input, silently producing a wrong report that a stakeholder catches two days later.
Under an orchestrator, job B would instead be declared to depend on job A's actual completion signal, so it would only start once A genuinely finished, whether that took 20 minutes or 45. This eliminates the entire failure class structurally, by removing the fixed-offset assumption altogether, not by picking a bigger safety margin and hoping it holds next time too.
Trade-offs and pitfalls
Adopting a full orchestrator for a small handful of genuinely independent cron jobs with no real dependencies between them is over-engineering: none of the orchestrator's core advantages apply if there is nothing to sequence, and the migration and learning-curve cost is real. The decision should be weighed against how many jobs actually have dependency, retry, or backfill needs today, not adopted reflexively because cron feels old-fashioned.
For a set of complex transformations, one candidate wants to write them as dbt models running entirely in SQL, another wants a Python/Spark job. When does SQL-in-the-warehouse stop being the right tool, and what does a Spark job buy you that dbt can't?
Sample Answer
SQL-in-the-warehouse (dbt) is the right default until the transformation needs something SQL genuinely can't express well or needs compute the warehouse can't give you economically. Both of those limits are concrete, not vibes.
Where dbt/SQL wins
- Anything expressible as joins, aggregations, and window functions, which covers the large majority of analytics transformations.
- Fast iteration: an analytics engineer edits a model, runs
dbt runagainst a small sample, and sees results in seconds, with tests and documentation attached to the same file. - Cost efficiency for warehouse-native compute: you're not paying for a separate cluster, you're using compute you're already paying the warehouse for.
Where Spark (or another general-purpose engine) becomes necessary
- Complex, imperative logic that SQL expresses awkwardly: iterative algorithms, custom state machines, or business logic that's naturally a sequence of conditional steps rather than a set-based query.
- Feature engineering for ML at scale: many feature transformations (sliding-window computations with complex conditional logic, joins against very large reference datasets with custom matching logic) are more naturally expressed and more efficiently executed in a DataFrame API with fine-grained control over partitioning and caching.
- Custom UDFs with non-SQL logic: calling out to a Python library (a geocoding library, a specialized parser, a model inference call) inside a transformation is straightforward in Spark and either impossible or a serious performance anti-pattern in most warehouse SQL engines.
- Data volumes or shapes SQL engines handle poorly: deeply nested, irregular semi-structured data at large scale, or workloads that need fine-grained control over partitioning and shuffle behavior a SQL optimizer won't give you.
The trade-off: Spark buys you expressiveness and low-level control at the cost of developer productivity (writing and testing a Spark job is slower iteration than writing and testing a dbt model) and operational complexity (you're now managing a cluster, not just SQL against a warehouse you already operate). The decision isn't "SQL vs Spark" as a permanent architectural choice, it's per-transformation: a data platform commonly runs both, dbt for the bulk of standard analytics transformations, Spark for the specific jobs that genuinely need it (typically ML feature pipelines and complex semi-structured processing).
A concrete rule of thumb: if you find yourself trying to express something in SQL that would be a five-line Python function with a for-loop and conditionals, that's usually the signal you've hit dbt's ceiling for that specific transformation, not a sign you're writing bad SQL.
Unlock Full Question Bank
Get access to all 30 ETL and ELT Design Patterns interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.