Data observability: find out that data broke before your stakeholders do
TL;DR
Difficulty: Advanced
Tests catch the failures you expected. Monitoring catches the rest, and the faster you detect, the less data you lose.
- Watch five signals: freshness, volume, schema, distribution and lineage.
- An empty result is not a pass: a missing day counts as zero and must fail.
- Compare Saturdays with Saturdays, using the median and the MAD, not fixed percentages.
- Watch the ratio between two sources that should move together.
- Agree service level objectives, alert on symptoms at the right severity, and tune until most alerts are real.
- In an incident, tell people first, fix the cause, backfill or mark the gap, and write a blameless postmortem.
- Start with SQL and a scheduler. Buy a tool when hand written checks stop scaling.
What to read first
Every test can pass while a source has quietly stopped sending. This chapter shows how to notice before the owner does: what to watch, how to set thresholds that do not cry wolf, and what to do in the hours after an alert, worked through the weekend an invented Leeds homeware shop lost its GA4 export.
Tests catch the failures you expected. Monitoring catches the rest.
The worst way to learn that your data broke is a message from the person who runs the business: "Why does the weekend show no visitors?" By then a report has been wrong for days, someone may have acted on it, and the question everyone asks next is whether any other number can be trusted.
The previous chapter, testing data pipelines, was about proving a pipeline right before its numbers reach a report. Tests are written for failures you can imagine: a key that must be unique, a status that must be one of five values. This chapter is about everything else. Sources stop sending, files change shape, a tracking tag quietly fires half as often, and every test still passes because nothing it checks is wrong. The question here is the one every data engineer meets eventually: how do I find out that data broke before my stakeholders do?
A few terms first, so nobody is left behind:
- Monitoring means checking, on a schedule, that the data behaves the way it normally does, and raising an alert when it does not.
- Data observability is the wider idea that you can see the health of your data from the outside at any time: how fresh it is, how much arrived, what shape it has, what its values look like and where it flows. The term was borrowed from software operations.
- Freshness is how recent the data is. Volume is how much of it arrived. Schema is its shape: the columns and their types. Distribution is what the values look like: averages, shares, how many are empty. Lineage is the map of which data feeds which table, report and decision.
- An incident is any time the data is wrong, late or missing in a way that matters to someone.
- A stakeholder is anyone who relies on the numbers: the owner, the marketing lead, the accountant.
The difference between tests and monitoring is worth holding on to. A test asks "is this rule broken?" and needs you to know the rule in advance. Monitoring asks "is today unusual compared with every other day?" and needs nothing but history. You need both. Tests stop the failures you predicted from reaching production, and monitoring finds the ones nobody predicted after they arrive.
Example: the weekend the GA4 export stopped at Wrenfield Home
Wrenfield Home is the invented homeware shop in Leeds that runs through this whole series (wrenfieldhome.example). Priya owns it. Callum builds the shop and the data platform. The shop runs on Ruby on Rails and Solidus with PostgreSQL. Google Analytics 4 (GA4) sends its raw events to BigQuery every day, one table per day named events_YYYYMMDD, and dbt Core turns those events into session and channel tables. Every number about this incident is invented for the example.
On Friday 5 February 2027 the payment card on Wrenfield's Google Cloud billing account expires. Google's documentation is plain about what that means: the BigQuery export needs a valid form of payment, and if the export is interrupted because the payment method is invalid, Google cannot export the data for that time again.1 So the tables events_20270206 (Saturday) and events_20270207 (Sunday) are never created.
Nothing fails. The nightly dbt run is green, because an incremental model that finds no new rows simply adds none. The tests are green, because a not_null or unique test on zero new rows has nothing to complain about. The orchestrator reports success. This is the silent success that the chapter on orchestration warned about.
On Tuesday 9 February at 9.30am Priya opens her weekly channel report. Revenue attributed to Meta ads looks a quarter lower than the week before, and the daily chart shows two empty days. She messages Callum. He finds the missing tables at 10am, updates the card at 10.40am, and Monday's table arrives on Tuesday afternoon as normal. The two weekend days are gone from BigQuery for good.
| When | What happened |
|---|---|
| Fri 5 Feb | Card on the billing account expires |
| Sun 7 Feb, mid afternoon | Saturday's table should arrive. It does not |
| Mon 8 Feb, mid afternoon | Sunday's table should arrive. It does not |
| Tue 9 Feb, 9.30am | Priya notices the empty weekend in her report |
| Tue 9 Feb, 10.40am | Callum fixes the payment method |
| Tue 9 Feb, 4pm | Monday's table arrives. Saturday and Sunday stay lost |
Every section below asks the same question of this weekend: what would have caught it sooner, and what would that have saved?
Data downtime is the number to make smaller
Before building checks, decide what you are trying to reduce. A useful measure is data downtime: the time during which data is partial, wrong, missing or otherwise inaccurate. The term and the formula below come from Barr Moses of Monte Carlo, a company that sells a data observability product, so treat them as a vendor's framing. The framing is still useful, and I use it here neutrally.2
where is the total data downtime over a period, in hours, is the number of incidents in that period, is the time from the moment incident made the data wrong to the moment someone knew about it, and is the time from knowing to the moment the data was right again, or honestly marked as incomplete. Monte Carlo writes the same idea as the number of incidents times the average time to detection plus the average time to resolution.2 It is a sum of durations, the same arithmetic as in Foundations: ratios and rates.
The formula shows the three levers. Have fewer incidents (tests and better sources). Detect faster (monitoring). Resolve faster (a practised incident response). Monitoring works on the middle term, which is usually the largest, because an unwatched failure lasts until a human happens to look.
Example: Wrenfield's weekend in hours
Callum counts from the moment the data became wrong for anyone relying on it. Saturday's table normally arrives by mid afternoon on Sunday, so he takes Sunday 7 February at 6pm as the moment the report would have shown a gap.
Detection took from Sunday 6pm to Tuesday 9.30am:
So is 39.5 hours: 24 hours from Sunday 6pm to Monday 6pm, plus 15.5 hours to Tuesday 9.30am.
Resolution took from Tuesday 9.30am until the data flowed again and the gap was marked in the reports at 4pm:
So is 6.5 hours, from 9.30am to 4pm on the same day.
So for this one incident:
So is 46 hours for a single incident.
Of those 46 hours, 39.5 were spent not knowing. That is 86% of the downtime, and it is the part a simple freshness check would have removed. Later in this chapter the same weekend is replayed with monitoring in place.
The signals worth watching
There are a handful of signals that catch most data failures. Monte Carlo popularised a list of five "pillars" of data observability: freshness, quality, volume, schema and lineage.3 It is a vendor's list, written to describe what their product watches, but it maps well onto how data actually fails. I use a slightly more concrete version with "quality" read as the distribution of values:
| Signal | The question it answers | Typical failure it catches |
|---|---|---|
| Freshness | Is the newest data as new as it should be? | A source stopped sending, a job did not run, a file is late |
| Volume | Did the usual amount arrive? | A partial load, a tag firing half as often, duplicated rows |
| Schema | Does the data still have the same columns and types? | A new column shifts a CSV, a renamed field arrives empty |
| Distribution | Do the values look like they usually do? | A unit change, a sudden rise in empty fields, a default value everywhere |
| Lineage | What depends on this, and what does it depend on? | Not a failure detector, but it tells you who is affected and where to look |
Each signal costs little to watch on its own. Together they cover most of the ways data goes wrong without an error message. The data quality dimensions chapter defined what "good" means for a single dataset. Monitoring watches those same properties over time and asks whether today differs from normal.
Example: which signal would have caught Wrenfield's known problems
Callum takes the list of known data problems from earlier chapters and asks which signal would raise each one if it happened again or got worse:
| Problem at Wrenfield | Signal that catches it |
|---|---|
| GA4 export stops (this chapter's incident) | Freshness, and volume of zero |
| 3PL returns file arrives up to five days late | Freshness of the file, with a deadline that allows for the known delay |
| GA4 shows about 15% fewer purchases than the shop | Volume, as a ratio between two sources that should move together |
| About 2% of orders have a missing or invalid phone number | Distribution: the share of empty values, watched for a jump |
| One supplier feed sends dimensions in millimetres | Distribution: a median that jumps by a factor of ten |
| 3PL file changes its columns | Schema of the file header |
| Duplicate customer accounts (3.1%) | Distribution: the duplicate share, watched for growth |
None of these needs a product. Each is a small query that runs on a schedule and compares today with a threshold or with history. The next sections build them one by one.
Freshness: is the data as new as it should be
Freshness is the first check to build, because a source that stops sending is the most common failure and the easiest to detect. There are two kinds, and mixing them up causes false alarms.
- Load freshness asks when data last arrived: the newest load time stamp, or the newest file.
- Event freshness asks how recent the newest event in the data is: the newest order time, the newest GA4 event time.
The lag is simply the difference between now and the newest time stamp:
where is the freshness lag, is the time the check runs and is the largest time stamp in the data, either load time or event time. A check fails when is larger than a threshold you choose from how the source normally behaves, not from how you wish it behaved. It is a plain difference between two times, and comparing it with a threshold is the same reasoning as any rate per period in Foundations: ratios and rates.
A threshold needs to know the source's rhythm. GA4's daily table is created after the day ends and typically arrives mid afternoon in the property's time zone, with no guaranteed time.4 A check at 7am would fail every single day. A check at 6pm fails only when something is genuinely wrong.
Example: choosing the GA4 freshness threshold
Wrenfield's GA4 property runs on London time, and the shop does not use the streaming (intraday) export. Callum works out the event lag in two cases, both checked at 6pm on Sunday 7 February.
If Saturday's table has arrived, the newest event is from Saturday just before midnight, so the lag at 6pm on Sunday is the 18 hours since midnight:
where is the lag in hours on a normal day.
If Saturday's table is missing, the newest event is from Friday just before midnight, so the lag is the whole of Saturday plus the same 18 hours of Sunday:
where is the lag in hours when the table did not arrive.
So a threshold of 42 hours separates the two cases at 6pm: on a normal day the lag is about 18 hours at that moment, and on a broken day it reaches 42. A warning at 39 hours (3pm on Sunday, when the table is usually there but not guaranteed) gives an early hint without a false page. Callum writes both thresholds into the source definition in the next section.
A freshness check in dbt and in plain SQL
dbt Core can check source freshness for you. You declare, per source, which column holds the time stamp and how old the newest row may be before dbt warns or errors.5 Since dbt 1.9 the freshness block sits under config, and since 1.10 loaded_at_field does too.5 The command dbt source freshness runs the checks.
# models/sources/ga4.yml (dbt Core 1.10)
sources:
- name: ga4
database: wrenfield-data
schema: analytics_123456789
tables:
- name: events
identifier: "events_*"
config:
loaded_at_field: "timestamp_micros(event_timestamp)"
freshness:
warn_after: {count: 39, period: hour}
error_after: {count: 42, period: hour}
filter: >
_TABLE_SUFFIX >= format_date('%Y%m%d', date_sub(current_date('Europe/London'), interval 7 day))
and _TABLE_SUFFIX not like 'intraday%'
Three details in this file matter:
identifier: "events_*"turns the daily tables into one wildcard table, and_TABLE_SUFFIXholds the part of the table name after the prefix.6event_timestampis stored in microseconds in UTC, so it needstimestamp_micros.7- The filter limits the scan to the last week. Without it, every freshness run reads the event time of five years of data. The second condition is there because the intraday tables also match
events_*, and their suffix starts with the wordintraday, which sorts after any date in a string comparison.
dbt is not required. A plain query works anywhere, and it is worth writing once by hand, because it shows the trap that catches most home made checks: an empty result is not a pass.
-- PostgreSQL: freshness of the 3PL import (raw.threepl_events)
-- WRONG: if the table is empty, max() is NULL, the comparison is NULL,
-- and the CASE falls through to 'pass'.
SELECT CASE
WHEN max(file_date) < current_date THEN 'fail'
ELSE 'pass'
END AS status
FROM raw.threepl_events;
-- RIGHT: a missing value is a failure, said explicitly.
SELECT
max(file_date) AS newest_file,
now() - max(loaded_at) AS load_lag,
CASE
WHEN max(file_date) IS NULL THEN 'fail'
WHEN max(file_date) < (now() AT TIME ZONE 'Europe/London')::date
THEN 'fail'
ELSE 'pass'
END AS status
FROM raw.threepl_events;
max() over no rows returns NULL, and in SQL a comparison with NULL is neither true nor false, so the first WHEN is skipped. The SQL traps chapter covers this three valued logic in depth. In a monitoring query it turns a broken pipeline into a green tick.
Example: the 3PL deadline
The 3PL warehouse uploads one CSV a day with the previous day's shipments and returns, normally before 6am. Its returns can be up to five days late, as earlier chapters measured, but the file itself always arrives daily, even when it contains few returns. So Callum checks load freshness of the file, not event freshness of the returns. A return dated five days ago in today's file is normal. No file today is not.
He sets the deadline at 9am London time: three hours after the usual arrival, early enough for the stock report at 10am. On a normal Wednesday the query at 9am returns newest_file = 2027-02-10, load_lag = 03:12:40, status = pass. On the day the 3PL's upload server is down, it returns newest_file = 2027-02-09 and fail, and Callum rings the 3PL before the stock report goes out.
Volume: did the usual amount arrive
Freshness tells you that something arrived. Volume tells you whether enough arrived. A table can be perfectly fresh and still hold half a day, because a load stopped part way or a tracking tag broke on one page type.
The usual first attempt is a fixed rule: "alert if today's rows differ from yesterday by more than 10%". It fails in both directions. Shops have strong weekly patterns, so Saturday is always lower than Friday and the rule fires every weekend. Black Friday is always higher, so it fires then too. And a slow decline of 3% a day never fires at all.
A better rule compares today with the same weekday in recent weeks, and uses the median rather than the mean, because one past incident or one sale day should not move the band. The spread is measured with the median absolute deviation (MAD), the median of how far each value lies from the median. Both are robust: a single extreme value barely moves them. The Foundations: median and mode and Foundations: spread sections explain them from scratch, and the chapter on outliers and anomalies applies them to single rows rather than to daily totals.
The score that says how unusual today is, the modified z score, comes from Iglewicz and Hoaglin as documented in the NIST/SEMATECH engineering statistics handbook:8
where is the modified z score for today, is today's row count, is the median of the comparison days, is the median absolute deviation of those days, and is a constant that puts on roughly the same scale as an ordinary z score for normally distributed data. Iglewicz and Hoaglin suggest treating as a potential outlier.8 Foundations: spread explains the MAD and the z score from scratch.
Solving for gives the expected band directly:
where and are the lowest and highest counts that still count as normal. The factor is about 5.19. It is the same idea as an interval around an estimate in Foundations: confidence intervals, built from robust measures instead of the mean and standard deviation.
Why 3.5 and not 2? Because false alarms add up. Classic control charts set their limits at three standard deviations, and for normally distributed data a point falls outside them by chance about 0.27% of the time.9 That sounds rare. But 40 tables checked once a day for 30 days are 1,200 checks, and
where is the expected number of false alarms in the month, the number of checks and the chance that one healthy check fails anyway. Real daily counts are rarely normal, so the true rate is usually higher. Wide bands are not laziness. They are what keeps alerts readable, the subject of a later section, and Foundations: probability explains the arithmetic of expected values.
Example: the band for Saturday 6 February
Callum takes the GA4 event counts of the eight Saturdays before 6 February (invented, but shaped like a real shop with about 110,000 sessions a month):
| Saturday | Events |
|---|---|
| 12 Dec | 71,240 |
| 19 Dec | 74,300 |
| 26 Dec | 68,920 |
| 2 Jan | 69,880 |
| 9 Jan | 73,510 |
| 16 Jan | 70,460 |
| 23 Jan | 70,980 |
| 30 Jan | 72,150 |
Step 1, the median. Sorted, the values are 68,920, 69,880, 70,460, 70,980, 71,240, 72,150, 73,510 and 74,300. With eight values the median is the mean of the fourth and fifth:
So events.
Step 2, the distances from the median: 2,190, 1,230, 650, 130, 130, 1,040, 2,400 and 3,190. Sorted: 130, 130, 650, 1,040, 1,230, 2,190, 2,400, 3,190. Their median is the MAD:
So events.
Step 3, the half width of the band:
where is the distance from the median to either edge of the band, rounded to the nearest ten. The edges follow:
That is the lower edge, . The upper edge adds the same width:
So any Saturday between and events counts as normal.
Step 4, the score for the broken Saturday. The table is missing, so the count is zero:
So , far beyond 3.5, the threshold from Foundations: spread. A partial day would show up too: 52,000 events would give . A normal Saturday such as 30 January, at 72,150 events, gives .
A volume check that treats a missing day as zero
The query below computes the same band in BigQuery for yesterday's GA4 events. Read it for one idea above all: it builds a list of every day it expects first (a date spine) and only then joins the counts to it. A missing table becomes a day with zero rows, which fails loudly. If you count only the tables that exist, a missing day is simply absent from the result, and absent rows raise no alerts.
-- BigQuery (GoogleSQL): volume check for yesterday's GA4 events
DECLARE check_day DATE DEFAULT DATE_SUB(CURRENT_DATE('Europe/London'), INTERVAL 1 DAY);
WITH days AS (
SELECT d
FROM UNNEST(GENERATE_DATE_ARRAY(DATE_SUB(check_day, INTERVAL 56 DAY), check_day)) AS d
),
counts AS (
SELECT PARSE_DATE('%Y%m%d', _TABLE_SUFFIX) AS d, COUNT(*) AS n
FROM `wrenfield-data.analytics_123456789.events_*`
WHERE _TABLE_SUFFIX BETWEEN FORMAT_DATE('%Y%m%d', DATE_SUB(check_day, INTERVAL 56 DAY))
AND FORMAT_DATE('%Y%m%d', check_day)
GROUP BY d
),
daily AS ( -- every expected day, zero where no table exists
SELECT days.d, COALESCE(counts.n, 0) AS n
FROM days LEFT JOIN counts USING (d)
),
history AS ( -- the same weekday in the eight weeks before
SELECT n
FROM daily
WHERE d < check_day
AND EXTRACT(DAYOFWEEK FROM d) = EXTRACT(DAYOFWEEK FROM check_day)
),
med AS (
SELECT ANY_VALUE(m) AS median_n
FROM (SELECT PERCENTILE_CONT(n, 0.5) OVER () AS m FROM history)
),
mad AS (
SELECT ANY_VALUE(m) AS mad_n
FROM (
SELECT PERCENTILE_CONT(ABS(h.n - med.median_n), 0.5) OVER () AS m
FROM history AS h CROSS JOIN med
)
)
SELECT
check_day,
today.n AS observed,
med.median_n,
mad.mad_n,
med.median_n - 3.5 / 0.6745 * mad.mad_n AS lower_bound,
med.median_n + 3.5 / 0.6745 * mad.mad_n AS upper_bound,
0.6745 * (today.n - med.median_n) / NULLIF(mad.mad_n, 0) AS modified_z,
IF(ABS(0.6745 * (today.n - med.median_n) / NULLIF(mad.mad_n, 0)) > 3.5
OR today.n = 0, 'fail', 'pass') AS status
FROM daily AS today
CROSS JOIN med
CROSS JOIN mad
WHERE today.d = check_day;
A few choices in this query deserve a sentence each:
GENERATE_DATE_ARRAYandUNNESTbuild the spine of 57 days: yesterday plus eight full weeks before it.- The
BETWEENon_TABLE_SUFFIXlimits the wildcard to the tables needed, which keeps the scan small.6 PERCENTILE_CONTis used as an analytic function over the whole history, which gives an exact median of the eight values.ANY_VALUEthen collapses the repeated result into one row.NULLIF(mad.mad_n, 0)guards against division by zero on a source so steady that every past value is identical. The extraOR today.n = 0makes sure a missing day fails even then.- Counting rows reads the event tables. For a quick check across many tables, BigQuery's
INFORMATION_SCHEMA.PARTITIONSview liststotal_rowsandlast_modified_timeper table from metadata, without reading the data. It returns at most 1,000 tables per query, and five years of daily GA4 tables are more than that, so filter ontable_name.10 DAYOFWEEKcompares Saturdays with Saturdays. For a source with a strong yearly pattern, such as December trade, eight weeks of the same weekday adapts quickly, and the article on forecasting demand with seasonality shows heavier tools when you need them.
Example: the result on Sunday 7 February
Run on Sunday 7 February with check_day = 2027-02-06, the query returns one row:
| check_day | observed | median_n | mad_n | lower_bound | upper_bound | modified_z | status |
|---|---|---|---|---|---|---|---|
2027-02-06 | 0 | 71110 | 1135 | 65220 | 77000 | -42.3 | fail |
The bounds are rounded here. The same query run against the shop's own order table, with orders per day instead of events, gives a second band that does not depend on GA4 at all.
Comparing two sources that should move together
Some failures are invisible in any single source. A tracking tag that stops firing on one payment method lowers GA4 purchases by 3% or 4%, well inside a daily band. The trick is to compare two sources that should move together and watch their ratio, because the ratio removes the weekly pattern and the season that both sources share.
At Wrenfield, GA4 counts about 15% fewer purchases than the shop, mainly because of consent choices and blockers. The article on reconciling analytics, ads and orders explains why that gap exists and why it is legitimate. Monitoring does not try to close it. It watches whether it stays the same.
where is the capture ratio, the number of purchase events in GA4 and the number of completed orders in the shop for the same period. See Foundations: ratios and rates.
How wide should the band around be? If each order has the same chance of being tracked, independently of the others, the ratio behaves like a proportion, and its standard error is:
where is the standard error of the ratio, the usual capture ratio and the number of shop orders in the period. Independence is an approximation, because one broken browser version affects many orders at once, but it gives a sensible starting width. Foundations: confidence intervals and Foundations: sampling explain where it comes from.
Example: daily or weekly?
With about 1,980 orders a month, Wrenfield has about 66 orders a day and about 462 a week, and .
For one day:
A band of three standard errors runs from to . That is too wide to catch a tag that broke for one payment method.
For one week:
Three standard errors are now , so the band runs from 0.80 to 0.90. Callum checks the ratio daily only for a collapse (below 0.5, which catches a missing day like 6 February at a ratio of zero) and weekly for drift.
The chart shows why. In this invented history, a theme update on 4 January moved the purchase event to a template that one payment method skips. The weekly ratio fell to about 0.71 and stayed there for three weeks before anyone looked. With the weekly check in place, the first Monday after the update would have flagged it.
Schema: did the shape of the data change
A schema change is the classic failure that tests miss, because the test was written for the old shape. A file gains a column, a field is renamed, a number becomes text. Depending on how the loader reads the data, the result is a crash (the good case), a column full of empty values, or values silently landing in the wrong column (the worst case).
There are two places to watch:
- At the edge, before loading: the header of a file, the fields of an API response. This is where you can still refuse the data.
- In the warehouse: the columns and types of every raw and modelled table, compared with yesterday.
The data types, schemas and formats chapter explains why types break pipelines, and the contracts in the testing chapter stop your own models from changing shape by accident. Schema monitoring covers the sources you do not control.
Example: the 3PL adds a column
The 3PL's file is semicolon delimited and encoded in Windows 1252, as every chapter of this series has noted. On 3 February the 3PL adds a column carrier_service in fourth position, without notice. Callum's old loader read columns by position, so from that day carrier_service (values such as 48H) would have landed in the quantity column, and the cast to an integer would have failed for some rows and silently produced nonsense for others.
He now checks the header before anything is loaded:
# check_threepl_header.py
import csv
from pathlib import Path
EXPECTED = ["shipment_ref", "order_number", "wh_sku", "quantity", "event_type", "event_time"]
def header_problems(path: Path) -> list[str]:
"""Return a list of problems with the file header, empty if it is as expected."""
with path.open(encoding="cp1252", newline="") as f:
header = next(csv.reader(f, delimiter=";"), [])
header = [h.strip().lower() for h in header]
problems = []
missing = [c for c in EXPECTED if c not in header]
new = [c for c in header if c not in EXPECTED]
if missing:
problems.append(f"missing columns: {missing}")
if new:
problems.append(f"new columns: {new}")
if not missing and [c for c in header if c in EXPECTED] != EXPECTED:
problems.append(f"columns in a different order: {header}")
return problems
On the file of 3 February it returns ["new columns: ['carrier_service']", "columns in a different order: [...]"], and the loader stops with that message instead of loading. Callum then decides deliberately: he reads columns by name from now on, adds carrier_service to the raw table and to EXPECTED, and loads the held file. The test that goes with it, in pytest, feeds the function a header with an extra column and asserts both messages, as the testing chapter showed for cleaning rules.
Watching the warehouse schema with INFORMATION_SCHEMA
Inside BigQuery, every dataset has an INFORMATION_SCHEMA.COLUMNS view with one row per column of every table: its name, position, data type and whether it may be empty.11 Saving that view once a day and comparing today with yesterday gives you a full schema history for the cost of a tiny query.
-- BigQuery (GoogleSQL): daily snapshot of the raw dataset's columns
INSERT INTO monitoring.schema_snapshots (snapshot_date, table_name, column_name, data_type, is_nullable)
SELECT CURRENT_DATE('Europe/London'), table_name, column_name, data_type, is_nullable
FROM `wrenfield-data`.raw.INFORMATION_SCHEMA.COLUMNS;
-- Compare today with yesterday
WITH t AS (SELECT * FROM monitoring.schema_snapshots WHERE snapshot_date = CURRENT_DATE('Europe/London')),
y AS (SELECT * FROM monitoring.schema_snapshots WHERE snapshot_date = DATE_SUB(CURRENT_DATE('Europe/London'), INTERVAL 1 DAY))
SELECT
COALESCE(t.table_name, y.table_name) AS table_name,
COALESCE(t.column_name, y.column_name) AS column_name,
CASE
WHEN y.column_name IS NULL THEN 'added'
WHEN t.column_name IS NULL THEN 'removed'
ELSE 'type or nullability changed'
END AS change,
y.data_type AS old_type,
t.data_type AS new_type
FROM t
FULL OUTER JOIN y
ON t.table_name = y.table_name AND t.column_name = y.column_name
WHERE y.column_name IS NULL
OR t.column_name IS NULL
OR t.data_type != y.data_type
OR t.is_nullable != y.is_nullable;
The FULL OUTER JOIN keeps columns that exist on only one side, which are exactly the added and removed ones.
Example: the GA4 schema grows
GA4 adds fields to its export schema from time to time. In this invented week, the snapshot diff on the GA4 dataset shows one row for every daily table created since the change: a new nested field inside a record. Callum's staging model selects named fields only, so nothing breaks. He classifies "added" as information, written to a log and summarised weekly, and "removed" or "type changed" as an alert, because those break models. That one decision cuts his schema alerts by about nine in ten without hiding anything that matters.
Distribution: do the values still look normal
Data can arrive on time, in the right amount and the right shape, and still be wrong. A field fills with a default value. A unit changes. A form change makes a field optional and half the customers skip it. These show up as a change in the distribution of the values: the share of empty fields, the share of each category, the median or the range of a number.
For each important column, pick one or two statistics and watch them the same way as volume, against recent history:
| Column type | Statistic worth watching |
|---|---|
| Any column | Share of empty values |
| Category (status, country, channel) | Share of each value, and any value never seen before |
| Number (price, quantity, weight) | Median, and the 1st and 99th percentile |
| Identifier | Share of duplicates |
| Time stamp | Share in the future, share older than expected |
Ratios between the new and the usual value can be read like fingerprints. A median that is exactly ten times its usual value points to centimetres becoming millimetres. A factor of about 2.54 points to inches. A factor of 100 points to pounds becoming pence. A factor of exactly 1.2 on a price points to VAT added or removed at 20%.
Example: the supplier that switched to millimetres
Wrenfield's feeds already include one supplier that sends dimensions in millimetres, which the standardising values chapter converts. In this invented case a second supplier, Holloway Textiles, switches its feed from centimetres to millimetres on 1 February without saying so.
Callum's check computes the median width per supplier each day and divides it by the median of the previous 30 days:
-- BigQuery (GoogleSQL): median width per supplier, today against the last 30 days
WITH today AS (
SELECT supplier, APPROX_QUANTILES(width, 100)[OFFSET(50)] AS med
FROM raw.supplier_feed
WHERE feed_date = CURRENT_DATE('Europe/London')
GROUP BY supplier
),
before AS (
SELECT supplier, APPROX_QUANTILES(width, 100)[OFFSET(50)] AS med
FROM raw.supplier_feed
WHERE feed_date BETWEEN DATE_SUB(CURRENT_DATE('Europe/London'), INTERVAL 30 DAY)
AND DATE_SUB(CURRENT_DATE('Europe/London'), INTERVAL 1 DAY)
GROUP BY supplier
)
SELECT t.supplier, b.med AS usual_median, t.med AS today_median,
SAFE_DIVIDE(t.med, b.med) AS factor
FROM today AS t JOIN before AS b USING (supplier)
WHERE SAFE_DIVIDE(t.med, b.med) NOT BETWEEN 0.5 AND 2;
APPROX_QUANTILES is approximate, which is fine here, because the question is whether the median moved by a factor of two or more, not its exact value. On 1 February the query returns one row: Holloway Textiles, usual median 45, today 450, factor 10.0. Cushion covers have not grown to 4.5 metres. Callum adds the supplier to the conversion rule before the feed reaches the product pages, where a wrong width would have changed the shipping band of 120 products.
Example: the phone number field
About 2% of Wrenfield's orders have a missing or invalid phone number, as the series has noted since the profiling chapter. Callum watches that share per day. A checkout release on a Thursday makes the field optional on mobile by mistake, and the share jumps to 9% the next day. The 3PL needs the number for one carrier, so the jump would have meant failed deliveries within a week. The volume of orders is normal and every test passes, because the column has always been allowed to be empty. Only the distribution moved.
Lineage: who is affected, and where to look
Lineage is the map of dependencies: which sources feed which tables, which tables feed which reports, and who reads those reports. It does not detect failures by itself. It answers the two questions that come straight after an alert: what else is broken because of this (the blast radius, looking downstream), and where did this start (the root cause, looking upstream).
dbt already knows the lineage of every model it builds, from the ref and source calls, and shows it in its documentation site. Tools that track lineage across systems often use OpenLineage, an open standard that describes jobs, runs and datasets as events.12 A later chapter in this series covers metadata, lineage and data catalogues in depth. For monitoring, a simple version is enough: for each source, a list of what depends on it, kept next to the checks.
Example: the blast radius of the missing GA4 tables
Callum reads it straight from dbt's lineage:
| Layer | Affected by the missing GA4 days |
|---|---|
| Staging | stg_ga4__events |
| Models | fct_sessions, fct_ga4_purchases, fct_channel_daily |
| Reports | Weekly channel report, conversion rate dashboard, return on ad spend by channel |
| Not affected | Revenue, orders, margin, stock (all from the shop database) |
That table is half of the message he would send to Priya. It tells her which numbers to distrust and, just as important, which numbers are fine. Without it, every stakeholder assumes everything is broken.
Service levels: SLIs, SLOs and SLAs for data
"Fresh enough" and "complete enough" need numbers, or every alert becomes a debate. Site reliability engineering, the discipline Google described in its book of the same name, gives three terms that transfer to data without change:13
- A service level indicator (SLI) is a carefully defined, quantitative measure of some aspect of the service. For data: the share of days on which yesterday's table arrived by its deadline.
- A service level objective (SLO) is a target value or range for an SLI. For data: 97% of days over the last 90.
- A service level agreement (SLA) is a contract with users that includes consequences if the objective is missed.13
Most small businesses need SLIs and SLOs and no SLA. An SLA makes sense when someone outside pays for the data, for example Ledgerline, an invented bookkeeping software company in Bristol whose customers receive monthly reports on a contractual date. Inside a shop, the SLO is an agreement between Callum and Priya about what "on time" means, written down so it can be measured.
The SRE book also advises choosing a handful of representative indicators rather than every metric you can track.13 For data that means one or two SLIs per data product people rely on, not one per table.
The gap between the objective and perfection is the error budget: how much failure the objective allows.14
where is the error budget in days, is the SLO as a share, and is the number of days in the window. See Foundations: percentages.
Example: the data objectives at Wrenfield
Callum and Priya agree four objectives:
| Data product | SLI | SLO over 90 days |
|---|---|---|
| Orders and revenue in the warehouse | Yesterday's orders loaded and reconciled with the shop by 7am | 99% |
| GA4 events | Yesterday's events table present with a normal volume by 6pm | 97% |
| 3PL shipments and returns | Today's file loaded by 9am | 95% |
| Weekly channel report | Built on Monday by 9am with every input within its SLO | 95% |
For GA4 the error budget is:
So is 2.7 days in 90. The February weekend used two of those days, of the budget, in a single incident. With monitoring in place, as the replay later in this chapter shows, it would have used one day, 37%. When a budget runs low, the agreed response is not panic but priority: Callum spends the next sprint on the cause (in this case a card expiry reminder and a second payment method on the billing account) instead of new reports.
Alerts people still read
An alert that fires too often stops being read, and an unread alert is worse than none, because everyone believes they are covered. This is alert fatigue. Google's SRE book puts the rule plainly: every page should be actionable, and every page should need a human's judgement, not a mechanical reply.15 It suggests asking of every alert rule whether you could ever ignore it knowing it is harmless, whether it definitely means users are affected, and whether anyone can act on it.15
The same chapter separates symptoms from causes: "what's broken" from "why".15 For data, the symptom is what a stakeholder would notice, a late or incomplete table. The cause is one of a hundred things: an expired card, a deleted service account, a full disk. Alert on symptoms, because there are few of them and they always matter. Watch causes on a dashboard or as low priority tickets, because there are many and most do not matter on their own.
Three severities are enough for a small team:
| Severity | Goes to | Example |
|---|---|---|
| Page | Phone notification, any time | Orders missing from the morning revenue report on a sale day |
| Ticket | Chat channel or email, handled the next working morning | GA4 table late, 3PL file late, a schema column removed |
| Log | A weekly summary | A schema column added, a distribution moving inside its band |
Ask of every alert which severity it really needs. A page wakes someone. It is only worth it if acting now saves something that acting in the morning does not.
The SRE workbook takes this further with burn rate alerts: alert when the error budget is being used up much faster than the SLO allows, over both a long and a short window, so that a brief blip does not page anyone and a sustained failure does.14 For a handful of daily data products that is more machinery than needed, but the idea is worth keeping: alert on the objective, not on every wobble.
Example: Callum's first six weeks of alerts
Callum's first version used fixed thresholds of 10% on 40 tables and a GA4 freshness check at 7am. In week 1 it raised 61 alerts. Three were real. The share of alerts that were real, the precision, was:
where is the precision of the alerts in that week. See Foundations: ratios and rates.
He made four changes over five weeks:
- weekday aware bands with the median and MAD instead of fixed percentages
- the GA4 deadline moved from 7am to 6pm
- one alert per source instead of one per table
- schema additions demoted to the weekly log
By week 6 there were five alerts, two of them real:
So rose from about 5% to 40%, the same ratio as in Foundations: ratios and rates.
He also checked that nothing real was lost: he replayed the last three months of known incidents against the new rules, and every one of them would still have raised an alert.
Incident response: detect, triage, communicate, fix, backfill, learn
When an alert is real, a calm routine beats heroics. Software teams have written these routines down for years. PagerDuty publishes its incident response guide, with severity levels and roles such as the incident commander, the scribe and the liaison who talks to stakeholders.16 A data team of one or two does not need the roles, but it needs the steps:
- Detect. An alert fires, or a stakeholder asks. Either way, write down the time. It is the start of .
- Triage. Is it real? How bad is it? Which data products and reports are affected (lineage)? Is personal data involved? Set a severity.
- Communicate. Tell the people who rely on the affected numbers, before they find out themselves. Say what is affected, what is not, what they should not use, and when you will update them next.
- Fix the cause. Stop the bleeding first, then repair. Restart the source, fix the payment method, roll back the release.
- Backfill or mark. Reload the missing data if the source still has it. If it does not, mark the gap so every report shows it.
- Learn. Write a short postmortem and turn its lessons into checks.
The step people skip is the third. It feels better to fix first and explain later. But a stakeholder who learns about an incident from you, with a clear list of what is safe, keeps trusting the numbers. One who discovers it alone starts checking everything by hand. The reporting on cleaned data chapter covers how to restate numbers afterwards without losing that trust.
Example: the message Priya receives
Callum sends this on Monday 8 February at 8.45am, in the replay with monitoring in place:
GA4 data for Saturday 6 February is missing. The Google Cloud payment card expired, so the export did not run. I have fixed the payment method. Sunday's data should arrive this afternoon as normal. Saturday cannot be recovered from the export.
Affected: the weekly channel report, conversion rate and return on ad spend by channel for last week. Please do not move ad budget on last week's channel figures until I send the corrected report.
Not affected: revenue, orders, margin and stock. They come from the shop database and are complete.
Next update: today at 5pm, when Sunday's table has arrived.
It is short, it names what is safe, and it gives a time for the next update. Priya can plan her Monday around it.
Backfill when you can, mark the gap when you cannot
After the cause is fixed, the missing data either still exists somewhere or it does not. If it does, reload it: rerun the load for the affected days, idempotently, as the chapters on incremental loading and orchestration showed, and then reconcile the totals with the source.
Some data cannot come back. Google states that a GA4 export interrupted by an invalid payment method cannot be exported again, and that when a standard property keeps exceeding the daily export limit of one million events, the export is paused and earlier days are not reprocessed.1 Other sources behave the same way: an API that only returns the last 30 days, a 3PL that deletes files from its server after a week. For those, speed of detection decides how much is lost, and that is the strongest argument for monitoring there is.
When data cannot be backfilled, do not hide the gap and do not fill it with invented numbers. Record it in a table that every report can read, and show it next to the affected figures.
-- BigQuery (GoogleSQL): a register of known data gaps that reports join to
CREATE TABLE IF NOT EXISTS monitoring.data_gaps (
source STRING NOT NULL,
gap_start DATE NOT NULL,
gap_end DATE NOT NULL,
affected ARRAY<STRING>,
note STRING,
recorded_at TIMESTAMP NOT NULL
);
INSERT INTO monitoring.data_gaps VALUES
('ga4_export', DATE '2027-02-06', DATE '2027-02-06',
['fct_sessions', 'fct_ga4_purchases', 'fct_channel_daily'],
'Export interrupted by an expired payment card; not recoverable from the export.',
CURRENT_TIMESTAMP());
Example: what Callum does with the lost Saturday
The export is a copy. Collection in GA4 itself carried on, so the standard reports in the GA4 interface still show sessions and purchases for 6 February. Callum takes the daily totals from there for the weekly report, labelled as coming from the interface rather than the export, and the row in monitoring.data_gaps makes every chart that uses fct_sessions show a note on that day. Event level analysis for that Saturday, such as paths through the site, is simply not possible, and the note says so. That is honest, and it is the approach the article on showing uncertainty honestly argues for.
The postmortem, without blame
A postmortem is a short written record of an incident: what happened, why, what it affected, and what will change. The SRE book describes a blameless postmortem as one that focuses on the contributing causes without indicting any individual or team.17 The reason is practical. If people expect blame, they hide mistakes, and hidden mistakes repeat.
The same chapter lists common triggers for writing one, among them data loss of any kind and a monitoring failure, which usually means the incident was discovered by hand.17 The GA4 weekend hits both.
A useful postmortem for a data incident fits on one page:
| Section | Content |
|---|---|
| Summary | Two sentences a stakeholder understands |
| Impact | Which data, which days, which reports, which decisions, the data downtime in hours |
| Timeline | Times from the cause to the resolution, from logs, not memory |
| Contributing causes | Usually several. Never "human error" as the answer: ask why the system let it happen |
| What went well | Worth keeping |
| Actions | Each with an owner and a date, most of them new or better checks |
Example: the postmortem for the GA4 weekend
Callum writes it on Wednesday 10 February:
- Summary. The GA4 export did not run for 6 and 7 February because the Google Cloud payment card expired. Both days are lost from BigQuery. Priya found the gap in her report on Tuesday.
- Impact. Two days of GA4 events. Weekly channel report, conversion rate and return on ad spend by channel wrong for the week of 1 February. Data downtime 46 hours. Error budget for GA4: 2 of 2.7 days used.
- Contributing causes. The billing account had a single card and the expiry reminder went to an old email address. No check watched for missing GA4 tables. The dbt models treated "no new rows" as success. The report showed zero instead of a warning.
- What went well. The shop data was unaffected and the lineage table made it quick to say so.
- Actions. Add a second payment method and send billing alerts to a shared address (Priya, Friday). Add the GA4 freshness and volume checks from this chapter (Callum, Friday). Make the channel report read
monitoring.data_gaps(Callum, next week). Add a calendar reminder one month before any card on a data service expires (Priya, today).
Notice that only one action fixes the card. The rest make the next unknown failure visible sooner. That is the point of the exercise.
Replaying the weekend with monitoring in place
Now run the same weekend again with the checks from this chapter. Nothing about the cause changes: the card still expires and Saturday's export still fails on Sunday afternoon.
At 6.05pm on Sunday the hourly check finds no table for Saturday. The freshness lag is 42 hours and the volume score is far beyond the band. Because GA4 is a ticket, not a page, the alert goes to the shared chat channel and email. Callum is not woken. That is deliberate: Saturday's export has already failed and cannot be repeated, so acting at 6pm on Sunday saves nothing that acting at 8.30am on Monday does not.
On Monday at 8.30am Callum reads the alert. At 8.45am he sends the message to Priya. At 9am he fixes the payment method. Sunday's table, due Monday afternoon, arrives at 4pm as normal.
Example: the downtime, before and after
Detection now takes about five minutes from the deadline:
So is about 0.1 hours, the five minutes between the deadline and the check.
Resolution runs from Sunday 6.05pm to Monday 4pm, when Sunday's data has arrived and Saturday's gap is marked: 5.9 hours to midnight and 16 hours on Monday.
So is 21.9 hours, and the downtime is:
So is 22 hours, against 46 without monitoring.
| Without monitoring | With monitoring | |
|---|---|---|
| Who found it | Priya, in her report | A scheduled check |
| Time to detect | 39.5 hours | 0.1 hours |
| Time to resolve | 6.5 hours | 21.9 hours |
| Data downtime | 46 hours | 22 hours |
| Days of GA4 data lost | 2 | 1 |
| Error budget used | 74% | 37% |
| Decisions made on wrong numbers | Possibly, for a week | None, the message came first |
Resolution takes longer in the second case, because the problem was known on a Sunday evening and fixed on a Monday morning. The total still halves, one day of data is saved, and above all Priya hears about it from Callum, with a list of what is safe, before she makes any decision.
Build basic monitoring with SQL and a scheduler first
You do not need to buy anything to get most of the value in this chapter. A first version needs four parts:
- A results table where every check writes one row per run: what was checked, the value, the bounds, pass or fail.
- Checks as SQL, like the ones above, each inserting into that table.
- A scheduler that runs them: BigQuery scheduled queries, the orchestrator you already have, or cron on a small server.
- A way to alert: a query that fails when any check failed, so the scheduler's own failure notification does the work.
BigQuery scheduled queries can send an email when a run fails, and can publish to a Pub/Sub topic, both set in the console. The shortest interval between runs is five minutes.18 BigQuery's ERROR() function makes a query fail with your own message.19 Together they make a complete alerting loop with no extra service.
-- BigQuery (GoogleSQL): results table
CREATE TABLE IF NOT EXISTS monitoring.check_results (
check_name STRING NOT NULL,
target STRING NOT NULL,
checked_at TIMESTAMP NOT NULL,
observed FLOAT64,
lower_bound FLOAT64,
upper_bound FLOAT64,
status STRING NOT NULL, -- 'pass', 'warn' or 'fail'
severity STRING NOT NULL, -- 'page', 'ticket' or 'log'
details STRING
);
-- Last statement of the hourly scheduled query: fail the run if any
-- ticket or page check failed in this run, so the failure email goes out.
SELECT IF(
COUNT(*) > 0,
ERROR(CONCAT('Data checks failed: ', STRING_AGG(CONCAT(check_name, ' on ', target), ', '))),
'all checks passed'
)
FROM monitoring.check_results
WHERE checked_at >= TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 10 MINUTE)
AND status = 'fail'
AND severity IN ('page', 'ticket');
If you already run Dagster, its freshness policies attach a time window to an asset, with a warning window and a failure window, so the orchestrator shows the asset as late.20 The feature is marked as a preview in Dagster's documentation, so check the current version before you rely on it. With dbt, dbt source freshness in the scheduled run covers freshness for every declared source.5
Example: what Wrenfield's monitoring costs
Callum's first version has 14 checks: freshness for six sources, volume bands for four, the capture ratio, one schema diff, and two distribution checks. They run hourly from 6am to 8pm. Each check reads a few days of one or two columns, or a metadata view. On Wrenfield's data volumes the whole set scans a small fraction of what one analyst query on the event tables does, which is why the filters on _TABLE_SUFFIX and dates matter in every query above. Building it took him two days, including the tests for the check queries themselves. The test for the freshness query feeds it an empty table and asserts fail, which is exactly the bug from the start of this chapter.
What monitoring tools add
Commercial and open source observability tools do the same things as the queries above, with less work per table and some things that are hard to build yourself. Described from their own documentation:
- Elementary, an open source dbt package with a paid cloud version, adds anomaly tests such as
volume_anomalies, which compare recent time buckets with a training period of 14 days by default and can account for the day of the week.21 - dbt itself covers source freshness, and its documentation site shows model lineage.5
- Dagster shows freshness and asset checks next to the pipeline that builds the data.20
- Monte Carlo and similar commercial platforms learn thresholds automatically for every table, track lineage across tools, and give incidents a shared place to be handled.3
What you get from a tool: coverage of hundreds of tables without writing a check for each, thresholds that learn seasonality, column level lineage across systems, and an interface for triage. What you do not get: knowledge of your business. No tool knows that GA4 should see about 85% of shop orders, that the 3PL is allowed five days for returns, or that a factor of ten in a width means millimetres. Those checks are yours to write, whatever you buy.
A fair rule of thumb: start with SQL and a scheduler. Consider a tool when the number of tables makes hand written checks a burden, when several people need to share incidents, or when you spend more time tuning thresholds than acting on alerts.
Example: does Wrenfield need a tool yet?
Wrenfield has about 40 raw tables, 25 models and two people who care about the data. Fourteen hand written checks cover every data product with an SLO. Callum reviews the question every six months against three facts: how many tables have no check, how many hours a month go into tuning, and how many incidents were found by a person rather than a check. In the first six months those are 8 tables (all low value), about one hour a month, and zero. The answer for now is no, and it is written down with the date, so the next review starts from facts rather than from a sales call.
When a data incident is also a personal data breach
Most data incidents are about late or missing numbers. Some touch personal data: an export of the newsletter list lands in a storage bucket that is readable by anyone, a model joins customers to the wrong orders and a report sends one customer's details to another, a deletion job removes customer records that should have been kept. Those can be a personal data breach in law, and then the incident has a legal clock as well as a technical one.
This is general information, not legal advice. Under the UK GDPR, a controller must report a personal data breach to the Information Commission (formerly the Information Commissioner's Office, ICO) without undue delay and, where feasible, not later than 72 hours after becoming aware of it, unless it is unlikely to result in a risk to people's rights and freedoms.22 The Information Commission explains that a breach is a security incident affecting the confidentiality, integrity or availability of personal data, so losing access to data can count too, and that every breach must be recorded internally, even those not reported.23
That is why the triage step asks "is personal data involved?" every time. If the answer is yes, the 72 hours start when you become aware, not when the postmortem is written.
Example: the export that went to the wrong bucket
In an invented variation, a change to a scheduled export writes the newsletter list (38,000 email addresses with first names) to a storage bucket that is shared with an external design agency for product images. A schema check on the bucket's contents flags an unexpected file on Tuesday at 11am. Callum's triage marks it as involving personal data, he removes the file and the agency's access, records the time of awareness, and tells Priya straight away so that she can decide, with advice, whether the breach must be reported to the Information Commission. The technical fix took 20 minutes. The legal clock runs regardless.
Conclusion
Tests protect you from the failures you can predict. Monitoring finds the rest: the source that stops, the file that changes shape, the tag that fires less often, the unit that changes overnight. Five signals cover most of it: freshness, volume, schema, distribution and lineage.
Build the checks with care for the traps: an empty result is not a pass, a missing day is a zero, Saturdays are compared with Saturdays, and a ratio between two sources finds what each alone hides. Agree service level objectives with the people who use the data, so "late" means the same thing to everyone. Alert on symptoms, at the severity they deserve, and keep tuning until most alerts are real.
When something does break, tell people first, fix the cause, backfill or mark the gap honestly, and write a postmortem that improves the system instead of blaming a person. Some data, like an interrupted GA4 export, cannot be recovered, and for that data, how quickly you find out decides how much you lose.
