NovaMarket has data scattered all over the place: orders and customers in the shop's relational database, events streaming in non-stop from the website and the app, carts in Redis, the catalogue in MongoDB. Each system serves its own application well, but none of them can answer the questions that cut across everything: what did customers in Valencia look at before buying? Which products are added to the cart and never bought?
What is needed is a place to bring all the data together, with its full history, and be able to analyse it with any tool. That place is the data lake. In this lesson you will see what it is, how it differs from a data warehouse, how it is organised into zones so that it does not degenerate into a dumping ground and how its directories are structured. At the end you will build a mini NovaMarket data lake on your own machine with the bronze and silver zones, using what you learnt about Parquet in lesson 02-02.
What a data lake is
A data lake is a centralised repository that stores large volumes of data of any type, in its original format, on cheap, scalable storage.
Let's break the definition down:
- Centralised: a single place where data from all the company's systems arrives.
- Of any type: structured (tables), semi-structured (JSON, application logs) and unstructured (images, PDFs, audio).
- In its original format: the data is first stored just as it arrives, without transforming it or deciding in advance what it will be used for.
- Cheap, scalable storage: physically, a data lake is a set of files in HDFS or, nearly always today, in an object store (lesson 02-01).
This last idea is the one that surprises people most at first: a data lake is not a product you install. It is a way of organising files on a storage system, plus some conventions and tools for finding and processing them. Thanks to the separation of compute and storage, those same files can be read by Spark, a SQL engine or a machine learning library.
That is where the lake metaphor comes from: data flows into it from many sources, like rivers, and accumulates in its natural state; everyone then comes along to draw the water they need.
Schema-on-write and schema-on-read
The difference in philosophy between a traditional database and a data lake comes down to when the schema is enforced.
| Schema-on-write | Schema-on-read | |
|---|---|---|
| When the structure is defined | Before storing | When reading the data |
| What happens to data that does not fit | It is rejected | It is stored anyway |
| Cost of bringing in a new source | High: tables and transformations have to be designed | Minimal: the files are copied |
| Quality guaranteed on reading | High | None: it depends on whoever reads |
| Characteristic of | Relational databases, data warehouses | Data lakes |
You have already practised schema-on-read without giving it a name: in lesson 02-02, spark.read.json(...) examined web_events.json and inferred its structure at the moment of reading it. Nobody had declared it beforehand.
The advantage is agility: NovaMarket can start storing the app's events today even though nobody yet knows what analysis will be done with them. Storing is cheap; not having stored a piece of data that later turns out to be valuable cannot be put right.
The drawback is that the complexity does not go away, it is merely postponed: somebody will have to understand, clean and give structure to that data before using it. The zone architecture you are about to see is the answer to that problem.
Data lake versus data warehouse: the essentials
The data warehouse is the classic analytical system: a database optimised for SQL queries over clean, structured data. It is studied in depth in the next lesson; here the essential comparison will do.
| Aspect | Data lake | Data warehouse |
|---|---|---|
| Data | Of any type, raw and refined | Structured, clean and modelled |
| Schema | On read | On write |
| Storage | Files in object storage or HDFS; very cheap | Managed by the engine itself; more expensive |
| Typical users | Data engineers and data scientists | Business analysts |
| Typical uses | Exploration, machine learning, keeping the full history | Reports and dashboards with SQL |
| Data reliability | Depends on the team's discipline | High: it is controlled at load time |
They do not compete: for years the usual arrangement has been to have both, with the data lake as the general repository and the data warehouse as the shop window for the business. Why that causes problems, and how the lakehouse solves them, is the subject of lesson 02-05.
Zone architecture: bronze, silver and gold
If everyone leaves files wherever they please, the lake becomes useless within months. The most widespread way of organising a data lake divides it into zones (or layers) through which the data moves, gaining quality as it goes. It is known as the medallion architecture, after the names of its three layers.
flowchart LR
F1[Shop DB] --> B
F2[Website and app] --> B
subgraph Lake[Data lake]
direction LR
B[Bronze<br/>raw data,<br/>just as it arrives]
P[Silver<br/>clean, typed data,<br/>no duplicates]
O[Gold<br/>aggregated data,<br/>ready for the business]
B --> P --> O
end
P --> ML[Data science<br/>and ML]
O --> BI[Reports and<br/>dashboards]
| Bronze (raw) | Silver (curated) | Gold (consumption) | |
|---|---|---|---|
| Content | A faithful copy of the source | Validated data, with correct types and no duplicates | Tables prepared for a specific use |
| Format | The original (CSV, JSON, Avro…) | Parquet | Parquet |
| Transformations | None | Cleaning, typing, deduplication, unification | Aggregations, joins, business metrics |
| Structure | That of the source | One table per entity (orders, events…) | One table per need (daily sales, funnel…) |
| Who uses it | Data engineering | Engineers, scientists and advanced analysts | Analysts, the business, applications |
| Is it modified? | Never: it is only appended to | It is regenerated from bronze | It is regenerated from silver |
The names vary between companies (raw/curated/consumption, landing/staging/mart…), but the idea is always the same.
Why keep the bronze layer
Storing the raw data as well as the clean data looks wasteful. It is not, for three reasons:
- Reprocessing. If an error is discovered in the cleaning logic, or a business rule changes, silver is regenerated from bronze. Without bronze, the error is permanent.
- Auditing. When the question is "did this data arrive like this or did we break it?", bronze is the evidence.
- Future uses. A field that is discarded in cleaning today may be the key to a model tomorrow.
That is why the golden rule of the bronze layer is immutability: you append, you never modify. Remember that storage is the cheap part of a data platform.
Directory layout and partitioning
A predictable path structure
A data lake is a directory tree, and its first mechanism for keeping order is its paths. A common convention is zone/dataset/:
lake/
├── bronze/
│ ├── orders/
│ └── web_events/
├── silver/
│ ├── orders/
│ └── web_events/
└── gold/
└── daily_sales/Anyone who knows the convention knows where to look and where to write. On large platforms a level is added for the source system or business area (bronze/shop/orders/, bronze/web/web_events/).
Hive-style partitioning
Nearly all queries on events refer to a period: "yesterday's funnel", "the last week". If the 2.79 TB of events a year sat in a single folder, every query would have to open all the files to find those for the dates of interest.
The solution is to partition the table: distribute its files into subdirectories according to the value of a column. The universal convention, inherited from Apache Hive, names each subdirectory column=value:
silver/web_events/ ├── date=2026-06-01/ │ └── part-00000-....snappy.parquet ├── date=2026-06-02/ │ └── part-00000-....snappy.parquet └── ...
This has two effects:
- The partition column is not stored inside the files: its value is in the directory name. When the table is read, the engine rebuilds it as one more column.
- Partition pruning: faced with a query containing
WHERE date = '2026-06-15', the engine looks at the directory names and opens only that one. The other 364 days of the year are not even touched.
This is the third mechanism for reading less, and the most powerful. It joins the two from lesson 02-02:
| Mechanism | What it avoids reading | Where the information is |
|---|---|---|
| Partition pruning | Entire directories | In the directory names |
| Predicate pushdown | Row groups within a file | In the statistics in the Parquet footer |
| Column pruning | Columns the query does not use | In the file's columnar structure |
Do not mix up the partitions. In lesson 01-04, a "partition" was each of the pieces a dataset is divided into so that it can be spread across the nodes. Here we are talking about directory partitions: a way of organising a table's files. The underlying idea is the same (dividing according to a key), but the purpose here is to avoid reads.
Choosing the partition column
| A good partition column… | Example at NovaMarket |
|---|---|
| Appears in the filters of most queries | date in web_events |
| Has few distinct values (tens, hundreds or a few thousand) | 365 dates a year |
| Splits the data into large pieces of similar size | ~40 million events a day |
The date is by far the most common choice. Several levels can be nested (year=2026/month=06/day=15/ or date=.../event_type=.../), but each level multiplies the number of directories.
The risk of over-partitioning
Partitioning too much is worse than not partitioning at all. Compare three options for a year of NovaMarket events (40 million a day; let's say around 600 MB a day in Parquet):
| Partition by | Directories a year | Size per directory | Verdict |
|---|---|---|---|
date |
365 | ~600 MB | Suitable |
date and hour |
8,760 | ~25 MB | Files too small |
customer_id |
2,000,000 | ~110 kB | Disastrous |
The last two reproduce the small files problem from lesson 02-01: millions of tiny files, more time spent opening files than reading data and, in HDFS, a saturated NameNode. As a guide, if the files in each partition end up well below about 100 MB, there are probably too many partitions.
A small table, such as orders (20,000 rows in the practice data) or products, is not partitioned: it fits in one file and there is nothing to gain.
The metadata catalogue
Paths bring order, but they are not enough. With hundreds of tables, nobody remembers that the events are in lake/silver/web_events/, that they are Parquet, that they are partitioned by date and what each column means.
A metadata catalogue is the registry that holds that information: for each table, its name, its location, its format, its schema and its partitions. It is the equivalent, for the whole lake, of what the NameNode is for HDFS: it does not contain data, but data about the data.
With a catalogue, Marc does not need to know any paths. He writes:
and the engine consults the catalogue to find out where the files for silver.web_events are, how to read them and which directory corresponds to that date. The catalogue turns folders of files into tables that can be queried with SQL.
The best-known technical catalogues are the Hive Metastore, the historical standard of the Hadoop ecosystem, and AWS Glue Data Catalog, its managed equivalent at Amazon; today's platforms come with their own. We will not use a catalogue in the practical work, because with five tables the paths are enough. Catalogues aimed at people (descriptions, owners, lineage) belong to data governance, which is covered in lesson 05-02.
The risk of the data swamp
A data lake without order degenerates into a data swamp: a huge store that nobody trusts and in which nobody can find anything. That was the fate of many first-generation data lakes, built to the slogan "let's store everything, we'll see later".
| Symptom of the swamp | How to avoid it |
|---|---|
| Nobody knows what each folder contains | Path convention and metadata catalogue |
Folders called test2, final_copy, tmp_laura in shared zones |
Defined zones; a separate scratch zone, with an expiry |
| Several versions of the "same" data, with different figures | A single reference table per entity in silver |
| Nobody knows whether a piece of data is clean | The zones indicate the level of quality; validations when moving from one to the next |
| Nobody is accountable for a dataset | An owner assigned to each one |
| Millions of tiny files | Sensible partitioning and periodic compaction |
| Everything is kept for ever | A retention and deletion policy |
The underlying lesson: schema-on-read does not exempt you from being disciplined. A data lake is only as useful as its conventions. Data governance (lesson 05-02) and security (Module 7) develop these ideas.
Warning: the bronze layer keeps the data just as it arrives, including customers' personal data. A data lake's access, retention and deletion policies must be reviewed with the organisation's data protection officer.
Hands-on: a mini data lake for NovaMarket
You are going to build the bronze and silver zones in ~/novamarket/lake/ with the five datasets. The gold zone will be left for an exercise.
Remember the deliberate defects in the data from lesson 01-05: 100 duplicate rows in orders.csv and 500 duplicate events in web_events.json. Silver is the place where they are corrected.
Create ~/novamarket/build_lake.py:
import shutil
from pathlib import Path
from pyspark.sql import SparkSession
from pyspark.sql import functions as F
BASE = Path.home() / "novamarket"
DATA_DIR = BASE / "data"
BRONZE = BASE / "lake" / "bronze"
SILVER = BASE / "lake" / "silver"
# ----------------------------------------------------------------------
# 1. Bronze zone: an exact copy of the source files
# ----------------------------------------------------------------------
for file in sorted(DATA_DIR.iterdir()):
target = BRONZE / file.stem # e.g. lake/bronze/orders/
target.mkdir(parents=True, exist_ok=True)
shutil.copy2(file, target / file.name)
print(f"bronze <- {file.name}")
# ----------------------------------------------------------------------
# 2. Silver zone: clean, typed data in Parquet
# ----------------------------------------------------------------------
spark = (
SparkSession.builder
.master("local[*]")
.appName("build_lake")
.getOrCreate()
)
spark.sparkContext.setLogLevel("ERROR")
def read_bronze_csv(name):
path = BRONZE / name / f"{name}.csv"
return spark.read.csv(str(path), header=True, inferSchema=True)
# 2a. Small tables: they only change format and gain types
for name in ["customers", "products", "order_lines"]:
df = read_bronze_csv(name)
df.write.mode("overwrite").parquet(str(SILVER / name))
print(f"silver <- {name}: {df.count()} rows")
# 2b. Orders: duplicate rows are removed
orders_bronze = read_bronze_csv("orders")
orders = orders_bronze.dropDuplicates()
orders.write.mode("overwrite").parquet(str(SILVER / "orders"))
print(f"silver <- orders: {orders_bronze.count()} rows read, "
f"{orders.count()} written")
# 2c. Events: no duplicates, with date types and partitioned by day
events_bronze = spark.read.json(str(BRONZE / "web_events" / "web_events.json"))
events = (
events_bronze
.dropDuplicates(["event_id"])
.withColumn("event_time", F.to_timestamp("event_time"))
.withColumn("date", F.to_date("event_time"))
)
(
events
.repartition("date")
.write.mode("overwrite")
.partitionBy("date")
.parquet(str(SILVER / "web_events"))
)
print(f"silver <- web_events: {events_bronze.count()} lines read, "
f"{events.count()} written")
spark.stop()What each block does
Block 1, bronze. Spark is not involved: it is a simple file copy with shutil.copy2. For each file in data/ a folder is created with its name minus the extension (file.stem) and the file is copied into it without touching a byte. That is the bronze layer. At the real NovaMarket, these files would arrive every day from the ingestion layer, and the usual thing would be to add a level with the load date.
Block 2a. customers, products and order_lines are read from bronze and written in Parquet. The reading and writing are those from lesson 02-02. They are not partitioned: they are small tables.
Block 2b, orders. dropDuplicates() with no arguments removes rows that are identical in all their columns, which is exactly the defect introduced into orders.csv. The 200 orders with an empty total_amount are kept with a null value: rebuilding them means joining with order_lines, and we will leave that for Module 3, when you know Spark's joins.
Block 2c, events. There are four chained steps:
dropDuplicates(["event_id"])keeps a single row for eachevent_id.withColumn("event_time", F.to_timestamp(...))replaces the text column with a genuine date and time. It corrects what schema inference left half done in lesson 02-02.withColumn("date", F.to_date(...))creates a new column with just the day: this will be the partition column..partitionBy("date")asks Spark to write one subdirectory for each value ofdate. The.repartition("date")before it first groups together all the rows for each day so that each directory receives a single file; without it, each directory would have several tiny files, one for each write task.
Run it with python build_lake.py. The output, taken from a real run, is:
bronze <- customers.csv bronze <- order_lines.csv bronze <- orders.csv bronze <- products.csv bronze <- web_events.json silver <- customers: 1000 rows silver <- products: 200 rows silver <- order_lines: 50107 rows silver <- orders: 20100 rows read, 20000 written silver <- web_events: 200500 lines read, 200000 written
The 100 duplicate orders and the 500 duplicate events have disappeared on the way from bronze to silver. In bronze they are still there, intact.
The resulting tree
~/novamarket/lake/
├── bronze/
│ ├── customers/customers.csv
│ ├── order_lines/order_lines.csv
│ ├── orders/orders.csv
│ ├── products/products.csv
│ └── web_events/web_events.json
└── silver/
├── customers/part-00000-....snappy.parquet
├── products/part-00000-....snappy.parquet
├── order_lines/part-00000-....snappy.parquet
├── orders/part-00000-....snappy.parquet
└── web_events/
├── date=2026-06-01/part-....snappy.parquet
├── date=2026-06-02/part-....snappy.parquet
├── ...
├── date=2026-06-30/part-....snappy.parquet
└── date=2026-07-01/part-....snappy.parquetYou can see it with ls lake/silver/web_events or, if you have it installed, with tree lake. Each silver folder also contains the _SUCCESS file and some hidden .crc checksum files that you can ignore. Three observations:
- There are 31 partitions, not 30. The last one,
date=2026-07-01, contains only 47 events: these are the sessions that began late on 30 June and ended after midnight, as lesson 01-05 warned. The partitioning reflects the data as it is. du -sh lake/bronze lake/silvershows around 38 MB in bronze and around 4.4 MB in silver: the same data, now clean, takes up almost nine times less.- The practice partitions are tiny (about 130 kB each), far below the 100 MB guideline. At this scale you would not partition; we do it to learn the technique, which at NovaMarket's real scale is indeed essential.
A read with partition pruning
Create query_lake.py:
from pathlib import Path
from pyspark.sql import SparkSession
SILVER = Path.home() / "novamarket" / "lake" / "silver"
spark = (
SparkSession.builder
.master("local[*]")
.appName("query_lake")
.getOrCreate()
)
spark.sparkContext.setLogLevel("ERROR")
events = spark.read.parquet(str(SILVER / "web_events"))
events.printSchema()
# Funnel for a single day: the filter is on the partition column
one_day = events.where("date = '2026-06-15'")
one_day.groupBy("event_type").count().orderBy("count", ascending=False).show()
one_day.explain()
spark.stop()You read the root folder of the table, silver/web_events, not a subdirectory. Spark discovers the partitions by itself. The output:
root |-- customer_id: long (nullable = true) |-- device: string (nullable = true) |-- event_id: string (nullable = true) |-- event_time: timestamp (nullable = true) |-- event_type: string (nullable = true) |-- product_id: long (nullable = true) |-- session_id: string (nullable = true) |-- date: date (nullable = true) +------------+-----+ | event_type|count| +------------+-----+ |product_view| 4605| | search| 1008| | add_to_cart| 748| | purchase| 281| +------------+-----+
- The schema includes
dateas the last column, of typedate, even though it is not inside any file: Spark has rebuilt it from the directory names. Andevent_timeis now atimestamp. - On 15 June there were 6,642 events, in the expected proportions.
In the plan printed by explain(), look in the FileScan parquet line for this fragment:
This is partition pruning: the filter is resolved using the directory names, and Spark opens only date=2026-06-15/. It has read about 130 kB of the table's 4 MB. At NovaMarket's real scale, that would be reading 600 MB instead of 220 GB.
Compare it with the plan in lesson 02-02, where the filter on event_type appeared in PushedFilters: that one was applied inside the files; this one, before opening them.
Common Mistakes and Tips
- Modifying or "cleaning" the bronze layer. It destroys the ability to reprocess and audit. Corrections are made in silver.
- Partitioning by a column with a huge number of values (
customer_id,event_id, a timestamp with seconds). It generates millions of directories. For columns like these there are other techniques, which you will see in lesson 03-04. - Filtering on an expression instead of on the partition column. With
WHERE to_date(event_time) = '2026-06-15'the engine does not know it can prune: it reads all 31 partitions. Always filter on the column itself:WHERE date = '2026-06-15'. - Reading a subdirectory directly (
silver/web_events/date=2026-06-15). It works, but thedatecolumn disappears from the result, because it only existed in the path. Read the root and filter. - Writing with
partitionBywithout grouping first. It produces many small files per partition. Userepartitionon the same column, as in the hands-on. - Using
mode("overwrite")lightly on a partitioned table. By default it replaces the whole table, not just the new partitions. For daily loads there are specific modes, which will be covered with pipelines (lesson 03-06). - Tip: document the lake's path convention somewhere visible and check that it is being followed. It is the cheapest measure against the swamp.
Exercises
Exercise 1: which column to partition by?
For each table, say whether you would partition it and by which column, thinking of NovaMarket's real scale:
order_lines: about 125,000 rows a day; it is nearly always queried by period.products: tens of thousands of rows; it is always read in full.web_events, if an analyst proposes partitioning bysession_id"because the funnel is calculated per session".
Exercise 2: a week of events
Modify query_lake.py to count the events in the first week of June (from the 1st to the 7th, both inclusive). How many are there? What does PartitionFilters show and how many directories are read?
Exercise 3: your first gold table
Create a script build_gold.py that generates lake/gold/daily_sales from silver/orders: one row per day and channel, with the number of orders and the sum of total_amount, excluding returned orders. Hints: F.to_date("order_date") extracts the day; .groupBy(...).agg(F.count("*").alias("num_orders"), F.sum("total_amount").alias("sales")) groups and aggregates.
Solutions
Exercise 1
- Yes, by order date, but probably by month rather than by day: 125,000 rows a day is a few MB in Parquet, too little for a partition. The
order_linestable has no date of its own, so one would have to be added by joining withorders. - No. It is small and is read whole: partitioning would only add files.
- No.
session_idhas millions of distinct values: it is the extreme case of over-partitioning. The fact that a calculation groups by a column does not make it a good partition column; what counts is which column you filter on. The right partition is stilldate.
Exercise 2
week = events.where("date BETWEEN '2026-06-01' AND '2026-06-07'")
print(week.count())
week.explain()The result is 47,536 events. PartitionFilters shows the two conditions of the range (date >= 2026-06-01 and date <= 2026-06-07) and Spark reads only 7 of the 31 directories.
Exercise 3
from pathlib import Path
from pyspark.sql import SparkSession
from pyspark.sql import functions as F
LAKE = Path.home() / "novamarket" / "lake"
spark = SparkSession.builder.master("local[*]").appName("build_gold").getOrCreate()
spark.sparkContext.setLogLevel("ERROR")
orders = spark.read.parquet(str(LAKE / "silver" / "orders"))
daily_sales = (
orders
.where("status <> 'returned'")
.groupBy(F.to_date("order_date").alias("date"), "channel")
.agg(F.count("*").alias("num_orders"),
F.round(F.sum("total_amount"), 2).alias("sales"))
)
daily_sales.coalesce(1).write.mode("overwrite").parquet(str(LAKE / "gold" / "daily_sales"))
result = spark.read.parquet(str(LAKE / "gold" / "daily_sales"))
print("Rows:", result.count())
result.orderBy("date", "channel").show(4)
spark.stop()Rows: 362 +----------+-------+----------+---------+ | date|channel|num_orders| sales| +----------+-------+----------+---------+ |2026-01-01| app| 39| 80553.4| |2026-01-01| web| 51| 91319.28| |2026-01-02| app| 41| 76874.23| |2026-01-02| web| 70|131121.11| +----------+-------+----------+---------+
That is 362 rows: 181 days times 2 channels. coalesce(1) gathers the result into a single file, the sensible thing for such a small table. The gold table takes up a few kB and answers instantly what a dashboard needs.
An important nuance: F.sum ignores null values, so the orders with no total_amount count in num_orders but add nothing to sales. The sales figures are therefore slightly understated until those amounts are rebuilt. It is a good example of why quality in silver conditions everything built on top of it.
Conclusion
A data lake is a central repository that stores data of any type in its original format, on cheap storage, and applies schema-on-read: first you store, then you interpret. So that this freedom does not end in a data swamp, it is organised into zones — bronze (raw and immutable), silver (clean and typed) and gold (ready for the business) — with a path convention, sensible directory partitioning that enables partition pruning, and a metadata catalogue that turns folders into tables. You have put it into practice: in ~/novamarket/lake/ you have a bronze zone with the faithful copies and a silver zone in Parquet, free of duplicates and with web_events partitioned by date.
But that lake has a weakness you may have sensed. If the status of five orders changes tomorrow, from pending to shipped, how are they updated in silver/orders? The files are immutable: the table would have to be rewritten, and if someone queries it halfway through the rewrite they will see half-finished data. A plain data lake has no transactions. Data warehouses do, but at the cost of another infrastructure and of duplicating the data. In the next lesson, Data Warehouses and the Lakehouse Architecture, you will see how a data warehouse works, how its data is modelled and how open table formats bring together the best of both worlds.
