Arquitectura de Datos

Data Mesh: Data Products, Characteristics, Contracts, and Consumer Experience

Learn how to engineer a Data Product in Data Mesh: design consumption interfaces (SQL, Parquet, APIs, and events), structure data contracts, organize the four metadata layers, enforce executable SLO validations, and manage schema evolution and versioning without breaking consumers.

Content explored 0%
18px

The indicator keeps the furthest percentage explored; marking the article complete is your choice.

When a Data Type Change Breaks Three Downstream Systems at 07:00 on Monday

In the previous article, we designed the value proposition of the daily-sales data product inside the Sales domain at CommerceFlow. We aligned on who it served (Business Intelligence and Finance) and what its business metrics meant.

Two months after going live, however, an incident occurs that proves good product intentions are not enough without a technical architecture for consumption interfaces, data contracts, and version management.

Late Sunday night, a Sales engineer deploys two well-intentioned tweaks to the table backing daily-sales:

  1. Changes the data type of gross_sales_usd from DECIMAL(14,2) to STRING formatted with a dollar sign ("$12,450.00") because "it looks nicer when exported to a spreadsheet."
  2. Renames the sales_channel column to origination_platform without notifying downstream teams.

At 07:00 UTC on Monday morning, three distinct consumer workflows fail simultaneously:

  • The Finance close report in Amazon Athena crashes with a SQL resolution error because sales_channel no longer exists.
  • The Data Science demand-forecasting pipeline in Python, which reads Apache Parquet files directly from Amazon S3, rejects the string column "$12,450.00" as non-numeric and aborts the weekly model training run.
  • The sales commission job, reading a JSON summary feed, silently parses the renamed field as null and calculates zero commissions.

What was missing? We had not yet engineered the Data Product as a complete architectural unit (an architectural quantum, as defined by Zhamak Dehghani): an autonomous unit with explicit consumption interfaces (output ports), a verifiable technical data contract, multi-layered metadata, executable service-level objective (SLO) checks, and strict schema evolution and versioning rules.

Technical Anatomy of a Data Product: Much More Than a Table on Disk

A common mistake is equating a Data Product with the physical file where rows are stored (such as a folder of Parquet files on S3). In Data Mesh, the physical file is merely an internal storage mechanism; the complete Data Product is an autonomous logical capsule composed of five technical building blocks that live and evolve together:

╔═══════════════════════════════════════════════════════════════════════════════════════╗
║                    TECHNICAL ANATOMY OF THE DATA PRODUCT: daily-sales                 ║
║                              (Owned by the Sales Domain)                              ║
╠═══════════════════════════════════════════════════════════════════════════════════════╣
║                                                                                       ║
║  1. INPUT PORTS                                                                       ║
║     • Operational Sales events / CDC replicas (orders, order_items)                   ║
║     • Peer Data Products (if governed cross-domain enrichment is required)            ║
║                                         │                                             ║
║                                         ▼                                             ║
║  2. INTERNAL TRANSFORMATION & SELF-VALIDATION (Code & Assertions)                     ║
║     • SQL/Python transformation logic + automated contract & quality test suite       ║
║                                         │                                             ║
║                                         ▼                                             ║
║  3. OUTPUT PORTS / CONSUMPTION INTERFACES                                             ║
║     ├── Tabular SQL Port: `sales_dp.daily_sales_v1` (Athena / Glue Data Catalog)      ║
║     ├── Columnar File Port: Partitioned Parquet dataset on S3 (for ML training)       ║
║     └── Event / API Port (optional depending on consumer latency needs)               ║
║                                                                                       ║
║  4. DATA CONTRACT & METADATA                                                          ║
║     • Strict schema, semantics, PII classification, lineage, SLOs (freshness/quality) ║
║                                                                                       ║
║  5. CONTROL & OBSERVABILITY PORT                                                      ║
║     • Live health status, SLO compliance metrics, access auditing (Lake Formation)    ║
╚═══════════════════════════════════════════════════════════════════════════════════════╝

This distinction is fundamental: a single Data Product can expose multiple consumption interfaces (output ports) over the exact same business truth without losing its identity or splitting domain accountability.

