Building Data Pipelines with Spark and dbt: Quality Control and Monitoring in Production

A pipeline that worked perfectly on a test dataset starts throwing errors in production. A familiar picture: the job ran, but the data in the report doesn't add up. Or worse — the report went to the client, and a day later it turned out that the join had multiplied the rows. Data Engineering (Spark, dbt) is not about "learning Spark and dbt," but about catching such situations before they become a problem. Let's break down what really stands behind building data pipelines and how to go from the first ETL to a production system.

What a data engineer actually does

From the outside it seems simple: take data from a source, put it in the warehouse, build a report. In practice, 80% of the time is spent not on transformations but on figuring out why the numbers don't match. Here's a typical scenario: an analyst says that yesterday's revenue on the dashboard is 30% lower than in the CRM. You start digging — it turns out a new order status appeared in the source that wasn't accounted for in the filter. Or the time zone: the CRM writes time in UTC, but the report is built in Moscow time, and night orders fall on the wrong day. More on the topic: “Data Engineering (Spark, dbt): How to Build Data Pipelines That Don't Fail in Production”.

A data engineer is the person responsible for ensuring that data travels from point A to point B without loss or distortion. And does so predictably. Spark is needed here for processing large volumes (when pandas can no longer cope), dbt — for organizing transformations inside the warehouse (SQL models, tests, documentation). Streaming (Kafka, Spark Structured Streaming) — when data is needed not once a day but every few seconds. Quality control (Great Expectations, dbt tests) — to prevent corrupted data from reaching the report. More on the topic: “Data Visualization: Why Most Charts Fail and How to Build Ones That Actually Work”.

One walkthrough: how a pipeline is built from source to mart

Imagine an online store. There's an orders database (PostgreSQL), click logs (files in S3), a product catalog (export from 1C). You need to update the sales mart daily, taking into account clicks and product categories. More on the topic: “SQL and Databases: What You Need to Know Before Starting — A Real-World Problem Breakdown and Pitfalls”.

Step 1. Extraction. We pull orders from PostgreSQL. It seems simple — SELECT *. But if you do this without a LIMIT and without accounting for new records, at a volume of several million rows the database will start to slow down. The right way is incremental extraction by the updated_at field: we pull only what has changed since the last run. This is where people often stumble: they forget about the time zone in updated_at or that some records are updated without changing this field (for example, via a direct UPDATE bypassing the trigger). More on the topic: “Vector Databases — From Search to RAG: Why Your RAG Chatbot Gives Wrong Answers and How to Fix Retrieval”.

Step 2. Loading into the warehouse. We put raw data into S3 or directly into Delta Lake / Iceberg. Important: we don't touch the raw data, we store it as is. This makes it possible to replay the pipeline if the transformation logic changes. A typical beginner mistake is to clean and enrich data immediately upon loading. Later it turns out that the filter was too strict, and the source data is already gone. The trade-off is real: keeping raw history forever costs storage, while a short retention window (say, 30–90 days, depending on your replay needs) caps the cost but limits how far back you can reprocess. Decide the retention period from how often business logic changes, not from what feels tidy. More on the topic: “Data Science from Scratch: Why 500 Clean Rows Beat 50,000 Dirty Ones — Debunking the "More Data Is Better" Myth”.

Step 3. Transformations in dbt. Here we describe the models: staging (light cleaning), intermediate (joins, aggregations), marts (ready-made data marts). dbt allows you to version SQL, test (not_null, unique, relationships), and document. But the main thing is that it makes transformations idempotent: re-running gives the same result. In dbt this comes from the incremental materialization plus a unique_key: on each run dbt issues a merge (or delete+insert, depending on the adapter) that replaces matching rows instead of appending them. If you use unique_key, make sure it is genuinely unique in the incoming batch — otherwise the merge itself will fail or pick an arbitrary row. For append-only event tables, an is_incremental() filter on a timestamp column is the alternative, but then late-arriving rows older than the filter boundary are silently dropped. More on the topic: “Data Science and Machine Learning: A Realistic Step-by-Step Plan — Python, Statistics, Models and Getting Them Into Production”.

Step 4. Orchestration. Airflow or Dagster run tasks on a schedule and monitor dependencies. It's important not to make the chain too long: if one step fails, it shouldn't drag everything else down. A common mistake is to run all tasks sequentially, although some can be parallelized.

Step 5. Quality control. After each key model, we run tests: the sum of orders must match the source, there must be no duplicates by id, dates must not be in the future. Great Expectations or dbt tests catch anomalies. But tests are not just "failed/passed." A good practice is to save metrics (row count, sum) and compare with the previous run. A sharp deviation is a signal, even if the test formally passed.

visual {"type":"flow","title":"Data path: from source to mart","steps":[{"label":"Extraction","detail":"Incremental extraction from the source"},{"label":"Loading","detail":"Raw data in S3 or Delta Lake"},{"label":"Transformations","detail":"dbt models: staging → intermediate → marts"},{"label":"Orchestration","detail":"Airflow or Dagster manages dependencies"},{"label":"Quality control","detail":"dbt tests and Great Expectations"}]} More on the topic: “Data Science Prompts That Actually Work: 12 Recipes from EDA to Feature Engineering That Turn an LLM Into a Real Analyst Partner”.

Where people stumble most often

The first stumbling block is underestimating dirty data. In educational examples, data is clean; in reality — gaps, duplicates, different date formats, encodings. In interviews they ask about Spark, but at work you have to figure out why the "amount" field contains "N/A" and how to handle it without losing half the orders.

