In lesson 01-04, before choosing a single technology, DataCorp wrote down six use cases. Since then they have served as the yardstick: every storage, management and processing decision was justified by what one of them needed. It is time to close the loop and walk through them end to end, from the source to the decision.
The walkthrough serves two purposes. The first is validation: if a use case cannot be traced all the way through the architecture, a piece is missing, and it is better to find out now than in production. The second is method: the six cases are described with the same sheet, which at the end of the lesson remains as a reusable template for any future analytical case.
Each case is presented with its question and the decision it enables, the type of analysis, the data it uses, its freshness, a representative code fragment and the piece of the architecture that makes it possible. The sample figures that do not come from October 2026 are illustrative.
UC-01: daily net sales
| Question and decision | How much did we sell yesterday, by category and city, and how are we doing against the target? It lets the company react within days, not at month-end close: boost a category, review a city |
| Type of analysis | Descriptive |
| Summary lineage | orders, order_lines, customers, products (replica) → raw → cleansed → fact_sales and dimensions → daily_net_sales, daily_orders |
| Freshness and mode | D+1 before 07:00; daily batch (nightly_load_sales, 01:15) |
| Metrics and consumer | net_sales, valid_orders, avg_order_value, cancellation_rate; management committee, in dashboard.sales |
-- Yesterday's net sales by category and city (management dashboard)
SELECT category, city, net_sales
FROM consumption.daily_net_sales
WHERE sales_date = DATE '2026-11-17'
ORDER BY net_sales DESC;The query is trivial, and that is the news. All the complexity (incremental extraction, deduplication, business date, status filter, SCD of the city) was solved upstream and tested with the DQ rules. What makes it possible: the dimensional model (lesson 02-05), the aggregate table (04-06) and the single definition of the metric (ADR-014). It is the case that settles the October dispute: €2,828,429.75, the same figure for everyone.
UC-02: campaign profitability
| Question and decision | Which campaigns return the most sales per euro invested? It lets the advertising budget be reallocated |
| Type of analysis | Descriptive, with diagnostic use |
| Summary lineage | marketing/campaigns and marketing/campaign_results → dim_campaign, fact_campaigns; orders.campaign_code → fact_sales.campaign_sk → daily_campaigns |
| Freshness and mode | D+1; daily batch (nightly_load_marketing, 04:00) |
| Metrics and consumer | campaign_cost, attributed_net_sales, roas; Marketing (Nuria Vidal, Dani), in dashboard.campaigns |
The case depends on attribution: deciding which orders are due to which campaign. ADR-008 set the rule (last click with a 7-day window, recorded in orders.campaign_code) and the conformed dimension dim_campaign, which makes it possible to join sales and costs.
SELECT campaign_code,
channel,
SUM(cost_amount) AS campaign_cost,
SUM(attributed_net_sales) AS attributed_sales,
ROUND(SUM(attributed_net_sales) / NULLIF(SUM(cost_amount), 0), 2) AS roas
FROM consumption.daily_campaigns
WHERE campaign_date >= DATE '2026-11-23' AND campaign_date < DATE '2026-11-30'
GROUP BY campaign_code, channel
ORDER BY roas DESC;ROAS is calculated as a quotient of sums, never by averaging the daily ROAS values (lesson 05-03). With the sample figures from that lesson, NAV26-EMAIL returns 12.00; BF26-ELECTRO, 4.50, and BF26-HOGAR, 2.70, for an overall 4.08.
What makes it possible: master data management (ADR-008) and conformed dimensions. Two limits must be shown on the dashboard: orders prior to the campaign_code column have no attribution, and ROAS measures sales, not margin. Another attribution rule (first click, linear split) would give other results: the rule is a business decision, and that is why it has an owner.
UC-03: stockout alert
| Question and decision | Which products are going to run out before the replenishment arrives? It lets the order to the supplier be brought forward or stock be moved between warehouses |
| Type of analysis | Simple prescriptive: a rule that triggers an action |
| Summary lineage | ERP API → erp/stock/ → current_stock; fact_sales → avg_product_demand |
| Freshness and mode | 15 minutes at most; micro-batch every 10 minutes (frequent_stock) |
| Metrics and consumer | Days of cover; the evaluate_stock_alerts task (an application), Purchasing and warehouses, in dashboard.stock |
The rule uses cover: how many days the stock will last at the current rate of sale.
-- current_stock(product_id, warehouse, stock, read_time)
-- avg_product_demand(product_id, units_per_day): average units sold
-- per day over the last 28 days, recalculated every night
SELECT cs.product_id,
SUM(cs.stock) AS total_stock,
d.units_per_day,
ROUND(SUM(cs.stock) / NULLIF(d.units_per_day, 0), 1) AS days_of_cover
FROM consumption.current_stock cs
JOIN consumption.avg_product_demand d ON d.product_id = cs.product_id
GROUP BY cs.product_id, d.units_per_day
HAVING SUM(cs.stock) / NULLIF(d.units_per_day, 0) < 7 -- alert threshold
ORDER BY days_of_cover;- The 7-day threshold is the usual replenishment lead time (5 days) plus a margin of 2. It is a business parameter, owned by Tomás Herrero.
- Average demand is calculated once every night, not every 10 minutes: the frequent query only joins two small tables and finishes in seconds, within the 3 minutes that ADR-010 allows it.
NULLIFavoids dividing by zero; products with no recent sales do not generate an alert.
Example: vacuum cleaner 3301 has 18 units across the three warehouses and sells 6 a day: 3 days of cover, alert.
What makes it possible: the stock micro-batch and the decision to serve it from the same consumption store (lesson 02-01). One limit: orders do not record which warehouse they ship from, so the cover is global and not per warehouse. Another: 28 days of sales do not anticipate a peak such as Black Friday; that is what UC-06 will contribute.
UC-04: conversion funnel
| Question and decision | At which step of the purchase do visitors drop off? It lets improvements to the website and the app be prioritized |
| Type of analysis | Descriptive, with diagnostic use |
| Summary lineage | Topic clickstream.events → clickstream/events/ → cleansed → fact_web_events → daily_funnel |
| Freshness and mode | Events at most 1 hour old (15-minute micro-batches); sessions and funnel, in batch (ADR-010) |
| Metrics and consumer | conversion_rate and step-through rates; Marketing and Product, in dashboard.funnel |
A funnel counts how many sessions reach each step of a journey. The events carry no session identifier: it has to be built with the rule from lesson 04-03 (a session ends after 30 minutes of inactivity).
WITH flagged AS ( -- 1. does this event open a new session?
SELECT customer_id, event_time, event_type,
CASE WHEN event_time - LAG(event_time) OVER
(PARTITION BY customer_id ORDER BY event_time)
<= INTERVAL '30' MINUTE
THEN 0 ELSE 1 END AS opens_session
FROM consumption.fact_web_events
WHERE "date" = DATE '2026-11-17' -- partition pruning
AND customer_id IS NOT NULL
),
numbered AS ( -- 2. number each customer's sessions
SELECT *, SUM(opens_session) OVER
(PARTITION BY customer_id ORDER BY event_time) AS session_num
FROM flagged
),
per_session AS ( -- 3. which steps did each session reach?
SELECT customer_id, session_num,
MAX(CASE WHEN event_type = 'product_view' THEN 1 ELSE 0 END) AS viewed,
MAX(CASE WHEN event_type = 'add_to_cart' THEN 1 ELSE 0 END) AS added,
MAX(CASE WHEN event_type = 'checkout_start' THEN 1 ELSE 0 END) AS started_checkout,
MAX(CASE WHEN event_type = 'purchase' THEN 1 ELSE 0 END) AS purchased
FROM numbered
GROUP BY customer_id, session_num
)
SELECT COUNT(*) AS sessions, -- 4. the funnel
SUM(viewed) AS with_view,
SUM(viewed * added) AS with_cart,
SUM(viewed * added * started_checkout) AS with_checkout_start,
SUM(viewed * added * started_checkout * purchased) AS with_purchase
FROM per_session;- Step 1:
LAGgets the same customer's previous event. If more than 30 minutes have passed, or there is no previous one (the result isNULLand theELSEapplies), the event opens a session. - Step 2: the running total of those flags numbers the sessions: 1, 1, 1, 2, 2...
- Step 3: one row per session, with a 1 for each step reached.
- Step 4: multiplying the indicators requires having reached all the previous steps.
Sample output: 50,000 sessions, 40,000 with a product view, 8,000 with a cart, 2,800 with a checkout start and 1,400 with a purchase. Conversion is 2.8%, and the actionable finding is a different one: half of those who start checkout do not finish it.
What makes it possible: the event log, the daily partitioning of the clickstream (ADR-004) and the micro-batches. The case also uncovers a gap: events without a customer_id, from unidentified visitors, are left out. A visitor identifier is needed in the event, which means changing the contract with the website team and reviewing the cookie consent. The query, simplified, does not check the order of the steps either, nor does it join sessions that cross midnight.
UC-05: issue reasons in tickets
| Question and decision | Why do customers write to us? It lets the cause be tackled (a carrier, a defective product) instead of answering ticket by ticket |
| Type of analysis | Diagnostic, on unstructured data |
| Summary lineage | Support API → support/tickets/ → cleansed.tickets (with description) → classification → fact_tickets (with reason, without description) |
| Freshness and mode | D+1; daily batch (nightly_load_support, 02:00) |
| Metrics and consumer | Tickets by reason, tickets per 100 orders; Customer Support (Rosa Molina, Pilar), in dashboard.issues |
The description is free text classified as restricted: it may contain addresses, phone numbers or health data that the customer wrote without anyone asking for it. The architectural solution is that the text does not travel: its classification does. A process with the svc_load identity reads the text in the cleansed zone and publishes only the reason to consumption.
import unicodedata
# Reason -> keywords (without accents and in lowercase). The order sets the priority.
RULES = {
"late_delivery": ["has not arrived", "delay", "not received", "tracking"],
"defective_product": ["broken", "defective", "does not work", "faulty", "won't turn on"],
"return_refund": ["return", "send it back", "refund", "reimburse"],
"billing": ["invoice", "charge", "charged twice", "vat"],
}
def normalize(text: str) -> str:
"""Convert to lowercase and strip accents to compare without surprises."""
unaccented = unicodedata.normalize("NFKD", text.lower())
return "".join(c for c in unaccented if not unicodedata.combining(c))
def classify(subject: str, description: str) -> str:
"""Return the first reason whose keywords appear in the ticket."""
text = normalize(f"{subject} {description}")
for reason, keywords in RULES.items():
if any(keyword in text for keyword in keywords):
return reason
return "other"
print(classify("Order 9005", "The vacuum cleaner arrived yesterday and DOES NOT WORK, I want to return it"))
# defective_product (it matches two rules; the first one in order wins)normalizedecomposes each accented letter into letter and accent mark (NFKD) and discards the accent marks, so that "café" and "cafe" match.classifygoes through the rules in order and returns the first reason that fits. The order is a business decision: a product that does not work and that the customer wants to return is counted as a defect, which is the cause."other"collects whatever no rule recognizes. Its size is the indicator of the classifier's quality.
A classifier like this is rudimentary, but transparent, cheap and enough to get started. Its quality is measured: every month Pilar reviews a sample of 200 tickets, and at least 85% accuracy and less than 20% in "other" are required. If that is not achieved, the next step is a text classification model, which would occupy the same place in the flow. Sample breakdown of the 12,400 tickets of one month: late deliveries 35%, returns 24%, defective product 18%, other 15% and billing 8%.
What makes it possible: the raw zone, which keeps the original text (ADR-002), column-level permissions (lesson 03-04) and Python in the pipeline (ADR-011).
UC-06: demand forecast
| Question and decision | How many units of each product will be sold in the next four weeks? It lets the company buy in time and in the right quantity |
| Type of analysis | Predictive |
| Summary lineage | fact_sales, dim_date, dim_product, fact_daily_inventory, dim_campaign → demand_forecast |
| Freshness and mode | Weekly; weekly batch (ADR-010) |
| Metrics and consumer | Forecast units and forecast error; Purchasing, and the UC-03 rule |
Before any model, you have to set a baseline: the simplest forecast that is reasonable. It serves as a reference: a model that does not beat it does not deserve its complexity. For sales with a weekly cycle, a good baseline is "next Monday will sell the average of the last four Mondays".
import pandas as pd
# 'series': units sold per day of one product, indexed by date (pandas Series)
def forecast_baseline(series: pd.Series, days: int = 28) -> pd.Series:
"""Forecast by day of the week: average of the last 4 weeks."""
last_weeks = series.iloc[-28:] # 4 full weeks
mean_by_weekday = last_weeks.groupby(last_weeks.index.dayofweek).mean()
future = pd.date_range(series.index[-1] + pd.Timedelta(days=1), periods=days)
return pd.Series(mean_by_weekday.loc[future.dayofweek].to_numpy(), index=future)
def pct_error(actual: pd.Series, predicted: pd.Series) -> float:
"""Total absolute error over actual sales, as a percentage."""
return 100 * (actual - predicted).abs().sum() / actual.sum()
# Honest evaluation: the last 28 days are forecast WITHOUT using them, and compared
train, test = series.iloc[:-28], series.iloc[-28:]
predicted = forecast_baseline(train)
print(f"Baseline error: {pct_error(test, predicted):.1f}%")groupby(last_weeks.index.dayofweek)groups the 28 days by day of the week (0 = Monday) and calculates the average of each.date_rangegenerates the future dates, and each one is assigned the average of its day of the week.- The evaluation sets aside the last 28 days, predicts them without having seen them and measures the error. Evaluating with the same data used to calculate the forecast would give a misleadingly low error.
Going from here to a machine learning model requires four things of the architecture:
| Need | What it involves | Status at DataCorp |
|---|---|---|
| History | At least two or three years, with several Black Fridays and Christmas seasons, and stable definitions | Available: orders are kept for 6 years (RQ-09) |
| Features | Calendar and holidays, price, active campaigns and, above all, days without stock: if there was no stock, sales do not measure demand | Partial: fact_daily_inventory and dim_campaign are planned; the price history does not exist |
| Environment | Notebooks and compute separate from the dashboards, tracking of experiments and of which data was used | Does not exist; it will be sized when the case is prioritized |
| Deployment | Orchestrated weekly run, results in consumption.demand_forecast with the model version, error monitoring and retraining |
Fits in the current orchestrator (ADR-012) |
What makes it possible: for now, the decision to keep the detail and the history in open formats. UC-06 remains low priority: the baseline can be calculated already, and the model will wait until the case is prioritized and the data allows it.
Summary: use cases and architecture components
| Case | Sources | Mode | Consumption tables | Tool | Key decisions |
|---|---|---|---|---|---|
| UC-01 | PostgreSQL | Daily batch | fact_sales, daily_net_sales, daily_orders |
BI dashboard | ADR-001, 009, 014 |
| UC-02 | Marketing, PostgreSQL | Daily batch | fact_campaigns, dim_campaign, daily_campaigns |
BI dashboard | ADR-008, 014 |
| UC-03 | ERP, PostgreSQL | 10-minute micro-batch | current_stock, avg_product_demand |
Alert task and dashboard | ADR-007, 010 |
| UC-04 | Clickstream | 15-minute micro-batch and batch | fact_web_events, daily_funnel |
BI dashboard, SQL | ADR-004, 010, 011 |
| UC-05 | Tickets | Daily batch | fact_tickets |
Python in the pipeline, dashboard | ADR-002, 006, 011 |
| UC-06 | All of the above | Weekly batch | demand_forecast |
Python notebooks | ADR-002, 004, 013 |
The table can be read in three ways. All the cases share the same layers (ingestion, three zones, orchestration, governance) and differ in very little. No component exists without a case that justifies it. And the cases build on one another: UC-03 will improve with UC-06, and the metric tree of UC-01 needs the conversion from UC-04.
Template for specifying an analytical use case
The six cases have been described with the same fields. Turned into a template, they ensure that any future request reaches the data team complete and comparable.
# governance/use_cases/UC-XX.yaml
id: UC-XX
name: <short name>
requester: <person and department>
owner: <who is accountable for the result>
priority: <high | medium | low>
question: <the business question, in one sentence>
decision: <what will be done differently depending on the answer>
analysis_type: <descriptive | diagnostic | predictive | prescriptive>
metrics: [<glossary terms; new ones are registered>]
dimensions: [<what it is filtered and broken down by>]
sources: [<source systems>]
consumption_tables: [<existing or new, with their grain>]
freshness: <maximum acceptable age of the data>
processing_mode: <daily batch | micro-batch | continuous streaming>
history_needed: <how much of the past is required>
consumers: [<profiles, number of users, tool>]
personal_data: <yes/no; classification and measures>
success_criterion: <how we will know it has been useful>
known_limits: [<what the case does not cover>]The most neglected fields are decision (a case without a decision should not be built), freshness (it determines the processing mode and, with it, the cost) and success_criterion (without it you cannot know whether the case has worked).
Typical cases in other industries
The patterns repeat across every industry; the sources and the constraints change.
| Industry | Use case | Type | Dominant architectural demand |
|---|---|---|---|
| Banking | Payment fraud detection | Predictive and prescriptive | Continuous streaming with a response in milliseconds; traceability of every decision |
| Banking | Regulatory risk reporting | Descriptive | Complete, auditable lineage; figures reproducible as of a given date |
| Healthcare | Bed occupancy and waiting times | Descriptive and predictive | Integration of many clinical systems; special category data |
| Healthcare | Analysis of treatment outcomes | Diagnostic | Strict pseudonymization and purpose-based access control |
| Manufacturing | Predictive maintenance of machines | Predictive | Streaming ingestion from sensors; large volumes of time series |
| Manufacturing | Production quality control | Descriptive and diagnostic | Low latency on the shop floor; joining machine data with ERP data |
Warning. Use cases with personal data (such as the text of the tickets or the clickstream) and those in regulated industries (banking, healthcare) have legal implications. Their design must be reviewed by the data protection officer or the compliance officer before they are built.
Common Mistakes and Tips
- Use cases without a decision. "We want a ticket dashboard" is not a use case. What will be decided with it?
- Asking for real time by default. Only UC-03 needs minutes. Every step up in freshness is paid for in cost and complexity.
- Starting with the flashiest case. The demand forecast looks better than daily sales, but it depends on them.
- Skipping the baseline. Without it, you do not know whether a model adds anything.
- Taking the sensitive data all the way to the analyst when a derivative, such as the ticket reason, is enough.
- Ignoring the limits of the case. Partial attribution, anonymous visitors, global cover: whatever is not documented ends up being misinterpreted.
- Building one table per request. Before creating one, check whether an existing one answers the question.
- Tip: walk through each new case from the source to the decision before building it; the gaps show up on paper.
- Tip: review the cases after six months against their success criterion. Those that have not changed any decision are candidates for retirement.
Exercises
Exercise 1: Specifying a use case
Operations requests a new case: knowing which products are returned the most and why, in order to stop selling the problematic ones. Fill in the question, decision, analysis_type, metrics, consumption_tables, freshness, processing_mode and known_limits fields of the template.
Exercise 2: Funnel by device
State what you would change in the funnel query to obtain a funnel by device type (device_type), and what decision would have to be made about the sessions.
Exercise 3: Which piece is missing?
For each request, state which component of the architecture is missing or has to change:
- Marketing wants the funnel to include unregistered visitors.
- Finance wants the margin per campaign, not just the ROAS.
- Purchasing wants the stock alert per warehouse.
Solutions
Exercise 1
question: Which products have an abnormal return rate, and for what reason?
decision: Review with the supplier, or remove from the catalog, the products that exceed the threshold
analysis_type: diagnostic
metrics: [units, returned_units, product_return_rate] # the last two are new
consumption_tables: [fact_sales, dim_product, fact_tickets]
freshness: D+1
processing_mode: daily batch
known_limits:
- A return takes days to be recorded, so the rate for the last month is incomplete
- The reason is only known if the customer opened a ticket linked to the orderKey points: the return rate per product is a ratio (returned units divided by units sold) and is registered as an official metric with an owner (Tomás Herrero). No new source is needed: fact_sales already stores the returned status, and fact_tickets provides the reason through order_id. Common mistake: comparing rates without requiring a minimum number of units; a product with 2 sales and 1 return has a 50% rate that means nothing.
Exercise 2
You have to add device_type to the first expression, carry it through to per_session and group by it in the final query. The pending decision is what to do with a session that uses two devices. The simplest option, and the most consistent, is to include the device in the definition of a session: PARTITION BY customer_id, device_type in the two window functions, so that mobile and computer are separate sessions. It has to be documented, because the total number of sessions will change slightly compared with the global funnel.
Exercise 3
- A visitor identifier is missing in the event: a change in the data contract with the website team, a new column in the cleansed clickstream and a review of the consent.
- A source is missing: the acquisition cost of the products, which is in the ERP and is not ingested. It requires a new integration, a cost measure in
fact_salesand a margin metric. - The shipping warehouse is missing from the orders, or at least the demand per warehouse. Until then, only the global cover can be calculated.
The three cases show the same thing: what limits an analysis is almost never the tool, but a piece of data that is not captured at the source.
Conclusion
DataCorp's six use cases span the four types of analysis and put the whole architecture to the test. Daily net sales come down to a trivial query because the complexity was solved upstream; campaign profitability depends on an attribution rule and a conformed dimension; the stock alert, on a micro-batch and a cover rule; the funnel, on rebuilding sessions over millions of events; the issue reasons, on classifying a text without exposing it; and the demand forecast, on a baseline and a history that the platform already keeps. Described with the same sheet, the cases become comparable, their gaps are in plain view and the sheet becomes the template with which any future analysis will be requested.
This lesson brings Module 5 to a close. DataCorp now knows how it is going to analyze its data: which types of analysis it needs and for whom, with which tools, with which official metrics defined in one place, how they are communicated in governed dashboards and how each use case crosses the platform from the source to the decision. However, we have built the architecture piece by piece without yet giving it a name or an overall shape: we talk about "the analytical platform" and "the analytical engine" without having decided what they are. Is it a data lake, a data warehouse or something in between? Which engine will run the queries? That is what Module 6 is about, devoted to modern data architectures, which begins with the concept that gave rise to all of them: Big Data.