Designing Consumption Interfaces: Choosing the Right Output Ports

The consumer experience of a data product depends on letting downstream users and systems read data natively, securely, and with minimal friction. Different consumers have different access patterns: a financial analyst wants declarative SQL, a machine learning engineer training models in Python wants high-throughput partitioned columnar files, and an operational service in a peer domain may need low-latency events or a key-value lookup API.

Compare the four primary consumption interfaces to decide which output ports your data product should expose:

Interface Type (Output Port)Ideal Consumer ProfileLatency & Read PatternPrimary StrengthsCosts and Boundaries to Evaluate
1. Cataloged SQL Table / View (e.g., AWS Glue + Amazon Athena)BI analysts, Finance, cross-domain analytical joinsMinutes to hours; ad-hoc aggregations and JOINsUniversal SQL interface; straightforward column-level governance via tools like AWS Lake FormationUnsuitable for millisecond transactional lookups from a customer-facing web app
2. Columnar Object Files (e.g., Apache Parquet on Amazon S3)Data scientists, batch ML training pipelines (Python/Spark)Batch; high-throughput scans across millions of rowsMaximum throughput and low cost for large-scale AI/ML feature extractionConsumers must resolve paths via the catalog contract rather than hardcoding internal temporary folders
3. Event Stream (e.g., immutable event topics)Reactive microservices, near-real-time fraud or stock alertsSub-second to seconds; continuous pub/sub consumptionDecouples producers and consumers when immediate event reaction is neededHigher operational cost; replaying multi-year history is slower than scanning a columnar table
4. Data API (REST / GraphQL)Operational apps fetching a single record by primary keyMilliseconds; point lookupsFamiliar contract for application developersPoor fit for bulk analytics; paging millions of rows over HTTP is slow and expensive

For our daily-sales data product in the Sales domain—whose primary consumers are Business Intelligence, Finance, and the Demand Forecasting ML pipeline—the optimal design exposes two synchronized output ports backed by the same dataset: a versioned SQL table interface in the catalog (sales_dp.daily_sales_v1) and governed columnar Apache Parquet access for Python ML readers.

Anatomy of a Data Contract and the Four Metadata Layers

We will dedicate Article 15 of this series to advanced Data Contracts implementation, but right now we must understand the role a contract plays inside a Data Product: it is the binding technical and semantic agreement between the owning domain and its downstream consumers.

A well-engineered data product contract specifies five core elements:

  1. Structural schema and strict data types: Every field name, exact data type (DATE, DECIMAL(14,2), STRING), nullability (nullable: false), and formatting rules.
  2. Granularity and logical primary key: Which exact combination of columns uniquely identifies a row (for example, sales_date + country_code + sales_channel + product_category). If uniqueness breaks, downstream JOINs silently multiply revenue numbers.
  3. Business semantics and domain invariants: What each field means and which domain constraints hold true (for example, country_code must match ISO 3166-1 alpha-2; net_sales_usd must never exceed gross_sales_usd).
  4. Operational guarantees (SLAs and SLOs):
    • SLO (Service Level Objective): The measurable technical target for freshness, completeness, and accuracy (for example, "closed daily partitions are published by 04:30 UTC on 99.5% of days").
    • SLA (Service Level Agreement): The organizational commitment defining what happens when an SLO is breached (support channel, maximum incident acknowledgment time by the Sales team, and remediation workflow).
  5. Versioning and compatibility policy: Which changes are allowed within the current major version (v1) and which require publishing a new major version (v2).

To make the product discoverable, self-serviceable, and auditable across the platform, its metadata is structured across four complementary layers:

  • Descriptive metadata: Title, business summary, owning domain, column glossary, and sample SQL queries.
  • Technical metadata: Physical schema, data types, storage format (PARQUET), partition keys (sales_date), and catalog address (sales_dp.daily_sales_v1).
  • Operational metadata (dynamic): Timestamp of the latest successful publish, row count written in the last batch, automated quality test results, and observed freshness latency.
  • Governance and security metadata: Confidentiality tier, PII presence indicator, retention policy, and authorized consumer roles in AWS Lake Formation.

