VAYULearn
Colour theme
Investigate a failure
VAYU Learn

Airflow & Orchestration

Great Expectations in Production - A Real Implementation Guide

Great Expectations Tutorials Show the Happy Path. Here Is What the Production Implementation Actually Looks Like.

Airflow & OrchestrationData Architecture & Reliability
Great Expectations is only half the solution. Production success comes from writing business-driven expectations, validating the right data, and building failure paths that quarantine bad batches instead of simply logging them.

TL;DR

  • Running full-table validation on every pipeline run is a common first mistake — it can double runtime on large tables; validate a representative sample or the incremental batch instead
  • Auto-profiling gives you a starting suite, but a suite built entirely from profiling encodes whatever the data happened to look like on day one — not what should be true
  • Expectations need to encode actual business rules, not just statistical properties of a sample — the difference between “this is what the data looked like” and “this is what the data must be”
  • Wiring Great Expectations into Airflow requires deciding what happens on failure — most teams stop at “log the result” and never build the quarantine and alert path
  • A validation failure should either block the pipeline or quarantine the batch — a check that fails and lets bad data through anyway provides no protection

The tutorial gets you to a green checkmark. Production requires deciding what happens when the checkmark turns red.


The team followed the Great Expectations quickstart. Connected a datasource, ran the profiler, got a suite with 40 auto-generated expectations. Wired it into the nightly DAG. Felt good.
Three months later, someone asked why the nightly job had gotten 12 minutes slower. The expectation suite was running full-table scans for expect_column_values_to_be_unique on a table that had grown from 2M to 40M rows.
Around the same time, a genuinely bad batch — a merchant_id field silently truncated by an upstream bug — passed validation completely. None of the 40 auto-generated expectations happened to cover that specific field’s format.
The suite was expensive and it wasn’t protecting the thing that actually broke. Auto-profiling had produced 40 checks and none of them were the right one.

What the Tutorial Doesn’t Show You

The Great Expectations quickstart is genuinely good at getting you to a working validation in under an hour. It is not designed to show you the decisions that matter in production: how to keep validation fast at scale, how to build a suite that encodes actual business knowledge rather than a snapshot of whatever the data looked like during setup, and — the part every tutorial skips — what happens after a validation fails.


Setup That Does Not Break Your Pipeline

The Performance Trap

The default behavior for many expectation types is to scan the entire table. expect_column_values_to_be_unique, expect_column_values_to_be_in_set with a large reference set, and distributional expectations all get more expensive as the table grows. A validation suite that took 30 seconds on a 2M row table during setup can take 10+ minutes on the same table at 40M rows — and that cost is paid on every single pipeline run, indefinitely.

Running Validation on a Sample, Not the Full Table

For most production use cases, validating a representative sample or the incremental batch is sufficient and dramatically cheaper than validating the entire table on every run.

import great_expectations as gx

context = gx.get_context()

# WRONG for large tables — validates the entire historical table every run
batch_request_full = {
"datasource_name": "prod_warehouse",
"data_asset_name": "transactions",
}

# BETTER — validate only today's incremental batch
batch_request_incremental = {
"datasource_name": "prod_warehouse",
"data_asset_name": "transactions",
"batch_spec_passthrough": {
"sampling_method": "_sample_using_limit", # or filter by partition
},
"runtime_parameters": {
"query": """
SELECT * FROM transactions
WHERE transaction_date = current_date()
"""

},
}

# For distributional checks that genuinely need broader context,
# use a statistically sound sample rather than the full table
batch_request_sampled = {
"datasource_name": "prod_warehouse",
"data_asset_name": "transactions",
"batch_spec_passthrough": {
"sampling_method": "_sample_using_random",
"sampling_kwargs": {"p": 0.05} # 5% sample
},
}

Validating the incremental batch — the data that was actually added in this run — catches the failures that matter (today’s data is corrupt) without re-scanning history that has already been validated and hasn’t changed. Reserve full-table or large-sample validation for periodic deeper audits, not every pipeline run.


Expectation Suites That Make Sense

Starting From Profiling, Not From a Blank Suite

The auto-profiler is a legitimate and useful starting point — it saves the time of writing 40 expectations from scratch. The mistake is treating its output as the finished suite rather than a first draft.

from great_expectations.profile.user_configurable_profiler import UserConfigurableProfiler

validator = context.get_validator(
batch_request=batch_request_incremental,
expectation_suite_name="transactions_suite"
)

profiler = UserConfigurableProfiler(
profile_dataset=validator,
excluded_expectations=["expect_column_values_to_be_unique"], # too expensive at scale
ignored_columns=["internal_debug_field"],
)

