🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

CDC Patterns: Datastream, Debezium & Firestore Exports

GCP Data EngineeringChange Data CaptuređŸŸĸ Free Lesson

Change Data Capture on GCP

Master Change Data Capture on GCP including Datastream, Debezium, Firestore exports, and real-time replication patterns.

16 min readAdvanced

What You'll Learn

  • 1Explain what a transaction log gives CDC that polling and triggers cannot
  • 2Compare Datastream, Debezium and change streams on cost, control and operations
  • 3Order a backfill against ongoing changes without losing or duplicating rows
  • 4Design schema evolution and idempotent writes so a stream survives a release

What a Log-Based Capture Actually Reads

Change data capture replicates the effect of every committed write instead of asking the database what it currently looks like. Two mechanisms matter in practice. Log based capture reads the transaction log that the database already writes for recovery: MySQL's binary log in ROW format, PostgreSQL's write ahead log with wal_level = logical, Oracle's archived redo, SQL Server's transaction log. Because the reader only consumes bytes the database produced anyway, the overhead on the primary is small and constant, and every operation is visible, including deletes.

The alternative mechanisms are weaker. Trigger based capture installs an AFTER INSERT OR UPDATE OR DELETE trigger that writes into a shadow table, which adds write latency to every statement and needs its own cleanup job. Query based capture, commonly called snapshot diffing, runs a SELECT and compares it with the previous result, so it can only see rows that still exist and it misses deletions entirely unless a soft delete column is maintained. Log based capture is therefore the default, and the price is that you must configure the source correctly before you start.

Three consequences follow. First, the log reader needs row images, so MySQL must run with binlog_row_image = FULL or the downstream cannot tell whether an unchanged column actually changed. Second, the replication slot or binlog file has a retention window: if the consumer stalls for hours, PostgreSQL will hold WAL until the slot is caught up and the disk fills, which is a real outage mode rather than a theoretical one. Third, the log is ordered per transaction but not globally, so the consumer must decide how to reconcile a row that arrives twice with different timestamps.

Choosing Between the Managed and Self-Run Options

ToolSource it readsWhere it runsSchema change handlingOperational surface
DatastreamMySQL, PostgreSQL, Oracle, SQL Server, Spanner, BigQuery, SalesforceManaged Google serviceAdditive changes applied automatically, others need actionLowest, no brokers to run
Debezium on KafkaDozens of connectors including MongoDB and DB2Kafka Connect on Dataproc or a managed KafkaSchema history topic records every DDLHighest, you own the cluster
BigQuery change streamsBigQuery tables onlyInside BigQueryFollows the BigQuery schemaLow, but BigQuery to BigQuery only
Firestore export pipelineFirestore documentsDataflow template on a scheduleSchemaless documents flattened on readLow, batch cadence rather than per commit

Datastream is the answer when the source is one of its supported engines and the destination is BigQuery or Cloud Storage, because connection profiles, backfill tasks, schema mapping and monitoring are all API objects you create with gcloud. Debezium earns its operational cost when you need a connector Datastream does not have, when downstream consumers need the raw change topic for more than one destination, or when transformations must happen before anything lands in the warehouse. The change topic then becomes a durable, replayable log rather than a one shot replication.

Provisioning a Stream with the CLI

Connection profiles and streams are ordinary resources, so they belong in Terraform or a deployment script rather than in a console session.

gcloud datastream connection-profiles create mysql-source \
  --location=us-central1 \
  --type=mysql \
  --hostname=10.0.0.1 \
  --port=3306 \
  --username=cdc_user \
  --display-name="MySQL production source"

gcloud datastream connection-profiles create bigquery-destination \
  --location=us-central1 \
  --type=bigquery \
  --display-name="BigQuery CDC dataset"

gcloud datastream streams create mysql-to-bq \
  --location=us-central1 \
  --source=projects/my-project/locations/us-central1/connectionProfiles/mysql-source \
  --destination=projects/my-project/locations/us-central1/connectionProfiles/bigquery-destination \
  --display-name="MySQL to BigQuery CDC" \
  --backfill-all

gcloud datastream streams list --location=us-central1

The --backfill-all flag schedules the full snapshot tasks that seed the destination before the stream switches to reading the log continuously. The Python client below exposes the same objects with per database and per table filters, plus the concurrency knobs that decide how many snapshot workers run at once.

python
from google.cloud import datastream_v1

client = datastream_v1.DatastreamClient()

