Arquitectura de Datos

Data Mesh: End-to-End Architecture of a Data Product, From Source to Consumption

Learn how to design the end-to-end technical architecture of a Data Product in Data Mesh, from operational capture and decoupled transformation to preventive validation and governed publication.

Content explored 0%
18px

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

When the Sales domain team at CommerceFlow was tasked with publishing its first Source-Aligned data product (sales-orders), they took what looked like the fastest shortcut: they configured an extraction job that copied the orders and order_items tables from their operational PostgreSQL database every hour into an Amazon S3 folder as Apache Parquet files, registered that folder in AWS Glue Data Catalog, and shared the link across the company announcing: "Our Data Product is live in production."

Within two weeks, three production incidents proved why dumping a raw replica of an operational database into S3 is not building a Data Product:

  1. Tight coupling to internal schemas: A Sales developer renamed the internal column disc_cents to promo_discount_bps in PostgreSQL to support percentage-based coupons. The extraction job replicated the change automatically and immediately broke the Finance and Marketing pipelines.
  2. Retry duplicates and ghost deletes: A transient network glitch caused the extraction job to retry an hourly batch, writing a second Parquet file containing 1,400 duplicate orders. Furthermore, when technical support physically deleted (DELETE) twenty test orders in the operational database, those rows remained alive forever inside older Parquet files in S3, inflating quarterly sales metrics.
  3. Dirty mid-run reads: While the transformation job was writing the day's files at 09:00 UTC, an analyst ran a query in Amazon Athena at 09:02 UTC and read only half of that hour's orders, sending an inaccurate report to executive leadership.

This story captures the central challenge of this article: for a data product to be trustworthy, decoupled, and governable, it needs an end-to-end architecture that cleanly separates internal capture, semantic transformation, preventive validation (Write-Audit-Publish), and the public consumption interface.


End-to-End Architectural Anatomy of a Data Product

A Data Product is not a static file sitting in an object storage bucket; it is an autonomous architectural quantum that encapsulates data, transformation code, metadata, quality checks, and access policies.

The diagram below traces the complete technical journey of the sales-orders product inside the Sales domain boundary, supported by CommerceFlow's self-serve data platform:

┌─────────────────────────────────────────────────────────────────────────┐
│                          DOMAIN BOUNDARY: SALES                         │
│                                                                         │
│ 1. Private Operational Source (PostgreSQL: core_monolith_pg)            │
│    [Internal tables: tbl_orders, tbl_order_items]                       │
│                           │                                             │
│                           ▼ (Incremental extraction / CDC events)       │
│ 2. Private Ingestion Zone (Internal S3 - Forbidden to consumers)        │
│    s3://cf-sales-internal/raw_cdc/orders/                               │
│                           │                                             │
│                           ▼ (Deduplication, canonical projection,       │
│                              line-item aggregation & delete handling)   │
│ 3. Candidate / Staging Zone (Write-Audit-Publish)                       │
│    s3://cf-sales-internal/staging/sales_orders_candidate/               │
│                           │                                             │
│                           ▼                                             │
│ 4. Preventive Gate (Quality & Contract Gate)                            │
│    [Verifies: unique PK, non-nulls, monetary math, valid schema]        │
│          │                                           │                  │
│     (If failed)                                (If approved)            │
│          ▼                                           ▼                  │
│   [Alert #sales-alerts                   5. Public Output Port          │
│    and abort publication]                   s3://cf-sales-public/       │
│                                             sales_orders/ (Parquet)     │
└──────────────────────────────────────────────────────┼──────────────────┘
                                                       │
         ┌─────────────────────────────────────────────┘
         ▼ (Shared Platform & Consumption Plane)
┌─────────────────────────────────────────────────────────────────────────┐
│ - Technical Registry & Schema: AWS Glue Data Catalog (sales_prod)       │
│ - Fine-Grained Authorization: AWS IAM + AWS Lake Formation (LF-Tags)    │
│ - Analytical SQL Querying: Amazon Athena                                │
└─────────────────────────────────────────────────────────────────────────┘

Why Separate Internal Zones from the Public Interface (Without Enforcing Bronze/Silver/Gold)