suite = profiler.build_suite()

The profiler tells you what the data looked like during the profiling run. It has no knowledge of what the data is supposed to look like — a field that happened to be 100% populated during profiling gets a not_null expectation regardless of whether nulls are actually invalid or just rare in that sample.

Writing Expectations That Encode Real Business Rules

The expectations worth keeping are the ones a domain expert would write, not the ones a profiler infers from a sample:

# Auto-generated — describes the sample, not a rule
validator.expect_column_values_to_be_between("amount", min_value=0.01, max_value=48293.20)
# 48293.20 was just the max value seen during profiling — meaningless as a rule

# Business rule — encodes an actual constraint
validator.expect_column_values_to_be_between(
"amount", min_value=0.01, max_value=1_000_000,
meta={"notes": "Business rule: transactions above $1M require manual review "
"and land in a separate table. Anything here above this "
"threshold indicates the routing logic failed."}
)

# Auto-generated — checks the specific set of values seen during profiling
validator.expect_column_values_to_be_in_set("status", ["completed", "pending", "failed"])
# Breaks the moment a legitimate new status is added upstream

# Business rule — checks structural validity, not an exhaustive value list
validator.expect_column_values_to_match_regex("status", r"^[a-z_]+$")
validator.expect_column_value_lengths_to_be_between("status", min_value=3, max_value=20)

# The check that would have caught the opening story's bug —
# format validation on a field the auto-profiler had no reason to flag
validator.expect_column_values_to_match_regex(
"merchant_id", r"^M\d{6}$",
meta={"notes": "merchant_id is always M followed by 6 digits. "
"A truncated or malformed ID indicates an upstream "
"extraction bug, not a data quality edge case."}
)

The meta field is not decoration — documenting why an expectation exists is what lets the next engineer understand whether a failure is a real problem or an expectation that needs updating.

Avoiding Expectation Bloat

A suite with 200 expectations is not more protective than one with 25 well-chosen ones — it is harder to review, slower to run, and more likely to fail on legitimate data changes that nobody bothers to investigate because “something in the suite always fails.” Prune aggressively. Every expectation should map to a specific, nameable failure mode you actually care about catching.


Integration With Airflow

The GreatExpectationsOperator Pattern

from great_expectations_provider.operators.great_expectations import GreatExpectationsOperator
from airflow import DAG
from datetime import timedelta

with DAG("transactions_pipeline", schedule_interval="@daily") as dag:

ingest = PythonOperator(
task_id="ingest_transactions",
python_callable=ingest_daily_transactions,
)

validate = GreatExpectationsOperator(
task_id="validate_transactions",
data_context_root_dir="/opt/airflow/great_expectations",
checkpoint_name="transactions_daily_checkpoint",
fail_task_on_validation_failure=True, # this is the decision that matters
return_json_dict=True,
)

quarantine_on_failure = PythonOperator(
task_id="quarantine_bad_batch",
python_callable=quarantine_failed_batch,
trigger_rule="one_failed", # only runs if validate failed
)

load_to_warehouse = PythonOperator(
task_id="load_to_warehouse",
python_callable=load_validated_data,
trigger_rule="all_success", # only runs if validate passed
)

ingest >> validate >> [load_to_warehouse, quarantine_on_failure]

Failing the DAG Correctly

fail_task_on_validation_failure=True is the setting most tutorials leave at its default or don't mention at all. Without it, a validation failure is recorded but the DAG continues as if nothing happened — the exact silent-failure pattern this whole exercise was supposed to prevent.

