Throughout the course you have been accumulating scripts in ~/novamarket/: build_lake.py, rebuild_amounts.py, star_schema.py… Each one works, but you have launched them yourself, by hand, once, and in the right order because you were following the lessons. At NovaMarket that will not do: every night 40 million new events and 50,000 orders arrive, and at eight in the morning Marc expects his figures to be up to date. Nobody is going to get up at three o'clock to run scripts.
A data pipeline is what turns loose scripts into a reliable process: a chain of steps that runs on its own, in order, knows how to recover from a failure and can be repeated without breaking anything. In this lesson you will learn how data enters a platform, the difference between ETL and ELT, why idempotency is the most important property of a data process and how an orchestrator such as Apache Airflow coordinates it all. You will also fulfil the last outstanding promise from Module 2: daily loads with partition overwriting. This lesson closes the processing module.
What a data pipeline is
A data pipeline is a set of automated steps that moves data from a source to a destination and transforms it along the way. It runs through the layers from lesson 01-04: it takes the data from the sources (ingestion), puts it into storage and processes it until it is ready for consumption.
flowchart LR
subgraph Sources
BD[(Shop database)]
K[Kafka:<br/>web_events]
end
BD -->|batch ingestion| B[Bronze]
K -->|stream ingestion| B
B -->|clean, type,<br/>deduplicate| P[Silver]
P -->|join, aggregate| O[Gold]
O --> BI[Dashboards]
P --> ML[Models]
ORQ[Orchestrator:<br/>schedules, orders, retries, alerts] -.-> B
ORQ -.-> P
ORQ -.-> O
What sets a pipeline apart from a script is not the code, but the properties demanded of it:
| Property | Meaning |
|---|---|
| Automated | It runs without human intervention, on a schedule or triggered by an event |
| Idempotent | Running it twice leaves the same result as running it once |
| Backfillable | It can be run again for any past date |
| Observable | You know whether it has finished, how long it took and how much data it moved |
| Fault-tolerant | It retries what is transient and raises the alarm about what it cannot resolve |
Ingestion patterns
Ingestion is the entry of data into the platform. There are four basic ways of doing it.
| Pattern | What it consists of | Advantages | Drawbacks | At NovaMarket |
|---|---|---|---|---|
| Full load | The whole source table is copied each time | Trivial; always consistent with the source | Unworkable with large tables; puts load on the source system | products (tens of thousands of rows) |
| Incremental load | Only the rows that are new or modified since the last load are copied | Fast and lightweight | Requires a reliable column to know what has changed; does not detect deletions | orders |
| CDC (Change Data Capture) | The changes are read from the database's transaction log | Captures inserts, updates and deletes, almost instantly and without querying the tables | More complex to set up and operate | orders, if it were needed to the minute |
| Stream ingestion | Events are published and consumed continuously | Latency of seconds | Permanent infrastructure (lesson 03-05) | web_events, via Kafka |
Incremental load and the high-water mark
An incremental load needs to remember how far it got last time. That value is called the load's high-water mark: normally, the maximum of a date column or of an increasing identifier. Do not confuse it with the watermark from lesson 03-05: they share a metaphor, a level that only rises, but that one measured the delay tolerated in a stream and this one marks the last piece of data already loaded.
# Illustrative: incremental load of orders from the shop's database
last_load = (
spark.read.parquet(silver_orders_path)
.agg(F.max("order_date")).first()[0]
)
new_orders = source_orders.where(F.col("order_date") > last_load)This scheme has a catch: it only sees new orders. If yesterday's order changes today from pending to shipped, its order_date does not change and the load never finds out. To capture modifications, the source table needs a last-modified date column that the application maintains rigorously, and the destination must be able to update rows, for example with the MERGE from lesson 02-05. Deletions still go undetected.
CDC
CDC gets round those limitations by reading the internal log in which the database records every change before applying it. From it you obtain a stream of occurrences of the kind "this row was inserted", "this row went from this value to that one", "this row was deleted", which is usually published to Kafka. The best-known open-source tool is Debezium; cloud services offer managed equivalents. It is the natural bridge between operational databases and a streaming platform.
ETL versus ELT
The acronyms describe the order of three operations: Extracting the data from the source, Transforming it and Loading it into the destination.
| ETL | ELT | |
|---|---|---|
| Order | Extract → Transform → Load | Extract → Load → Transform |
| Where the transformation happens | In an intermediate engine, before reaching the destination | Inside the destination, with its own computing power |
| What reaches the destination | Only the data already transformed | The raw data; afterwards, the transformed data |
| Is the raw data kept? | Not necessarily | Yes |
| Changing a transformation rule | Forces you to extract from the source again | It is enough to re-transform what has already been loaded |
| Usual language | Graphical tools or code | SQL |
| Era and context | Classic data warehouses, with expensive storage and compute | Cloud, lakehouse: cheap storage and elastic compute |
Classic ETL made sense when the data warehouse was expensive and small: only the essentials went in, already cleaned. With cheap storage and scalable engines, ELT dominates today: everything is loaded raw and transformed afterwards.
What you have been building since lesson 02-04 is ELT: the files arrive untouched in bronze (E and L) and Spark transforms them inside the lake itself, from bronze to silver and from silver to gold (T). You already know the advantage: if a rule changes, everything is regenerated from bronze without disturbing the source system.
In practice, the boundaries blur and many teams say "the ETL" to refer to any pipeline.
dbt, the T in ELT
When the transformations are done in SQL inside the warehouse or the lakehouse, the most widespread tool for organising them is dbt (data build tool). Each table is defined as a SELECT query in a file; dbt works out from the references between queries the order in which it must run them, and adds quality tests, documentation and version control. It neither extracts nor loads data, and does not process it itself: it sends the SQL to the engine. You will come across it mainly in analytics teams.
Idempotency and backfills
Pipelines fail: a network outage, a file that arrives late, a cluster without resources. The normal response to a failure is to run it again. Hence the most important property of a data process:
A process is idempotent if running it several times with the same input data leaves exactly the same result as running it just once.
If yesterday's load is not idempotent and has to be relaunched, yesterday's data ends up duplicated, and that day's sales come out doubled. Worse still if it failed halfway: part of the data will be there twice and the rest once.
| Way of writing | Idempotent? | Why |
|---|---|---|
mode("append") |
No | Each run adds the rows again |
mode("overwrite") of the whole table |
Yes | But it forces you to recompute the entire history every day |
| Overwriting only the affected partition | Yes | It replaces the day processed and leaves the others alone |
MERGE by key (table formats) |
Yes | It updates what exists and inserts what is new; it never duplicates |
For idempotency to be possible, the process must be parameterised by the date it processes, and never depend on "today" or "yesterday" worked out from the clock. A script that processes "yesterday's data" cannot be used on Thursday to repair Monday. One that receives 2026-06-15 as an argument always does the same thing, whenever it runs.
That same parameterisation makes backfills possible: running the pipeline for a range of past dates, whether to fill in history in a new table or to correct data after fixing an error in the logic.
Partition overwriting
Lesson 02-04 warned that mode("overwrite") on a partitioned table replaces the whole table. The behaviour is governed by a parameter:
spark.sql.sources.partitionOverwriteMode |
What mode("overwrite") does with partitionBy |
|---|---|
static (default) |
Deletes all the table's partitions and writes the new ones |
dynamic |
Replaces only the partitions present in the data being written; the rest are left intact |
The difference, measured on a copy of silver/web_events (31 partitions, 200,000 rows) when writing only the 6,642 events of 15 June:
| Write mode | Partitions after writing | Rows in the table |
|---|---|---|
overwrite with static |
1 | 6,642: the other 30 days have been lost |
overwrite with dynamic |
31 | 200,000: day 15 replaced; the rest intact |
append |
31 | 206,642: day 15 duplicated |
Dynamic mode is the basis of daily loads on Parquet. With a table format such as Delta or Iceberg, the equivalent is a MERGE or an overwrite with a condition on the partition, with the added advantage of being transactional: whoever is reading never sees a half-replaced partition.
Hands-on: NovaMarket's daily load
You are going to write the daily events pipeline: for one day, it moves the events from bronze to silver and computes in gold that day's conversion funnel (lesson 03-03). Create ~/novamarket/daily_load.py:
"""Daily load of web events: bronze -> silver -> gold.
Usage: python daily_load.py DATE [END_DATE] (dates in YYYY-MM-DD format)
"""
import sys
from datetime import date, timedelta
from pathlib import Path
from pyspark.sql import SparkSession
from pyspark.sql import functions as F
LAKE = Path.home() / "novamarket" / "lake"
BRONZE_EVENTS = str(LAKE / "bronze" / "web_events" / "web_events.json")
SILVER_EVENTS = str(LAKE / "silver" / "web_events")
GOLD_FUNNEL = str(LAKE / "gold" / "daily_funnel")
SCHEMA = ("event_id STRING, customer_id BIGINT, session_id STRING, event_type STRING, "
"product_id BIGINT, event_time TIMESTAMP, device STRING")
SILVER_COLUMNS = ["customer_id", "device", "event_id", "event_time",
"event_type", "product_id", "session_id", "date"]
def has(event_type):
"""1 if the session contains some event of that type; 0 otherwise."""
return F.max((F.col("event_type") == event_type).cast("int"))
def process_day(spark, day):
"""Processes the events of one day. Repeating it leaves the same result."""
# --- 1. Bronze -> silver: only the day's events, cleaned --------------
day_events = (
spark.read.schema(SCHEMA).json(BRONZE_EVENTS)
.where(F.to_date("event_time") == F.lit(day))
.dropDuplicates(["event_id"])
.withColumn("date", F.to_date("event_time"))
.select(SILVER_COLUMNS)
)
num_events = day_events.count()
if num_events == 0:
raise ValueError(f"There are no events in bronze for {day}")
(
day_events.coalesce(1)
.write.mode("overwrite") # in dynamic mode: only date=day
.partitionBy("date")
.parquet(SILVER_EVENTS)
)
# --- 2. Silver -> gold: the day's conversion funnel -------------------
by_session = (
spark.read.parquet(SILVER_EVENTS)
.where(F.col("date") == F.lit(day))
.groupBy("session_id")
.agg(has("product_view").alias("viewed"),
has("add_to_cart").alias("added"),
has("purchase").alias("bought"))
)
funnel = by_session.agg(
F.count("*").alias("sessions"),
F.sum("viewed").alias("with_view"),
F.sum(F.col("viewed") * F.col("added")).alias("with_cart"),
F.sum(F.col("viewed") * F.col("added") * F.col("bought")).alias("with_purchase"),
).withColumn("date", F.lit(day).cast("date"))
(
funnel.coalesce(1)
.write.mode("overwrite")
.partitionBy("date")
.parquet(GOLD_FUNNEL)
)
print(f"{day}: {num_events} events loaded into silver; funnel updated in gold")
if __name__ == "__main__":
if len(sys.argv) not in (2, 3):
sys.exit(__doc__)
start = date.fromisoformat(sys.argv[1])
end = date.fromisoformat(sys.argv[2]) if len(sys.argv) == 3 else start
spark = (
SparkSession.builder
.master("local[*]")
.appName(f"daily_load_{start}")
.config("spark.sql.sources.partitionOverwriteMode", "dynamic")
.getOrCreate()
)
spark.sparkContext.setLogLevel("ERROR")
day = start
while day <= end:
process_day(spark, day.isoformat())
day += timedelta(days=1)
spark.stop()What makes this script a pipeline
- It is parameterised by date. The day comes in as an argument.
date.fromisoformatvalidates it: a badly written date stops the script before it touches anything. - It reads with an explicit schema (lesson 03-02): an unexpected change at the source does not alter the silver types.
- Step 1 selects the day's events, deduplicates them and gives them exactly the columns and order that
silver/web_eventsalready has. On the real platform, bronze would be organised by arrival date and only the day's folder would be read; here, bronze is a single file and it is filtered. - It fails loudly. If there are no events for that day, it raises an error instead of writing an empty partition. A pipeline that "finishes successfully" without data is more dangerous than one that fails: nobody finds out until someone looks at a report.
- It writes with dynamic overwriting. The
partitionOverwriteMode=dynamicsetting makesmode("overwrite")replace onlydate=<day>. That single line is what makes the script idempotent. - Step 2 reads from silver, not from the variable in step 1. That way gold is computed on what was actually written, and the steps could be separated into different tasks.
- It creates
gold/daily_funnel, a new table partitioned bydate: one row per day, with the number of sessions and how many reached each step. - It accepts a range of dates, for backfills.
Running it and checking idempotency
cd ~/novamarket
source .venv/bin/activate
python daily_load.py 2026-06-15
python daily_load.py 2026-06-15Both runs print the same thing and, what matters, leave the same thing behind: silver/web_events still has 31 partitions and 200,000 rows, with 6,642 on 15 June (the figure you obtained in lesson 02-04). You can check it with query_lake.py. If you changed overwrite to append, the second run would leave 13,284 events on that day.
A full backfill
To fill in the funnel for the whole period, all you need is to give the range. It is a backfill:
It takes about half a minute and leaves 31 rows in gold/daily_funnel:
+--------+---------+---------+-------------+----------+ |sessions|with_view|with_cart|with_purchase| date| +--------+---------+---------+-------------+----------+ | 1051| 1028| 501| 139|2026-06-01| | 1040| 1005| 488| 120|2026-06-02| | 1059| 1023| 509| 109|2026-06-03| +--------+---------+---------+-------------+----------+ only showing top 3 rows
A design detail: the daily sessions add up to 30,952, more than the month's 30,759 distinct sessions. The difference of 193 is made up of sessions that cross midnight and count on two days. It is a consequence of processing day by day; what matters is documenting the criterion so that nobody sums the column expecting unique sessions.
Orchestration
You now have an idempotent, parameterised process. What is missing is someone to launch it every night. The first idea is cron, the Linux task scheduler:
# Every day at 03:00, process the previous day
0 3 * * * cd ~/novamarket && .venv/bin/python daily_load.py $(date -d yesterday +\%F)For a single script it may be enough. But NovaMarket's real pipeline has dozens of steps that depend on one another, and that is where cron falls short:
| Need | With cron |
With an orchestrator |
|---|---|---|
| Dependencies: run B only if A finished successfully | Work out timings "with some slack" and hope | Declared; B waits for A |
| Retries after transient failures | By hand | Automatic, with a configurable wait |
| Alerts when something fails | You have to program them | Built in (email, messaging) |
| Backfilling a range of dates | A manual loop | One command |
| Visibility: what ran, how long it took, what failed | Digging through log files | Web interface with history |
| Parallelism between independent tasks | No | Yes |
An orchestrator is the system that schedules, orders, monitors and retries the tasks in pipelines. It is the cross-cutting layer from lesson 01-04. It is important to understand what it does not do: it does not process data. It is the conductor, not a musician; the work is done by Spark, the warehouse or the scripts it launches.
The model almost all of them use is the DAG, the same directed acyclic graph you came across in Spark: the tasks are the nodes and the dependencies, the arrows. Directed, because the dependencies have a direction; acyclic, because there can be no cycles, or no task could ever start.
Apache Airflow
Apache Airflow is the most widespread open-source orchestrator. Pipelines are defined in Python, and it has connectors (providers) for almost any system.
| Concept | What it is |
|---|---|
| DAG | A pipeline: a set of tasks with their dependencies and their schedule |
| Task | A step in the DAG |
| Operator | The type of task: run a command, launch a Spark job, run SQL… |
| Scheduler | The service that decides which tasks are due to run |
| DAG run | Each time the DAG runs, associated with a date |
| Logical date | The date the run represents; it is passed to the tasks as a parameter |
The DAG for NovaMarket's daily pipeline
The nightly pipeline brings together the course scripts: the event load from this lesson, the amount rebuild from 03-03, the star schema from 02-05 and a final validation you will see in the last section.
flowchart LR
A[check_source] --> B[load_events]
A --> C[rebuild_amounts]
C --> D[star_schema]
B --> E[validate_load]
D --> E
The file would be saved as novamarket_daily.py in Airflow's DAG folder. It is illustrative code, written for Airflow 3; the imports and some parameters change between versions.
from datetime import datetime, timedelta
from airflow.sdk import DAG
from airflow.providers.standard.operators.bash import BashOperator
PROJECT = "cd ~/novamarket && .venv/bin/python"
# Day being processed: the one before the run date
DAY = "{{ macros.ds_add(ds, -1) }}"
with DAG(
dag_id="novamarket_daily",
description="Daily load: events, orders and star schema",
schedule="0 3 * * *", # every day at 03:00
start_date=datetime(2026, 6, 2),
catchup=False, # do not run pending past dates
max_active_runs=1, # never two runs at once
default_args={
"retries": 2, # retry twice...
"retry_delay": timedelta(minutes=10), # ...waiting 10 minutes
},
tags=["novamarket"],
) as dag:
check_source = BashOperator(
task_id="check_source",
bash_command="test -s ~/novamarket/lake/bronze/web_events/web_events.json",
)
load_events = BashOperator(
task_id="load_events",
bash_command=f"{PROJECT} daily_load.py {DAY}",
)
rebuild_amounts = BashOperator(
task_id="rebuild_amounts",
bash_command=f"{PROJECT} rebuild_amounts.py",
)
star_schema = BashOperator(
task_id="star_schema",
bash_command=f"{PROJECT} star_schema.py",
)
validate_load = BashOperator(
task_id="validate_load",
bash_command=f"{PROJECT} validate_load.py {DAY}",
)
# Dependencies
check_source >> [load_events, rebuild_amounts]
rebuild_amounts >> star_schema
[load_events, star_schema] >> validate_load- The
with DAG(...)block defines the pipeline: its identifier, its schedule incronsyntax, when it starts from and the default behaviour of its tasks in the event of a failure. BashOperatorruns a shell command. The task is considered successful if the command ends with exit code 0, and failed otherwise. That is why it mattered thatdaily_load.pyraised an error when there was no data: it is the way to communicate the problem to the orchestrator.check_sourceusestest -s, which fails if the file does not exist or is empty. If the source data has not arrived, there is no point launching the rest.- The expressions in double curly braces are templates that Airflow fills in on each run.
dsis the logical date inYYYY-MM-DDformat andmacros.ds_add(ds, -1)the day before. It is the piece that connects the orchestrator with the parameterisation by date: Airflow decides the date, and the script always does the same thing for it. - The
>>operator declares the dependencies:a >> bmeans "b after a". A list indicates tasks that can run in parallel.validate_loadwaits for its two predecessors to finish successfully. catchup=Falseprevents Airflow, when the DAG is activated, from launching in one go a run for every day elapsed sincestart_date.
To backfill the first week of June, the code is not touched. You ask the orchestrator, which launches one run per date (the exact syntax depends on the version):
And since the tasks are idempotent, backfilling does not duplicate anything.
Which date is
ds? The exact meaning of the logical date has changed between versions of Airflow: depending on the version and the configuration, in a daily DAG it may be the very day on which it runs or the start of the interval being processed, that is, the previous day. Before relying on it, check in your installation which date the task receives. It is a classic source of "off by one day" errors.
Trying it out (optional)
Airflow is an application with several services and many dependencies. If you want to try the DAG, install it in a separate virtual environment, following the method in the official documentation (which pins the dependency versions with a constraints file). The airflow standalone command starts a local test instance with its web interface, and airflow dags test novamarket_daily 2026-06-16 runs the DAG once for that date without needing the scheduler. It is not necessary to follow the course.
In production, BashOperator is usually replaced by specific operators, such as the one that submits a job with spark-submit to a cluster, or a managed Airflow service in the cloud is used (lesson 06-04).
Alternatives
| Tool | Approach | When it fits |
|---|---|---|
| cron | Operating system scheduler | One or two independent scripts |
| Apache Airflow | DAG of tasks in Python; the industry standard | Batch pipelines with many dependencies; teams that want a broad ecosystem |
| Dagster | Focused on the data produced (assets), not just on the tasks; testing and lineage built in | New projects that prioritise quality and traceability |
| Prefect | Flows as ordinary Python functions, with little ceremony | Small teams; dynamic flows |
| Cloud services | Each provider's managed orchestrators | When the whole platform lives in one cloud |
Monitoring and common failures
The orchestrator marking every task green means that the processes finished, not that the data is correct. A pipeline needs monitoring on three levels:
| Level | Question | Example signal |
|---|---|---|
| Execution | Has it finished? On time? | Failed task; twice the usual duration |
| Volume | Has it moved a reasonable amount of data? | 40 million events a day, and today 3 million |
| Content | Does the data make sense? | Duplicate keys, nulls where there should be none |
The last task in the DAG takes care of the essentials. Create validate_load.py:
"""Checks that the load for a day has left consistent data.
Usage: python validate_load.py DATE
Exits with code 0 if everything is correct and with code 1 otherwise.
"""
import sys
from pathlib import Path
from pyspark.sql import SparkSession
from pyspark.sql import functions as F
LAKE = Path.home() / "novamarket" / "lake"
day = sys.argv[1]
spark = SparkSession.builder.master("local[*]").appName("validate_load").getOrCreate()
spark.sparkContext.setLogLevel("ERROR")
events = spark.read.parquet(str(LAKE / "silver" / "web_events")).where(F.col("date") == day)
funnel = spark.read.parquet(str(LAKE / "gold" / "daily_funnel")).where(F.col("date") == day)
errors = []
num_events = events.count()
if num_events == 0:
errors.append("silver has no events for that day")
if num_events != events.select("event_id").distinct().count():
errors.append("there are duplicate event_id values in silver")
rows = funnel.collect() # a single row: collect is safe
if len(rows) != 1:
errors.append(f"expected 1 funnel row and found {len(rows)}")
else:
f = rows[0]
if not (f["sessions"] >= f["with_view"] >= f["with_cart"] >= f["with_purchase"] >= 0):
errors.append("the funnel steps are not decreasing")
spark.stop()
if errors:
print(f"VALIDATION FAILED for {day}:", "; ".join(errors))
sys.exit(1)
print(f"Validation passed for {day}: {num_events} events")If it is launched for a date that has not been loaded, it ends with sys.exit(1): the orchestrator marks the task as failed and raises the alarm. These checks are the minimum; systematic quality rules, their tools and data governance are developed in lesson 05-02.
The failures you will come across again and again:
| Failure | Symptom | Prevention |
|---|---|---|
| The source data arrives late | The load processes an incomplete or empty day | A task that checks the source before starting; fail if there is no data |
| Schema change at the source | Null columns or a read error | Explicit schema; FAILFAST mode for what is critical |
| A rerun that duplicates | Inflated figures after a retry | Idempotency: partition overwriting or MERGE |
| Failure halfway through a write | Incomplete partition | Transactional table formats; validate after writing |
| Implicit dependency | A task reads a table that another has not yet updated | Declare every dependency in the DAG |
| Growth in volume | The process takes longer every day, until it overlaps with the next one | Monitor the duration; optimise (lesson 03-04) |
| Silent logic error | All green, wrong figures | Content validations; compare with the previous day |
Common Mistakes and Tips
- Using
appendin periodic loads. Sooner or later there will be a retry and, with it, duplicates. - Using
overwriteon a partitioned table without dynamic mode. It deletes the entire history to write one day. Always check it first on a copy. - Working out the date from the clock inside the script. It makes backfilling impossible. The date must be a parameter.
- Putting the transformation logic in the DAG. The orchestrator should launch and monitor; the computation lives in scripts that can be tested separately.
- Accepting a run as good because it has not failed. Validate volumes and content.
- Swallowing errors. A
try/exceptthat logs the problem and carries on turns a visible failure into invisible incorrect data. Let the process fail. - Overusing retries. They are for transient failures (network, resources). A logic error will fail all three times just the same and will only delay the alert.
- Building your own orchestrator out of scripts and
cron. It starts out simple and ends up reinventing, badly, what already exists. - Tip: before considering a pipeline finished, put it through three tests: run it twice in a row for the same date, run it for an old date and run it with no input data. If it behaves as you expect in all three cases, it is ready.
Exercises
Exercise 1: choosing the ingestion pattern
State the appropriate pattern for each NovaMarket source and justify it:
- The
productstable: 30,000 rows, with frequent price changes. - The
orderstable: 50,000 new ones a day, and existing ones change status over two weeks. - The warehouse inventory, which the operations dashboard must reflect with less than a minute's delay.
- A CSV file of price lists that a supplier sends once a month.
Exercise 2: is it idempotent?
Reason out whether each process is idempotent and, if it is not, how you would correct it:
- It reads the orders for the day received as a parameter and writes them with
mode("append")tosilver/orders. - It recomputes the whole of
gold/daily_salesfromsilver/orders_completeand writes it withmode("overwrite"). - It processes "the events of the last 24 hours", counted from the moment it starts.
- It sends an email with the sales summary for the day received as a parameter.
Exercise 3: one more gold table
Extend daily_load.py with a third step that maintains gold/events_by_type: for each day, the number of events of each event_type, in a table partitioned by date. Run it for 15 June and check the result and the idempotency.
Solutions
Exercise 1
- Full load. The table is small: copying it in full every night is the simplest option and captures all the changes, deletions included.
- Incremental with a last-modified column (and
MERGEat the destination), or CDC. An incremental load byorder_datewould miss the status changes. A simple, robust variant: reload the window of the last 15 days every night with partition overwriting. - CDC on the warehouse database, published to Kafka and consumed as a stream. With a one-minute margin, batches are not enough.
- Batch full load, triggered by the arrival of the file. There is nothing to make incremental.
Exercise 2
- No. Each run adds the orders again. Correction: partition by date and overwrite the partition in dynamic mode, or
MERGEbyorder_id. - Yes. The result depends only on the input, and the full overwrite replaces what was there before. It is inefficient with a lot of history, but correct; for small tables it is the simplest option.
- No. The result depends on the time of the run: relaunching it two hours later processes a different interval, with overlaps and gaps. Correction: receive the start and end of the interval as parameters.
- No, and it cannot be entirely: a sent email cannot be "unsent". External effects are isolated in a final task of their own, without automatic retries, or the sends already made are recorded so as not to repeat them.
Exercise 3
A constant is added and, at the end of process_day, before the print:
# --- 3. Silver -> gold: the day's events by type ----------------------
by_type = (
spark.read.parquet(SILVER_EVENTS)
.where(F.col("date") == F.lit(day))
.groupBy("date", "event_type")
.agg(F.count("*").alias("events"))
)
(
by_type.coalesce(1)
.write.mode("overwrite")
.partitionBy("date")
.parquet(GOLD_BY_TYPE)
)After python daily_load.py 2026-06-15, the table contains, for that day:
+------------+------+----------+ | event_type|events| date| +------------+------+----------+ |product_view| 4605|2026-06-15| | search| 1008|2026-06-15| | add_to_cart| 748|2026-06-15| | purchase| 281|2026-06-15| +------------+------+----------+
These are the figures you obtained in lesson 02-04 by querying silver directly. When you run the script a second time, the table still has those 4 rows: dynamic overwriting, inherited from the session configuration, replaces the partition. date appears at the end because it is the partition column.
Common mistake: forgetting the filter on date when reading silver. The script would aggregate all 31 days and, with dynamic mode, rewrite all 31 partitions on every daily run: the result would be correct, but the cost thirty times higher, and it would grow every day.
Conclusion
A data pipeline is an automated chain of steps that takes data from the source to consumption. Data comes in through a full load, an incremental load with a high-water mark, CDC or streaming, depending on its size and the latency required; and it is transformed before loading (ETL) or, as is usual today and as you have done throughout the course, after being loaded raw (ELT). The property that underpins everything else is idempotency: a process parameterised by date that writes with dynamic partition overwriting or with MERGE can be retried and backfilled without duplicating anything, as you have checked with daily_load.py and the new gold/daily_funnel table. An orchestrator such as Apache Airflow organises the tasks into a DAG, schedules them, respects their dependencies, retries them and raises the alarm when they fail. And since "it has finished" does not mean "it is correct", every pipeline ends with validations.
This lesson brings Module 3 to a close. You started with the model that started it all, MapReduce, and with its limits; you opened up the black box of Spark until you understood drivers, executors, DataFrames and lazy evaluation; you learnt to combine and summarise tables with joins, aggregations and windows, and to read an execution plan in order to optimise; you saw how data is processed as it arrives, with Kafka and Structured Streaming; and you have just turned all of that into automatic, reliable processes. NovaMarket's lake is no longer just a store: in ~/novamarket/lake/ you have a clean, complete silver zone, with orders_complete and the events partitioned by day, and a gold zone with the star schema and the daily funnel, which update themselves.
The data is stored, clean and up to date. What is missing is what justifies all the effort: drawing conclusions from it. Marc has been waiting for three modules. In Module 4, Big Data Analysis, you will move from preparing the data to interrogating it: exploring it at scale, training models with it, visualising it and turning it into decisions. The first lesson, Analysis Tools, surveys the range of instruments with which an analyst looks into a lakehouse, from interactive SQL engines to notebooks, and will help you know which one suits each situation.