Complete Practical Walkthrough at CommerceFlow: Contract, SQL Interface, Validation, and Consumption of daily-sales

Let us now assemble the concrete technical artifacts for daily-sales (v1) so an incident like our opening Monday-morning failure is caught automatically before ever reaching consumers.

1. Declarative Data Contract and Metadata Descriptor (Educational YAML)

(Important reminder: The YAML file below is an educational structure illustrating how contract and metadata fields fit together. Declaring a guarantee in YAML does not enforce it automatically; as we will see in Step 3, every declared constraint must be backed by executable checks).

# Educational Data Contract & Technical Descriptor: daily-sales-contract-v1.yaml
apiVersion: contracts.commerceflow.io/v1
kind: DataProductContract

productMetadata:
  urn: "urn:commerceflow:dataproduct:sales:daily-sales:v1"
  name: "daily-sales"
  domain: "sales"
  majorVersion: 1
  minorVersion: 2
  patchVersion: 0
  ownerTeam: "sales-core-engineering"
  ownerContact: "sales-dp-owners@commerceflow.internal"

governanceMetadata:
  confidentialityLevel: "INTERNAL_FINANCIAL"
  containsPii: false
  retentionPeriodDays: 2555 # 7 years for financial audit compliance
  accessControlRef: "lakeformation:tag:domain=sales,tier=curated_financial"

interfaces:
  - portName: "athena_sql_v1"
    type: "SQL_TABLE"
    catalog: "aws_glue_datacatalog"
    database: "sales_dp"
    table: "daily_sales_v1"
    storageFormat: "PARQUET"
    locationUri: "s3://commerceflow-data-products-prod/sales/daily_sales/v1/"
    partitionKeys: ["sales_date"]

schemaContract:
  granularity: "One unique row per combination of sales_date, country_code, sales_channel, and product_category."
  primaryKeyColumns: ["sales_date", "country_code", "sales_channel", "product_category"]
  evolutionPolicy: "BACKWARD_COMPATIBLE_ONLY"
  columns:
    - name: "sales_date"
      logicalType: "DATE"
      nullable: false
      description: "UTC calendar date when the order was confirmed."
    - name: "country_code"
      logicalType: "STRING"
      nullable: false
      constraints:
        pattern: "^[A-Z]{2}$"
      description: "ISO 3166-1 alpha-2 country code."
    - name: "sales_channel"
      logicalType: "STRING"
      nullable: false
      constraints:
        allowedValues: ["WEB", "MOBILE_APP", "STORE_POS"]
      description: "Purchase origination channel."
    - name: "product_category"
      logicalType: "STRING"
      nullable: false
      description: "Canonical commercial product category."
    - name: "confirmed_orders_count"
      logicalType: "BIGINT"
      nullable: false
      constraints:
        min: 1
      description: "Total distinct confirmed orders in the segment."
    - name: "gross_sales_usd"
      logicalType: "DECIMAL(14,2)"
      nullable: false
      constraints:
        min: 0.00
      description: "Gross sales in USD prior to promotional discounts."
    - name: "total_discounts_usd"
      logicalType: "DECIMAL(14,2)"
      nullable: false
      constraints:
        min: 0.00
      description: "Total promotional discounts applied in USD."
    - name: "net_sales_usd"
      logicalType: "DECIMAL(14,2)"
      nullable: false
      constraints:
        min: 0.00
      description: "Net commercial sales in USD (gross_sales_usd - total_discounts_usd - cancellations)."

serviceLevelObjectives:
  freshness:
    targetTimeUtc: "04:30"
    maxAllowedDelayMinutes: 60
  completeness:
    minExpectedCountriesPerDay: 4
  supportSla:
    criticalIncidentAckMinutes: 30

2. SQL Interface Definition (sales_dp.daily_sales_v1)

Notice that the public table name includes the major version suffix (_v1). If Sales ever needs to introduce a breaking structural change in v2, daily_sales_v1 and daily_sales_v2 can run side by side during the migration window without breaking existing Amazon Athena queries:

-- Public SQL interface definition registered in AWS Glue Data Catalog
-- and backed by partitioned Apache Parquet files in Amazon S3.