Notice that the architecture above contains two private zones inside the domain (Private Ingestion and Candidate Staging) and a single Public Output Port:

  • Internal zones are a private implementation detail of the domain: No external squad or consumer holds permissions in AWS IAM or AWS Lake Formation to read s3://cf-sales-internal/. This allows the Sales team to refactor its operational tables in PostgreSQL without breaking any downstream consumer, provided the transformation projects the same public contract.
  • There is no need to expose three public layers (Bronze, Silver, Gold): Unlike a traditional Data Lake where analysts are invited to query raw or intermediate zones, a Data Product exposes to the corporate catalog only the verified dataset that passes the preventive quality gate.
Architectural ResponsibilityDomain Team (Sales)Self-Serve Data PlatformConsumers (Payments, Finance, BI)
Source & ingestionSelects source tables and defines the incremental key or CDC stream.Provides reusable connectors and encrypted S3 storage.Never access the operational database or private ingestion bucket.
Transformation & qualityWrites the SQL/Python decoupling logic and defines business quality thresholds.Executes the preventive validation engine (Write-Audit-Publish) and halts faulty deployments.Consume public freshness and quality status metrics in the catalog.
Publication & accessDeclares the public schema, column classifications, and authorized consumers in the YAML manifest.Registers the version in AWS Glue Data Catalog and enforces grants in AWS Lake Formation / IAM.Query the public output port via Amazon Athena using standard SQL.

Step-by-Step Walkthrough: Designing the Architecture of sales-orders

Let's walk through each technical stage required to build sales-orders end to end while preventing the three production incidents the team experienced on its first attempt.

Step 1: Operational Source Analysis and Capture Strategy

Inside the Sales domain's operational PostgreSQL database, an order is split across two internal tables optimized for low-latency transactions:

  • tbl_orders: stores internal_id (BIGINT, e.g., 98412), cust_id (451200), st_code (SMALLINT: 1=CART, 2=CONFIRMED, 3=FULFILLED, 9=CANCELLED), curr ('USD'), tax_cents (1200), disc_cents (500), created_ts, and updated_ts.
  • tbl_order_items: stores order line items with order_internal_id, sku_code, qty, and unit_price_cents.

Whether we use incremental extraction based on updated_ts or Change Data Capture (CDC—whose detailed comparison we will cover in Article 18), every state change in PostgreSQL lands an event record in the private ingestion zone carrying three technical control attributes:

  • cdc_op: 'I' (insert), 'U' (update), or 'D' (hard delete in source).
  • cdc_sequence_num: monotonically increasing transaction sequence number.
  • extracted_at_utc: exact capture timestamp.

Step 2: Decoupling Transformation, Deduplication, and Tombstone Handling

The domain's transformation engine reads the captured events from the private zone and builds the candidate dataset by applying four critical architectural rules:

  1. Deterministic deduplication: If a network retry produced duplicate records or if an order changed state three times within the last hour, we select only the latest state using ROW_NUMBER() OVER (PARTITION BY internal_id ORDER BY cdc_sequence_num DESC).
  2. Explicit deletion handling (tombstones): If a test order was physically deleted in the source database (cdc_op = 'D'), we do not leave the old row active; we filter it out of valid commercial orders or mark it explicitly.
  3. Semantic and type translation: We format internal_id into the canonical global identifier ORD-000098412, translate numeric st_code values into human-readable lifecycle states (CHECKOUT_COMPLETED, FULFILLED, CANCELLED), and convert integer cents into DECIMAL(18,4).
  4. Physical partitioning: We derive the partition column order_placed_date_utc (DATE) so query engines like Amazon Athena scan only the Parquet files for the requested dates.
-- Transformation building the sales-orders candidate dataset (Staging Zone)
-- Purpose: Decouple internal PostgreSQL schemas, deduplicate CDC events,
-- aggregate order line items, and project the interoperable public contract.

WITH deduplicated_orders_header AS (
    SELECT
        internal_id,
        cust_id,
        st_code,
        curr,
        tax_cents,
        disc_cents,
        created_ts,
        updated_ts,
        cdc_op,
        ROW_NUMBER() OVER (
            PARTITION BY internal_id
            ORDER BY cdc_sequence_num DESC, extracted_at_utc DESC
        ) AS row_rank
    FROM sales_internal_staging.raw_orders_cdc
),

