๐extract.py
Stream rows from orders.csv
๐งนtransform.py
Validate, clean, de-duplicate โ CleanOrder | rejected
๐ฆQuality gate
Too many rejects? stop with exit code 1
๐load.py
Upsert into PostgreSQL, one transaction
Project structure
shopkart/
โโโ .env.example โ which settings exist (no real secrets)
โโโ requirements.txt โ pinned dependencies
โโโ data/orders.csv โ input (in production: a landing folder or bucket)
โโโ shopkart_etl/
โ โโโ __init__.py
โ โโโ config.py โ settings from environment variables
โ โโโ extract.py โ read the source
โ โโโ transform.py โ business rules (pure functions)
โ โโโ load.py โ write to the database
โ โโโ pipeline.py โ CLI entry point: wires it all together
โโโ tests/
โโโ test_transform.py โ pytestpsycopg[binary]==3.3.9
pytest==9.2.0# Copy to .env and fill in. Never commit the real .env.
DATABASE_URL=postgresql://user:password@localhost:5432/shopkartconfig.py: settings from the environment
import os
from dataclasses import dataclass
@dataclass(frozen=True)
class Config:
database_url: str
max_bad_ratio: float = 0.3
def load_config() -> Config:
"""Read settings from environment variables (12-factor style)."""
url = os.environ.get("DATABASE_URL")
if not url:
raise RuntimeError("DATABASE_URL is not set")
return Config(database_url=url, max_bad_ratio=float(os.environ.get("MAX_BAD_RATIO", "0.3")))The same code runs on your laptop, in CI and in production; only environment variables change. Missing config fails immediately with a clear message.
extract.py: stream the source
import csv
from collections.abc import Iterator
from pathlib import Path
def read_orders(path: Path) -> Iterator[dict]:
"""Yield raw order rows from a CSV file, one at a time."""
with path.open(newline="", encoding="utf-8") as f:
yield from csv.DictReader(f)transform.py: the business rules
from dataclasses import dataclass
from datetime import date
VALID_STATUSES = {"PLACED", "DELIVERED", "CANCELLED", "RETURNED"}
@dataclass(frozen=True)
class CleanOrder:
order_id: int
customer_id: int
product: str
quantity: int
price: int
status: str
order_date: date
@property
def amount(self) -> int:
return self.quantity * self.price
def clean_row(row: dict) -> CleanOrder:
"""Turn one raw CSV row into a CleanOrder, or raise ValueError saying why not."""
if not row["customer_id"].strip():
raise ValueError("missing customer_id")
if not row["quantity"].strip().isdigit() or int(row["quantity"]) <= 0:
raise ValueError(f"bad quantity {row['quantity']!r}")
status = row["status"].strip().upper()
if status not in VALID_STATUSES:
raise ValueError(f"unknown status {row['status']!r}")
return CleanOrder(
order_id=int(row["order_id"]),
customer_id=int(row["customer_id"]),
product=row["product"].strip(),
quantity=int(row["quantity"]),
price=int(row["price"]),
status=status,
order_date=date.fromisoformat(row["order_date"]),
)
def transform(rows) -> tuple[list[CleanOrder], list[dict]]:
"""Split rows into clean orders (one per order_id, last wins) and rejected rows with a reason."""
clean: dict[int, CleanOrder] = {}
rejected: list[dict] = []
for row in rows:
try:
order = clean_row(row)
except ValueError as e:
rejected.append({**row, "reason": str(e)})
continue
clean[order.order_id] = order # duplicates collapse to one
return list(clean.values()), rejectedclean_rowis a pure function: same input, same output, no files or database. Easy to test.- Problems raise
ValueErrorwith a reason;transformturns them into rejected rows instead of crashing. - Keying the dict by order_id collapses duplicates (last one wins).
load.py: idempotent, transactional load
import psycopg
DDL = """
CREATE TABLE IF NOT EXISTS orders (
order_id INT PRIMARY KEY,
customer_id INT NOT NULL,
product TEXT NOT NULL,
quantity INT NOT NULL CHECK (quantity > 0),
price INT NOT NULL,
status TEXT NOT NULL,
order_date DATE NOT NULL,
amount INT NOT NULL,
loaded_at TIMESTAMP NOT NULL DEFAULT now()
)
"""
UPSERT = """
INSERT INTO orders (order_id, customer_id, product, quantity, price, status, order_date, amount)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
ON CONFLICT (order_id) DO UPDATE SET
status = EXCLUDED.status, quantity = EXCLUDED.quantity, amount = EXCLUDED.amount, loaded_at = now()
"""
def load(orders, database_url: str) -> int:
"""Idempotent load: upsert every order in ONE transaction. Returns rows in the table."""
with psycopg.connect(database_url) as conn: # commits on success, rolls back on error
conn.execute(DDL)
with conn.cursor() as cur:
cur.executemany(UPSERT, [
(o.order_id, o.customer_id, o.product, o.quantity, o.price, o.status, o.order_date, o.amount)
for o in orders
])
return conn.execute("SELECT COUNT(*) FROM orders").fetchone()[0]pipeline.py: the command-line entry point
import argparse
import csv
import logging
import sys
from pathlib import Path
from .config import load_config
from .extract import read_orders
from .load import load
from .transform import transform
log = logging.getLogger("shopkart_etl")
def main(argv=None) -> int:
parser = argparse.ArgumentParser(description="Load a ShopKart orders CSV into PostgreSQL")
parser.add_argument("csv_path", type=Path)
parser.add_argument("--rejected", type=Path, default=Path("rejected.csv"))
args = parser.parse_args(argv)
logging.basicConfig(level=logging.INFO, format="%(levelname)-7s %(name)s: %(message)s", stream=sys.stdout)
config = load_config()
orders, rejected = transform(read_orders(args.csv_path))
log.info("read %s: %d clean, %d rejected", args.csv_path, len(orders), len(rejected))
if rejected:
with args.rejected.open("w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=list(rejected[0].keys()))
writer.writeheader()
writer.writerows(rejected)
log.warning("wrote %d rejected rows to %s", len(rejected), args.rejected)
bad_ratio = len(rejected) / max(1, len(orders) + len(rejected))
if bad_ratio > config.max_bad_ratio:
log.error("%.0f%% rejected is above the %.0f%% limit: not loading", bad_ratio * 100, config.max_bad_ratio * 100)
return 1
total = load(orders, config.database_url)
log.info("loaded %d orders; table now has %d rows", len(orders), total)
return 0
if __name__ == "__main__":
sys.exit(main())Tests first
import pytest
from shopkart_etl.transform import clean_row, transform
GOOD = {"order_id": "101", "customer_id": "1", "product": " Headphones ", "quantity": "2",
"price": "1999", "status": "delivered", "order_date": "2026-04-01"}
def test_clean_row_normalises_values():
order = clean_row(GOOD)
assert order.product == "Headphones"
assert order.status == "DELIVERED"
assert order.amount == 3998
@pytest.mark.parametrize("field, value, reason", [
("customer_id", "", "missing customer_id"),
("quantity", "two", "bad quantity"),
("quantity", "0", "bad quantity"),
("status", "LOST", "unknown status"),
])
def test_clean_row_rejects_bad_rows(field, value, reason):
with pytest.raises(ValueError, match=reason):
clean_row({**GOOD, field: value})
def test_transform_removes_duplicates_and_keeps_rejects():
rows = [GOOD, GOOD, {**GOOD, "order_id": "102", "quantity": "x"}]
clean, rejected = transform(rows)
assert [o.order_id for o in clean] == [101]
assert len(rejected) == 1 and rejected[0]["reason"].startswith("bad quantity")$ python -m pytest -q ...... [100%] 6 passed in 0.02s
parametrize runs one test for each kind of bad row: 6 tests from 3 functions, all passing.
Run it
$ python -m shopkart_etl.pipeline data/orders.csv INFO shopkart_etl: read data/orders.csv: 7 clean, 2 rejected WARNING shopkart_etl: wrote 2 rejected rows to rejected.csv INFO shopkart_etl: loaded 7 orders; table now has 7 rows
Now run it again, as a scheduler retry would:
$ python -m shopkart_etl.pipeline data/orders.csv INFO shopkart_etl: read data/orders.csv: 7 clean, 2 rejected WARNING shopkart_etl: wrote 2 rejected rows to rejected.csv INFO shopkart_etl: loaded 7 orders; table now has 7 rows
Still 7 rows: the upsert updated existing orders instead of duplicating them. That's idempotency, proven.
$ cat rejected.csv order_id,customer_id,product,quantity,price,status,order_date,reason 108,,Smartwatch,1,4999,DELIVERED,2026-04-15,missing customer_id 109,1,Headphones,two,1999,DELIVERED,2026-05-02,bad quantity 'two'
$ python -m shopkart_etl.pipeline --help usage: pipeline.py [-h] [--rejected REJECTED] csv_path Load a ShopKart orders CSV into PostgreSQL positional arguments: csv_path options: -h, --help show this help message and exit --rejected REJECTED
From here to production
| Need | Add |
|---|---|
| Run every morning | cron, Airflow, or a Databricks/cloud scheduled job running the same command |
| Secrets | A secrets manager injecting DATABASE_URL |
| Same environment everywhere | A Docker image with requirements.txt installed |
| Catch mistakes before merge | CI running pytest (and a linter like ruff) on every pull request |
| Know when it breaks | Alerts on non-zero exit codes; logs shipped to monitoring |
| Bigger data | Load via COPY into staging + SQL MERGE; or move the transform to Spark |
๐ฏ Interview questions on this topic
Try to answer out loud first, then tap to check.
Q1Walk me through a Python ETL pipeline you built.1โ3 yrs+
Q2How do you test a data pipeline?1โ3 yrs+
Q3How do you make a pipeline restartable after failure?1โ3 yrs+
Q4How would you handle schema changes in the source CSV?3+ yrs+
Q5How do you manage configuration across dev and prod?3+ yrs+
Key takeaways
- โA clean structure makes pipelines testable and maintainable.
- โPure transforms + tests catch rule bugs before production.
- โTransactional upserts make reruns safe.
- โLast lesson: Python interview questions and coding problems.
Frequently asked questions
What is ETL?
Extract data from sources, Transform it (clean, validate, reshape), Load it into a target like a database or lakehouse. In ELT, raw data is loaded first and transformed inside the target.
Why split a pipeline into extract, transform and load modules?
Each part can be tested and changed alone. The transform, which holds most business rules, becomes pure functions you can unit-test without files, networks or databases.
What makes a pipeline idempotent?
Running it twice gives the same result as once. Here, the load upserts by order_id in one transaction, so a rerun updates the same rows instead of duplicating them.
How do I schedule this pipeline?
Anything that runs a command on a schedule: cron on a server, Airflow, a Databricks job, AWS/Azure schedulers. Because it's a CLI with exit codes and logs, any scheduler can run and monitor it.
What should I test in a data pipeline?
Unit tests for transformation rules (good rows, every kind of bad row, duplicates), plus integration tests that run the whole pipeline against a test database, and data quality checks on the output.
๐ง Quick check: building an ETL pipeline
1. Where should most business rules live?
2. The pipeline ran twice and the table still has 7 rows. That proves it is...
3. Where does DATABASE_URL come from?
4. Why return exit code 1 when too many rows are rejected?
Checking your accessโฆ