StackPractices
advanced By Mathias Paulenko

Data Lineage Tracking: Track Origin End-to-End

How to track data origin and transformations end-to-end. Covers column-level lineage, OpenLineage, Marquez, metadata injection, and impact analysis.

Topics: data

Overview

Your warehouse customers table feeds a churn model, three dashboards and a weekly finance report. Someone renames a column upstream — which of those break? Without lineage you find out when they break. Data lineage records where data comes from, how it’s transformed and where it ends up: every pipeline run, every SQL transformation, every column mapping is captured as metadata and connected into a graph — source table → transformation → intermediate table → final report. When a source column changes, you can trace which downstream tables, dashboards and ML models depend on it before you merge the change.

The de-facto standard for that metadata is OpenLineage, an open event spec with integrations in Airflow, Spark and dbt; Marquez is its reference backend. Lineage is also what makes broader data pipeline architectures governable — GDPR and CCPA deletion requests require knowing where personal data flows, and “somewhere in the warehouse” isn’t an answer.

flowchart diagram: SRC[

When to Use

  • Data governance and compliance (GDPR, CCPA, SOX)
  • Impact analysis before schema changes or pipeline modifications
  • Debugging data quality issues, tracing bad data back to the source
  • Multi-team data platforms where teams need to understand dependencies
  • Regulatory audits requiring data flow documentation

When NOT to Use

  • Small projects with a single pipeline and no dependencies
  • Prototypes and exploratory work
  • Systems where all data flows are documented manually and rarely change

Solution

OpenLineage event structure

// openlineage_event.json — OpenLineage run event
{
  "eventType": "START",
  "eventTime": "2026-07-05T10:00:00.000Z",
  "run": {
    "runId": "abc-123-def",
    "facets": {
      "nominalTime": {
        "_producer": "https://github.com/OpenLineage/OpenLineage",
        "_schemaURL": "https://openlineage.io/schema/facets/1.0/nominalTime.json",
        "nominalStartTime": "2026-07-05T10:00:00.000Z",
        "nominalEndTime": "2026-07-05T10:05:00.000Z"
      }
    }
  },
  "job": {
    "namespace": "shop",
    "name": "etl.customers_daily",
    "facets": {
      "sql": {
        "query": "SELECT id, email, status FROM source.customers WHERE updated_at >= ?"
      }
    }
  },
  "inputs": [
    {
      "namespace": "postgres://source-db",
      "name": "shop.public.customers",
      "facets": {
        "schema": {
          "fields": [
            {"name": "id", "type": "long"},
            {"name": "email", "type": "string"},
            {"name": "status", "type": "string"}
          ]
        }
      }
    }
  ],
  "outputs": [
    {
      "namespace": "postgres://warehouse",
      "name": "warehouse.customers",
      "facets": {
        "schema": {
          "fields": [
            {"name": "id", "type": "long"},
            {"name": "email", "type": "string"},
            {"name": "status", "type": "string"},
            {"name": "is_active", "type": "boolean"}
          ]
        },
        "columnLineage": {
          "fields": {
            "is_active": {
              "inputFields": [
                {"namespace": "postgres://source-db", "name": "shop.public.customers", "field": "status"}
              ]
            }
          }
        }
      }
    }
  ]
}

Python lineage tracking with OpenLineage

# lineage_tracker.py — emit OpenLineage events from Python pipelines
from openlineage.client import OpenLineageClient
from openlineage.client.event_v2 import (
    InputDataset, Job, OutputDataset, Run, RunEvent, RunState,
)
from openlineage.client.uuid import generate_new_uuid
from datetime import datetime, timezone

client = OpenLineageClient(url="http://marquez:5000")

# producer identifies this emitter; use a repo URL or service name
PRODUCER = "https://github.com/shop/data-pipelines/tree/main/lineage_tracker"


class LineageTracker:
    def __init__(self, job_name, job_namespace="shop"):
        self.job = Job(namespace=job_namespace, name=job_name)
        self.run_id = str(generate_new_uuid())

    def _emit(self, state, inputs, outputs, run_facets=None, job_facets=None):
        run = Run(runId=self.run_id, facets=run_facets or {})
        job = Job(
            namespace=self.job.namespace,
            name=self.job.name,
            facets=job_facets or {},
        )
        event = RunEvent(
            eventType=state,
            eventTime=datetime.now(timezone.utc).isoformat(),
            run=run,
            job=job,
            producer=PRODUCER,
            inputs=[self._to_input_dataset(d) for d in inputs],
            outputs=[self._to_output_dataset(d) for d in outputs],
        )
        client.emit(event)

    def start(self, inputs, outputs, sql=None):
        job_facets = {"sql": {"query": sql}} if sql else {}
        self._emit(RunState.START, inputs, outputs, job_facets=job_facets)

    def complete(self, inputs, outputs):
        self._emit(RunState.COMPLETE, inputs, outputs)

    def fail(self, error_message):
        self._emit(
            RunState.FAIL, [], [],
            run_facets={"errorMessage": {"message": error_message}},
        )

    def _to_input_dataset(self, spec):
        return InputDataset(
            namespace=spec.get("namespace", "default"),
            name=spec["name"],
            facets=spec.get("facets", {})
        )

    def _to_output_dataset(self, spec):
        return OutputDataset(
            namespace=spec.get("namespace", "default"),
            name=spec["name"],
            facets=spec.get("facets", {}),
            outputFacets={}
        )

Using lineage tracker in a pipeline

# etl_with_lineage.py — ETL pipeline with lineage tracking
from lineage_tracker import LineageTracker

def run_customer_etl():
    tracker = LineageTracker("etl.customers_daily")

    inputs = [{
        "namespace": "postgres://source-db",
        "name": "shop.public.customers",
        "facets": {
            "schema": {
                "fields": [
                    {"name": "id", "type": "long"},
                    {"name": "email", "type": "string"},
                    {"name": "status", "type": "string"}
                ]
            }
        }
    }]

    outputs = [{
        "namespace": "postgres://warehouse",
        "name": "warehouse.customers",
        "facets": {
            "schema": {
                "fields": [
                    {"name": "id", "type": "long"},
                    {"name": "email", "type": "string"},
                    {"name": "is_active", "type": "boolean"}
                ]
            },
            "columnLineage": {
                "fields": {
                    "is_active": {
                        "inputFields": [
                            {"namespace": "postgres://source-db",
                             "name": "shop.public.customers",
                             "field": "status"}
                        ]
                    }
                }
            }
        }
    }]

    sql = "SELECT id, LOWER(email) as email, status = 'active' as is_active FROM source.customers"

    try:
        tracker.start(inputs, outputs, sql=sql)

        # Run the actual ETL
        df = extract_from_source()
        df = transform(df)
        load_to_warehouse(df)

        tracker.complete(inputs, outputs)

    except Exception as e:
        tracker.fail(str(e))
        raise

Column-level lineage with SQL parsing

# column_lineage.py — extract column-level lineage from SQL
import sqlglot
from sqlglot import exp

def extract_column_lineage(sql, source_table, target_table):
    """Parse SQL and extract column-level lineage."""
    parsed = sqlglot.parse_one(sql)
    lineage = {}

    for select in parsed.find_all(exp.Select):
        # select.expressions are the projection items; the alias (or the
        # column name when there's no alias) is the output column.
        for expr in select.expressions:
            target_col = expr.alias_or_name

            for column in expr.find_all(exp.Column):
                lineage.setdefault(target_col, []).append({
                    "source_table": column.table or source_table,
                    "source_column": column.name
                })

    return lineage

# Example
sql = """
SELECT
    id,
    LOWER(email) AS email,
    status = 'active' AS is_active,
    CONCAT(first_name, ' ', last_name) AS full_name
FROM source.customers
"""

lineage = extract_column_lineage(sql, "source.customers", "warehouse.customers")
# Result:
# {
#   "id": [{"source_table": "source.customers", "source_column": "id"}],
#   "email": [{"source_table": "source.customers", "source_column": "email"}],
#   "is_active": [{"source_table": "source.customers", "source_column": "status"}],
#   "full_name": [{"source_table": "source.customers", "source_column": "first_name"},
#                 {"source_table": "source.customers", "source_column": "last_name"}]
# }

Impact analysis query

-- impact_analysis.sql — find all downstream tables affected by a source change
WITH RECURSIVE lineage_graph AS (
    -- Start from the changed table
    SELECT
        downstream_table,
        downstream_column,
        upstream_table,
        upstream_column,
        1 AS depth
    FROM lineage_edges
    WHERE upstream_table = 'source.customers'
      AND upstream_column = 'email'

    UNION ALL

    -- Recurse through downstream dependencies
    SELECT
        e.downstream_table,
        e.downstream_column,
        e.upstream_table,
        e.upstream_column,
        g.depth + 1
    FROM lineage_edges e
    JOIN lineage_graph g ON e.upstream_table = g.downstream_table
                        AND e.upstream_column = g.downstream_column
    WHERE g.depth < 10  -- prevent infinite loops
)
SELECT DISTINCT
    downstream_table,
    downstream_column,
    depth,
    STRING_AGG(upstream_table || '.' || upstream_column, ' -> ') AS path
FROM lineage_graph
GROUP BY downstream_table, downstream_column, depth
ORDER BY depth, downstream_table;

Airflow integration with OpenLineage

# airflow_lineage.py — Airflow DAG with automatic lineage extraction
from airflow import DAG
from airflow.operators.python import PythonOperator
from datetime import datetime, timedelta

default_args = {
    'owner': 'data-team',
    'depends_on_past': False,
    'retries': 1,
    'retry_delay': timedelta(minutes=5),
}

dag = DAG(
    'etl_with_lineage',
    default_args=default_args,
    schedule='0 2 * * *',
    start_date=datetime(2026, 1, 1),
    tags=['etl', 'lineage'],
)

# Airflow automatically emits OpenLineage events when configured.
# Add to airflow.cfg (or AIRFLOW__OPENLINEAGE__TRANSPORT env var):
# [openlineage]
# transport = {"type": "http", "url": "http://marquez:5000"}

def extract(**context):
    # The Airflow extractor reads XCom for dataset info
    context['ti'].xcom_push(key='inputs', value=[
        {"namespace": "postgres://source", "name": "shop.customers"}
    ])
    context['ti'].xcom_push(key='outputs', value=[
        {"namespace": "postgres://warehouse", "name": "warehouse.customers"}
    ])
    # Actual ETL logic here
    pass

extract_task = PythonOperator(
    task_id='extract',
    python_callable=extract,
    dag=dag,
)

Java lineage with custom metadata

// LineageEmitter.java — emit lineage events from Java pipelines
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.URI;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.UUID;
import java.time.Instant;

public class LineageEmitter {
    private static final String MARQUEZ_URL = "http://marquez:5000";
    private final HttpClient client = HttpClient.newHttpClient();
    private final ObjectMapper mapper = new ObjectMapper();

    public void emitRun(String jobName, String runId, String eventType,
                        String[] inputTables, String[] outputTables) {
        try {
            var event = mapper.createObjectNode();
            event.put("eventType", eventType);
            event.put("eventTime", Instant.now().toString());

            var run = mapper.createObjectNode();
            run.put("runId", runId);
            event.set("run", run);

            var job = mapper.createObjectNode();
            job.put("namespace", "shop");
            job.put("name", jobName);
            event.set("job", job);

            var inputs = mapper.createArrayNode();
            for (String table : inputTables) {
                var ds = mapper.createObjectNode();
                ds.put("namespace", "postgres://source");
                ds.put("name", table);
                inputs.add(ds);
            }
            event.set("inputs", inputs);

            var outputs = mapper.createArrayNode();
            for (String table : outputTables) {
                var ds = mapper.createObjectNode();
                ds.put("namespace", "postgres://warehouse");
                ds.put("name", table);
                outputs.add(ds);
            }
            event.set("outputs", outputs);

            var request = HttpRequest.newBuilder()
                .uri(URI.create(MARQUEZ_URL + "/api/v1/lineage"))
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(mapper.writeValueAsString(event)))
                .build();

            client.send(request, HttpResponse.BodyHandlers.ofString());
        } catch (Exception e) {
            throw new RuntimeException("Failed to emit lineage event", e);
        }
    }
}