CREATE EXTERNAL TABLE IF NOT EXISTS sales_dp.daily_sales_v1 (
    country_code STRING COMMENT 'ISO 3166-1 alpha-2 storefront country code',
    sales_channel STRING COMMENT 'Origination channel: WEB, MOBILE_APP, STORE_POS',
    product_category STRING COMMENT 'Canonical commercial product category',
    confirmed_orders_count BIGINT COMMENT 'Distinct confirmed orders count',
    gross_sales_usd DECIMAL(14, 2) COMMENT 'Gross sales in USD before discounts',
    total_discounts_usd DECIMAL(14, 2) COMMENT 'Total promotional discounts in USD',
    net_sales_usd DECIMAL(14, 2) COMMENT 'Net commercial sales revenue in USD'
)
COMMENT 'Official Sales Domain Data Product (Contract v1)'
PARTITIONED BY (sales_date DATE)
STORED AS PARQUET
LOCATION 's3://commerceflow-data-products-prod/sales/daily_sales/v1/'
TBLPROPERTIES (
    'data_product_urn' = 'urn:commerceflow:dataproduct:sales:daily-sales:v1',
    'owner_domain' = 'sales',
    'contract_version' = '1.2.0',
    'classification' = 'INTERNAL_FINANCIAL'
);

3. From Promise to Verification: Enforcing the Contract with Python and SQL

A contract that is not automatically verified before publication is just wishful documentation. Before exposing a new daily partition on sales_dp.daily_sales_v1, the internal pipeline of the Sales domain runs an automated contract gate.

Below is a self-contained Python snippet demonstrating how the owning domain validates both schema types (preventing anyone from turning DECIMAL into a formatted STRING or renaming sales_channel) and domain invariants on a candidate batch:

# Self-contained Python snippet (standard library only: decimal and datetime).
# Demonstrates how an owning domain validates a candidate batch against Contract v1
# before publishing it to the daily_sales_v1 output port.

from datetime import date
from decimal import Decimal
from typing import Any

ALLOWED_CHANNELS = {"WEB", "MOBILE_APP", "STORE_POS"}
REQUIRED_COLUMNS = {
    "sales_date": date,
    "country_code": str,
    "sales_channel": str,
    "product_category": str,
    "confirmed_orders_count": int,
    "gross_sales_usd": Decimal,
    "total_discounts_usd": Decimal,
    "net_sales_usd": Decimal,
}


def validate_daily_sales_contract_v1(rows: list[dict[str, Any]]) -> list[str]:
    """Returns a list of Contract v1 violations. An empty list means the batch is valid."""
    errors: list[str] = []
    seen_primary_keys: set[tuple[Any, ...]] = set()

    if not rows:
        return ["Completeness violation: candidate batch is empty (0 rows)."]

    for index, row in enumerate(rows):
        # 1. Verify presence and strict type of every column in Contract v1
        for col_name, expected_type in REQUIRED_COLUMNS.items():
            if col_name not in row or row[col_name] is None:
                errors.append(f"Row {index}: missing required column '{col_name}'.")
                continue
            if not isinstance(row[col_name], expected_type):
                actual_type = type(row[col_name]).__name__
                errors.append(
                    f"Row {index}: '{col_name}' expected {expected_type.__name__}, "
                    f"got {actual_type} ({row[col_name]!r})."
                )

        if errors:
            continue

        # 2. Verify composite primary key uniqueness (promised granularity)
        pk = (
            row["sales_date"],
            row["country_code"],
            row["sales_channel"],
            row["product_category"],
        )
        if pk in seen_primary_keys:
            errors.append(f"Row {index}: duplicate primary key for segment {pk}.")
        seen_primary_keys.add(pk)

        # 3. Verify Sales domain semantic and accounting constraints
        if row["sales_channel"] not in ALLOWED_CHANNELS:
            errors.append(f"Row {index}: invalid sales_channel '{row['sales_channel']}'.")
        if row["net_sales_usd"] < Decimal("0.00"):
            errors.append(f"Row {index}: negative net_sales_usd ({row['net_sales_usd']}).")
        if row["net_sales_usd"] > row["gross_sales_usd"]:
            errors.append(
                f"Row {index}: net_sales_usd ({row['net_sales_usd']}) "
                f"exceeds gross_sales_usd ({row['gross_sales_usd']})."
            )

    return errors


