Volume vs expected: analytics.fct_orders
Rows loaded per hour, last 7 days, with the learned expected range
Project 05 · Data quality
Bad data is cheaper to catch at the door than in a board deck. This platform watches 148 tables across the warehouse and the lake. Great Expectations suites validate each batch inside the PySpark job that writes it, Monte Carlo learns every table's normal freshness and volume and flags anomalies no rule anticipated, and records that cannot be parsed go to a dead-letter queue instead of disappearing. All results land in one metrics store that Grafana and this dashboard read, and incidents go to the owning team with the failing rows attached.
Rows loaded per hour, last 7 days, with the learned expected range
Time since last update. The white mark is each table's SLA.
By quality dimension
Records rejected in the last 30 days
Opened automatically from checks and anomaly monitors
Critical suites block the write when they fail
Rules for what we know can break, learning for what we don't, and a home for every rejected record.
01 · Validate on write
Great Expectations + PySpark
Each batch is checked before it is published: nulls, ranges, uniqueness, row counts. Critical suites block the write.
02 · Route bad records
Dead-letter queue
Records that fail parsing or a contract go to a Kafka DLQ topic with the reason attached, so nothing disappears.
03 · Learn normal
Monte Carlo
Learns each table's usual freshness, volume and schema, and flags changes nobody wrote a rule for.
04 · Measure
Prometheus
Check results, table ages and DLQ counts become metrics labelled with the table and its owner.
05 · Alert
Grafana
Freshness SLAs alert the owning team's channel with a runbook link; dashboards per domain.
06 · Respond
Incidents
Each alert opens an incident with the failing rows, the lineage and the reports downstream.
Check results and rejected records are data too: both are tables with an owner and a retention policy.
dq.check_resultsIceberg table · one row per check runrun_idstringtable_name / ownerstringcheck_name / dimensionstringorder_id_unique, Uniquenesspassedbooleanobserved_value / thresholddoublerun_tstimestampdlq.recordsKafka topic, mirrored to a tablesource_topic / partition / offsetstring / int / bigintreasonstringproducerstringpayloadstringrejected_attimestampcheck_results_dailyAggregate · the CSV downloaddatedatedimensionstringchecks_run / checks_failedintpass_ratedoubleValidation inside the write path, the dead-letter routing, and the freshness alert rule.
Runs the critical suite on each batch inside the PySpark job. Failing batches go to quarantine; results become metrics.
import great_expectations as gx
import great_expectations.expectations as gxe
from prometheus_client import CollectorRegistry, Gauge, push_to_gateway
from pyspark.sql import functions as F
context = gx.get_context(mode="file", project_root_dir="gx")
suite = context.suites.add_or_update(gx.ExpectationSuite(
name="orders.critical",
expectations=[
gxe.ExpectColumnValuesToNotBeNull(column="order_id"),
gxe.ExpectColumnValuesToBeUnique(column="order_id"),
gxe.ExpectColumnValuesToBeBetween(column="total_usd", min_value=0, max_value=50_000),
gxe.ExpectColumnValuesToBeInSet(column="status", value_set=["placed", "paid", "shipped", "cancelled"]),
gxe.ExpectTableRowCountToBeBetween(min_value=1_000, max_value=2_000_000),
],
))
batch_def = (
context.data_sources.add_or_update_spark(name="spark")
.add_dataframe_asset(name="orders_batch")
.add_batch_definition_whole_dataframe("per_run")
)
validation = context.validation_definitions.add_or_update(
gx.ValidationDefinition(name="orders.critical", data=batch_def, suite=suite)
)
def publish_if_valid(df, run_id: str) -> bool:
result = validation.run(batch_parameters={"dataframe": df})
registry = CollectorRegistry()
passed = Gauge("dq_checks_passed", "Checks passed", ["table", "suite"], registry=registry)
failed = Gauge("dq_checks_failed", "Checks failed", ["table", "suite"], registry=registry)
stats = result.statistics
passed.labels("analytics.fct_orders", "orders.critical").set(stats["successful_expectations"])
failed.labels("analytics.fct_orders", "orders.critical").set(stats["unsuccessful_expectations"])
push_to_gateway("pushgateway:9091", job="dq-orders", registry=registry)
if result.success:
df.writeTo("lake.analytics.fct_orders").append()
return True
# Keep the batch for inspection and replay; downstream readers never see it.
df.withColumn("run_id", F.lit(run_id)).writeTo("lake.quarantine.fct_orders").append()
return False
Structured Streaming: valid events continue, anything that cannot be parsed or breaks the contract goes to the DLQ with a reason.
from pyspark.sql import functions as F
from schemas import ORDER_EVENT # the contract, plus a _corrupt_record string field
raw = (
spark.readStream.format("kafka")
.option("kafka.bootstrap.servers", "kafka:9092")
.option("subscribe", "orders.events")
.load()
.select("topic", "partition", "offset", F.col("value").cast("string").alias("payload"))
)
checked = (
raw.withColumn("e", F.from_json("payload", ORDER_EVENT,
{"mode": "PERMISSIVE", "columnNameOfCorruptRecord": "_corrupt_record"}))
.withColumn("reason",
F.when(F.length("payload") > 512_000, "Payload too large")
.when(F.col("e._corrupt_record").isNotNull(), "Not valid JSON")
.when(F.col("e.order_id").isNull() | F.col("e.status").isNull(), "Missing required field")
.when(F.col("e.event_ts").isNull(), "Invalid timestamp")
.when(~F.col("e.status").isin("placed", "paid", "shipped", "cancelled"), "Unknown enum value"))
)
def route(batch, batch_id):
batch.persist()
(batch.where("reason IS NULL").select("e.*").drop("_corrupt_record")
.writeTo("lake.staging.order_events").append())
(batch.where("reason IS NOT NULL")
.select(
F.col("payload").alias("value"),
F.array(
F.struct(F.lit("reason").alias("key"), F.col("reason").cast("binary").alias("value")),
F.struct(F.lit("source").alias("key"),
F.concat_ws(":", "topic", "partition", "offset").cast("binary").alias("value")),
).alias("headers"))
.write.format("kafka")
.option("kafka.bootstrap.servers", "kafka:9092")
.option("topic", "dlq.orders.events")
.option("includeHeaders", "true")
.save())
batch.unpersist()
(checked.writeStream.foreachBatch(route)
.option("checkpointLocation", "s3://lake/checkpoints/order_events")
.trigger(processingTime="30 seconds")
.start())
Prometheus alerting rule behind the freshness meters: fires when a table is older than its own SLA.
groups:
- name: data-freshness
rules:
- record: dq:table_age_seconds
expr: time() - dq_table_last_loaded_timestamp_seconds
- alert: TableFreshnessSLABreached
expr: dq:table_age_seconds > on (table) dq_table_freshness_sla_seconds
for: 5m
labels:
severity: critical
annotations:
summary: "{{ $labels.table }} has not loaded for {{ $value | humanizeDuration }}"
owner: "{{ $labels.owner }}"
runbook_url: "https://runbooks.example.com/data/freshness"
- alert: TableFreshnessNearSLA
expr: dq:table_age_seconds > on (table) (0.8 * dq_table_freshness_sla_seconds)
for: 10m
labels:
severity: warning
At noon on Oct 2 an upstream API outage cut hourly order volume by about 80%. The anomaly monitor opened INC-2286 six minutes later, before anyone looked at a report, and a backfill closed it in three hours.
At 14:00 on Oct 5, volume jumped 95%. The order_id uniqueness check showed a retried batch had loaded twice; it was removed before finance saw inflated numbers.
Mean time to detect fell from 9 to 7 minutes after freshness checks for critical tables moved from hourly to every 10 minutes.
Of 48K rejected records, 38% were schema mismatches from one mobile app version. It was fixed in the next release and 17K records were replayed.
About the data. Every number on this page is sample data from a seeded generator written for this project. It is shaped to behave like a real workload, with daily peaks, late events and the odd incident, but it does not come from any employer or client. Download it as check_results_daily.csv or read data.json.