Module 8 ยท Information Systems ยท Lesson 5 ยท Week 4

Instruction session ยท Thursday, November 5, 2026 ยท 14:00 to 16:00

Data Warehouses: the hybrid Silver layer

The orders of Olist, a Brazilian marketplace, enter the platform as raw CSV files and become a Silver layer in two copies: a long-lived lake in RustFS, read with DuckDB, and ClickHouse for tactical queries. The session ends with a star schema built over that Silver layer with views and materialized views, which answers how many sales the North made each month compared with the Southeast. The professor builds it live with a coding agent in four steps.

Olist datasetdata_ingestao ยท data_linha ยท data_tagDuckDB lakeClickHouse TTLStar schemaViews and materialized views

Project ritual

Daily ยท 15 minutes

Each group reports the progress of its deliverables, the work planned for this session and the blockers that require a decision.

15:00
What I didWhat I will doBlockersProgress
Agenda ยท 14:15 to 16:00
Four steps of prompt, build and explanation

The professor sends each prompt to the coding agent. While the agent writes, the slides explain the concept that the step implements, and the step ends with a review against the counts measured in the rehearsal.

14:25 ยท step 01Contract and decisionAgent: contract, ADR, DDLSlides: the Silver layer as a Data Warehouse; the three columns, JSON and tags
14:40 ยท step 02Hybrid loadAgent: src/load_hybrid.pySlides: normalising, aggregating and deriving; the lake first
15:00 ยท step 03Audit and lifecycleAgent: src/reconcile.pySlides: Redshift and ClickHouse, TTL and the clock of the retention
15:15 ยท step 04Star schemaAgent: views and materialized viewsSlides: dimensional modelling and the question of the business
14:15

Case, data and environment

The Olist dataset, the hybrid architecture, the raw CSV files and the local RustFS and ClickHouse.

15:42

Verification and artifact

The checks that close the lab and how they map to the Data Ingestion Structure artifact of the week.

15:52

Closing

What each group takes to its own data before Lesson 6, and the self-study.

14:15 ยท Running case
The orders of a Brazilian marketplace

Olist connects small shops to the large marketplaces of Brazil. Its public dataset has 99,441 orders placed between September 2016 and October 2018, with the customers, sellers, products and items of each order, extracted from the transactional system without any treatment.

Tactical need

The commercial area asks every month

How many sales did each region make this month, and how does the North compare with the Southeast? The answer must come in under a second, for a dashboard.

Strategic need

Data science asks once a quarter

Is the growth of the North seasonal or structural, and which categories drive it? The answer needs every year that the platform has kept, and it may run for hours.

Audit need

The partner asks after an incident

Where did this number come from, and can you rebuild it? The answer needs the source file of each record and proof that no copy was altered.

Question of the sessionHow can one Silver layer serve a fast dashboard, a study that reaches years back and an audit that must prove every row, and how is a model of the business built on top of it to answer a question such as North against Southeast?
14:17 ยท Target architecture
One enriched table, two copies and a star on top

Every load writes the lake first and then loads ClickHouse from the files it has just written. ClickHouse therefore never holds a row that the lake does not hold, and the star schema of the Gold database is computed from it.

BronzeRustFS ยท bronze/8 CSV files, unchanged EnrichDuckDB ยท httpfsnormalise ยท aggregatederive ยท quarantine 1 ยท Lake (source of truth)silver/enriched/data_tag=โ€ฆ/ingestion_date=โ€ฆ/data.parquetsilver/_manifests/run_โ€ฆ.jsonSHA-256 of every file 2 ยท ClickHousesilver.enrichedloaded from the lake filesMergeTree ยท partition by monthTTL 1 year 3 ยท gold ยท star schemaviews and materialized views Years and decadesstrategy ยท data science ยท audit One load, in this orderenrich, write the lake, load ClickHouse from the lake, write the manifest, refresh the star
14:19 ยท Two lifecycles
Why the two copies keep data for different periods

The two copies answer different kinds of question, and each kind needs a different period of history and a different cost per query.

ClickHouseLake in RustFS, read with DuckDB
Questionstactical: sales of the month by region, late deliveries of the weekstrategic: seasonality, trends over years, models
Userscommercial area, operations, dashboardsanalysts, data scientists, auditors
Period keptup to one year, removed by TTLyears and decades, every version
Cost profileserver always on, data on fast diskobject storage, compute only when a job runs
Typical runsub-second queries, many per minutejobs of minutes, hours or days
If lostrebuilt from the lakethe record of the platform; must be protected
The one-year window is a business decisionEngineering measures the cost and the speed of each window, but the period is decided by the business, with the legal retention periods and the partner's needs. The lab writes it as a hypothesis in the ADR, with the name of who decides it, and Step 03 shows that the clock it counts from is a decision as well.
14:21 ยท The raw data
Eight CSV files, exactly as Olist published them

The archive below holds the files of the case without any change. The lab copies it into the Bronze layer, so every defect of the source is still there for the Silver layer to treat.

FileBronze entityRowsMB
olist_orders_dataset.csvorders99,44117.7
olist_order_items_dataset.csvorder_items112,65015.0
olist_customers_dataset.csvcustomers99,4418.6
olist_sellers_dataset.csvsellers3,0950.2
olist_products_dataset.csvproducts32,9512.4
product_category_name_translation.csvproduct_category_translation710.0
olist_order_payments_dataset.csvpayments103,8865.6
olist_order_reviews_dataset.csvreviews99,22414.5
Download

olist_raw_csv.zip ยท 28 MB

The eight files, the licence and a note on the source. Payments and reviews stay in the Bronze for the groups to explore; the Silver layer of the lab uses the other six.

โฌ‡ Raw data (CSV)

Source: github.com/olist/work-at-olist-data, MIT licence. The same data is published on Kaggle as Brazilian E-Commerce Public Dataset by Olist. The 61 MB geolocation file is left out because the lab does not use it.

14:22 ยท Step 00 ยท Environment
RustFS, ClickHouse and the Bronze of Olist

The support files are in lab/lesson-5/ of the module, with the archive of raw data in data/. The folder lesson_05_dw/ starts as a copy of it, and load_bronze.py uploads the eight files to RustFS byte for byte.

Terminal ยท classroom computer
git clone --depth 1 https://github.com/afonsolelis/aulas.git
cp -r aulas/pages/module-8-sistemas-informacao/lab/lesson-5 ~/lesson_05_dw
cd ~/lesson_05_dw
cp .env.example .env              # passwords changed off screen
docker compose up -d --wait       # rustfs and clickhouse healthy
python3 -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt
python load_bronze.py             # 8 objects in bronze/
echo "@AGENTS.md" > CLAUDE.md && claude
AGENTS.md ยท rules that matter today
  • Bronze is read-only.
  • The three columns keep the names data_ingestao, data_linha, data_tag.
  • Lake first, then ClickHouse from the lake, then the manifest.
  • data_linha is JSON in ClickHouse, never String.
  • Every CSV column is read as text and converted explicitly.
  • The retention is a business hypothesis.

RustFS speaks the S3 API, accepts only path-style addresses and has its console at localhost:9001/rustfs/console/. ClickHouse answers on localhost:8123 and reaches RustFS inside the compose network at rustfs:9000. The archive is already inside the folder; the download button is for studying the files at home.

14:24 ยท Step 00 ยท What the source delivers
Defects that the Silver layer must treat

load_bronze.py counts them at the end of the upload. None of them is planted: they are what a transactional extract without treatment looks like, and each one becomes a rule of the contract in Step 01.

Defect in the BronzeCountRule of the Silver layer
orders delivered without order_delivered_customer_date8quarantine, with the 8 items of those orders
orders delivered without order_approved_at14kept, with approved_at null
zip prefixes with 4 digits, the leading zero lost at the source23,995 ยท 1,027customers ยท sellers: text padded to 5 characters
products without category ยท category without English name610 ยท 13unknown ยท the Portuguese name as fallback
headers product_name_lenght, product_description_lenght2renamed in the contract
translation file starting with a UTF-8 byte order mark1read with the mark removed, or the join finds no column
timestamps without offset, local time of a country that had daylight saving time until 2019allISO 8601 with -03:00 or -02:00 of that date

Step 01 ยท 14:25 ยท Contract and decision

The contract of the enriched table

Before any code, the agent writes what the Silver layer promises: three columns, one tag per kind of record, the layout of the lake and the decision of the two copies, plus the DDL of ClickHouse.

Files

specs/silver_contract.md, docs/adr/ADR-002-hybrid-silver.md and sql/clickhouse_enriched.sql, applied in ClickHouse.

Review before moving on
  • Are the three columns named exactly data_ingestao, data_linha and data_tag?
  • Does every tag have a key and its rules?
  • Is zip_prefix a string of 5 characters?
  • Is the one-year retention a business hypothesis with an owner?
  • Does SHOW CREATE TABLE show the JSON type and the TTL?
Prompt 01 ยท CREATE
[C] Character
You are a senior data architect. You work in the folder lesson_05_dw/,
which holds the Bronze layer of the Olist case (a Brazilian marketplace,
orders from 2016-09 to 2018-10) in a local RustFS, an S3-compatible
object storage, and an empty ClickHouse. In this step you write the
contract of the Silver layer, the decision record and one DDL file; you
do not write Python.

