The Complete Guide to Data Observability and Lineage Tracking

The Complete Guide to Data Observability and Lineage Tracking

What is Data Observability?

Software engineering has long relied on observability, logs, metrics, and traces, to understand system behavior and debug issues. Data engineering needs the same rigor. Data observability is the practice of monitoring your data pipelines and datasets to detect, diagnose, and resolve data quality issues before they impact business decisions.

The five pillars of data observability mirror the concept from software engineering:

  • Freshness: Is your data up to date? When was the last update?
  • Volume: Are you receiving the expected amount of data?
  • Schema: Has the structure of your data changed unexpectedly?
  • Distribution: Are the values within expected ranges?
  • Lineage: What depends on this data, and where does it come from?

Implementing Freshness Monitoring

The most common data incident is stale data. Set up automated freshness checks:

# freshness_monitor.py
import sqlite3
from datetime import datetime, timedelta
from dataclasses import dataclass
from typing import Optional, Callable

@dataclass
class FreshnessCheck:
    table_name: str
    timestamp_column: str
    max_age_minutes: int
    alert_channels: list
    owner: str

class FreshnessMonitor:
    def __init__(self, db_connection, alert_fn: Callable):
        self.conn = db_connection
        self.alert_fn = alert_fn
    
    def check_table_freshness(self, check: FreshnessCheck) -> dict:
        """Check if a table's data is within the expected freshness window."""
        query = f"""
            SELECT 
                MAX({check.timestamp_column}) as last_update,
                COUNT(*) as total_rows,
                TIMESTAMPDIFF(MINUTE, 
                    MAX({check.timestamp_column}), 
                    CURRENT_TIMESTAMP()) as minutes_since_update
            FROM {check.table_name}
        """
        cursor = self.conn.execute(query)
        row = cursor.fetchone()
        
        result = {
            "table": check.table_name,
            "last_update": row[0],
            "total_rows": row[1],
            "minutes_since_update": row[2],
            "is_fresh": row[2] <= check.max_age_minutes,
            "severity": self._calculate_severity(row[2], check.max_age_minutes)
        }
        
        if not result["is_fresh"]:
            self.alert_fn(
                severity=result["severity"],
                message=f"Table {check.table_name} is stale. "
                        f"Last update: {row[2]} minutes ago "
                        f"(max: {check.max_age_minutes})",
                channels=check.alert_channels,
                owner=check.owner
            )
        
        return result
    
    def _calculate_severity(self, minutes_since: int, max_minutes: int) -> str:
        ratio = minutes_since / max_minutes
        if ratio <= 1.5: return "warning"
        if ratio <= 3.0: return "critical"
        return "emergency"

Schema Change Detection

Unexpected schema changes break downstream queries silently. Detect them proactively:

# schema_monitor.py
from typing import Dict, Set, List
import hashlib

class SchemaMonitor:
    def __init__(self, db_connection):
        self.conn = db_connection
        self.schema_registry = {}
    
    def capture_schema(self, table_name: str) -> Dict[str, str]:
        """Capture current schema of a table."""
        query = f"""
            SELECT column_name, data_type, is_nullable
            FROM information_schema.columns
            WHERE table_name = '{table_name}'
            ORDER BY ordinal_position
        """
        cursor = self.conn.execute(query)
        schema = {}
        for row in cursor.fetchall():
            schema[row[0]] = {
                "type": row[1],
                "nullable": row[2] == "YES"
            }
        return schema
    
    def detect_changes(self, table_name: str) -> List[dict]:
        """Compare current schema against baseline."""
        current = self.capture_schema(table_name)
        baseline = self.schema_registry.get(table_name, {})
        
        changes = []
        
        # Detect new columns
        new_cols = set(current.keys()) - set(baseline.keys())
        for col in new_cols:
            changes.append({
                "type": "column_added",
                "column": col,
                "details": current[col],
                "severity": "info"
            })
        
        # Detect removed columns
        removed_cols = set(baseline.keys()) - set(current.keys())
        for col in removed_cols:
            changes.append({
                "type": "column_removed",
                "column": col,
                "details": baseline[col],
                "severity": "critical"  # Breaking change!
            })
        
        # Detect type changes
        for col in set(current.keys()) & set(baseline.keys()):
            if current[col]["type"] != baseline[col]["type"]:
                changes.append({
                    "type": "type_changed",
                    "column": col,
                    "from": baseline[col]["type"],
                    "to": current[col]["type"],
                    "severity": "critical"
                })
        
        # Update baseline
        self.schema_registry[table_name] = current
        return changes

Data Lineage with OpenLineage

OpenLineage provides an open standard for tracking data lineage across tools and platforms:

# lineage_tracker.py
from openlineage.client import OpenLineageClient
from openlineage.client.run import RunEvent, RunState
from openlineage.client.job import Job
import uuid

class LineageTracker:
    def __init__(self, api_url: str):
        self.client = OpenLineageClient(api_url)
        self.run_id = str(uuid.uuid4())
    
    def track_job_start(self, job_name: str, inputs: list, outputs: list):
        """Track the start of a data processing job."""
        event = RunEvent(
            eventType=RunState.START,
            run=self._create_run(),
            job=Job(namespace="production", name=job_name),
            inputs=[self._create_dataset(d) for d in inputs],
            outputs=[self._create_dataset(d) for d in outputs]
        )
        self.client.emit(event)
    
    def track_job_complete(self, job_name: str, inputs: list, outputs: list):
        """Track job completion with row counts."""
        event = RunEvent(
            eventType=RunState.COMPLETE,
            run=self._create_run(),
            job=Job(namespace="production", name=job_name),
            inputs=[self._create_dataset(d) for d in inputs],
            outputs=[self._create_dataset(d, rows=10000) for d in outputs]
        )
        self.client.emit(event)
    
    def _create_dataset(self, dataset_info: dict, rows: int = 0):
        from openlineage.client.dataset import Dataset
        return Dataset(
            namespace=dataset_info.get("namespace", "s3://data-lake"),
            name=dataset_info["name"],
            schema=None,
            description=None
        )
    
    def _create_run(self):
        from openlineage.client.run import Run
        return Run(runId=self.run_id)

Building a Data Quality Scorecard

Create organizational visibility with a data quality scorecard:

# Build a quality scorecard across all monitored tables
quality_scorecard = {
    "overall_score": 94.2,
    "freshness": {
        "score": 97.5,
        "tables_passing": 185,
        "tables_failing": 5,
        "critical_stale": 1
    },
    "volume": {
        "score": 92.1,
        "tables_passing": 178,
        "tables_failing": 12,
        "anomalies_detected": 8
    },
    "schema": {
        "score": 99.8,
        "tables_stable": 190,
        "recent_changes": 2,
        "breaking_changes": 0
    },
    "distribution": {
        "score": 87.3,
        "tables_normal": 170,
        "tables_drifting": 20,
        "critical_drift": 3
    }
}

Conclusion

Data observability is not a luxury. It's a necessity for any organization that makes decisions based on data. By implementing monitoring across freshness, volume, schema, distribution, and lineage, you transform data quality from a reactive firefighting exercise into a proactive, measurable practice. Start with the basics (freshness and volume), add schema monitoring, and progressively build toward full lineage tracking. The investment pays for itself the first time it prevents a bad data incident from reaching your executives' dashboards.

Share this article

Back to Blog See Projects