active_orders_header AS (
    SELECT *
    FROM deduplicated_orders_header
    WHERE row_rank = 1
      -- Exclude source hard deletes (cdc_op = 'D') and unsubmitted carts (st_code = 1)
      AND cdc_op <> 'D'
      AND st_code IN (2, 3, 9)
),

order_items_aggregated AS (
    SELECT
        order_internal_id,
        COUNT(DISTINCT sku_code) AS distinct_sku_count,
        SUM(qty) AS total_units_quantity,
        -- Select primary_sku_code deterministically
        MIN(sku_code) AS primary_sku_code,
        SUM(CAST(qty * unit_price_cents AS DECIMAL(18,4)) / DECIMAL '100.0000') AS net_merchandise_amount
    FROM sales_internal_staging.raw_order_items_latest
    GROUP BY order_internal_id
)

SELECT
    -- Canonical CommerceFlow global identifiers
    CONCAT('ORD-', LPAD(CAST(h.internal_id AS VARCHAR), 9, '0')) AS order_id,
    CONCAT('CUS-', LPAD(CAST(h.cust_id AS VARCHAR), 9, '0')) AS customer_id,
    i.primary_sku_code,
    i.distinct_sku_count,
    i.total_units_quantity,
    -- Normalized UTC timestamps
    CAST(h.created_ts AT TIME ZONE 'UTC' AS TIMESTAMP) AS order_placed_at_utc,
    CAST(h.updated_ts AT TIME ZONE 'UTC' AS TIMESTAMP) AS order_last_updated_at_utc,
    -- Standardized monetary amounts in DECIMAL(18,4) + ISO-4217 currency_code
    UPPER(h.curr) AS currency_code,
    i.net_merchandise_amount,
    CAST(h.disc_cents AS DECIMAL(18,4)) / DECIMAL '100.0000' AS discount_amount,
    CAST(h.tax_cents AS DECIMAL(18,4)) / DECIMAL '100.0000' AS tax_amount,
    (
        i.net_merchandise_amount
        - (CAST(h.disc_cents AS DECIMAL(18,4)) / DECIMAL '100.0000')
        + (CAST(h.tax_cents AS DECIMAL(18,4)) / DECIMAL '100.0000')
    ) AS gross_order_amount,
    -- Translation of internal numeric codes to the domain's public vocabulary
    CASE h.st_code
        WHEN 2 THEN 'CHECKOUT_COMPLETED'
        WHEN 3 THEN 'FULFILLED'
        WHEN 9 THEN 'CANCELLED'
        ELSE 'UNKNOWN_STATE'
    END AS order_lifecycle_status,
    -- Physical partition column (low daily cardinality)
    CAST(DATE_TRUNC('day', h.created_ts AT TIME ZONE 'UTC') AS DATE) AS order_placed_date_utc
FROM active_orders_header AS h
INNER JOIN order_items_aggregated AS i
    ON h.internal_id = i.order_internal_id;

Step 3: Write-Audit-Publish (WAP) Publication Flow in Python