[R] Request
Write three files:
1. specs/silver_contract.md: the enriched table of the Silver layer, with
   exactly three columns:
   - data_ingestao: date and time at which the record entered the
     platform, in America/Sao_Paulo: the ingestion_date partition of the
     Bronze object at 00:00. It is not the date of the order.
   - data_linha: JSON with the normalised and derived fields of one
     record, always including source_file.
   - data_tag: 'olist.<entity>.v<N>', or 'quarantine.v1' for rejected
     records, whose data_linha holds entity, key, reason and source_file.
   Five tags enter the Silver layer: olist.customer.v1, olist.seller.v1,
   olist.product.v1, olist.order.v1 and olist.order_item.v1. Payments and
   reviews stay in the Bronze. The fields of data_linha, besides
   source_file, are:
   - customer: customer_id, customer_unique_id, zip_prefix, city, state,
     region;
   - seller: seller_id, zip_prefix, city, state, region;
   - product: product_id, category_pt, category_en, name_length,
     description_length, photos_qty, weight_g, length_cm, height_cm,
     width_cm;
   - order: as in the example below;
   - order_item: order_id, order_item_id, product_id, seller_id,
     shipping_limit_at, price, freight_value, item_total.
   Include a catalogue with one entry per tag (fields, key used for
   deduplication, rules) and the layout of the lake:
   silver/enriched/data_tag=<tag>/ingestion_date=<D>/data.parquet (Parquet
   zstd, the same key is overwritten on a rerun) and
   silver/_manifests/run_<run_id>.json (per file: key, data_tag, rows,
   bytes, sha256; plus rows per tag, times and status).
2. docs/adr/ADR-002-hybrid-silver.md: every load writes the lake first and
   then loads ClickHouse from the files it has just written. The lake is
   the source of truth and keeps every version for years, for strategic
   analysis and data science read with DuckDB. ClickHouse keeps a short
   window for tactical queries and deletes older rows by TTL. Compare
   with two alternatives: ClickHouse only, and lake only.
3. sql/clickhouse_enriched.sql: database silver and table silver.enriched
   (data_ingestao DateTime64(3, 'America/Sao_Paulo'), data_tag
   LowCardinality(String), data_linha JSON), MergeTree, partition by month
   of data_ingestao, order by (data_tag, data_ingestao), TTL of 1 year on
   data_ingestao. Apply it and show SHOW CREATE TABLE.

Facts measured on 05/11/2026 (confirm before use):
- Bronze: 8 CSV objects under
  bronze/source=olist/entity=<e>/ingestion_date=2026-11-05/, written
  unchanged by load_bronze.py, which prints the defects of the source.
- Rows in the Bronze: orders 99,441, order_items 112,650, customers
  99,441, sellers 3,095, products 32,951, category translation 71.
- Defects: 8 orders 'delivered' without order_delivered_customer_date;
  14 orders 'delivered' without order_approved_at (kept, approved_at
  null); 23,995 customer and 1,027 seller zip prefixes with 4 digits (the
  leading zero was lost at the source); 610 products without category
  and 13 whose category has no English translation; headers
  product_name_lenght and product_description_lenght misspelt; the
  translation file starts with a UTF-8 byte order mark; timestamps
  without offset, in local time of Brazil, which had daylight saving
  time until 2019.