# Quick verification test across a valid batch and the broken Sunday-night batch
valid_batch = [
    {
        "sales_date": date(2026, 11, 6),
        "country_code": "MX",
        "sales_channel": "WEB",
        "product_category": "ELECTRONICS",
        "confirmed_orders_count": 145,
        "gross_sales_usd": Decimal("18500.00"),
        "total_discounts_usd": Decimal("1200.00"),
        "net_sales_usd": Decimal("17300.00"),
    }
]

broken_batch = [
    {
        "sales_date": date(2026, 11, 6),
        "country_code": "MX",
        "origination_platform": "WEB",      # Bug: renamed sales_channel without notice
        "product_category": "ELECTRONICS",
        "confirmed_orders_count": 145,
        "gross_sales_usd": "$18,500.00",    # Bug: changed Decimal to formatted '$' str
        "total_discounts_usd": Decimal("1200.00"),
        "net_sales_usd": Decimal("17300.00"),
    }
]

assert validate_daily_sales_contract_v1(valid_batch) == []
assert len(validate_daily_sales_contract_v1(broken_batch)) == 2

With this check wired into the Sales publication pipeline, broken_batch is blocked immediately before touching sales_dp.daily_sales_v1, protecting Finance and Data Science from Monday-morning outages.

4. Consumer Experience and Operational Status via JSON

Beyond querying the SQL table, programmatic consumers (such as an automated ML training job) can inspect the product's control and operational metadata port in JSON to verify that today's partition passed all quality checks and met its freshness SLO before kicking off downstream training:

{
  "dataProductUrn": "urn:commerceflow:dataproduct:sales:daily-sales:v1",
  "contractVersion": "1.2.0",
  "latestAvailablePartition": "2026-11-06",
  "lastPublishedAtUtc": "2026-11-07T04:12:08Z",
  "sloStatus": {
    "freshnessCompliant": true,
    "observedDelayMinutes": 12,
    "qualityAssertionsPassed": true,
    "failedChecksCount": 0
  },
  "outputPorts": {
    "athenaSqlTable": "sales_dp.daily_sales_v1",
    "s3ParquetPartitionUri": "s3://commerceflow-data-products-prod/sales/daily_sales/v1/sales_date=2026-11-06/"
  }
}

Schema Evolution and Versioning: Compatible vs. Breaking Changes

Business requirements evolve continuously, and a Data Product must neither freeze in stone nor break downstream consumers on every update. To balance agility and stability, apply semantic versioning (MAJOR.MINOR.PATCH) to the data product contract:

Type of Data Product ChangeBackward-Compatible?Version BumpedHow It Must Be Managed
Fix an internal calculation bug without altering schema or agreed semanticsYesPATCH (1.2.0 → 1.2.1)Deploy transparently and log the fix in the product changelog.
Append a new nullable/optional column (e.g., loyalty_orders_count)YesMINOR (1.2.0 → 1.3.0)Update daily_sales_v1 in place; consumers listing explicit columns (SELECT col1, col2) continue running without changes.
Rename or drop an existing column (e.g., sales_channel → origination_platform)No (Breaking Change)MAJOR (1.x → 2.0.0)Publish a new daily_sales_v2 interface and keep daily_sales_v1 active throughout the announced deprecation window.
Change a column's data type (e.g., DECIMAL → STRING)No (Breaking Change)MAJOR (1.x → 2.0.0)Forbidden inside the current major version; requires a new column or v2 interface.
Change granularity or semantic meaning (e.g., switch from UTC day to local time, or include shipping fees inside net_sales_usd)No (Breaking Change)MAJOR (1.x → 2.0.0)Even if SQL syntax does not fail, the semantic contract is broken; introduce a new column or cut v2.

(Practical tip for consumers: To ensure MINOR additive updates never break downstream jobs, production consumers should avoid SELECT * and always project required columns explicitly).

