What You'll Learn
- 1Explain why CPU and memory are secondary signals while lag and freshness are primary
- 2Publish a custom metric from a pipeline and graph it alongside the built-in service metrics
- 3Write an alert policy with a sensible threshold, duration, and notification route
- 4Design a log export and dashboard layout that answers an incident question in under a minute
Monitoring a data pipeline is not the same as monitoring a web service. A web service either responds or it does not, while a pipeline can respond instantly and still be delivering numbers that are an hour stale, which is why the discipline leans on lag, freshness, and volume rather than on uptime alone. This lesson covers the signals worth watching on Google Cloud, how to publish the ones the platform does not know about, how to alert without exhausting the people who receive alerts, and what to do in the minutes after a page fires.
Signals that predict an incident
Three signals catch most pipeline failures early. The first is lag: how far behind real time the pipeline is running, whether that is Dataflow system lag, the age of the newest row in a table, or the depth of a Pub/Sub subscription backlog. The second is volume: rows or bytes processed per window compared with yesterday and last week, because an upstream system that stops sending data looks exactly like success to a system that processes whatever arrives. The third is failure rate: job failures, error counts in logs, and the share of records rejected by validation.
# Key metrics for data pipeline monitoring
metrics = {
"bigquery": {
"query_count": "Number of queries executed",
"bytes_scanned": "Total bytes scanned by queries",
"slots_used": "Number of slots in use",
"query_duration": "Query execution time",
"load_job_count": "Number of load jobs",
"storage_bytes": "Total storage used"
},
"dataflow": {
"element_count": "Elements processed",
"data_volume": "Data volume processed",
"system_lag": "Processing lag",
"worker_count": "Number of workers",
"cpu_utilization": "Worker CPU usage",
"pending_elements": "Elements in backlog"
},
"dataproc": {
"cluster_status": "Cluster health",
"yarn_apps": "Running YARN applications",
"hdfs_usage": "HDFS storage usage",
"job_duration": "Spark job execution time",
"worker_count": "Number of workers"
},
"pubsub": {
"message_count": "Messages published",
"unacked_messages": "Unacknowledged messages",
"publish_latency": "Time to publish",
"subscription_backlog": "Subscription queue depth"
}
}
Resource metrics such as CPU and worker count still matter, but as diagnostic context rather than as alerts. When system lag climbs, CPU tells you whether the pipeline is struggling to keep up or waiting on something else entirely, such as a full temporary directory or a locked table. Alert on the symptom the business feels, then use the resource graphs to explain it.
Publishing custom metrics
Most business facts are invisible to Cloud Monitoring until you write them there. Record counts after deduplication, the age of the newest event, and a quality score are all values your code already computes, and the monitoring API takes them as time series that you can graph and alert on like any built-in metric.
from google.cloud import monitoring_v3
from google.protobuf import timestamp_pb2
import time
def create_custom_metric(project_id, metric_type, value):
"""Create a custom metric for pipeline monitoring."""
client = monitoring_v3.MetricServiceClient()
project_name = f"projects/{project_id}"
series = monitoring_v3.TimeSeries()
series.metric.type = f"custom.googleapis.com/pipeline/{metric_type}"
series.resource.type = "global"
series.resource.labels["project_id"] = project_id
now = time.time()
seconds = int(now)
nanos = int((now - seconds) * 10**9)
interval = monitoring_v3.TimeInterval(
end_time={"seconds": seconds, "nanos": nanos}
)
point = monitoring_v3.Point(
interval=interval,
value=monitoring_v3.TypedValue(double_value=value)
)
series.points = [point]
client.create_time_series(
request={
"name": project_name,
"time_series": [series]
}
)
Two habits keep custom metrics affordable and readable. Emit them once per window rather than once per record, since custom metric volume is charged and a per-record write will dominate your bill. And keep the metric names stable and predictable under a single prefix, because the alternative is a dashboard nobody can navigate six months later when the person who named things has moved on.
Capacity and cost signals
Cost is a monitoring signal, not just a finance topic, because a sudden rise in bytes scanned usually means someone removed a partition filter or a new job started reading history on every run. Watch daily bytes billed, peak slot usage on BigQuery, and the number of jobs per day, each of which has a clear baseline once you have a week of history. A spike in job count with flat data volume often points at a retry loop, while flat job count with rising bytes points at a widening scan.
Storage growth deserves the same attention. Tables that grow far past their retention policy inflate query costs and slow maintenance, and a partitioned table whose oldest partitions suddenly disappear suggests a retention rule nobody remembers writing. Graphing storage alongside pipeline volume separates expected seasonal growth from an issue that needs an owner, and it gives the team a number to quote when someone asks what the new retention window would save.
Alert policies without fatigue
An alert policy is a filter, a comparison, a threshold, a duration, and a place to send the result. The filter selects the metric, the comparison and threshold decide what counts as a breach, the duration stops a one second spike from paging anyone, and the notification channel decides who finds out.
from google.cloud import monitoring_v3
def create_pipeline_alert(project_id, metric_name, threshold):
"""Create alert for pipeline metric."""
client = monitoring_v3.AlertPolicyServiceClient()
alert_policy = monitoring_v3.AlertPolicy(
display_name=f"Pipeline Alert: {metric_name}",
conditions=[
monitoring_v3.AlertPolicy.Condition(
display_name=f"{metric_name} threshold",
condition_threshold=monitoring_v3.AlertPolicy.Condition.MetricThreshold(
filter=f'resource.type="global" AND metric.type="custom.googleapis.com/pipeline/{metric_name}"',
comparison=monitoring_v3.ComparisonType.COMPARISON_GT,
threshold_value=threshold,
duration="60s",
),
)
],
notification_channels=[],
alert_strategy=monitoring_v3.AlertPolicy.AlertStrategy(
auto_close="1800s"
),
)
request = monitoring_v3.CreateAlertPolicyRequest(
name=f"projects/{project_id}",
alert_policy=alert_policy,
)
response = client.create_alert_policy(request=request)
print(f"Created alert: {response.name}")
Calibration matters more than the code. Derive thresholds from two weeks of history rather than intuition, require a breach to last long enough to cover normal jitter, and separate the two audiences: thresholds that mean someone should look now belong on a paging channel, while thresholds that mean someone should look today belong in a digest. An alert that fires nightly and is ignored nightly is worse than no alert, because it teaches the team that red does not mean red.
Logs, exports, and dashboards
Metrics tell you that something is wrong, and logs tell you what. Cloud Logging collects stdout from every job, and Log Explorer queries let you filter on a pipeline identifier and read the stack trace without leaving the incident. Saving those queries as one click filters for the on-call engineer is a small courtesy that pays for itself at three in the morning.
For anything longer than the default retention window, attach a log sink that exports to BigQuery, where you can join error spikes against deploy timestamps and answer whether the incident started with a code change. Logs-based metrics turn repeated error patterns into chartable series, and dashboards then follow a simple rule: one page per pipeline, with a health row of lag, volume, and failures at the top, a cost row underneath, and links to the runbook and the latest deploy. Anything an engineer would otherwise have to type during an incident belongs in the dashboard before the incident happens.
Handling the incident
| Step | Action | Typical tool |
|---|---|---|
| Detect | Alert fires or a freshness check misses its window | Cloud Monitoring alert |
| Triage | Confirm scope: one pipeline, one table, or everything | Dashboard and Log Explorer |
| Mitigate | Pause the broken source, backfill, or roll back the deploy | Composer or Cloud Build |
| Diagnose | Find the first bad run and the change that preceded it | Log export in BigQuery |
| Prevent | Add the missing check and update the runbook | Dataplex scan or assertion |
Backfills deserve a note of their own, because the recovery path is often the second failure. Replaying a day of data at full parallelism can starve other pipelines of slots, so throttle the replay, run it against a staging table first, and verify row counts against the source before it replaces anything the business reads.
Close every incident with a short written review that records detection time, the cause, what made it hard to diagnose, and the single check that would have caught it earlier. Two numbers tracked over time tell you whether the practice is working: how long detection took, and how long mitigation took. Both improve when the missing signal, dashboard panel, or runbook step is added as part of the fix rather than filed as a separate improvement item that nobody schedules.
Common Mistakes
Alerting on CPU and disk while nobody watches table freshness
Fix: Page on the signal the business feels, such as lag or missing rows, and keep resource metrics as graphs for diagnosis after the page.
Sending every alert to one shared channel with no owner
Fix: Route each alert to the team that can fix it, attach a runbook link, and review rules that fire often enough to be ignored.
Keeping logs only in Cloud Logging for a few days
Fix: Export to BigQuery with a sink so incident analysis can correlate error spikes with deploys months later.
Best Practices
- Alert on lag, freshness, and failure rate; treat CPU as diagnostic context
- Emit custom metrics once per window under a stable prefix to control cost and keep dashboards readable
- Keep a dashboard, a runbook, and a tested backfill procedure for every pipeline you own
Key Takeaways
- A pipeline can respond instantly and still be wrong, so lag and freshness outrank uptime as signals
- Custom metrics make business facts such as row counts and data age alertable through the same policies as built-in metrics
- Thresholds should come from history, and alerts that are ignored nightly should be reclassified or removed
- Log export to BigQuery turns a one-off investigation into a repeatable query against deploy and error history
Interview Questions
Q1: What are the key metrics to monitor for data pipelines?
Lag or freshness, processed volume against baseline, error and failure rates, resource utilization for diagnosis, quality rule failures, and cost. Lag and volume come first because they detect both slowdowns and silent upstream outages.
Q2: How do you set up effective alerting?
Derive thresholds from history, require a sustained breach, route to the owning team, separate paging from digest channels, and attach a runbook. Then measure how often each alert fires and how often it leads to real action, and tune or retire the ones that do not.
Q3: Why export logs to BigQuery?
Default log retention is short and ad hoc filtering is slow. A sink to BigQuery gives long retention, SQL over error patterns, and the ability to correlate spikes with deploy timestamps, which is how you prove what caused an incident instead of guessing.
Q4: How do you monitor a streaming pipeline differently from a batch one?
Streaming is judged continuously, so system lag, subscription backlog, and watermark age are the primary signals with minute level alerting. Batch pipelines are judged against a schedule, so the equivalent signals are completion against the expected window and row counts versus the previous run.
Q5: What belongs on a pipeline dashboard?
A health row with lag, volume, and failures, a cost row, the latest deploy marker, and links to the runbook and the quality scan results. The test is whether an on-call engineer can answer scope, cause, and next action without typing a query.