Anatomy of a pipeline
Part of the free LogicWiz Data Engineering course, Module 6: Batch pipelines. The SQL and Python run in the app, on real Postgres and real Python in the browser.
It is 9:10 on Monday. Tess has found a bug: the script that cleans the orders dropped every returned order for two weeks, so May's revenue is wrong. "Fix the script and run it again," says Nora. You can fix the script. You cannot run it again: it kept only the cleaned totals, and the store has shipped or cancelled those orders since. The rows as they were on those days are gone.
You'll learn to
- Name the three jobs of every pipeline: extract, load, transform
- Keep what arrived unchanged, with the file it came from
- Publish a table so readers never see it empty
- Say what ETL and ELT mean, and why most teams load first
Learn
One script did three jobs
The old script did three things in one go, and that was the problem.
It read the orders from the store's database. That is extract. It wrote something into a place the data team controls. That is load. And it cleaned and reshaped the rows on the way. That is transform.
Every pipeline does these three jobs. A batch pipeline does them on a schedule, one chunk at a time: last night's orders, the last hour of clicks. Most pipelines in most companies are batch.
The script mixed the three, so a bug in the cleaning also destroyed the only copy. This module keeps them apart, so a pipeline survives real life: files that arrive twice, rows that arrive late, jobs that run again.
The data lifecycle from source to serve, with the ingest stage highlighted: this is where extract and load happen.
Find the highlighted stage, ingest: that is extract and load together. Transform is the next stage, and it starts only when the data is somewhere you control.
Keep a copy of exactly what arrived
Here is the rule that would have saved May. Before you change anything, keep a copy of exactly what you received.
Think of an accountant who keeps every paper receipt in a box. The accounts can always be redone, because the receipts are still there.
That box is the raw layer (Databricks calls it bronze). It is append-only: new data is added, nothing is edited, nothing is deleted. Each row also says where it came from, in columns such as _source_file and _loaded_at.
You will open the box for three reasons:
- Replay: a transform had a bug. Fix the code, rebuild from raw.
- Audit: finance asks "what did the store send us on 3 June?"
- Debug: a number looks wrong, and you trace it back to one file.
Remember: land first, clean second. Storage is cheap. Lost source data cannot be bought back.
Seven days of files, one sent twice
SwiftKart now works that way. Every night the store drops a file of orders into a folder called landing/. A file holds the orders created or changed that day, so an order shows up again each time its status changes.
The folder is not tidy. The 3 June file was sent twice. One order line points at a product that does not exist. One click arrived a day late.
Your first job is not to fix any of that. It is to load every file into one raw table, unchanged.
What is in the landing folder
| File | What it holds | Watch out for |
|---|---|---|
| landing/orders/2025-06-01.csv to 2025-06-07.csv | Orders created or changed that day | An order appears again each time its status changes |
| landing/orders/2025-06-03retry.csv | The 3 June batch, sent a second time | Every row is a copy |
| landing/orderitems/2025-06-02.csv | Order lines for 2 June | One line points at product 999 |
| landing/events/2025-06-01.jsonl to 03 | App clicks, as nested JSON | One event in the 3 June file is from 2 June |
This is what the store sent, mistakes included. Raw keeps all of it as it came: fixing the mistakes is the transform's job.
Extract and load: land every file as it came
import duckdb
# Load every daily file into one raw table, unchanged.
# all_varchar keeps each value as text; filename records where it came from.
duckdb.sql("""
CREATE TABLE raw_orders AS
SELECT *
FROM read_csv_auto('landing/orders/*.csv', filename = true, all_varchar = true)
""")
for name, rows in duckdb.sql("""
SELECT filename, COUNT(*)
FROM raw_orders
GROUP BY 1
ORDER BY 1
""").fetchall():
print(name, rows)
print("total:", duckdb.sql("SELECT COUNT(*) FROM raw_orders").fetchone()[0])
all_varchar = true keeps every value as text, exactly as the file wrote it, so a strange value can never stop the load. filename = true adds a column saying which file each row came from. Real raw tables add the load time too (_loaded_at). The total is 68 rows. Keep that number in mind: the store took only 40 orders.
Cleaning is a separate step
Raw is safe. Now you can clean, and a mistake costs nothing.
The transform reads raw and writes a new table, usually called staging (Databricks says silver). It turns text into numbers and timestamps, drops the retry's copies and keeps each order's latest status. If it has a bug, you fix it and run it again from raw.
Splitting the steps also splits the failures. If the store's export is down, extract fails and you retry it later. If the transform chokes on a bad value, the raw data is already safe, and you fix the code in the morning.
Follow one order, number 1012, through both layers.
Order 1012: three raw rows, one staging row
Order 1012 lands in the raw table three times, as placed, as shipped and as a copy from the retry file, and the transform then builds one typed staging row from them.
2 June. The store's file says order 1012 was placed. One row lands in raw, as text, with the name of its file.
3 June. The order ships, so the next file carries it again. Raw now holds two versions of the same order. Nothing was edited: a row was added.
The retry. The 3 June file is sent a second time. Raw takes it as it came: three rows now, the last one an exact copy.
The transform. Staging turns the text into real types and keeps the row with the latest
updated_at: one row, shipped, a real timestamp. Raw still holds all three.
Press Next step and watch the left box. Raw only ever gains rows. Staging is built from raw, and can be built again.
The trap: cleaning on the way in. A loader that drops "bad" rows, fixes values or keeps only the latest status before saving anything has thrown away what the source sent. When the cleaning rule turns out to be wrong, there is nothing to rebuild from. And never edit the raw layer by hand: if a raw row is wrong, the fix is a rule in the transform, where it is reviewed and runs every time.
Raw to staging in Postgres
-- raw.orders holds all 68 landed rows as text.
-- Staging: cast the types and keep each order's latest version.
CREATE SCHEMA staging;
CREATE TABLE staging.orders AS
SELECT order_id, customer_id, order_ts, status, updated_at
FROM (
SELECT
order_id::INT AS order_id,
customer_id::INT AS customer_id,
order_ts::TIMESTAMP AS order_ts,
status,
updated_at::TIMESTAMP AS updated_at,
ROW_NUMBER() OVER (PARTITION BY order_id ORDER BY updated_at DESC) AS rn
FROM raw.orders
) AS versions
WHERE rn = 1;
SELECT
(SELECT COUNT(*) FROM raw.orders) AS raw_rows,
(SELECT COUNT(*) FROM staging.orders) AS staged_orders;
Raw is untouched: 68 rows, retry included. Staging has 40, one typed row per order. ROW_NUMBER numbers each order's versions from newest to oldest and rn = 1 keeps the newest, as in Module 2.
At 2:00 a.m. the dashboard says $0
Staging is built. The last step is to publish: put the new table where dashboards read it. This is where a second kind of wrong number is born.
Dana mentions that the revenue dashboard shows $0 for a short while every night, then recovers. You look at the job. It runs two statements:
TRUNCATE dw.daily_revenue;empties the table.INSERT ... SELECTfills it again. That takes 40 seconds.
Each statement commits on its own: its result becomes visible to everyone the moment it finishes.
The 40-second hole
A timeline of the nightly job: the truncate commits, the insert runs for 40 seconds, and for those 40 seconds readers see an empty table.
Read the bottom lane: it is what a dashboard sees at each second. The red bar is the hole between the two commits. (The times are made up for the example.)
Remember: a reader should see yesterday's whole table or today's whole table. Never half, never nothing.
Build in private, check, then switch
One fix is to put both statements in one transaction: readers keep seeing the old rows until COMMIT (Lesson 6.7 shows how Postgres does that). But a two-hour rebuild inside one transaction holds its locks, and the old rows it replaced, for two hours.
So teams do it another way. Build tonight's table somewhere nobody reads. Check it. Then switch it in with one short step.
With the checks as a gate, this is called write-audit-publish (WAP):
- Write the result to a private build table.
- Audit it: row counts against the source, unique keys, no NULL amounts (the checks of Module 7).
- Publish only if every check passes.
A failed audit leaves yesterday's table in place: stale, but right. And an alert tells someone why.
Write, audit, publish with a swap
A job builds orders_build while a dashboard keeps reading yesterday's dw.orders, audits the build, then swaps the two tables in one short transaction; the dashboard's next query reads the new table.
Read it top to bottom. The dashboard asks twice: before the swap it gets yesterday's complete rows, after it gets today's. There is no moment in between.
Build, audit and swap in Postgres
-- 1. Write: build tonight's table where nobody reads
CREATE TABLE dw.orders_build AS
SELECT DISTINCT ON (order_id::INT) order_id::INT AS order_id, status, updated_at::TIMESTAMP AS updated_at
FROM raw.orders
ORDER BY order_id::INT, updated_at::TIMESTAMP DESC;
-- 2. Audit: every check must return 0
SELECT
(SELECT COUNT(*) - COUNT(DISTINCT order_id) FROM dw.orders_build) AS duplicate_keys,
(SELECT COUNT(*) FROM dw.orders_build WHERE status IS NULL) AS null_status,
(SELECT COUNT(*) FROM dw.orders) - (SELECT COUNT(*) FROM dw.orders_build
WHERE order_id IN (SELECT order_id FROM dw.orders)) AS orders_lost;
-- 3. Publish: one short transaction (Postgres DDL can roll back)
BEGIN;
SET LOCAL lock_timeout = '5s';
ALTER TABLE dw.orders RENAME TO orders_old;
ALTER TABLE dw.orders_build RENAME TO orders;
COMMIT;
DROP TABLE dw.orders_old;
SELECT COUNT(*) AS published_orders FROM dw.orders;
The audit returns three zeros, so the swap goes ahead: 17 orders yesterday, 40 now. In Postgres a rename is part of the transaction, so a ROLLBACK would undo both renames. Had an audit failed, the job would DROP TABLE dw.orders_build and alert, leaving yesterday's table untouched. The lock_timeout line is the next clue.
The swap waits in a queue
Last night the swap itself hung for 25 minutes, and every dashboard hung with it. Nothing was wrong with the swap.
To rename a table, Postgres needs to be alone with it. The lock it asks for is called ACCESS EXCLUSIVE. It waits for every query already running on the table. And while it waits, every new query queues behind it.
An analyst had started a long query at 01:40. The swap arrived at 02:00 and waited. Every dashboard query after 02:00 waited behind the swap, until the analyst's query ended at 02:25.
The guard is lock_timeout. Its default is 0, which means wait forever. Set it to a few seconds so the swap gives up fast, and let the job try again.
One long query, a 25-minute queue
A timeline: an analyst query runs from 01:40 to 02:25, the swap waits behind it from 02:00, and every dashboard query waits behind the swap until 02:25.
Minutes since 01:40. Read the lanes top to bottom: the swap waits for the analyst, and the dashboards wait for the swap.
Five ways to make the switch
| How | The switch | Where | What it costs |
|---|---|---|---|
| Build a table, then swap | ALTER TABLE ... RENAME twice in one transaction | Postgres (a rename can roll back) | Needs an ACCESS EXCLUSIVE lock for a moment |
| Swap in one statement | ALTER TABLE ordersbuild SWAP WITH orders | Snowflake | The two tables trade names in one transaction |
| Move a view | CREATE OR REPLACE VIEW orders AS SELECT FROM ordersv42 | Any SQL engine | Keeps old versions until you drop them |
| One table-format commit | INSERT OVERWRITE, replaceWhere, MERGE: one new log entry | Delta, Iceberg | Readers keep the version they started with; no lock |
| Branch, then fast-forward | Write to an audit branch, then fastforward main | Iceberg | Needs write.wap.enabled on the table |
Every row does the same thing: readers see yesterday's complete table or today's, never a mix. The last two rows exist because a data lake cannot rename. On a general-purpose S3 bucket, "moving" a folder of 2,000 files is 2,000 copies and 2,000 deletes, and a reader in between sees a mix. So Delta and Iceberg publish by writing one new log file: one object, so the switch is atomic.
ETL or ELT?
One question is left from Monday: should the cleaning happen before the data lands, or after?
Twenty years ago warehouse storage was expensive. Teams cleaned data on a separate server and loaded only the result: transform, then load. That order is ETL.
Cloud warehouses such as Snowflake, BigQuery and Databricks store data cheaply and run SQL on many machines. So it became easier to load raw data first and transform it where it lives. That order is ELT, and you built it today.
Most teams do a bit of both: a light touch on the way in (unzip files, drop a password column that must never be stored), then the real modelling after. When someone asks "ETL or ELT?", answer two things: where the transform runs, and whether you keep the raw data.
ETL and ELT side by side
| ETL: transform, then load | ELT: load, then transform |
|---|---|
| The transform runs in a separate tool before the warehouse | Raw data lands in the warehouse or lake, and SQL transforms it there |
| Only clean data reaches the warehouse | Raw and clean data both live in the warehouse |
| A transform bug means extracting from the source again | A transform bug means rerunning SQL over raw you already have |
| Still used to drop or mask sensitive fields before they land | The usual default today: a loader such as Fivetran or Airbyte, then dbt |
Numbers to remember
| Name | Value | What it is |
|---|---|---|
| Raw lineage columns | sourcefile, loadedat, batchid | Where each raw row came from, when it was loaded, and in which batch |
| locktimeout | default 0: wait forever | How long a statement waits for a lock. SET LOCAL locktimeout = '5s' before the swap, then retry |
| ALTER TABLE ... RENAME | takes ACCESS EXCLUSIVE | Waits for running queries on the table; new queries queue behind it |
| TRUNCATE in Postgres | not MVCC-safe | A transaction that started earlier can see the table as empty once the truncate commits (Lesson 6.7 explains MVCC) |
| write.wap.enabled | true, on the Iceberg table | Lets a job write to a branch that readers do not see |
| spark.wap.branch | audit, in the Spark session | The branch the job's writes land on |
| fastforward | CALL catalog.system.fastforward('db.orders', 'main', 'audit') | After the checks pass, moves main to the audited snapshot |
| Raw on Databricks and Azure | Auto Loader; Data Factory copy activity | Auto Loader appends files from S3 or ADLS to a bronze Delta table with the file name and load time; a copy activity lands files in ADLS before anything transforms them |
You do not need these to follow the story. Come back to them when you build the real thing.
What changed at SwiftKart
The one script is now three steps. Every night's file lands in raw, unchanged, with its file name. Staging is rebuilt from raw. Each new table is built in private, audited, and switched in with one short transaction and a lock_timeout.
May cannot be rebuilt: those rows were never kept. But from 1 June on, a bug is a code fix and a rerun, and the $0 at 2:00 a.m. is gone.
One thing still bothers Nora. Every night the job reads the store's whole orders table to pick up a handful of changes. Lesson 6.2 loads only what changed.
In one line
Land what you receive unchanged, build clean tables from that copy, and switch a checked table in with one short step, so any bug is a code fix and a rerun.
Interview corner
What is the difference between ETL and ELT? Which would you use?
In ETL the transform runs before loading, in a separate tool, and only clean data reaches the warehouse. In ELT raw data is loaded first and transformed inside the warehouse or lakehouse with SQL. For most cloud setups I would use ELT, because storage is cheap, raw data is kept for replay, and transforms are just SQL I can rerun. I would still drop or mask sensitive fields before they land.
Why keep raw data if you already have clean tables?
Because transforms have bugs and requirements change. With raw kept as it came, I fix the code and rebuild any period without going back to the source, which may have changed or deleted the data. Raw is also the evidence for audits and for debugging a number that looks wrong.
How do you publish a rebuilt table so readers never see it empty or half-built?
Build into a private table, audit it, then switch in one short atomic step. In Postgres that is two ALTER TABLE ... RENAMEs in one transaction (DDL rolls back), with lock_timeout set because the rename needs an ACCESS EXCLUSIVE lock and would otherwise queue behind long queries and block every new reader. Snowflake has ALTER TABLE ... SWAP WITH; Delta and Iceberg publish with one commit to the log, so readers keep their snapshot without any lock. What I avoid is TRUNCATE then INSERT as two autocommit statements, which publishes an empty table.
What is write-audit-publish, and what does it cost?
The job writes its output somewhere unpublished (a build table or an Iceberg branch with spark.wap.branch), runs the quality checks against it, and publishes only when they pass, for example with fast_forward on Iceberg or a swap elsewhere. The benefit is that consumers never see data that failed its checks: a failed audit leaves yesterday's table, stale but correct. The costs are double storage during the build, the check time on the critical path, and a stale table that someone must be alerted about.