[E] Example
### olist.order.v1
Source: bronze/source=olist/entity=orders/*/olist_orders_dataset.csv
Key: order_id; keep the latest ingestion_date, then the latest file.
data_linha: order_id, customer_id, order_status, purchased_at,
approved_at, delivered_carrier_at, delivered_customer_at (ISO 8601 with
the offset of America/Sao_Paulo on that date, -03:00 or -02:00),
estimated_delivery_on, customer_state, customer_region, delivery_days,
delivered_late, source_file.
Rules: customer_state and customer_region joined from the customers;
region from the state (North, Northeast, Central-West, Southeast,
South); delivery_days and delivered_late derived.
Quarantine: orphan customer; status 'delivered' without delivery date.

[A] Adjustments
- Keep the three column names exactly as written: data_ingestao,
  data_linha, data_tag.
- Read every CSV column as text and convert it explicitly; zip_prefix is
  a string of 5 characters, never a number.
- An order item whose order went to quarantine also goes to quarantine,
  with the reason 'order in quarantine'. A superseded duplicate of a key
  goes to quarantine with the reason 'duplicate key, superseded', so
  that every Bronze record ends in exactly one tag.
- data_linha is of type JSON in ClickHouse, never String.
- The retention of 1 year is a business parameter: mark it "hypothesis,
  to validate with the partner", and say who decides it.
- No Python in this step.

[T] Type of output
Three files. The contract has the column table, the tag catalogue, the
lake layout and a section "Facts, gaps and assumptions". The ADR has
Context, Decision, Alternatives (table), Consequences and a Mermaid
flowchart Bronze -> enrich -> lake -> ClickHouse.

[E] Extras
Read AGENTS.md first. Show the tag catalogue before writing the files.
Record this prompt in docs/prompts.md. Stop at the end.

Step 01 ยท While the agent works

What makes the Silver layer a Data Warehouse

The agent showed its plan, received the go-ahead and is writing. The next slides explain the concept that the prompt asked for, and the review of the files comes after them.

Theory of this step
  1. The Silver layer as a Data Warehouse: a corporate view of the core entities
  2. The enriched table: data_ingestao, data_linha, data_tag
  3. JSON and tags: schema evolution, versioning and filtering
Back at the files

Read the tag catalogue against the counts of the Bronze and check that the ADR names who decides the retention.

Excerpt of prompt 01
   - data_tag: 'olist.<entity>.v<N>', or 'quarantine.v1' for rejected
     records, whose data_linha holds entity, key, reason and source_file.
Step 01 ยท Theory 1
The Silver layer as a Data Warehouse

In the medallion architecture, Silver combines and cleans what arrived in Bronze and offers one corporate view of the core business entities. Inmon defined a Data Warehouse by four properties, and the Silver layer of the lab has each of them.

Subject-oriented

Organised around orders, items, customers, sellers and products, and not around the tables of the transactional system that produced them.

Integrated

One format for dates, one for zip prefixes and one name per category for all files. The 23,995 short zip prefixes arrive padded.

Time-variant

Every record carries data_ingestao, so the warehouse can answer what was known at any moment, not only the current state.

Non-volatile

Loads add or replace whole files; nobody edits a row by hand. A rerun with the same Bronze gives the same Silver.

Self-service analytics

Analysts query Silver directly, because the cleaning and the integration were done once, upstream, with rules that are written down.

Foundation for Gold

The star schema of Step 04 is computed from Silver, so an error fixed in Silver is fixed in every fact and every dimension.

Step 01 ยท Theory 2
Three columns for every record

The enriched table stores every kind of record in the same three columns. The fixed part is what the platform needs to manage the data, and the variable part travels in JSON.

ColumnType in ClickHouseMeaning
data_ingestaoDateTime64(3, 'America/Sao_Paulo')when the record entered the platform: the partition date of the Bronze object
data_linhaJSONthe normalised and derived fields of one record, always with source_file
data_tagLowCardinality(String)olist.<entity>.v<N> or quarantine.v1
One row of olist.order.v1
data_ingestao  2026-11-05 00:00:00.000
data_tag       olist.order.v1
data_linha     {"order_id":"a985d695โ€ฆ",
                "order_status":"delivered",
                "purchased_at":
                  "2018-03-14T10:11:04-03:00",
                "customer_state":"MG",
                "customer_region":"Southeast",
                "delivery_days":8,
                "delivered_late":false,
                "source_file":"s3://โ€ฆ/orders/โ€ฆcsv"}
Two dates in the same rowdata_ingestao says when the platform received the record, and purchased_at says when the customer bought. The orders are from 2018, but they entered the platform on 05/11/2026; the TTL and the analysis use different dates, and Step 03 measures what that means.
Step 01 ยท Theory 3
JSON for the content, tags for the kind

JSON lets records of different shapes share one table, and the tag says which shape each record has. Together they absorb new sources and new versions without a change of DDL.

JSON in data_linha

Flexible and still columnar

  • Holds structured rows and semi-structured payloads in the same column.
  • ClickHouse splits each JSON path into a typed subcolumn: delivery_days Int64, price Float64, purchased_at String.
  • A query reads only the paths it uses, as in any columnar table.
  • A new field is a new path, with no ALTER TABLE.
Tags in data_tag

Versioning, categorisation, filtering

  • olist.order.v1 names source, entity and version of the contract.
  • A change of shape is a new version, such as olist.order_item.v2.
  • Every query filters by tag first, and the table is ordered by it.
  • quarantine.v1 keeps rejected records visible, with a reason.
data_tagRows expected after Step 02Key of deduplication
olist.order.v1 ยท olist.order_item.v199,433 ยท 112,642order_id ยท order_id, order_item_id
olist.customer.v1 ยท olist.seller.v199,441 ยท 3,095customer_id ยท seller_id
olist.product.v132,951product_id
quarantine.v116entity and key
total347,578

Step 02 ยท 14:40 ยท Enrichment and hybrid load

Enrich once, write the lake, then ClickHouse

The agent applies the rules of the contract in DuckDB, produces the three columns for every tag, writes one Parquet file per tag and day with its SHA-256, and loads ClickHouse from those files.

Files

src/config.py, src/enrich.py, src/lake.py, src/clickhouse.py, src/load_hybrid.py and tests/test_enrich.py.

Review before moving on
  • Is the lake written before ClickHouse and the manifest last?
  • Do both copies show 347,578 rows and 16 in quarantine?
  • Did purchased_at keep its offset and stay String in ClickHouse?
  • Does a second run arrive at the same counts?
Prompt 02 ยท CREATE
[C] Character
You are the data engineer who implements the hybrid load. You follow
specs/silver_contract.md and docs/adr/ADR-002-hybrid-silver.md, and you
only touch src/ and tests/.

[R] Request
Write:
1. src/config.py: reads .env (names only, never the values).
2. src/enrich.py: DuckDB SQL that reads the Bronze over httpfs and builds
   one relation (data_ingestao, data_tag, data_linha) with every tag of
   the contract: normalise (text columns, 5-digit zip prefixes, fixed
   headers, ISO 8601 timestamps with offset, categories in English with
   the Portuguese name as fallback and 'unknown' when empty), aggregate
   sources (state and region of the customer into each order), derive
   (region, delivery_days, delivered_late, item_total), deduplicate by
   the keys of the contract and send rejected records to quarantine.v1
   with a reason.
3. src/lake.py: writes one Parquet file per (data_tag, day of
   data_ingestao) under silver/enriched/, computes the SHA-256 of the
   bytes it uploads and writes the manifest of the run.
4. src/clickhouse.py: truncates silver.enriched and loads it with the
   s3() table function of ClickHouse reading the Parquet files of the
   lake, never the Bronze.
5. src/load_hybrid.py, run as python -m src.load_hybrid: enrich, write the
   lake, load ClickHouse from the lake, write the manifest with status ok.
   If ClickHouse fails, write the manifest with status error_clickhouse
   and exit with a non-zero code.
6. tests/test_enrich.py with small fixtures in tests/fixtures/, one
   example of each defect, without network.
Then run the load and print the rows per data_tag in the lake and in
ClickHouse.

Facts measured on 05/11/2026 (confirm before use):
- Expected Silver: olist.customer.v1 99,441, olist.seller.v1 3,095,
  olist.product.v1 32,951, olist.order.v1 99,433, olist.order_item.v1
  112,642, quarantine.v1 16 (8 orders and their 8 items). Total 347,578
  rows in 6 Parquet files.
- Whole run about 2.5 s on the preparation machine (0.8 s to enrich,
  0.8 s to write the lake, 0.9 s to load ClickHouse).
- In ClickHouse the JSON paths keep their types: purchased_at and
  zip_prefix stay String, delivery_days Int64, price Float64,
  delivered_late Bool.

[E] Example
data_tag:      olist.order.v1
data_ingestao: 2026-11-05 00:00:00.000 -03:00
data_linha:    {"order_id":"a985d695ba083a66246dd48086ad4cab",
  "customer_id":"db9fca3fe54ebcbdb9ccf151ab539a1c",
  "order_status":"delivered","purchased_at":"2018-03-14T10:11:04-03:00",
  "delivered_customer_at":"2018-03-22T15:28:56-03:00",
  "estimated_delivery_on":"2018-04-06","customer_state":"MG",
  "customer_region":"Southeast","delivery_days":8,
  "delivered_late":false,"source_file":"s3://olist-lake/bronze/
  source=olist/entity=orders/ingestion_date=2026-11-05/
  olist_orders_dataset.csv", ...}

[A] Adjustments
- Order of the run: lake, then ClickHouse, then the manifest. ClickHouse
  never holds a row that the lake does not hold.
- A rerun gives the same result: the lake keys are overwritten and
  ClickHouse is rebuilt from the lake.
- Every INSERT uses input_format_try_infer_dates = 0,
  input_format_try_infer_datetimes = 0 and async_insert = 0, so that the
  timestamps keep their text and offset.
- DuckDB reaches RustFS with URL_STYLE 'path' and USE_SSL false; it
  needs the pytz package to hand TIMESTAMPTZ values to Python. In DuckDB
  2.0 a relation has no fetchone(): use con.execute(...).fetchone().
- ClickHouse reaches RustFS at S3_ENDPOINT_FROM_CLICKHOUSE, the address
  inside the compose network, not at localhost.
- Read the Bronze with hive_partitioning = false and take
  ingestion_date as text from the path, so that no column is typed by
  the reader.
- pytest runs from the root of the folder: add tests/conftest.py that
  puts the root on sys.path, so that the tests can import src.
- Pass the credentials of s3() from .env at run time, never written in
  a file, and record in the ADR that they appear in system.query_log of
  ClickHouse (a named collection would avoid it).
- Do not use CREATE PERSISTENT SECRET.

[T] Type of output
The six files, the output of pytest -q and of the load, and a table
data_tag | rows in the lake | rows in ClickHouse.

[E] Extras
Show the plan before editing. Record this prompt in docs/prompts.md.
Stop at the end.

Step 02 ยท While the agent works

Enrichment and the order of the copies

The agent showed its plan, received the go-ahead and is writing. The next slides explain the concept that the prompt asked for, and the review of the files comes after them.

Theory of this step
  1. Enrichment: normalise, aggregate sources, derive fields
  2. The lake first: the order of the run and the manifest
  3. Auditability: what the SHA-256 and the rebuild prove
Back at the files

Compare the table lake against ClickHouse with the expected counts, then open one Parquet file in the console of RustFS.

Excerpt of prompt 02
- Order of the run: lake, then ClickHouse, then the manifest. ClickHouse
  never holds a row that the lake does not hold.
Step 02 ยท Theory 1
Three operations of enrichment

Enrichment adds to a record what it needs to be used without returning to its source. In the lab it has three operations, each measured in the Bronze of Olist.

Normalise

One format and one unit

23,995 customer and 1,027 seller zip prefixes padded to 5 characters; every timestamp written in ISO 8601 with its offset; two misspelt headers renamed; 610 empty categories as unknown.

Aggregate sources

Join what lives elsewhere

Each order receives customer_state and customer_region from the customers file, and each product receives its category in English from the translation file.

Derive

Fields the business asked for

region from the state, delivery_days and delivered_late for every delivered order, and item_total = price + freight for every item.

Enrichment and the star pull in opposite directionsCopying the region of the customer into every order repeats the same five values 99,433 times. The enriched table accepts that repetition so that one tag answers a question without joins; the star schema of Step 04 keeps the region once, in dim_customer.
Step 02 ยท Theory 2
The lake is written first

The order of the run decides what a failure leaves behind. Writing the lake first means that any failure afterwards leaves ClickHouse behind the lake, never ahead of it.

  1. DuckDB reads the Bronze over httpfs, every column as text, and builds the three columns for every tag.
  2. One Parquet file per tag and day goes to silver/enriched/, with the SHA-256 of its bytes.
  3. ClickHouse is truncated and loaded with its s3() function reading those files, never the Bronze.
  4. The manifest of the run is written with status ok; if ClickHouse fails, with error_clickhouse.
Manifest of a run (excerpt)
{"run_id": "20261105T135218Z_7f349d",
 "status": "ok",
 "rows_lake": 347578, "rows_sent_ch": 347578,
 "seconds": {"enrich": 0.75, "lake": 0.8,
             "clickhouse": 0.85},
 "files": [{"key": "silver/enriched/
   data_tag=olist.order.v1/
   ingestion_date=2026-11-05/data.parquet",
   "rows": 99433, "sha256": "โ€ฆ"}, โ€ฆ]}
Step 02 ยท Numerical example
What the rehearsal measured

Rehearsal on 05/11/2026 with RustFS 1.0.4, DuckDB 2.0.0 and ClickHouse 26.8.15.10. The counts are the expected result of the step; the times change with the machine.

347,578rows in the lake and in ClickHouse, in 6 tags
6Parquet files, one per tag and day
16records in quarantine: 8 orders and their 8 items
2.5 swhole run: 0.8 enrich, 0.8 lake, 0.9 ClickHouse
Proof of origin

Every data_linha carries source_file, so any number of a dashboard can be traced to the Bronze object it came from.

Proof of integrity

The SHA-256 in the manifest is computed on the bytes uploaded. Recomputing it later shows whether a file of the lake was altered.

Proof of reproducibility

A second run overwrites the same keys and rebuilds ClickHouse from the lake, arriving at the same 347,578 rows.

Step 02 ยท Check 1 of 4
Rows per tag in the enriched table

Open http://10.8.8.10:8123/play, the copy of the class on the server shrek2, with the user aluno and the password aluno, which can only read. Play runs one statement at a time, so each slide holds one.

ClickHouse Play ยท one statement ยท Ctrl+Enter
SELECT data_tag, count() AS rows
FROM silver.enriched
GROUP BY data_tag
ORDER BY data_tag;
What comes back
data_tagrows
olist.customer.v199,441
olist.order.v199,433
olist.order_item.v1112,642
olist.product.v132,951
olist.seller.v13,095
quarantine.v116

The total is 347,578 rows, the same count that the manifest of the run records for the lake. Opening the address of ClickHouse without a query returns Empty query, which is not an error of the login.

Step 02 ยท Check 2 of 4
Three records of one tag

The three columns of the contract appear as they are stored: the ingestion date, the tag and the record in JSON.

ClickHouse Play ยท one statement ยท Ctrl+Enter
SELECT data_ingestao, data_tag, data_linha
FROM silver.enriched
WHERE data_tag = 'olist.customer.v1'
LIMIT 3;
What comes back

2026-11-05 00:00:00.000 ยท olist.customer.v1 ยท {"city":"osasco", "customer_id":"00012a2cโ€ฆ", "region":"Southeast", "state":"SP", "zip_prefix":"06273", "source_file":"s3://olist-lake/bronze/โ€ฆ"}

The zip_prefix keeps five characters, with the leading zero that the CSV had lost, and source_file points to the Bronze object that produced the record.

Step 02 ยท Check 3 of 4
Orders per region of the customer

A path of the JSON is read with a dot. Its type is Dynamic, which ClickHouse refuses in GROUP BY until it is cast to a concrete type.

ClickHouse Play ยท one statement ยท Ctrl+Enter
SELECT data_linha.customer_region::String AS region,
       count() AS orders
FROM silver.enriched
WHERE data_tag = 'olist.order.v1'
GROUP BY region
ORDER BY orders DESC;
What comes back
regionorders
Southeast68,259
South14,147
Northeast9,394
Central-West5,782
North1,851

These are all orders, in any status. The question of Step 04 counts only delivered orders, which is why the North drops to 1,796 there.

Step 02 ยท Check 4 of 4
What went to the quarantine

Rejected records stay in the table with the tag quarantine.v1, the entity, the key and the reason, so that no line of the source disappears without a trace.

ClickHouse Play ยท one statement ยท Ctrl+Enter
SELECT data_linha.entity::String AS entity,
       data_linha.reason::String AS reason,
       count() AS records
FROM silver.enriched
WHERE data_tag = 'quarantine.v1'
GROUP BY entity, reason;
What comes back
entityreasonrecords
ordersdelivered without delivery date8
order_itemsorder in quarantine8

The wording of the reason is the one written by the agent in Step 02 and may differ slightly; the counts, 8 orders and their 8 items, may not.

Step 03 ยท 15:00 ยท Audit and lifecycle

Prove every row and choose the clock of the TTL

The agent writes the reconciliation of the two copies, shows that a rerun and a rebuild reach the same counts, and measures what the retention would keep if it counted from the date of the order.

Files

src/reconcile.py and the section "Measured consequences" of the ADR.

Review before moving on
  • Is every tag OK, with 0 SHA-256 mismatches?
  • Did the rebuild read only the lake?
  • Is the window read from the TTL of the table?
  • Does the ADR ask the owner which clock the retention follows?
Prompt 03 ยท CREATE
[C] Character
You are the data engineer responsible for the audit of the Silver layer.
The partner asks two questions before trusting it: can every number be
proved against the lake, and how long will ClickHouse keep the orders?

[R] Request
1. Write src/reconcile.py, run as python -m src.reconcile, which prints
   for each data_tag: rows in the lake, rows in the lake inside the
   retention window of ClickHouse, rows in ClickHouse and OK or DIFF
   (a comparison of counts per tag, not row by row); and
   which checks the SHA-256 of every file listed in the last manifest. It
   exits with a non-zero code on any DIFF or mismatch.
2. Run python -m src.load_hybrid twice and python -m src.reconcile after
   each run, to show that a rerun arrives at the same counts.
3. Drop silver.enriched, recreate it from sql/clickhouse_enriched.sql,
   reload it from the lake only with the function of src/clickhouse.py
   and time the rebuild.
4. Without changing the table, measure how many orders would remain in
   ClickHouse if the TTL counted from purchased_at instead of
   data_ingestao.
5. Append to docs/adr/ADR-002-hybrid-silver.md a section "Measured
   consequences" with the numbers of this run and the question of which
   clock the retention follows, addressed to the owner of the decision.

Facts measured on 05/11/2026 (confirm before use):
- Reconciliation: 6 tags OK, 6 files, 0 SHA-256 mismatches, 0.4 s.
- Rebuild of ClickHouse from the lake: 347,578 rows in about 1 s.
- TTL on data_ingestao keeps every row, because everything was ingested
  on 2026-11-05. A TTL on purchased_at would keep 0 of the 99,433
  orders, because the newest one is from 2018-10-17.
- SHOW CREATE TABLE writes the TTL as toIntervalYear(1), not as
  INTERVAL 1 YEAR.

[E] Example
window of ClickHouse read from the TTL: 1 Year
data_tag                  lake  window  clickhouse
olist.order.v1           99433   99433       99433  OK
quarantine.v1               16      16          16  OK
files=6 sha256_mismatches=0

[A] Adjustments
- The window comes from the TTL of the table (read it from ClickHouse),
  not from a constant copied into the script.
- A tag with more rows in ClickHouse than in the lake is a DIFF,
  whatever the window.
- Bronze stays read-only; load_bronze.py is its only writer.
- Ask before the DROP of step 3.
- Do not change tests to make them pass.

[T] Type of output
The new src/reconcile.py, the output of the two loads, of the
reconciliations and of the rebuild, the count of step 4 and the new
section of the ADR.

[E] Extras
Show the plan before editing. Record this prompt in docs/prompts.md.
Stop at the end.

Step 03 ยท While the agent works

Columnar warehouses and the lifecycle of data

The agent showed its plan, received the go-ahead and is writing. The next slides explain the concept that the prompt asked for, and the review of the files comes after them.

Theory of this step
  1. Redshift and ClickHouse: columnar, distributed warehouses
  2. Inside ClickHouse: MergeTree, partitions, ordering key and TTL
  3. Retention as a business decision
  4. Which clock the retention follows
Back at the files

Read the reconciliation table and the count of step 4 of the prompt: the same rows, two possible windows.

Excerpt of prompt 03
- The window comes from the TTL of the table (read it from ClickHouse),
  not from a constant copied into the script.
Step 03 ยท Theory 1
Two columnar warehouses

Both store each column separately and compressed, so an analytical query reads only the columns it uses. They differ in how they are operated and paid for.

Amazon RedshiftClickHouse
Modelmanaged service of AWS, cluster or serverlessopen source server; also offered as a managed cloud
Storagecolumnar, compressed, distributed across nodes (MPP)columnar, compressed parts of a MergeTree table
Data layoutdistribution key and sort key per tablepartition key and ordering key per table
Lake accessRedshift Spectrum queries Parquet in S3s3() table function queries Parquet in S3
Semi-structuredSUPER type with PartiQLJSON type with typed subcolumns
Materialized viewsrefreshed manually, on a schedule or automaticallyincremental (on insert) or refreshable (on a schedule)
Retentionjobs that delete or unload old dataTTL clause applied by the server during merges

The architecture does not depend on the product: the lake stays the source of truth, and the columnar engine is the fast copy that can be replaced or rebuilt. In this lab ClickHouse plays the role that Redshift would play in an AWS stack.

Step 03 ยท Theory 2
MergeTree, partitions and TTL

Each insert writes an immutable part on disk. Background merges join parts of the same partition, and the TTL clause tells the server which rows to drop while it merges.

sql/clickhouse_enriched.sql
CREATE TABLE silver.enriched
(
    data_ingestao DateTime64(3, 'America/Sao_Paulo'),
    data_tag      LowCardinality(String),
    data_linha    JSON
)
ENGINE = MergeTree
PARTITION BY toYYYYMM(data_ingestao)  -- one month per partition
ORDER BY (data_tag, data_ingestao)    -- filter by tag first
TTL toDateTime(data_ingestao) + INTERVAL 1 YEAR;
What each clause buys
  • PARTITION BY month: a whole month expires as one unit, which makes deletion cheap.
  • ORDER BY tag and time: a query of one tag reads a contiguous range.
  • LowCardinality: six tag values stored as a dictionary.
  • TTL: the server stores it as toIntervalYear(1), so a script that searches for the text INTERVAL 1 YEAR finds nothing.
Step 03 ยท Theory 3
Who decides how long data is kept

The TTL is one line of SQL, but the number in it carries obligations. Engineering informs the decision with cost and speed; the business makes it, and the ADR records it.

Legal and contractual

Minimum and maximum periods

Tax records set periods that sales must be kept, and the LGPD limits how long personal data may be kept. customer_unique_id, the city and the zip prefix identify a customer indirectly, so they are personal data.

Business use

How far back each decision looks

The commercial area compares months; a plan for a new region compares years. A window of one year serves the first and leaves the second to the lake.

Cost

Fast disk against object storage

ClickHouse keeps its data on servers that are always on; the lake keeps Parquet in object storage and pays for compute only when a job runs.

How the lab writes it"Retention of ClickHouse: 1 year. Hypothesis, to validate with the partner. Decided by the business owner of the data, informed by the measured cost of each window." The number may change; the lake keeps the history either way.
Step 03 ยท Theory 4
Which clock the retention follows

The same table, with the same rows, keeps everything or nothing depending on the date that the TTL counts from. The choice belongs to the owner of the decision, and the ADR must state it.

TTL on data_ingestao ยท the lab

99,433 of 99,433 orders kept

Every record entered the platform on 05/11/2026, so a window of one year keeps the whole history of 2016 to 2018 until November 2027. The window measures how recent the delivery is, not how recent the sale is.

TTL on purchased_at ยท measured, not applied

0 of 99,433 orders kept

The newest order is from 17/10/2018. A window of one year counted from the purchase would leave ClickHouse empty, and every question of the case would have to go to the lake.

Consequence for the designA tactical copy of recent sales needs the TTL on the business date; a copy that holds whatever arrived recently, including history loaded late, needs it on the ingestion date. For a dataset that ends in 2018, only the second keeps a copy to query, which is why the lab uses it and writes the question in the ADR.
Step 03 ยท Numerical example
The reconciliation of the two copies

The window is read from the TTL of the table, and every tag is compared inside it. Two loads in a row and a rebuild from the lake reach the same counts.

data_tagLakeLake in windowClickHouseStatus
olist.customer.v199,44199,44199,441OK
olist.order.v199,43399,43399,433OK
olist.order_item.v1112,642112,642112,642OK
olist.product.v132,95132,95132,951OK
olist.seller.v13,0953,0953,095OK
quarantine.v1161616OK
total347,578347,578347,5786 files ยท 0 SHA-256 mismatches
Rebuild testClickHouse was dropped and rebuilt from the 6 files of the lake in about 1 s, and the reconciliation was OK again. The copy can be lost without loss of data, which is what the ADR promised.

Step 04 ยท 15:15 ยท Star schema

A star for the question of the business

The enriched table records what arrived. The commercial area needs a model of the business: the agent designs a star schema, builds it in ClickHouse from the Silver layer with views and materialized views, and checks the answer against the lake.

Files

docs/star_model.md, sql/star_clickhouse.sql, sql/star_duckdb.sql and sql/question.sql.

Review before moving on
  • Is the grain of the fact one order item?
  • Are the dimensions views and only the fact and the aggregate stored?
  • Are sales counted with uniqExact(order_id)?
  • Do the three ways of answering give North 1,796 and Southeast 66,193?
Prompt 04 ยท CREATE
[C] Character
You are a dimensional modeller. The enriched table records what arrived;
the commercial area of Olist needs a model that answers its questions.
You design a star schema, build it in ClickHouse from silver.enriched
with views and materialized views, and build the same star in DuckDB
over the lake to check the answer.

[R] Request
1. docs/star_model.md: the business question "How many sales were made
   each month in the North, compared with the Southeast?", the
   definition of a sale (a delivered order, counted once, in the month of
   purchased_at, in the region of the customer), the grain of the fact
   (one order item), the dimensions and a Mermaid ER diagram of the star.
2. sql/star_clickhouse.sql, database gold:
   - views dim_customer, dim_seller and dim_product over
     silver.enriched, one per tag, with typed columns;
   - view dim_date (date_key yyyymmdd, date, month 'YYYY-MM', quarter,
     year, weekday) generated with numbers(), from 2016-01-01 for 1,096
     days;
   - refreshable materialized view fact_order_item (REFRESH EVERY
     1 HOUR, MergeTree): one row per order item, with order_id,
     order_item_id, date_key, customer_id, seller_id, product_id,
     order_status, price and freight_value, joining the tags
     olist.order_item.v1 and olist.order.v1;
   - refreshable materialized view agg_sales_month_region (DEPENDS ON
     gold.fact_order_item): month, region, orders (distinct order_id),
     items and revenue (sum of price, without freight) of the delivered
     orders.
3. sql/star_duckdb.sql: views enriched (read_parquet of the lake),
   dim_customer, dim_date and fact_order_item in WAREHOUSE_PATH.
4. sql/question.sql: the question answered from agg_sales_month_region,
   one row per month with north, southeast and north as a percentage of
   southeast. Run it, run the same question from fact_order_item and
   from DuckDB over the lake, and compare the three answers and times.

Facts measured on 05/11/2026 (confirm before use):
- dim_customer 99,441, dim_seller 3,095, dim_product 32,951, dim_date
  1,096; fact_order_item 112,642; agg_sales_month_region 107 rows.
- 96,470 delivered orders; North 1,796, Southeast 66,193. Example
  months: 2017-11 North 124, Southeast 5,000; 2018-01 North 135,
  Southeast 4,816; 2018-08 North 73, Southeast 4,690.
- Times: 0.002 s from the aggregate, 0.06 s from the fact with the
  joins, 0.5 s in DuckDB over the lake; the three answers are equal.
- SYSTEM REFRESH VIEW gold.fact_order_item does not refresh the
  aggregate: DEPENDS ON orders only the scheduled refreshes.

[E] Example
CREATE OR REPLACE VIEW gold.dim_customer AS
SELECT data_linha.customer_id::String AS customer_id,
       data_linha.city::String        AS city,
       data_linha.state::String       AS state,
       data_linha.region::String      AS region
FROM silver.enriched
WHERE data_tag = 'olist.customer.v1';

[A] Adjustments
- Dimensions are views; only the fact and the aggregate are stored.
- Parse purchased_at with its offset (parseDateTime64BestEffort with
  'America/Sao_Paulo'), so that the month is the month in Brazil.
- A sale is counted with uniqExact(order_id), never with count() of
  items.
- The percentage returns NULL when the Southeast has no sales in the
  month, never inf or nan.
- The duckdb command line is not installed: run sql/star_duckdb.sql and
  the DuckDB question from Python, with the secret of RustFS created in
  the session.
- After each load, refresh fact_order_item, wait for it, then refresh
  agg_sales_month_region (SYSTEM REFRESH VIEW and SYSTEM WAIT VIEW).
- Mermaid without semicolons in labels.

[T] Type of output
The four files, the rows of every object of gold, the result of the
question and a table source | north | southeast | seconds for the three
ways of answering it.

[E] Extras
Show the plan before editing. Record this prompt in docs/prompts.md.
Stop at the end.

Step 04 ยท While the agent works

From the Silver layer to a star schema

The agent showed its plan, received the go-ahead and is writing. The next slides explain the concept that the prompt asked for, and the review of the files comes after them.

Theory of this step
  1. Dimensional modelling: process, grain, dimensions and facts
  2. The star of the case
  3. How the Silver layer reaches the star
  4. Views and materialized views in ClickHouse
  5. The answer and the three ways of reaching it
Back at the files

Check the rows of every object of gold, then read the answer month by month.

Excerpt of prompt 04
- A sale is counted with uniqExact(order_id), never with count() of
  items.
Step 04 ยท Theory 1
Dimensional modelling in four decisions

Kimball designs a model from a business process and a question, not from the tables of the source. Each decision constrains the next, and the grain is the one that is hardest to change later.

1 ยท Process

Selling

The process measured is the sale of the marketplace: an order placed by a customer, with one or more items from one or more sellers.

2 ยท Grain

One order item

Each row of the fact is one item of one order. A finer grain answers more questions; this one still lets an order be counted once with a distinct count.

3 ยท Dimensions

Who, what, where, when

Customer, seller, product and date describe the context of each item. Region and state live in the dimension, once per customer.

4 ยท Facts

What is measured

price and freight_value add across any dimension. A count of orders does not: it must be distinct, because one order has several items.

Why a star and not 3NF for this questionThird normal form removes redundancy for the systems that write the data. The star accepts some redundancy in the dimensions so that a question needs one join per dimension, which is what a dashboard and an analyst write. 3NF and Data Vault remain valid choices for the Silver layer itself.
Step 04 ยท Theory 2
The star of the case

One fact in the centre and four dimensions around it, all in the database gold of ClickHouse. The numbers are the rows measured in the rehearsal.

fact_order_item112,642 rows ยท one order itemorder_id ยท order_item_id ยท date_keycustomer_id ยท seller_id ยท product_idorder_status ยท price ยท freight_value dim_customer ยท 99,441customer_idcity, state, region dim_date ยท 1,096date_key = yyyymmdddate, month, quarter, year dim_seller ยท 3,095seller_idcity, state, region dim_product ยท 32,951product_idcategory in English, weight dimensions: views ยท fact: materialized view
Step 04 ยท Theory 3
How the Silver layer reaches the star

Each dimension reads one tag of silver.enriched and turns JSON paths into typed columns. The fact joins two tags, items and orders, and takes the date of the purchase in the time zone of Brazil.

Dimension ยท a plain view over one tag
CREATE OR REPLACE VIEW gold.dim_customer AS
SELECT data_linha.customer_id::String AS customer_id,
       data_linha.city::String        AS city,
       data_linha.state::String       AS state,
       data_linha.region::String      AS region
FROM silver.enriched
WHERE data_tag = 'olist.customer.v1';
Fact ยท two tags joined (excerpt)
SELECT i.order_id, i.order_item_id,
       toUInt32(toYYYYMMDD(o.purchased_at)) AS date_key,
       o.customer_id, i.seller_id, i.product_id,
       o.order_status, i.price, i.freight_value
FROM (โ€ฆ WHERE data_tag = 'olist.order_item.v1') AS i
JOIN (SELECT โ€ฆ, parseDateTime64BestEffort(
        data_linha.purchased_at::String, 0,
        'America/Sao_Paulo') AS purchased_at
      โ€ฆ WHERE data_tag = 'olist.order.v1') AS o
  ON i.order_id = o.order_id

The filter by tag goes inside each subquery. Parsing purchased_at over the whole table fails on the rows of other tags, where the path is empty, which the rehearsal met as a CANNOT_PARSE_DATETIME error.

Step 04 ยท Theory 4
Views and materialized views in ClickHouse

A view stores a query; a materialized view stores a result. ClickHouse offers two kinds of materialized view, and only one of them fits a fact that joins two tags of a table that every load truncates.

ViewIncremental materialized viewRefreshable materialized view
Storesonly the querya table, fed on every inserta table, recomputed on a schedule
When it runsat each queryon each block inserted into one source tableREFRESH EVERY 1 HOUR, or SYSTEM REFRESH VIEW
Joinsanyonly inserts into the left table fire itany; the whole query runs again
Truncate and reloadno effectdoes not remove what was computednext refresh replaces the result atomically
In the starthe four dimensionsnot usedfact_order_item and agg_sales_month_region
Trap met in the rehearsalagg_sales_month_region is declared with DEPENDS ON gold.fact_order_item, but a manual SYSTEM REFRESH VIEW of the fact does not refresh the aggregate: the dependency orders only the scheduled refreshes. After a load, refresh the fact, wait for it, then refresh the aggregate.
Step 04 ยท Theory 5
An aggregate made for the question

The aggregate keeps one row per month and region of the customer, 107 rows in all. It answers the dashboard without touching the 112,642 rows of the fact, and it is valid because each order belongs to one month and one region.

sql/star_clickhouse.sql (excerpt)
CREATE MATERIALIZED VIEW gold.agg_sales_month_region
REFRESH EVERY 1 HOUR DEPENDS ON gold.fact_order_item
ENGINE = MergeTree ORDER BY (month, region)
AS
SELECT d.month, c.region,
       uniqExact(f.order_id) AS orders,
       count()               AS items,
       sum(f.price)          AS revenue
FROM gold.fact_order_item AS f
JOIN gold.dim_customer AS c USING (customer_id)
JOIN gold.dim_date     AS d USING (date_key)
WHERE f.order_status = 'delivered'
GROUP BY d.month, c.region;
sql/question.sql
-- How many sales were made each month in the
-- North, compared with the Southeast?
SELECT month,
       sumIf(orders, region = 'North')     AS north,
       sumIf(orders, region = 'Southeast') AS southeast,
       if(southeast = 0, NULL,
          round(100 * north / southeast, 2))
         AS north_pct_of_southeast
FROM gold.agg_sales_month_region
WHERE region IN ('North', 'Southeast')
GROUP BY month
ORDER BY month;

Summing orders across months or regions is correct, because no order is in two cells. Summing it across products would count an order with items of two categories twice; for that question the distinct count must run on the fact.

Step 04 ยท Numerical example 1
North against Southeast, month by month

Delivered orders by month of purchase and region of the customer. The North made 1,796 sales and the Southeast 66,193, so the North is 2.71 % of the Southeast over the whole period.

MonthNorthSoutheastNorth / SE %
2016-09010.00
2016-1051722.91
2017-01174853.51
2017-02551,1034.99
2017-03701,7264.06
2017-04761,5095.04
2017-05822,3313.52
2017-06642,1183.02
2017-07592,6062.26
2017-08982,7553.56
2017-09902,7533.27
MonthNorthSoutheastNorth / SE %
2017-10923,0193.05
2017-111245,0002.48
2017-12983,8182.57
2018-011354,8162.80
2018-021064,4502.38
2018-031204,8242.49
2018-041134,7272.39
2018-05914,8371.88
2018-061004,2792.34
2018-071284,1743.07
2018-08734,6901.56

November and December of 2016 have no delivered orders in these two regions. The share of the North is highest in February and April of 2017, near 5 %, and falls below 2 % in May and August of 2018, while the Southeast grows faster.

Step 04 ยท Numerical example 2
Three ways of answering the same question

The agent answered the question from the aggregate, from the fact with its joins, and from DuckDB over the lake. The three answers are identical, which checks the star against the source of truth.

Source of the answerNorthSoutheastSecondsWho uses it
gold.agg_sales_month_region ยท ClickHouse1,79666,1930.002the dashboard of the commercial area
gold.fact_order_item with the dimensions ยท ClickHouse1,79666,1930.06an analyst who needs another cut
star views in DuckDB over the Parquet of the lake1,79666,1930.47data science and the audit
96,470

delivered orders in the star: the 96,478 of the source minus the 8 in quarantine.

5 regions

Southeast 66,193, South 13,813, Northeast 9,044, Central-West 5,624 and North 1,796.

Freshness

The aggregate is as recent as its last refresh; a load is complete only after the star is refreshed.

Step 04 ยท Gold live 1 of 14
The Gold database

Every object of the star lives in a database of its own, so that Silver and Gold can be read, granted and dropped separately. On shrek2 the professor creates the objects, and the user aluno runs the queries of the charts.

ClickHouse Play ยท one statement ยท Ctrl+Enter
CREATE DATABASE IF NOT EXISTS gold;
What comes back

Ok. and no rows, because a CREATE returns nothing.

Run it once; the next slides create the dimensions, the fact, the aggregate and the report tables inside it.

From here on the statements build the star of Step 04 by hand, in the order of the dependencies: dimensions, fact, aggregate and reports.

Step 04 ยท Gold live 2 of 14
Dimension of the customer, as a view

A view stores only its query, so the dimension is computed from silver.enriched at each use and never falls out of date.

ClickHouse Play ยท one statement ยท Ctrl+Enter
CREATE OR REPLACE VIEW gold.dim_customer AS
SELECT data_linha.customer_id::String        AS customer_id,
       data_linha.customer_unique_id::String AS customer_unique_id,
       data_linha.zip_prefix::String         AS zip_prefix,
       data_linha.city::String               AS city,
       data_linha.state::String              AS state,
       data_linha.region::String             AS region
FROM silver.enriched
WHERE data_tag = 'olist.customer.v1';
What comes back

Ok. and no rows, because a CREATE returns nothing.

Check with SELECT count() FROM gold.dim_customer: 99,441 rows.

The region is kept here once per customer; the fact refers to it through customer_id.

Step 04 ยท Gold live 3 of 14
Dimension of the seller, as a view

The seller has its own region, which the report of the flow between regions compares with the region of the customer.

ClickHouse Play ยท one statement ยท Ctrl+Enter
CREATE OR REPLACE VIEW gold.dim_seller AS
SELECT data_linha.seller_id::String  AS seller_id,
       data_linha.zip_prefix::String AS zip_prefix,
       data_linha.city::String       AS city,
       data_linha.state::String      AS state,
       data_linha.region::String     AS region
FROM silver.enriched
WHERE data_tag = 'olist.seller.v1';
What comes back

Ok. and no rows, because a CREATE returns nothing.

Check with SELECT count() FROM gold.dim_seller: 3,095 rows.

Two dimensions read the same five regions from different tags, which is why the region was derived once, in the Silver layer.

Step 04 ยท Gold live 4 of 14
Dimension of the product, as a view

The category comes in English from the Silver layer; the 610 products without category arrive as unknown.

ClickHouse Play ยท one statement ยท Ctrl+Enter
CREATE OR REPLACE VIEW gold.dim_product AS
SELECT data_linha.product_id::String        AS product_id,
       data_linha.category_en::String       AS category,
       data_linha.weight_g::Nullable(Int64) AS weight_g
FROM silver.enriched
WHERE data_tag = 'olist.product.v1';
What comes back

Ok. and no rows, because a CREATE returns nothing.

Check with SELECT count() FROM gold.dim_product: 32,951 rows.

The weight is Nullable because a few products of the source have no measures.

Step 04 ยท Gold live 5 of 14
Dimension of the date, generated

The calendar does not come from the source: it is generated, one row per day, so that a month without sales still exists as a row.

ClickHouse Play ยท one statement ยท Ctrl+Enter
CREATE OR REPLACE VIEW gold.dim_date AS
SELECT toUInt32(toYYYYMMDD(d))    AS date_key,
       d                          AS date,
       formatDateTime(d, '%Y-%m') AS month,
       toQuarter(d)               AS quarter,
       toYear(d)                  AS year,
       toDayOfWeek(d)             AS weekday
FROM (SELECT toDate('2016-01-01') + number AS d
      FROM numbers(1096));
What comes back

Ok. and no rows, because a CREATE returns nothing.

Check with SELECT count() FROM gold.dim_date: 1,096 days, from 2016-01-01 to 2018-12-31.

The key date_key is the date written as a number, such as 20180115, which the fact computes from purchased_at.

Step 04 ยท Gold live 6 of 14
The fact, one row per order item

The fact is a refreshable materialized view: a table that ClickHouse fills as soon as it is created and recomputes every hour.

ClickHouse Play ยท one statement ยท Ctrl+Enter
CREATE MATERIALIZED VIEW IF NOT EXISTS gold.fact_order_item
REFRESH EVERY 1 HOUR
ENGINE = MergeTree ORDER BY (date_key, order_id, order_item_id)
AS
SELECT i.order_id, i.order_item_id,
       toUInt32(toYYYYMMDD(o.purchased_at)) AS date_key,
       o.customer_id, i.seller_id, i.product_id,
       o.order_status, i.price, i.freight_value
FROM (SELECT data_linha.order_id::String      AS order_id,
             data_linha.order_item_id::UInt16 AS order_item_id,
             data_linha.seller_id::String     AS seller_id,
             data_linha.product_id::String    AS product_id,
             toDecimal64(data_linha.price::Float64, 2)         AS price,
             toDecimal64(data_linha.freight_value::Float64, 2) AS freight_value
      FROM silver.enriched WHERE data_tag = 'olist.order_item.v1') AS i
INNER JOIN
     (SELECT data_linha.order_id::String     AS order_id,
             data_linha.customer_id::String  AS customer_id,
             data_linha.order_status::String AS order_status,
             parseDateTime64BestEffort(data_linha.purchased_at::String,
                                       0, 'America/Sao_Paulo') AS purchased_at
      FROM silver.enriched WHERE data_tag = 'olist.order.v1') AS o
ON i.order_id = o.order_id;
What comes back

Ok. and no rows, because a CREATE returns nothing.

Check with SELECT count() FROM gold.fact_order_item: 112,642 items.

Each subquery filters its tag before parsing, because the paths of an order do not exist in the rows of the other tags.

Step 04 ยท Gold live 7 of 14
The aggregate by month and region

The aggregate answers the question of the business with 107 rows. It depends on the fact, so its scheduled refresh runs after the refresh of the fact.

ClickHouse Play ยท one statement ยท Ctrl+Enter
CREATE MATERIALIZED VIEW IF NOT EXISTS gold.agg_sales_month_region
REFRESH EVERY 1 HOUR DEPENDS ON gold.fact_order_item
ENGINE = MergeTree ORDER BY (month, region)
AS
SELECT d.month AS month, c.region AS region,
       uniqExact(f.order_id) AS orders,
       count()               AS items,
       sum(f.price)          AS revenue
FROM gold.fact_order_item AS f
INNER JOIN gold.dim_customer AS c ON f.customer_id = c.customer_id
INNER JOIN gold.dim_date     AS d ON f.date_key    = d.date_key
WHERE f.order_status = 'delivered'
GROUP BY month, region;
What comes back

Ok. and no rows, because a CREATE returns nothing.

Check with SELECT count() FROM gold.agg_sales_month_region: 107 rows. If it returns 0, the aggregate ran before the fact was ready: run SYSTEM REFRESH VIEW gold.agg_sales_month_region and count again.

After a new load of the Silver layer, run SYSTEM REFRESH VIEW and SYSTEM WAIT VIEW on the fact first and on the aggregate next: a manual refresh does not cascade.

Step 04 ยท Gold live 8 of 14
North against Southeast, month by month

This is the question of the session, answered from the aggregate in a few milliseconds.

ClickHouse Play ยท one statement ยท Ctrl+Enter
SELECT month,
       sumIf(orders, region = 'North')     AS north,
       sumIf(orders, region = 'Southeast') AS southeast,
       if(southeast = 0, NULL,
          round(100 * north / southeast, 2)) AS north_pct_of_southeast
FROM gold.agg_sales_month_region
WHERE region IN ('North', 'Southeast')
GROUP BY month
ORDER BY month;
What comes back
monthnorthsoutheast%
2017-111245,0002.48
2018-011354,8162.80
2018-05914,8371.88
2018-08734,6901.56
total1,79666,1932.71

The query returns 22 months. The guard against a division by zero matters in 2016-09, when the Southeast had a single delivered order and the North none.

Step 04 ยท Gold live 9 of 14
Report table: indicators per month

Each report is one more materialized view over the star, with one row per point of a chart, so the dashboard reads tens of rows instead of the 112,642 of the fact.

ClickHouse Play ยท one statement ยท Ctrl+Enter
CREATE MATERIALIZED VIEW IF NOT EXISTS gold.rpt_kpi_month
REFRESH EVERY 1 HOUR DEPENDS ON gold.fact_order_item
ENGINE = MergeTree ORDER BY month
AS
SELECT d.month AS month,
       uniqExact(f.order_id)    AS orders,
       uniqExact(f.customer_id) AS customers,
       uniqExact(f.seller_id)   AS sellers,
       sum(f.price)             AS revenue,
       round(sum(f.price) / uniqExact(f.order_id), 2) AS avg_ticket
FROM gold.fact_order_item AS f
INNER JOIN gold.dim_date AS d ON f.date_key = d.date_key
WHERE f.order_status = 'delivered'
GROUP BY month;
What comes back

Ok. and no rows, because a CREATE returns nothing.

Check with SELECT count() FROM gold.rpt_kpi_month: 23 months.

The average ticket divides the revenue by the distinct orders, not by the items, because an order with three items is one purchase.

Step 04 ยท Gold live 10 of 14
Chart: revenue and ticket per month

The data of a line chart: one row per month, read in milliseconds.

ClickHouse Play ยท one statement ยท Ctrl+Enter
SELECT month, orders, revenue, avg_ticket
FROM gold.rpt_kpi_month
ORDER BY month;
What comes back
monthordersrevenueticket
2017-01750111,797.92149.06
2017-117,288987,643.58135.51
2018-056,749977,539.82144.84
total96,47013,220,181.73

The best month is 2017-11, with 7,288 delivered orders. The first months of 2016 have one or two orders and show how the marketplace started.

Step 04 ยท Gold live 11 of 14
Report table: revenue by month and category

The category comes from dim_product, so the report joins the fact to two dimensions.

ClickHouse Play ยท one statement ยท Ctrl+Enter
CREATE MATERIALIZED VIEW IF NOT EXISTS gold.rpt_revenue_month_category
REFRESH EVERY 1 HOUR DEPENDS ON gold.fact_order_item
ENGINE = MergeTree ORDER BY (month, category)
AS
SELECT d.month AS month, p.category AS category,
       uniqExact(f.order_id) AS orders,
       count()               AS items,
       sum(f.price)          AS revenue,
       sum(f.freight_value)  AS freight
FROM gold.fact_order_item AS f
INNER JOIN gold.dim_product AS p ON f.product_id = p.product_id
INNER JOIN gold.dim_date    AS d ON f.date_key   = d.date_key
WHERE f.order_status = 'delivered'
GROUP BY month, category;
What comes back

Ok. and no rows, because a CREATE returns nothing.

Check with SELECT count() FROM gold.rpt_revenue_month_category: 1,273 rows.

Summing revenue across months is correct. Summing orders across categories is not, because an order with items of two categories appears in both.

Step 04 ยท Gold live 12 of 14
Chart: the ten categories that sell most

The data of a bar chart, summed over the months of the report table.

ClickHouse Play ยท one statement ยท Ctrl+Enter
SELECT category,
       sum(revenue) AS revenue,
       sum(orders)  AS orders
FROM gold.rpt_revenue_month_category
GROUP BY category
ORDER BY revenue DESC
LIMIT 10;
What comes back
categoryrevenueorders
health_beauty1,233,124.148,647
watches_gifts1,165,897.515,493
bed_bath_table1,023,428.739,272
sports_leisure954,669.337,529
computers_accessories888,609.436,529

The table shows the first five of the ten. Watches sell fewer orders than bed and bath but more revenue, because the ticket is higher.

Step 04 ยท Gold live 13 of 14
Report table: flow between regions

The report crosses the region of the seller with the region of the customer, which needs both dimensions at once.

ClickHouse Play ยท one statement ยท Ctrl+Enter
CREATE MATERIALIZED VIEW IF NOT EXISTS gold.rpt_region_flow
REFRESH EVERY 1 HOUR DEPENDS ON gold.fact_order_item
ENGINE = MergeTree ORDER BY (seller_region, customer_region)
AS
SELECT s.region AS seller_region,
       c.region AS customer_region,
       uniqExact(f.order_id)          AS orders,
       sum(f.price)                   AS revenue,
       round(avg(f.freight_value), 2) AS avg_freight
FROM gold.fact_order_item AS f
INNER JOIN gold.dim_seller   AS s ON f.seller_id   = s.seller_id
INNER JOIN gold.dim_customer AS c ON f.customer_id = c.customer_id
WHERE f.order_status = 'delivered'
GROUP BY seller_region, customer_region;
What comes back

Ok. and no rows, because a CREATE returns nothing.

Check with SELECT count() FROM gold.rpt_region_flow: 23 pairs of regions.

This is the question that the star answers and the enriched table does not: the order of the Silver layer carries the region of the customer, not of the seller.

Step 04 ยท Gold live 14 of 14
Chart: who sells to the North

The data of a matrix or a stacked bar: where the orders of the North came from and what the freight cost.

ClickHouse Play ยท one statement ยท Ctrl+Enter
SELECT seller_region, orders, avg_freight
FROM gold.rpt_region_flow
WHERE customer_region = 'North'
ORDER BY orders DESC;
What comes back
seller_regionordersavg_freight
Southeast1,50935.49
South20346.86
Northeast4544.74
Central-West4327.29

Of the orders of the North, 83.8 % came from sellers of the Southeast. The rows add up to 1,800, not 1,796, because an order with sellers of two regions appears in both rows.

Your turn ยท 1 of 9
Log in to the class server

Open http://10.8.8.10:8123/play and fill in the user aluno and the password aluno at the top right. The user reads silver and gold and creates objects only in the database lab.

shrek2 ยท user aluno ยท one statement ยท Ctrl+Enter
SELECT count() AS rows FROM silver.enriched;
What comes back
rows
347,578

Every object of the group is named with its number, as in lab.g01_โ€ฆ: replace g01 with the number of your group in every statement that follows, because all groups share the same database.

Your turn ยท 2 of 9
A dimension as a normal view, with JSONExtract

JSONExtractString(data_linha, 'state') reads one key of the JSON and returns it as text. There are versions for each type: JSONExtractUInt, JSONExtractFloat, JSONExtractBool.

shrek2 ยท user aluno ยท one statement ยท Ctrl+Enter
CREATE OR REPLACE VIEW lab.g01_dim_customer AS
SELECT JSONExtractString(data_linha, 'customer_id') AS customer_id,
       JSONExtractString(data_linha, 'city')        AS city,
       JSONExtractString(data_linha, 'state')       AS state,
       JSONExtractString(data_linha, 'region')      AS region
FROM silver.enriched
WHERE data_tag = 'olist.customer.v1';
What comes back

Ok. and no rows, because a CREATE returns nothing.

Check with SELECT count() FROM lab.g01_dim_customer: 99,441 customers.

A normal view stores only the query. Each time someone reads it, ClickHouse runs the query again over silver.enriched, so the view is always current and costs the full computation at every use.

Your turn ยท 3 of 9
The fact as a materialized view

The fact joins the items to their orders, one row per order item. As a refreshable materialized view, ClickHouse computes it once, stores the result and recomputes it every hour.

shrek2 ยท user aluno ยท one statement ยท Ctrl+Enter
CREATE MATERIALIZED VIEW IF NOT EXISTS lab.g01_fact_order_item
REFRESH EVERY 1 HOUR
ENGINE = MergeTree ORDER BY (order_id, order_item_id)
AS
SELECT i.order_id, i.order_item_id, o.customer_id, i.seller_id,
       i.product_id, o.order_status, o.purchased_at,
       i.price, i.freight_value
FROM (SELECT JSONExtractString(data_linha, 'order_id')      AS order_id,
             JSONExtractUInt(data_linha, 'order_item_id')   AS order_item_id,
             JSONExtractString(data_linha, 'seller_id')     AS seller_id,
             JSONExtractString(data_linha, 'product_id')    AS product_id,
             JSONExtractFloat(data_linha, 'price')          AS price,
             JSONExtractFloat(data_linha, 'freight_value')  AS freight_value
      FROM silver.enriched WHERE data_tag = 'olist.order_item.v1') AS i
INNER JOIN
     (SELECT JSONExtractString(data_linha, 'order_id')     AS order_id,
             JSONExtractString(data_linha, 'customer_id')  AS customer_id,
             JSONExtractString(data_linha, 'order_status') AS order_status,
             parseDateTimeBestEffort(JSONExtractString(data_linha, 'purchased_at'),
                                     'America/Sao_Paulo')  AS purchased_at
      FROM silver.enriched WHERE data_tag = 'olist.order.v1') AS o
ON i.order_id = o.order_id;
What comes back

Ok. and no rows, because a CREATE returns nothing.

Check with SELECT count() FROM lab.g01_fact_order_item: 112,642 items.

Each subquery filters its tag before extracting the keys, because a key of an order does not exist in the rows of a customer or a product.

Your turn ยท 4 of 9
A report as a normal view

The report answers how many delivered orders and how much revenue each state of the customer had. First as a normal view, which stores only the query.

shrek2 ยท user aluno ยท one statement ยท Ctrl+Enter
CREATE OR REPLACE VIEW lab.g01_v_sales_state AS
SELECT c.state AS state,
       uniqExact(f.order_id)  AS orders,
       round(sum(f.price), 2) AS revenue
FROM lab.g01_fact_order_item AS f
INNER JOIN lab.g01_dim_customer AS c ON f.customer_id = c.customer_id
WHERE f.order_status = 'delivered'
GROUP BY state;
What comes back

Ok. and no rows, because a CREATE returns nothing.

Nothing is computed yet: the view runs only when it is read.

The same query will now be created a second time, as a materialized view, so that the two can be compared.

Your turn ยท 5 of 9
The same report as a materialized view

The query is identical. The difference is in the first two lines: REFRESH EVERY 1 HOUR and an engine to store the result.

shrek2 ยท user aluno ยท one statement ยท Ctrl+Enter
CREATE MATERIALIZED VIEW IF NOT EXISTS lab.g01_mv_sales_state
REFRESH EVERY 1 HOUR
ENGINE = MergeTree ORDER BY state
AS
SELECT c.state AS state,
       uniqExact(f.order_id)  AS orders,
       round(sum(f.price), 2) AS revenue
FROM lab.g01_fact_order_item AS f
INNER JOIN lab.g01_dim_customer AS c ON f.customer_id = c.customer_id
WHERE f.order_status = 'delivered'
GROUP BY state;
What comes back

Ok. and no rows, because a CREATE returns nothing.

ClickHouse computes the 27 states as soon as the view is created and keeps them in a table of its own.

A materialized view of ClickHouse can also be incremental, fed on each insert into one source table; with joins and a table that is reloaded, the refreshable kind is the safe choice.

Your turn ยท 6 of 9
Reading the normal view

Run the report from the normal view and look at the line under the result in Play, which shows the time and the rows read.

shrek2 ยท user aluno ยท one statement ยท Ctrl+Enter
SELECT state, orders, revenue
FROM lab.g01_v_sales_state
ORDER BY revenue DESC
LIMIT 10;
What comes back
stateordersrevenue
SP40,4945,066,562.98
RJ12,3501,759,651.13
MG11,3541,552,481.83
โ€ฆ
timeโ‰ˆ 0.18 s219,138 rows read

To answer, ClickHouse read the fact and the customers again and grouped them, the whole computation for ten rows of result.

Your turn ยท 7 of 9
Reading the materialized view

Run the same report from the materialized view and compare the line under the result with the previous one.

shrek2 ยท user aluno ยท one statement ยท Ctrl+Enter
SELECT state, orders, revenue
FROM lab.g01_mv_sales_state
ORDER BY revenue DESC
LIMIT 10;
What comes back
stateordersrevenue
SP40,4945,066,562.98
RJ12,3501,759,651.13
MG11,3541,552,481.83
โ€ฆ
timeโ‰ˆ 0.005 s54 rows read

The rows are the same, read about 35 times faster, because the result was already stored. The price is freshness: after a new load of the Silver layer, the materialized view shows the old numbers until SYSTEM REFRESH VIEW lab.g01_mv_sales_state, while the normal view is current at once.

Your turn ยท 8 of 9
Where each one lives

The catalogue of ClickHouse shows what each object keeps: a view has no rows of its own, a materialized view has a table behind it.

shrek2 ยท user aluno ยท one statement ยท Ctrl+Enter
SELECT name, engine, total_rows, total_bytes
FROM system.tables
WHERE database = 'lab' AND name LIKE 'g01_%'
ORDER BY name;
What comes back
nameenginetotal_rows
g01_dim_customerViewNULL
g01_fact_order_itemMaterializedView112,642
g01_mv_sales_stateMaterializedView27
g01_v_sales_stateViewNULL

Use a normal view when the result must always be current or is read rarely, as in the dimensions; use a materialized view when the result is read often and can wait for the next refresh, as in the fact and the tables of a dashboard.

Your turn ยท 9 of 9
A report of the group

Each group chooses one question of the business, builds its own dimension, fact and report in lab with the prefix of the group, once as a view and once as a materialized view, and writes the query of the chart.

Late deliveries

Which region of the customer has the highest share of late orders? The order carries delivered_late (Bool) and delivery_days (Int) in olist.order.v1.

Freight by category

In which categories does the freight weigh most against the price? The item carries freight_value, and the product carries category_en in olist.product.v1.

Sellers far from customers

Do sellers of one region sell more to their own region? The seller carries region in olist.seller.v1, and the customer carries it in olist.customer.v1.

Deliver the statements in the order they were run, the result of the chart query and one sentence on why the report was kept as a view or as a materialized view. Objects of other groups must not be dropped; DROP works only inside lab.

15:42 ยท Verification
What closes the lab

Each check has a command and an expected result. The professor runs them on the projector; the groups will run the same checks on their own data.

CheckCommandExpected
every record ends in one tagpython -m src.load_hybrid347,578 rows; 16 in quarantine
lake and ClickHouse agreepython -m src.reconcileOK for every tag inside the window
no file of the lake was alteredsame command0 SHA-256 mismatches
ClickHouse is rebuildabledrop and reload from the lakesame counts, about 1 s
the star is completeSELECT count() FROM gold.fact_order_item112,642 items; 107 rows in the aggregate
the star is freshsystem.view_refresheslast success after the last load
the answer is consistentsql/question.sql and DuckDBNorth 1,796 ยท Southeast 66,193 in both
15:46 ยท Artifact of the week
From the lab to Data Ingestion Structure

The artifact asks each group for an ETL from Object Storage into an OLAP database, documented in Data_Ingestion.md, with a UML component diagram from data collection to the DataAPP. The lab gives a pattern for each criterion.

Criterion on AdaloveWhat the lab showedWhat the group adapts
efficient and appropriate extractionDuckDB reads the Bronze over httpfs, every column as textthe formats and partitions of the partner data
transformations ensuring qualitynormalise, aggregate, derive, quarantine with reasonthe defects measured in the partner data
correct loading into the OLAP databaselake first, ClickHouse from the lake, reconciliation, star refreshedthe OLAP engine and the window agreed with the partner
clear UML component diagramBronze, enrich, lake, ClickHouse, staradd the DataAPP and the sources of the partner
detailed documentationcontract, ADR-002, star model and prompt logthe same documents, with the group's numbers

Weight 6 on Adalove. Follow the Sprint Increment Delivery Checklist of the module.

15:52 ยท Closing
What each group does before Lesson 6

The lab used the orders of Olist. The groups repeat the same structure with the partner data during the week, and can practise first with the payments and reviews that the lab left in the Bronze.

For the artifact
  • the enriched table of the partner data, with the three columns and a tag catalogue
  • the ADR of the copies, with the retention, its clock and its owner written as a hypothesis
  • one question of the partner answered by a star schema, with its grain and dimensions
  • the UML component diagram up to the DataAPP
For Lesson 6
  • a reconciliation of the copies with the counts of the group
  • the questions of the partner classified as tactical or strategic
  • the defects found in the partner data and the tag that receives each one
Support materialThe four prompts, the reference numbers, the raw data and the checklist of the environment are in the reading material and in lab/lesson-5/ of the module.
Self-study
Self-study for this session

Readings and a video assigned on Adalove for week 4. They extend the modelling part of the session: warehouse and mart, fact and dimension tables, and granularity.

Self-study 3 ยท optional

Recent Developments in Data Warehousing

Open-access article on strategic concepts, development approaches and business impact of data warehousing.

aisel.aisnet.orgยท 60 min
Reading material

Lesson 5 material

The theory of each step in depth, the four prompts in full, the reference numbers and the mistakes that agents usually make in this lab.

this module

About this session

Data Warehouses: the hybrid Silver layer ยท 05/11/2026 ยท Prof. Afonso

Learning objective

By the end of the session, students should be able to design the Silver layer of a Data Warehouse for the Olist orders as an enriched table with the data_ingestao, data_linha and data_tag columns, loaded first into a long-lived lake read with DuckDB and then into ClickHouse with a one-year retention, to reconcile both copies, and to build over it a star schema with views and materialized views that answers how many sales the North made each month compared with the Southeast, justifying the grain, the dimensions and the retention.

Session strategy

Practice and theory interleaved. The professor builds the Silver layer and the star schema live with a coding agent in four steps (contract and decision, hybrid load, audit and lifecycle, and star schema), pasting each CREATE prompt over the raw CSV files of Olist, and while the agent works the slides explain the concept that the step implements. Each step ends with a review against counts measured in the rehearsal, and the session closes with the connection to the Data Ingestion Structure artifact.

Session structure

  1. Daily โ€” 15 min
  2. Running case, hybrid architecture, raw data and local environment โ€” 10 min
  3. Step 01: contract of the enriched table and ADR; the Silver layer as a Data Warehouse and the data_ingestao, data_linha and data_tag columns โ€” 15 min
  4. Step 02: enrichment and hybrid load; normalising, aggregating and deriving, and auditability with the lake first โ€” 20 min
  5. Step 03: audit and lifecycle; Redshift and ClickHouse, TTL and the clock of the retention โ€” 15 min
  6. Step 04: star schema over the Silver layer; dimensional modelling, views and materialized views, and the North against the Southeast โ€” 27 min
  7. Verification and the Data Ingestion Structure artifact โ€” 10 min
  8. Closing and self-study โ€” 8 min