The trigger_rule configuration is what makes the failure path do something useful instead of just stopping. quarantine_on_failure runs only when validation fails; load_to_warehouse runs only when it succeeds. Without explicit branching like this, a failed validation either blocks everything (including work that didn't depend on the failing check) or blocks nothing (defeating the purpose).


What to Do When Expectations Fail

Quarantine, Don’t Just Alert

An alert without quarantine means a human has to notice the alert, investigate, and manually intervene before the bad data does damage — which in practice means the bad data sits in the production table for however long it takes someone to see the message.

def quarantine_failed_batch(**context):
validation_result = context["ti"].xcom_pull(task_ids="validate_transactions")

failed_expectations = [
r["expectation_config"]["expectation_type"]
for r in validation_result["results"]
if not r["success"]
]

# Move the batch to a quarantine location — never let it reach
# the table downstream consumers actually query
move_batch_to_quarantine(
source="s3://bucket/staging/transactions/",
destination="s3://bucket/quarantine/transactions/"
)

send_alert(
channel="#data-quality-alerts",
message=(
f"Batch quarantined: transactions\n"
f"Failed expectations: {', '.join(failed_expectations)}\n"
f"Data docs: {validation_result.get('data_docs_url', 'n/a')}"
)
)

raise AirflowFailException(
f"Validation failed — batch quarantined. "
f"Failed checks: {failed_expectations}"
)

The batch never reaches the table downstream consumers query. The alert tells someone what specifically failed, with a link to the full Data Docs report rather than just “validation failed.”

The Triage Decision

Not every failure should have the same severity. A single row with an out-of-range value is different from every row in a batch failing a schema check. Distinguish these in the checkpoint configuration rather than treating every failure identically:

checkpoint_config = {
"name": "transactions_daily_checkpoint",
"validations": [{
"batch_request": batch_request_incremental,
"expectation_suite_name": "transactions_suite",
}],
"action_list": [
{
"name": "store_validation_result",
"action": {"class_name": "StoreValidationResultAction"},
},
{
"name": "update_data_docs",
"action": {"class_name": "UpdateDataDocsAction"},
},
],
}

# Check the mostly_ parameter on individual expectations to set
# a tolerance rather than requiring 100% pass rate on every row
validator.expect_column_values_to_not_be_null("amount", mostly=0.98)
# Allows up to 2% null rate before this specific expectation fails —
# useful for fields where a small amount of missingness is expected
# and shouldn't halt the entire pipeline

mostly is the parameter most tutorials mention once and most production suites underuse. It is the difference between a suite that fails the whole pipeline over one bad row and one that fails only when the problem is actually significant.


Checkpoints and Validation Results in Practice

A checkpoint bundles a batch request, an expectation suite, and a set of actions to take on the result — it is the unit that actually gets run, not the suite alone.

checkpoint = context.add_or_update_checkpoint(
>"transactions_daily_checkpoint"
,
validations=[{
"batch_request": batch_request_incremental,
"expectation_suite_name": "transactions_suite",
}],
)

result = checkpoint.run()

if not result["success"]:
failed_results = [
r for r in result.list_validation_results()
if not r["success"]
]
# Inspect failed_results to build a targeted response
# rather than a generic "something failed" message

Data Docs — the auto-generated HTML report — is genuinely useful in production, but only if someone knows it exists and where to find it. Publish the Data Docs URL to S3 or a static site as part of the checkpoint’s actions, and include the direct link in every failure alert. A validation failure message with no link to the details gets ignored after the second time it fires.


The Great Expectations Production Checklist

Performance
□ Validation runs against the incremental batch, not the full table
□ Expensive expectations (uniqueness at scale) are scoped or excluded
□ Validation runtime is monitored — alert if it grows unexpectedly

Suite quality
□ Auto-profiled suite has been reviewed and pruned, not deployed as-is
□ Each expectation has a documented reason in meta
□ Expectations encode actual business rules, not just sample statistics
□ mostly thresholds used where 100% pass rate isn't the real requirement

Airflow integration
□ fail_task_on_validation_failure is explicitly set, not left at default
□ trigger_rule branches correctly to a quarantine path on failure
□ Validation task runs before data reaches the table downstream teams query

Failure handling
□ Failed batches are quarantined, not just logged
□ Alerts include which expectations failed and a link to Data Docs
□ Severity is differentiated — a single bad row isn't treated like a full outage

Maintenance
□ Suite is revisited when upstream schemas or business rules change
□ Expectations that fail on legitimate changes are updated, not ignored

Final Takeaway

Great Expectations gets you a working validation pipeline in an afternoon. What makes that pipeline useful in production is entirely in the decisions the tutorial doesn’t cover: validating the right scope so the check doesn’t become the bottleneck, writing expectations that encode what should be true rather than what a sample happened to look like, and building a failure path that actually stops bad data instead of just logging a warning next to it.

📌 Core Principle

A validation suite that always passes is not protecting anything. A validation suite that fails and lets the data through anyway is not protecting anything either. The suite only matters if a failure changes what happens next.

Next in Series

Data Reconciliation Pipelines — Building the Safety Net

Your pipeline ran successfully. Your validation suite passed. Your numbers are still wrong.

Next: reconciliation pipelines — the safety net that catches what schema checks and expectation suites cannot, by comparing source-of-truth totals against downstream aggregates. Revenue reconciliation patterns, alerting on discrepancies, and how to schedule reconciliation jobs so they catch problems before your stakeholders do.