What You'll Learn
- 1Assemble a Cloud Build pipeline that lints, tests, compiles, and deploys in a sensible order
- 2Choose the right test level for a data change and write one that fails for the right reason
- 3Handle schema changes safely with dry runs, backfill-first ordering, and versioned migrations
- 4Design a rollback that restores both code and the data a bad release produced
Shipping a transformation change is not the same as shipping an application change, because a bad query can rewrite a table that a thousand dashboards read before anyone notices. Continuous integration for data therefore tests more than code: it validates SQL, compiles the graph, checks the data it will write, and estimates what the run will cost. Continuous delivery then has to solve a second problem that applications rarely face, which is that the artifact being deployed includes state. This lesson covers the build steps, the test levels, the migration ordering rules, and the rollback that accounts for data as well as code.
Why data delivery is different
Three properties of data work change the pipeline design. First, changes are often irreversible in place: dropping a column cannot be undone by redeploying the previous version once the write has happened. Second, correctness depends on the input, so a transformation that passed yesterday can fail today because the source changed shape overnight. Third, the cost of a change is not bounded by the change itself, because a removed partition filter turns a five gigabyte query into a five terabyte one.
Those properties push work earlier in the pipeline. Cost is estimated before execution with a dry run, schema compatibility is checked against live tables before any write, and tests run against representative data rather than fixtures that always match. The build is the cheapest place to discover every one of these problems, and the only place where discovery costs nothing.
Cloud Build pipeline
A single Cloud Build configuration can lint Python, lint SQL, compile and test Dataform models, build a Dataflow template, and ship DAGs to Composer, with each step ordered so that cheap checks fail first.
# cloudbuild.yaml
steps:
# Step 1: Lint and test Python code
- name: 'python:3.11'
entrypoint: 'bash'
args:
- '-c'
- |
pip install flake8 pytest pytest-cov
flake8 src/ --max-line-length=100
pytest tests/ --cov=src/ --cov-report=html
# Step 2: Run SQL linting
- name: 'python:3.11'
entrypoint: 'bash'
args:
- '-c'
- |
pip install sqlfluff
sqlfluff lint models/ --dialect bigquery
# Step 3: Test Dataform models
- name: 'gcr.io/my-project/dataform-tester'
entrypoint: 'bash'
args:
- '-c'
- |
dataform compile
dataform test
# Step 4: Build Dataflow template
- name: 'gcr.io/cloud-builders/gcloud'
entrypoint: 'bash'
args:
- '-c'
- |
gcloud dataflow flex-templates build \
gs://my-templates/pipeline \
--image=gcr.io/my-project/pipeline:latest \
--sdk-language=PYTHON
# Step 5: Deploy to Cloud Composer
- name: 'gcr.io/cloud-builders/gcloud'
entrypoint: 'bash'
args:
- '-c'
- |
gsutil cp dags/*.py gs://my-composer-bucket/dags/
timeout: '1800s'
options:
logging: CLOUD_LOGGING_ONLY
Order matters more than the individual tools. Lint and unit tests take seconds and catch obvious damage, so they run first; compilation and data tests take minutes and run next; anything that writes to an environment runs last, only after everything cheaper has passed. Failures then map to a clear owner, because a lint failure never hides behind a slow integration test that failed for an unrelated reason.
Testing at each level
Data changes need four distinct test levels, and skipping any one of them moves a class of defect into production.
| Level | What it proves | Example |
|---|---|---|
| Unit | A single transform behaves as specified | Parse a fixture event and assert the fields |
| Integration | The pipeline runs end to end on sample input | DirectRunner job writing to a test dataset |
| Data quality | The output satisfies business rules | Null, duplicate, and range assertions on results |
| Cost and performance | The query fits the budget | Dry run bytes billed compared with a threshold |
# Unit tests for data transformations
import pytest
from src.transformations import parse_event, validate_record
def test_parse_event():
"""Test event parsing."""
raw_event = '{"event_id": "123", "type": "purchase", "amount": 99.99}'
result = parse_event(raw_event)
assert result['event_id'] == '123'
assert result['amount'] == 99.99
def test_validate_record_valid():
"""Test valid record validation."""
record = {'event_id': '123', 'amount': 100}
assert validate_record(record) is True
def test_validate_record_invalid():
"""Test invalid record validation."""
record = {'amount': -1}
assert validate_record(record) is False
# Data quality tests
def test_bigquery_data_quality():
"""Test BigQuery data quality."""
from google.cloud import bigquery
client = bigquery.Client()
query = """
SELECT
COUNT(*) as total,
COUNTIF(order_id IS NULL) as null_ids,
COUNTIF(amount < 0) as negative_amounts
FROM `project.analytics.sales`
WHERE DATE(processed_at) = CURRENT_DATE()
"""
results = client.query(query).result()
row = list(results)[0]
assert row.null_ids == 0, f"Found {row.null_ids} null order IDs"
assert row.negative_amounts == 0, f"Found {row.negative_amounts} negative amounts"
Run Dataflow pipelines locally with the DirectRunner on a small sample before ever submitting to the service, because a coding error costs nothing to find there and a full deploy costs minutes plus worker time. Reserve a separate integration test dataset in BigQuery for tests that must touch the real service, and give it a name that makes it obvious to everyone that reads are allowed to fail.
Schema changes and migrations
Schema changes are where most data incidents start, so they get their own rules. Additive changes, such as a new nullable column, are safe to deploy before the code that reads them. Removing or renaming a column is not: the new code must not assume the column is gone until every reader has been updated and every backfill has finished.
BigQuery dry runs give you the cost half of the check for free. Running any query with dry run set returns bytes billed without executing, which belongs in the build as a hard ceiling, so a pull request that accidentally removes a partition filter cannot merge at all. Dataform compilation provides the other half, since compiling the graph resolves references and catches a broken model name before any scheduler ever sees it.
Rollback for code and for data
Rolling back code is straightforward when templates and DAGs are versioned: redeploy the previous build. The harder question is what to do with rows the bad version already wrote, and the answer depends on how the write happened. An append-only load can delete the affected partition or run an inverse transformation, a merge can be re-applied with corrected logic, and a table that supports time travel can be restored by copying from a point before the bad run.
-- Restore the previous state of a table after a bad release
CREATE OR REPLACE TABLE `project.analytics.sales` AS
SELECT *
FROM `project.analytics.sales`
FOR SYSTEM_TIME AS OF TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 24 HOUR);
Write the rollback steps into the pull request template and rehearse them once per quarter against a non-production table. Rollback procedures discovered for the first time during an incident are guesses, and a guess made while the business is waiting is a bad version of a decision you could have practised.
Permissions the pipeline runs with
Every build runs as a service account, and that account is an attack surface as well as a blast radius. Give the build account only the roles its steps need, which is usually BigQuery job user and data editor on development datasets, Dataform permissions on the development repository, and storage object writer on the template bucket, rather than the broad editor role that gets attached during initial setup and never removed. The deployment step should use a different account from the test step, so a compromised test job cannot promote artifacts to production.
Credentials belong in Secret Manager, referenced from the build configuration, never in a repository file or an environment variable that ends up in a build log. Service account keys are the worst option available and should be replaced by workload identity or short lived tokens wherever the platform supports it. Review the granted roles on a schedule, because permissions accumulate as teams experiment and rarely shrink on their own.
Promotion between environments
Separate projects for development, staging, and production keep credentials, costs, and blast radius apart, and they let the pipeline promote an artifact rather than rebuild it. The same container image or Dataflow template moves through the environments, promoted by a tag, so what was tested is exactly what runs. Configuration such as dataset names, schedules, and machine types lives in environment specific files rather than in code, because an environment specific branch is a merge conflict waiting to happen.