To prevent consumers from reading half-written files or corrupted batches, the architecture implements the Write-Audit-Publish (WAP) pattern:

  1. Write (in private): The transformation writes Parquet files to an isolated candidate path (s3://cf-sales-internal/staging/sales_orders_candidate/run_20261107_1900/).
  2. Audit (preventively): An automated validator inspects the candidate batch, verifying primary key uniqueness, non-null constraints, monetary math reconciliation, and freshness.
  3. Publish (atomically): Only if every check passes does the pipeline promote the partition or update the metadata pointer in AWS Glue Data Catalog / transactional table metadata so that it becomes visible on the public port.

The following Python script is self-contained (Python 3.10+) and demonstrates the exact logic of the audit-and-publish gate:

# File: publish_gate_sales_orders.py
# Purpose: Implement the preventive audit stage of the Write-Audit-Publish (WAP) pattern
# prior to exposing a new update of the 'sales-orders' Data Product to consumers.

from dataclasses import dataclass
from decimal import Decimal
from typing import Any


@dataclass(frozen=True)
class QualityGateResult:
    passed: bool
    checked_rows: int
    failures: list[str]
    published_location: str | None


def execute_write_audit_publish_gate(
    candidate_rows: list[dict[str, Any]],
    staging_uri: str,
    public_port_uri: str,
) -> QualityGateResult:
    failures: list[str] = []

    if not candidate_rows:
        failures.append("[WAP-EMPTY-001] Candidate batch is empty (0 rows).")
        return QualityGateResult(False, 0, failures, None)

    seen_order_ids: set[str] = set()
    allowed_statuses = {"CHECKOUT_COMPLETED", "FULFILLED", "CANCELLED"}

    for idx, row in enumerate(candidate_rows):
        oid = row.get("order_id")

        # 1. Primary key uniqueness and non-null check (Grain: order_id)
        if not oid:
            failures.append(f"[WAP-PK-002] Row {idx} has a null or empty 'order_id'.")
        elif oid in seen_order_ids:
            failures.append(f"[WAP-DUP-003] Duplicate primary key detected for order_id='{oid}'.")
        else:
            seen_order_ids.add(oid)

        # 2. Lifecycle status integrity check
        status = row.get("order_lifecycle_status")
        if status not in allowed_statuses:
            failures.append(
                f"[WAP-STAT-004] Order '{oid}' contains an unmapped lifecycle status: '{status}'."
            )

        # 3. Monetary arithmetic invariant: gross = net_merchandise - discount + tax
        try:
            net_merch = Decimal(str(row["net_merchandise_amount"]))
            discount = Decimal(str(row["discount_amount"]))
            tax = Decimal(str(row["tax_amount"]))
            gross = Decimal(str(row["gross_order_amount"]))

            expected_gross = net_merch - discount + tax
            if gross != expected_gross or gross < Decimal("0.0000"):
                failures.append(
                    f"[WAP-MATH-005] Monetary mismatch in '{oid}': "
                    f"gross={gross} != expected={expected_gross}."
                )
        except (KeyError, ValueError, TypeError) as exc:
            failures.append(f"[WAP-TYPE-006] Numeric type error in '{oid}': {exc}")

    # Publication decision: if any check fails, abort promotion to the public port
    if failures:
        return QualityGateResult(
            passed=False,
            checked_rows=len(candidate_rows),
            failures=failures,
            published_location=None,
        )

    # If all checks pass, promote the candidate batch to the governed public location
    return QualityGateResult(
        passed=True,
        checked_rows=len(candidate_rows),
        failures=[],
        published_location=public_port_uri,
    )


# --- Verification assertions for the Write-Audit-Publish gate ---
if __name__ == "__main__":
    staging_path = "s3://cf-sales-internal/staging/sales_orders_candidate/run_01/"
    public_path = "s3://cf-sales-public/sales_orders/"

    # Case 1: Clean, reconciled batch -> Approved and published
    clean_batch = [
        {
            "order_id": "ORD-000098412",
            "customer_id": "CUS-000451200",
            "currency_code": "USD",
            "net_merchandise_amount": "142.9900",
            "discount_amount": "5.0000",
            "tax_amount": "12.0000",
            "gross_order_amount": "149.9900",
            "order_lifecycle_status": "CHECKOUT_COMPLETED",
        },
        {
            "order_id": "ORD-000098413",
            "customer_id": "CUS-000451201",
            "currency_code": "USD",
            "net_merchandise_amount": "50.0000",
            "discount_amount": "0.0000",
            "tax_amount": "9.5000",
            "gross_order_amount": "59.5000",
            "order_lifecycle_status": "FULFILLED",
        },
    ]
    res_ok = execute_write_audit_publish_gate(clean_batch, staging_path, public_path)
    assert res_ok.passed is True
    assert res_ok.published_location == public_path

    # Case 2: Batch with a retry-induced duplicate and arithmetic mismatch -> Blocked
    corrupted_batch = [
        clean_batch[0],
        clean_batch[0],  # Duplicate of ORD-000098412
        {
            **clean_batch[1],
            "order_id": "ORD-000098414",
            "gross_order_amount": "999.9900",  # Mismatch with net - discount + tax
        },
    ]
    res_fail = execute_write_audit_publish_gate(corrupted_batch, staging_path, public_path)
    assert res_fail.passed is False
    assert res_fail.published_location is None
    assert any("[WAP-DUP-003]" in f for f in res_fail.failures)
    assert any("[WAP-MATH-005]" in f for f in res_fail.failures)
    print("WAP Gate verified successfully. Blocked failures:", res_fail.failures)

Step 4: Comprehensive Data Product Architectural Descriptor in YAML

All the components above (source, private zones, transformation, WAP quality checks, public storage, catalog, and access controls) come together in the architectural descriptor sales-orders-architecture.yaml:

# File: sales-orders-architecture.yaml
# Purpose: End-to-end architectural specification of the 'sales-orders' Data Product.
data_product:
  id: "sales.sales_orders"
  name: "sales-orders"
  domain: "sales"
  orientation: "source_aligned"
  version: "1.4.0"
  owner_email: "sales-dpo@commerceflow.internal"
  oncall_channel: "#sales-data-alerts"

input_ports:
  - source_id: "core_monolith_pg_orders"
    source_type: "postgresql_operational"
    ingestion_mode: "incremental_cdc"
    schedule_cron: "0 * * * *"  # Hourly execution at minute 0
    private_landing_uri: "s3://cf-sales-internal/raw_cdc/orders/"

internal_processing:
  staging_uri: "s3://cf-sales-internal/staging/sales_orders_candidate/"
  deduplication_key: ["internal_id"]
  ordering_column: "cdc_sequence_num"
  delete_handling_policy: "exclude_hard_deletes_and_carts"
  late_arriving_lookback_hours: 72

quality_and_publish_gate:
  pattern: "write_audit_publish"
  checks:
    - id: "pk_uniqueness"
      column: "order_id"
      must_be_unique: true
      must_not_be_null: true
    - id: "gross_amount_reconciliation"
      expression: "gross_order_amount == net_merchandise_amount - discount_amount + tax_amount"
    - id: "freshness_sla"
      max_staleness_minutes: 90

output_ports:
  - port_id: "sales_orders_sql_port"
    port_type: "analytical_sql"
    public_storage_uri: "s3://cf-sales-public/sales_orders/"
    file_format: "apache_parquet"
    compression: "snappy"
    partition_columns:
      - "order_placed_date_utc"
    catalog_registration:
      provider: "aws_glue_data_catalog"
      database_name: "sales_prod"
      table_name: "sales_orders"
      query_engine: "amazon_athena"
    access_control:
      enforcement_mechanism: "aws_lake_formation_and_iam"
      default_classification: "confidential"

Key Architectural Decisions and Trade-Offs

When designing the end-to-end architecture of a Data Product, the domain engineering team must make four structural decisions and understand their operational consequences:

Architectural DecisionRecommended Choice in sales-ordersCommon Mistake to AvoidWhy It Changes Production Outcomes
S3 Partitioning GranularityPartition by business date (order_placed_date_utc, ~365 partitions/year).Partitioning by high-cardinality columns such as order_id or customer_id.Partitioning by order_id creates millions of tiny Parquet files (small files problem), severely degrading Amazon Athena query times and exhausting Glue Catalog limits.
Late-Arriving Data HandlingRe-evaluation lookback window or key-based merge across affected partitions.Processing only the current hour's partition and ignoring updates to orders placed two days ago.If an order placed on Friday is cancelled on Sunday, ignoring late updates leaves the order marked as 'CHECKOUT_COMPLETED' forever in the analytical product.
Schema EvolutionBackwards-compatible additive changes (appending optional columns); new major version for breaking changes.Overwriting data types or renaming columns in-place inside sales_prod.sales_orders.Prevents an internal domain refactoring from breaking SQL queries across dozens of downstream consumers.
Failure Recovery (Idempotency)Idempotent batch writes to staging + atomic promotion after passing the WAP gate.Appending rows (INSERT INTO) directly into the public S3 folder without deduplication.Allows re-running the pipeline after any network drop or worker crash without duplicating a single order in consumer queries.

Three Real-World Scenarios with Different Architectural Decisions

Scenario 1: High-Frequency Transactional Product (CommerceFlow sales-orders)

  • Context: sales-orders receives tens of thousands of new orders and status updates every hour and feeds Payments, Finance, and Marketing.
  • Architectural decision: Hourly incremental/CDC ingestion (with a lookback merge window for status transitions), storage in Apache Parquet partitioned by order_placed_date_utc, a preventive Write-Audit-Publish gate, and exposure via AWS Glue Data Catalog and Amazon Athena governed by AWS Lake Formation.

Scenario 2: Low-Frequency Reference Product (Carrier Shipping Rate Cards)

  • Context: The Inventory / Logistics domain publishes carrier-contract-tariffs, containing negotiated shipping rates per weight bracket and postal zone across courier partners. These rate cards change only once a month when contracts are renegotiated.
  • Architectural decision: Implementing continuous CDC capture or daily date partitioning for a 2,500-row table that changes monthly would be unnecessary engineering complexity. Here, the optimal architecture is a versioned full-snapshot overwrite triggered whenever a new tariff sheet is approved, while preserving the exact same preventive WAP gate and catalog registration.

Scenario 3: When a Simpler Alternative Is Sufficient (Internal Service Operational Metrics)

  • Context: Developers on the cart microservice inside Sales want to monitor how many HTTP requests took longer than 500 ms over the last 15 minutes to tune container autoscaling.
  • Architectural decision: These metrics are not a cross-domain Data Product. Building a pipeline into S3 Parquet files, registering them in Glue Data Catalog, and configuring Lake Formation grants would add latency and cost with zero external consumers. For internal technical telemetry used solely by the service squad, emitting metrics directly to an operational monitoring system (such as Amazon CloudWatch or Prometheus/Grafana) is sufficient.

Using Artificial Intelligence to Review and Design Data Product Architectures

Large language models are effective assistants for auditing whether an architectural design overlooks edge cases such as duplicates, late-arriving updates, or poor partitioning, provided an engineer validates actual infrastructure constraints.

Prompt 1: Auditing a Data Product Architecture Against Operational Failure Modes

Act as a principal data engineering architect.
Context: We are designing the end-to-end architecture of a Source-Aligned Data Product on Amazon S3 (Apache Parquet), AWS Glue Data Catalog, and Amazon Athena, fed from an operational PostgreSQL database.

Constraints:
- Analyze the YAML descriptor and SQL transformation query pasted below.
- Evaluate 5 concrete operational risks:
  1. What happens if the ingestion job runs twice for the same hourly window (idempotency)?
  2. How does the chosen partition column affect the size and count of Parquet files in S3?
  3. What happens if an older record is updated or physically deleted in PostgreSQL 48 hours after creation?
  4. Can Athena consumers read partial data while the pipeline is mid-execution?
  5. Does any column couple the public interface to private internal microservice implementation details?

Expected output:
A prioritized list of architectural vulnerabilities found and exact technical changes to fix them.

[PASTE YAML DESCRIPTOR AND SQL TRANSFORMATION]

What a human must verify: Check the actual daily row volume and average megabyte size per S3 partition (aiming for Parquet file sizes between 128 MB and 512 MB when volume permits) and confirm how the operational PostgreSQL source handles physical vs. logical deletes.

Prompt 2: Generating Rules for a Write-Audit-Publish (WAP) Gate

Act as a data quality engineer.
Context: We need to define the preventive validations for the Audit stage (in a Write-Audit-Publish workflow) for a Data Product prior to promoting a new partition to the public catalog.

Constraints:
- Based on the output port SQL schema below, propose the essential minimum checks grouped into:
  1. Structural and grain integrity (primary key, nulls).
  2. Row-level semantic and arithmetic invariants across columns.
  3. Volume anomaly detection compared against the previous run (for example, a sudden 90% drop in row count).
- Express each rule as a verifiable logical condition in SQL or Python.

[PASTE OUTPUT TABLE SCHEMA]

What a human must verify: Calibrate volume anomaly thresholds against real business seasonality (for instance, Tuesday 3:00 AM traffic is naturally much lower than Friday afternoon campaign traffic, so a poorly tuned static threshold would trigger false positives and block legitimate publications).


Practical Application Exercises

Exercise 1: Diagnosing a Performance and Cost Bottleneck in Amazon Athena

An engineer in the Inventory domain designs the architecture for the inventory-stock-movements product (which records 2 million warehouse movements per day). To speed up lookups by product and movement, they configure Amazon S3 writes partitioned by PARTITIONED BY (sku_code, movement_id). Two weeks later, Amazon Athena queries take over 4 minutes to return a simple daily count, and S3 API request costs skyrocket.

Question: What architectural mistake caused this degradation, and how should the partitioning and physical sorting of the Parquet files be redesigned?

Exercise 2: Handling Orders Updated Days After Creation

In the sales-orders product, a customer places order ORD-000099100 on 2026-11-01 with status CHECKOUT_COMPLETED. On 2026-11-05, the customer cancels the order, and in PostgreSQL the row changes to CANCELLED with updated_ts = '2026-11-05 14:20:00'. If the Data Product pipeline only rewrites the partition for the current day (order_placed_date_utc = '2026-11-05'), what inconsistency will consumers see when querying order ORD-000099100, and how should the product architecture resolve it?

Exercise 3: Separating Private Tables from the Public Port

The Sales application squad needs to add a column named internal_postgres_ctid and another named redis_lock_token to their operational table tbl_orders to debug concurrency locks in the Checkout microservice. An engineer asks whether they should also add those two columns to the public schema of sales-orders in AWS Glue Data Catalog so that "the S3 table stays identical to PostgreSQL."

Question: Should those columns be included in the Data Product's public output port? Justify your answer based on the zone architecture covered in this article.


Reasoned Solutions to the Exercises

Solution to Exercise 1

The engineer triggered the small files problem by partitioning on movement_id (unique per row) and sku_code (thousands of distinct values). This forces S3 to create millions of prefixes containing tiny Parquet files of only a few kilobytes each; Amazon Athena spends almost all its execution time listing S3 object metadata rather than reading columnar data.

Architectural fix:

  1. Change the partition key to a low-cardinality temporal column such as movement_date_utc (DATE, 1 partition per day).
  2. Sort (cluster) the rows inside each daily Parquet file by (warehouse_id, sku_code) at write time. Each daily partition will then contain a small number of compact Parquet files, and Parquet's min/max row group statistics will allow Athena to skip irrelevant blocks whenever a consumer filters by sku_code.

Solution to Exercise 2

Because the order was placed on 2026-11-01, its row lives in the order_placed_date_utc=2026-11-01 partition. If the 2026-11-05 pipeline writes the update into the new day's partition or ignores older partitions, one of two bugs occurs: either the order remains stuck as CHECKOUT_COMPLETED forever in the November 1 partition, or two rows appear for the same order_id (one on Nov 1 as completed and another on Nov 5 as cancelled), violating primary key uniqueness.

Architectural fix: The publication pipeline must identify which historical order_placed_date_utc partitions contain records modified in the current incremental batch (or use a transactional table format over Parquet such as Apache Iceberg that supports MERGE INTO sales_orders USING updates ON sales_orders.order_id = updates.order_id) and atomically update the original 2026-11-01 partition after passing the WAP gate.

Solution to Exercise 3

They must NOT be included in the public output port. internal_postgres_ctid and redis_lock_token are ephemeral technical artifacts of the microservice's internal implementation and carry zero analytical meaning for the rest of the organization. Exposing them on the public port would force unnecessary contract deprecation cycles if the team later replaces Redis with another locking mechanism. Those fields should either be omitted during extraction or remain confined to the private ingestion zone—never projected into sales_prod.sales_orders.


When to Apply This Reference Architecture and Final Summary

Use this end-to-end architecture (Source $\rightarrow$ Private Ingestion $\rightarrow$ Decoupling Transformation $\rightarrow$ WAP Gate $\rightarrow$ Governed Public Port) whenever you build a Data Product whose data will be consumed by other domains, financial reports, or AI systems that depend on contractual stability and corruption-free data.

Keep three practical principles front of mind when bringing this design to your organization:

  1. A raw replica is not a Data Product: Never expose your microservice's internal operational tables or your private S3 landing zone directly as a public interface.
  2. Nobody reads unaudited data: Always enforce the Write-Audit-Publish pattern so an ingestion glitch or retry duplicate halts the pipeline internally before contaminating consumer queries.
  3. The output contract drives the architecture: This clean separation between a domain's private zones and its public output port is what sets the stage for formalizing and automating Data Contracts between producers and consumers in the next installment.

Loading conversation…

Keep learning