The second is ignoring idempotency. If a pipeline fails midway and is restarted, it must not duplicate data. In Spark the practical route is df.write.mode("overwrite").partitionBy(...) with spark.sql.sources.partitionOverwriteMode=dynamic, so only the partitions present in the new batch are replaced; a full overwrite of the table is the blunt alternative, and mode("append") is what causes the numbers to grow every day. In dbt it's materialized='incremental' with a unique_key, as described above.

The third is lack of monitoring. A pipeline can run without errors but produce empty data (for example, if the source is temporarily unavailable and processing continued with an empty DataFrame). You need alerts not only for failures but also for anomalies: a sharp drop in row count, schema changes, increased execution time. Concretely: write one row per run into a metrics table (model name, run timestamp, row count, sum of the key measure, duration), then compare each run against a baseline — the median of the last 7–14 runs at the same hour of day. Alert when the row count drops more than ~30% below that median or the sum deviates more than ~20%; tune both numbers against your own history once you have a few weeks of it, because a fixed percentage borrowed from someone else's pipeline will either fire constantly or never. Route alerts to the channel the on-call actually reads, and include the metric name, the expected vs. actual value, and a link to the run.

The fourth is complexity instead of simplicity. Sometimes a task is solved with Spark when SQL in the warehouse would suffice. Or streaming is built when an hourly batch is enough. Tool choice should be driven by volume and latency requirements, not by fashion. Streaming buys seconds of latency at the cost of exactly-once semantics, watermark handling and harder debugging; batch buys simplicity and cheap reprocessing at the cost of freshness. Pick the cheapest option that meets the latency the business actually needs.

The fifth is the join that multiplies rows. Say orders are joined to a product catalog that has two rows for the same product_id (a re-export from 1C left a duplicate). A 10,000-row order table becomes 10,050 rows, and revenue is overstated. Two defenses: a dbt unique test on product_id in the catalog staging model, which fails the run before the mart is built; and, when duplicates are legitimate (e.g. a slowly changing dimension), a window function — row_number() over (partition by product_id order by updated_at desc) — to keep only the latest version before joining. After the join, assert that the row count equals the pre-join count.

The sixth is schema evolution and late-arriving data. A new column in the source, or a column changing type from int to string, breaks a strict schema. In Spark, define an explicit schema for critical fields and let non-critical ones land in a map or a raw JSON column; in the warehouse, add columns rather than renaming them, and keep transformations reading by name. For late data, decide the policy up front: either the incremental filter looks back a few days (re-processing a small window every run) or late rows go to a separate table for manual reconciliation. Without a policy, late rows either vanish or double-count.

A failure scenario, start to finish

The dashboard shows night orders on the wrong day. Resolution: confirm the source stores UTC and the report applies Moscow time (UTC+3); check whether the conversion happens in the staging model or only in the mart's where clause; move the conversion to one place — the staging model — and store both the raw UTC timestamp and the converted local one; add a dbt test that no order's local date differs from its UTC date by more than the offset; backfill the affected partitions by re-running the incremental model with a widened lookback window. The lesson generalizes: time zone logic belongs in exactly one model, and the test that guards it should exist before the bug does.

Learning paths: what to choose and what to pay

Self-study is the cheapest path, but also the longest. Spark and dbt documentation is extensive but scattered. YouTube courses give the basics but don't teach you how to debug a pipeline when it fails at 3 a.m. Practice on real projects is the best teacher, but mistakes in production are costly. Therefore, people often follow the path: courses for the basics, then an internship or a pet project with real data.

Courses with feedback and a structured program save time but cost money. It's important that the course provides not only theory but also analysis of typical mistakes and the opportunity to check your solutions. For example, the course Data Engineering (Spark, dbt) focuses on practical assignments with review and an AI tutor who answers questions on the topic. This doesn't replace real experience but helps you not get stuck on elementary things.

Another option is open-source projects. You can find a repository with a pipeline and try to improve it. But without a mentor, it's hard to understand which practices are truly good and which are outdated.

Who this suits and who it doesn't

Data Engineering (Spark, dbt) is not for those who want to quickly master a profession from scratch in a month. This is an area that requires a foundation: understanding of SQL (you can't do without it), basics of Python, an idea of how distributed systems work. If you're an analyst who already writes SQL and wants to move on to building pipelines — this path is logical. If you're a developer familiar with infrastructure but haven't worked with data — it will also suit you.

You shouldn't go here if you only enjoy visualization and communicating with the customer, and digging through logs and figuring out why a join gave the wrong result is boring. It's also not suitable for those who expect instant results: the first months will be spent learning the tools and understanding how they work together.

In conclusion

Building data pipelines is a discipline where it's more important not to know all Spark functions but to be able to design processes that don't break when data changes. Start small: build a simple pipeline from source to mart, add tests, learn to restart it without duplicates. Gradually increase complexity. If you need a structured start with error analysis and feedback, check out the course Data Engineering (Spark, dbt) — it has practical assignments and an AI tutor who helps you understand difficult parts.

AssetMaterials for this article

A document from this article — download and apply it.

  • XLSXPre-Production Pipeline Quality Gate Checklist.xlsxXLSX · 9.5 KBDownload
← All posts

Ask AI about this article

Ask a question about this article — ASI Biont will answer based on its text and the attached files.