Three Real-World Scenarios with Different Product Design Decisions

Let us see how output port, contract, and versioning choices adapt to different enterprise scenarios.

Scenario 1: Real-Time Credit Risk Engine vs. Quarterly Regulatory Audit

  • Context: At a lending platform, the CreditRisk domain produces borrower creditworthiness evaluations (credit-assessments). It serves two consumers with opposite access patterns: the mobile loan checkout service (needs a single customer's latest assessment in under 40 milliseconds) and the Regulatory Compliance team (needs to run SQL aggregations across millions of historical evaluations over the past quarter).
  • Interface design decision: Rather than creating two disconnected data products maintained by separate pipelines, the CreditRisk domain owns a single Data Product exposing two output ports:
    1. A low-latency key-value / API port indexed by customer_id for the operational loan service.
    2. A columnar analytical SQL port (credit_risk_dp.assessments_v1 over Parquet in S3 and Athena) for regulatory analytics.
  • Key takeaway: A Data Product is defined by its semantic boundary and domain ownership, not restricted to a single physical read engine.

Scenario 2: Customs Regulation Overhaul in Freight Logistics (Migrating v1 to v2)

  • Context: An international freight operator publishes customs_dp.import_declarations_v1, reporting duties in a single customs_duty_usd column keyed by shipment declaration ID. A new customs law mandates reporting tariff line items individually with environmental levies and anti-dumping surcharges, changing the table's primary key from one row per declaration to one row per tariff line item.
  • Versioning decision: Because the granularity (primary key) changed, simply adding columns to v1 would break every downstream JOIN. The domain publishes customs_dp.import_declarations_v2 in parallel, marks v1 as DEPRECATED in the catalog with a 90-day sunset date, and migrates its three registered consumers before decommissioning v1.

Scenario 3: Private Intermediate Staging Table Inside One Team (When Simple Is Enough)

  • Context: Inside the Inventory engineering team, a developer creates an intermediate staging table tmp_aisle_rebalance_calc that is only read ten minutes later by the next step of the same internal nightly job. Someone suggests authoring a public YAML data contract, setting a 30-minute on-call SLA, creating versioned _v1 views, and registering it in the company-wide catalog.
  • Recommended decision: Keep it as a private internal table. Public data contracts, multi-port versioning, and consumer SLAs exist for public output ports that cross domain boundaries. Imposing full external product ceremony on private intermediate tables inside a single team adds friction with zero benefit.

Production Readiness Checklist for Publishing a Data Product

Before promoting any Data Product to production in your catalog, verify these six readiness criteria:

  1. Verifiable identity and owner: Does it have a unique URN, semantic version (1.0.0), accountable domain team, and active support channel?
  2. Decoupled from internal operational models: Does the public schema hide internal surrogate keys, ORM join tables, synthetic QA records, and transient application states?
  3. Explicit contract and granularity: Is it documented what a single row represents, which columns form the unique key, and what every attribute means unambiguously?
  4. Active automated assertions: Are executable checks wired into the pipeline to halt publication if a batch is empty, contains duplicate keys, or violates numeric bounds?
  5. Governed access control: Are columns classified by sensitivity and authorized by role (for example, in AWS Lake Formation) before opening read access?
  6. Realistic SLO commitments: Does the promised refresh schedule align with the actual cadence of upstream operational sources?

Practical AI Prompts to Design Contracts and Audit Consumer Experience

Use these two prompts when authoring a technical Data Product contract or assessing the impact of a proposed schema change.

Prompt 1: Generating a Data Contract, Versioned SQL Interface, and Validation Suite

Act as a data architect specializing in Data Products and Data Contracts. I need to design the v1 technical specification for a new Data Product so it is ready for production publication.

Product context:
- Owning domain: [E.G., Payments]
- Data Product name: [E.G., confirmed-payments]
- Exact granularity (what one row represents): [E.G., One settled payment record per order]
- Business columns to expose: [LIST COLUMNS AND MEANINGS]
- Target consumer profiles: [E.G., Finance SQL analysts and Python ML pipelines]
- Required refresh cadence: [E.G., Hourly]

Constraints:
- Do not leak internal operational table details.
- Clearly separate the declarative contract from the executable assertions that enforce it.

Expected output:
1. Structured YAML technical contract (metadata, granularity, logical primary key, data types, domain constraints, and SLOs).
2. Versioned SQL `CREATE EXTERNAL TABLE` statement (`_v1`) with semantic column comments.
3. Four executable SQL assertion queries that the domain pipeline must run to verify uniqueness, completeness, and consistency prior to publishing each batch.

What a human must verify when reviewing the output: Ensure monetary columns use fixed-precision DECIMAL types (never binary floating-point FLOAT or DOUBLE, which introduce rounding errors) and verify that the declared primary key is genuinely unique against real production data.

Prompt 2: Assessing Whether Proposed Schema Changes Break a Contract (Compatibility Analysis)

Act as a data contract guardian on a Data Mesh platform. The owning team of a production Data Product wants to deploy several changes to its schema and calculation logic. Classify each change and define a safe rollout plan that will not break downstream consumers.

Current contract state (v1.3.0):
- Current granularity: [DESCRIBE CURRENT PRIMARY KEY]
- Current columns and types: [PASTE CURRENT SCHEMA]
- Known active consumers: [DESCRIBE WHO QUERIES THE TABLE]

Proposed changes:
1. [DESCRIBE CHANGE 1, E.G., Add an optional column]
2. [DESCRIBE CHANGE 2, E.G., Change column formula to exclude taxes]
3. [DESCRIBE CHANGE 3, E.G., Rename a column or change its type]

Expected output:
1. Classification of each change into PATCH, MINOR (backward-compatible), or MAJOR (breaking change), explaining what would fail in downstream consumers if deployed in place on v1.
2. Recommended technical strategy for each change (what can ship in `v1.4.0` vs. what requires a new column or `v2.0.0` interface).
3. Consumer communication and deprecation plan.

What a human must verify when reviewing the output: Watch closely for silent semantic breaking changes (where column names and data types stay identical, but the business formula changes): always treat those as MAJOR breaking changes or introduce a new explicitly named column.

Application Exercises

Test your technical design judgment across these three practical Data Product scenarios.

Exercise 1: Classifying Four Changes to the daily-sales Contract

The Sales domain team operates sales_dp.daily_sales_v1 (version 1.2.0) in production. For the upcoming sprint, they propose four modifications:

  • Modification A: Append a new column refunded_orders_count BIGINT at the end of the table (nullable for historical partitions).
  • Modification B: Change the formula of net_sales_usd starting tomorrow so that it also includes shipping fees charged to the buyer, while keeping the column name net_sales_usd.
  • Modification C: Fix an internal timestamp boundary bug where orders confirmed at exactly 23:59:59 UTC were accidentally excluded due to a < operator instead of <=.
  • Modification D: Add warehouse_id to the grouping key of the table, so there are now multiple rows per date, country, channel, and category (one per fulfillment warehouse).

Question: Classify each of the four modifications as PATCH, MINOR, or MAJOR (Breaking Change) and justify your answer.

Exercise 2: Selecting the Right Output Ports for inventory-availability

CommerceFlow's Inventory domain is designing its stock availability data product. During consumer discovery, three requirements emerge:

  1. Business Intelligence needs to join two years of daily closing stock snapshots with daily sales using SQL in Amazon Athena.
  2. Data Science needs to read 365 days of historical stock rotation features in bulk from Python to train a replenishment model.
  3. The Sales domain needs to be notified within 5 seconds whenever sellable stock for a high-demand SKU drops to 0 so the storefront can display an "Out of Stock" badge immediately.

Question: Why is a single nightly SQL table insufficient to satisfy all three requirements, and what combination of output ports should the Inventory domain expose?

Exercise 3: Catching "Paper Guarantees" During a Production Readiness Review

A team in the Payments domain submits their new payments_dp.settled_payments_v1 data product for production release. They proudly present a neatly formatted contract.yaml file declaring:

  • containsPii: false
  • primaryKey: [payment_id]
  • freshnessMaxDelayMinutes: 15

When you inspect the actual implementation, however, you discover that: (1) the public table includes unmasked cardholder_full_name and payer_phone_number columns; (2) there are zero automated validation queries or tests in their pipeline; and (3) the scheduled job runs only once a day at 23:00 UTC.

Question: Identify the three severe gaps between the declared contract and technical reality, and specify the concrete mechanisms that must be put in place before approving publication.


Reasoned Solutions

Solution to Exercise 1

  • Modification A (MINOR, version 1.3.0): Appending a new optional column while preserving existing columns and types is an additive, backward-compatible change (provided consumers project columns explicitly).
  • Modification B (MAJOR / Breaking Change): Even though the column name net_sales_usd and type DECIMAL(14,2) remain unchanged, altering the underlying business formula to include shipping fees breaks the semantic contract. Financial reports comparing prior months (excluding shipping) against new months (including shipping) will report distorted revenue growth. It requires either adding a new explicit column (net_sales_incl_shipping_usd) or publishing v2.
  • Modification C (PATCH, version 1.2.1): Fixes an implementation bug so the product accurately fulfills its original specification ("all orders confirmed on that UTC calendar day") without changing schema or semantics.
  • Modification D (MAJOR / Breaking Change, version 2.0.0): Adding warehouse_id to the grouping key changes the granularity and primary key of the table. Any downstream consumer joining on (sales_date, country_code, sales_channel, product_category) expecting a unique row will now suffer fan-out row multiplication across warehouses. It requires a separate data product or a v2 interface.

Solution to Exercise 2

A nightly batch SQL table works well for historical analysis, but its 24-hour latency cannot notify the storefront within 5 seconds when an item sells out.

The Inventory domain should expose two coordinated output ports from its data product:

  1. Columnar Analytical & SQL Port (inventory_dp.daily_stock_v1): Stored as partitioned Apache Parquet files on Amazon S3 and registered in AWS Glue. This single port satisfies both BI (querying via SQL in Amazon Athena) and Data Science (reading Parquet partitions directly from Python at high throughput).
  2. State-Change Event Port (inventory.stockout.events.v1): An event stream emitting a message whenever sellable units for a product_sku cross a critical threshold (such as reaching 0), enabling the Sales storefront to react in seconds without coupling to Inventory's internal database.

Solution to Exercise 3

The team fell into the "paper guarantees" trap—treating a static YAML file as if writing text enforced reality:

  1. Unaddressed PII exposure: They declared containsPii: false while exposing full cardholder names and phone numbers. They must either strip those columns if unnecessary for analytical use cases, or set containsPii: true and enforce column-level masking/authorization policies in AWS Lake Formation.
  2. Missing executable contract checks: They declared primaryKey: [payment_id] with zero verification. They must wire an automated assertion into their pipeline verifying COUNT(*) = COUNT(DISTINCT payment_id) before any batch is published.
  3. Unachievable freshness SLO: Promising a 15-minute maximum delay in YAML while scheduling the job once every 24 hours misleads consumers. They must either re-architect the pipeline to run every 10–15 minutes with active staleness alerts, or update the contract to honestly declare a daily (24-hour) refresh cadence.

Decision Criteria for Applying What You Learned and Final Summary

Before marking any Data Product ready for production, apply these engineering criteria:

  • Decouple the logical product from physical storage: Expose output ports (SQL, columnar files, events, or APIs) tailored to how your consumers actually work.
  • Turn every contract promise into an automated test: If your contract promises key uniqueness, non-negative amounts, or freshness SLOs, enforce those promises via automated pre-publish assertions that block defective batches.
  • Enforce disciplined versioning: Treat public schemas and column semantics with the same rigor as a production API—use additive MINOR updates when possible, and publish a parallel v2 interface whenever structure, types, or granularity must change.

Of course, if every domain team had to build its own custom engine to parse YAML contracts, provision S3 storage, register Glue catalog versions, run quality assertions, and configure Lake Formation permissions from scratch, domain teams would collapse under infrastructure toil. How do we make building, validating, and publishing a Data Product fast and repeatable? That is the mission of the third pillar of Data Mesh, which we will explore in the next article: Self-Serve Data Platform.

Loading conversation…

Keep learning