Explanation

Each RunEvent carries three things: what ran (the job), which run produced it (run), and what it read and wrote (inputs/outputs with optional facets). A START event followed by a COMPLETE or FAIL event gives the backend a complete run record, and the columnLineage facet on an output dataset is what upgrades a table-level edge into a column-level one. Emitted events go to a lineage backend — Marquez stores them in Postgres and exposes a graph API, while DataHub and OpenMetadata ingest OpenLineage events through their own endpoints and add search and ownership on top.

Column-level versus table-level is the main trade-off. Table-level lineage is cheap (name your inputs and outputs) but it can only answer “does warehouse.customers depend on source.customers?”. Column-level lineage answers “which columns break if status is renamed?”, which is what impact analysis actually needs. The cost is extraction: either you parse SQL yourself (the sqlglot example), or you rely on extractors that can see the real query plan — Spark and Snowflake integrations can do this well; a generic Python operator can’t see inside your code, which is why the Airflow example pushes dataset info to XCom by hand.

Instrumentation isn’t free either. Emitting events inline adds a network call to every run. For most pipelines over HTTP the overhead is small, but at high task volume prefer an async transport like Kafka or a queue-backed transport so a slow backend can’t block your workers. Keep the emitted payload honest: include the SQL text in the job facet, because “job X read table A and wrote table B” without the query is rarely enough to debug a wrong number.