stream = client.create_stream(
    request={
        "parent": "projects/my-project/locations/us-central1",
        "stream_id": "mysql-to-bigquery",
        "stream": {
            "display_name": "MySQL to BigQuery CDC",
            "source_config": {
                "source_connection_profile":
                    "projects/my-project/locations/us-central1/connectionProfiles/mysql-source",
                "mysql_source_config": {
                    "include_databases": ["production"],
                    "include_objects": {
                        "production": {"tables": ["users", "orders", "products"]}
                    },
                    "max_concurrent_cdc_tasks": 4,
                    "max_concurrent_full_snapshot_tasks": 2
                }
            },
            "destination_config": {
                "destination_connection_profile":
                    "projects/my-project/locations/us-central1/connectionProfiles/bigquery-destination",
                "bigquery_destination_config": {
                    "single_target_dataset": {"dataset_id": "cdc_replicated"}
                }
            }
        }
    }
)
print("created:", stream.name)

Backfill, Ordering and Idempotency

The hard part of any CDC rollout is not the log reader, it is making the initial snapshot agree with changes that happen while it runs. Datastream handles this by recording the log position it will resume from, copying the table state, and then replaying every change that occurred after that position. Debezium does the same with its snapshot mode: initial performs a consistent snapshot before streaming, when_needed repeats it only if the binlog offset was lost, and never assumes the destination is already populated.

Whatever the tool, the consumer must be idempotent, because at least once delivery is the only realistic guarantee. The pattern that survives reprocessing is an upsert keyed on the source primary key, written through a merge into the destination rather than a blind append. If the destination is BigQuery, that means the stream needs to know the key columns: Datastream reads them from the source definition, and a table that receives updates or deletes without a declared primary key will fail the stream rather than silently double count.

Ordering has the same shape. A row modified at 10:00:01 and again at 10:00:02 may arrive out of order across two log readers, so the write must be rejected when an incoming read_timestamp is older than the value already stored. The safe rule is to keep one monotonically increasing version per key and to treat every incoming row as a candidate replacement that only wins when it is newer.

Schema Evolution While the Stream Runs

Additive changes are the easy case: a new nullable column, a widened string, an added table. Datastream maps these onto the BigQuery destination automatically when the mapping rule allows field addition, and Debezium records the new column in the schema history topic so messages carry it. The failure mode that ends up in incident reviews is the non additive change: a renamed column, a type narrowing, a dropped field, or a column that changes from nullable to not null.

The discipline that works is to treat the stream as a contract with a four step procedure. Pause the stream, apply the change in a way the destination can absorb, update the schema mapping or the connector configuration, then resume and verify lag returns to normal. For BigQuery, widening is cheap because the column can be added with ALTER TABLE ... ADD COLUMN; converting a STRING to NUMERIC is not, and needs a new column plus a backfill of the old values. Test the whole sequence in a staging stream, because a schema change that only fails under production volume is indistinguishable from a source outage until someone correlates the two.

Debezium, Transformations and the Outbox Table

Running Debezium yourself buys the change topic and the ability to route, filter and enrich before anything is stored. A connector configuration is a flat map of properties, and the single message transform below renames topics so downstream jobs do not depend on physical database names.

python
debezium_config = {
    "name": "mysql-cdc-connector",
    "config": {
        "connector.class": "io.debezium.connector.mysql.MySqlConnector",
        "database.hostname": "10.0.0.1",
        "database.port": "3306",
        "database.user": "cdc_user",
        "database.password": "secure-password",
        "database.server.id": "1",
        "database.include.list": "production",
        "table.include.list": "production.users,production.orders",
        "snapshot.mode": "initial",
        "database.history.kafka.bootstrap.servers": "kafka:9092",
        "database.history.kafka.topic": "schema-changes",
        "tombstones.on.delete": "true",
        "transforms": "route",
        "transforms.route.type": "org.apache.kafka.connect.transforms.RegexRouter",
        "transforms.route.regex": "([^.]+)\\.([^.]+)\\.([^.]+)",
        "transforms.route.replacement": "cdc-$3"
    }
}

For a service that writes to its own database, the transactional outbox pattern removes the dual write problem entirely: the application inserts the business row and an event row into an outbox table in the same transaction, and Debezium reads only the outbox table. No message is ever published for a transaction that rolled back, and no message is missed because the publisher crashed after committing. tombstones.on.delete matters as well, because a tombstone tells compaction that the key has been deleted rather than leaving a stale value behind.

Firestore, BigQuery and Other Non-Relational Sources

Firestore does not expose a transaction log to Datastream, so the usual pattern is a scheduled export to BigQuery: a Cloud Scheduler job triggers a Dataflow pipeline, or a Firestore native export writes into a GCS prefix that a BigQuery load job picks up. Documents are schemaless, so each read flattens nested fields and arrays into columns, and a document that gains a new field widens the destination only if the load job is configured to allow it. Because the cadence is a batch, this pipeline gives you minute level freshness rather than second level, which is a budget you agree on with the consumer rather than a limitation to hide.