Two edge cases bite in practice. Lineage rots: delete or rename a pipeline and its edges stay in the graph unless you emit fresh metadata or prune them, and a stale edge makes impact analysis worse than useless: it reports dependencies that no longer exist. And batch versus streaming jobs emit differently: a long-running streaming job emits START once and then heartbeats, while a batch DAG emits START/COMPLETE pairs per run. The Batch-to-Streaming Bridge pattern covers how to keep both feeding the same store.

Variants

Table-level lineage (simpler)

# table_lineage.py — simple table-level lineage without column detail
from datetime import datetime

class TableLineage:
    def __init__(self):
        self.edges = []  # list of (source_table, target_table, job_name)

    def record(self, source, target, job):
        self.edges.append({
            "source": source,
            "target": target,
            "job": job,
            "recorded_at": datetime.now().isoformat()
        })

    def get_downstream(self, table):
        """Find all tables that depend on this table."""
        visited = set()
        queue = [table]
        result = []

        while queue:
            current = queue.pop(0)
            for edge in self.edges:
                if edge["source"] == current and edge["target"] not in visited:
                    visited.add(edge["target"])
                    result.append(edge["target"])
                    queue.append(edge["target"])

        return result

Lineage from dbt models

# dbt_lineage.yml — dbt automatically generates lineage from model dependencies
version: 2
models:
  - name: stg_customers
    description: "Staged customer data"
    columns:
      - name: id
        tests: [not_null, unique]
      - name: email
        tests: [not_null]

  - name: dim_customers
    description: "Customer dimension with enriched fields"
    depends_on:
      - ref('stg_customers')
      - ref('stg_orders')
    columns:
      - name: customer_id
        tests: [not_null, unique]
      - name: lifetime_value
        description: "Calculated from stg_orders"

Best Practices

  • Emit lineage events at both START and COMPLETE so you can see running pipelines and their results
  • Track column-level lineage when possible — table-level is a start, but column-level lets you do precise impact analysis
  • Use the OpenLineage standard; don’t build a custom lineage format, OpenLineage has wide tool support
  • Include SQL in job facets: the query is the most useful lineage metadata for debugging
  • Automate lineage collection with extractors for Airflow, Spark and dbt instead of manual emission
  • Store lineage in a queryable system — Marquez, DataHub, or Amundsen for querying the lineage graph
  • Run impact analysis before schema changes: “who depends on this column?” before dropping it
  • Keep lineage metadata in sync — if a pipeline is removed, clean up its lineage edges

Common Mistakes

  • No lineage at all: when something breaks, you can’t trace the data back to the source. What should take minutes becomes hours of grepping through pipelines.
  • Only table-level lineage: you know warehouse.customers depends on source.customers but not which columns. Dropping a column breaks unknown downstream consumers.
  • Not including SQL: a bare “A → B” edge tells you two tables are related but not how, which is the part you need when the numbers are wrong.
  • Tracking lineage by hand: spreadsheets and wiki pages go stale the week after you fill them in. If the pipeline doesn’t emit it, it isn’t real lineage.
  • No impact analysis: merging schema changes without checking what depends on the changed columns, the exact scenario lineage exists to prevent.

See Also

Frequently Asked Questions

What is data lineage?

The recorded path data takes through your systems: which source it came from, which jobs transformed it and which tables, dashboards or models consume it. It's stored as a graph of edges; the OpenLineage event above is the smallest unit of that graph.

What is OpenLineage?

The open spec for lineage events: a JSON schema covering runs, jobs, datasets and facets. It isn't a database or a UI; it just defines what an event looks like. Marquez is the reference backend that stores and serves those events, and Airflow, Spark and dbt emit them through plugins.

What is column-level lineage?

Edges between columns instead of tables: warehouse.customers.is_active traced back to source.customers.status. It's what lets you answer "will renaming this column break anything downstream?". A table-level edge can only tell you the two tables are related.

How do I implement lineage with dbt?

You mostly already have it: dbt builds the DAG from your ref() calls, so dbt docs generate followed by dbt docs serve (port 8080 by default) shows model lineage with no extra work. To push the same graph into a shared backend, use the dbt-openlineage adapter.

Why is lineage important for compliance?

Deletion requests under GDPR and CCPA need a map: every copy of a user's data, across tables, exports and downstream models. Without lineage you're grepping column names and hoping. The same map feeds any serious data governance policy and doubles as your audit trail.