BigQuery to BigQuery replication uses change streams with a Dataflow pipeline template, which is the mechanism behind cross region copies and lakehouse feeds. It captures row level inserts, updates and deletes on the source table and applies them downstream, with the same idempotency requirement: every write must be a merge keyed on the primary key so replays are harmless.

Watching Lag, Errors and the Source

A CDC pipeline has four numbers worth alerting on, and none of them is throughput. Replication lag, the distance between the newest change applied and the newest change committed, should sit in single digits of seconds for a real time feed and should page someone once it passes a minute. Error rate on the destination catches schema mismatches and quota failures that would otherwise stall silently. Unacknowledged or backlog depth on the broker shows whether the consumer is keeping up. Source database health, specifically replication slot growth and WAL disk usage, catches the case where the pipeline is down but the database is paying for it anyway.

✨

Best Practice: Prefer Datastream when the source is supported, because log reading, schema mapping and backfill are managed. Keep one monotonic version per primary key and write through merges so at least once delivery cannot double count. Alert on replication lag, destination errors and source WAL growth together, since the three fail as a group.

Common Interview Questions

Q1: What is CDC and why does it beat a nightly batch?

Answer: CDC captures every committed insert, update and delete as it happens by reading the transaction log, so downstream systems stay seconds behind the source instead of a day. It has a small, constant overhead on the primary, and unlike a snapshot it can observe deletions without a soft delete column.

Q2: Datastream or Debezium?

Answer: Datastream is managed, supports the mainstream relational sources plus Spanner, BigQuery and Salesforce, and writes straight to BigQuery or GCS with backfill tasks included. Debezium runs on Kafka Connect, supports more engines and lets several consumers share one durable change topic. Choose Datastream for a single destination, Debezium for transformation or fan out.

Q3: How are schema changes handled mid stream?

Answer: Additive changes are applied automatically by Datastream and recorded in Debezium's schema history topic. Non additive changes require pausing the stream, altering the destination, updating the mapping and resuming, and that sequence should be rehearsed in a staging stream before it is needed in production.

Q4: What are the limits of log based CDC?

Answer: The source must expose a log in a supported format, log retention is finite so the consumer cannot stall indefinitely, schema evolution still needs handling, and bulk operations such as TRUNCATE or multi row updates may bypass row level capture depending on the engine. Some sources cannot be captured at all without a trigger fallback.

Q5: How do you monitor CDC health?

Answer: Track replication lag and alert past a minute, count destination write errors and schema mismatches, watch consumer backlog, monitor source replication slot and WAL growth, and record the rows applied per second so a flat line is visible before a consumer notices missing data.

Interview Questions

Q1: Why must MySQL run with binlog_row_image = FULL for CDC?

Partial row images omit unchanged columns, so the consumer cannot tell whether a value really changed and cannot rebuild the full row for an update, which leads to wrong downstream values rather than missing rows.

Q2: What happens if a Kafka consumer is down for six hours?

The replication slot retains WAL for the whole outage, disk usage on the source grows, and PostgreSQL can stop accepting writes when it fills. Alert on slot lag and provision the retention window to match the worst tolerated outage.

Q3: How does the transactional outbox pattern avoid dual writes?

The business row and the event row are inserted in one transaction; Debezium reads only the outbox table, so a rollback discards both and a crash can never commit one without the other.

Q4: Which CDC failures are invisible in throughput graphs?

Schema mismatches that park a stream, stale log positions after a restore, and deletes that never reach the destination because the table has no declared primary key. Each needs its own error counter.

Common Mistakes

Starting a stream before confirming the source log configuration

Fix: Verify binlog format is ROW with FULL row images, or wal_level is logical, before creating the stream.

Appending change rows instead of merging on the primary key

Fix: Write through a merge keyed on the source primary key so at least once delivery replays cleanly.

Treating replication lag as a dashboard metric rather than an alert

Fix: Page on lag past a minute and alert on destination errors and source WAL growth at the same time.

Key Takeaways

  • Log based CDC reads the binary log or write ahead log the database already writes, so deletes are visible and overhead stays constant
  • Datastream is the managed path to BigQuery, Debezium is the self run path when you need a shared change topic or extra connectors
  • Snapshot and stream must be ordered against each other, and every downstream write must be idempotent because delivery is at least once
  • Additive schema changes apply automatically, renamed or narrowed columns require a paused stream and a rehearsed four step procedure
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert GCP Data Engineering Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement