CDC Pipelines with Debezium, Kafka, and Beam on GKE
Change data capture (CDC) moves committed row changes, rather than complete tables, from an operational database into downstream systems. Debezium reads a database transaction log, Kafka Connect publishes ordered change envelopes to Kafka, and Apache Beam turns those envelopes into validated records for an analytical or serving sink.
Running those boundaries on GKE does not remove the correctness work. A row can be duplicated after a Connect retry, replayed after a Beam restore, or arrive before a schema consumer is ready. This design makes the source position, transaction identity, schema version, and sink commit independently observable.
Responsibility by layer
The database remains authoritative:
- the database transaction log preserves committed operation order;
- Debezium translates log records into versioned envelopes;
- Kafka Connect stores source offsets and connector state;
- Strimzi operates Kafka brokers, internal topics, users, and configuration;
- Beam validates, deduplicates, groups, and transforms events;
- the sink applies an idempotent or transactional materialization.
Kafka is replayable, but it is not an indefinite source archive. Size topic retention and database-log retention from the maximum outage and catch-up duration. If Debezium’s current position becomes unavailable in the source log, resetting Kafka offsets cannot recover it.
Strimzi and Kafka topology
A small production topology uses at least three Kafka brokers across independent GKE node zones, with at least three replicas for internal Connect topics and source topics where availability requires it. Strimzi Custom Resources keep the desired topology in Git:
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
name: cdc
spec:
kafka:
version: 3.6.0
replicas: 3
listeners:
- name: plain
port: 9092
type: internal
tls: false
- name: tls
port: 9093
type: internal
tls: true
config:
offsets.topic.replication.factor: 3
transaction.state.log.replication.factor: 3
transaction.state.log.min.isr: 2
default.replication.factor: 3
min.insync.replicas: 2
storage:
type: persistent-claim
size: 500Gi
deleteClaim: false
zookeeper:
replicas: 3
storage:
type: persistent-claim
size: 20Gi
deleteClaim: false
Newer Kafka versions can use KRaft and omit ZooKeeper; select one topology from the exact Strimzi support matrix. The important operational constraints are quorum diversity, persistent storage, rolling-update capacity, and enough disk headroom for the longest recovery.
Plain internal listeners are shown only to reduce connector examples. Use TLS and mTLS in production, then grant a dedicated Kafka user only the topic and group permissions required by the connector and Beam job.
Database and Debezium setup
A PostgreSQL source needs a replication user, logical decoding plugin, publication, and a replication slot. Keep the plugin and privilege choices version-specific. For pgoutput, a connector can look like:
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaConnector
metadata:
name: orders-postgres-cdc
labels:
strimzi.io/cluster: cdc-connect
spec:
class: io.debezium.connector.postgresql.PostgresConnector
tasksMax: 1
config:
database.hostname: orders-db.data.svc.cluster.local
database.port: "5432"
database.user: "${secrets:cdc-namespace/orders-db:username}"
database.password: "${secrets:cdc-namespace/orders-db:password}"
database.dbname: orders
topic.prefix: orders-prod
plugin.name: pgoutput
slot.name: orders_gke_cdc
table.include.list: public.orders,public.order_items
publication.name: orders_cdc
snapshot.mode: initial
decimal.handling.mode: precise
tombstones.on.delete: "true"
heartbeat.interval.ms: "10000"
key.converter: io.apicurio.registry.utils.converter.AvroConverter
key.converter.apicurio.registry.url: http://schema-registry.data.svc
value.converter: io.apicurio.registry.utils.converter.AvroConverter
value.converter.apicurio.registry.url: http://schema-registry.data.svc
tasksMax: 1 is expected for a single database log: parallel source tasks cannot independently preserve one ordered transaction log. Scale throughput by database capacity, snapshot strategy, topic partitioning after capture, and downstream Beam parallelism.
Use a connector secret provider instead of placing raw credentials in the resource. initial includes a coordinated snapshot followed by ongoing log consumption; test the same mode against data volume, because a large snapshot can hold log position and increase source-log pressure.
Kafka Connect deployment
Deploy a Strimzi KafkaConnect cluster with distributed offsets:
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaConnect
metadata:
name: cdc-connect
annotations:
strimzi.io/use-connector-resources: "true"
spec:
version: 3.6.0
replicas: 2
bootstrapServers: cdc-kafka-bootstrap.data.svc:9093
tls:
trustedCertificates:
- secretName: cdc-cluster-ca-cert
certificate: ca.crt
config:
group.id: cdc-connect
offset.storage.topic: cdc.connect.offsets
config.storage.topic: cdc.connect.configs
status.storage.topic: cdc.connect.status
offset.storage.replication.factor: 3
config.storage.replication.factor: 3
status.storage.replication.factor: 3
key.converter: org.apache.kafka.connect.storage.StringConverter
value.converter: org.apache.kafka.connect.json.JsonConverter
build:
output:
type: docker
image: registry.example.com/data/debezium-connect:2.5.4
plugins:
- name: debezium-postgres
artifacts:
- type: tgz
url: https://repo1.maven.org/maven2/io/debezium/debezium-connector-postgres/2.5.4.Final/debezium-connector-postgres-2.5.4.Final-plugin.tar.gz
The registry image is an example and should be produced in a controlled build pipeline. Pin plugin, Connect, Kafka, and schema-registry converter versions, scan the image, and promote digests rather than mutable tags. Test an upgrade with a savepoint or paused connector and a known offset.
CDC envelope and schema policy
A simplified Debezium value is:
{
"before": {"id": 1842, "status": "PENDING", "version": 7},
"after": {"id": 1842, "status": "PAID", "version": 8},
"source": {
"connector": "postgresql",
"db": "orders",
"schema": "public",
"table": "orders",
"txId": 481902,
"lsn": 482910034
},
"op": "u",
"ts_ms": 1684418400211,
"transaction": null
}
The Kafka key identifies the row. The source transaction ID and log sequence identify order. A Beam consumer should preserve:
- Kafka topic, partition, offset;
- source connector, database, schema, and table;
- source LSN or equivalent log position;
- source transaction ID;
- operation (
c,r,u,d, tombstone); - schema subject and version;
- event-time and ingest-time values.
Use compatibility enforcement in a schema registry. A nullable column addition can be compatible. Renaming a column, changing a type, or changing deletion meaning requires a versioned contract and consumer rollout. Do not generate sink columns directly from arbitrary Kafka values.
Deletes require deliberate handling. Debezium may emit a delete envelope followed by a null tombstone. Beam must preserve the delete marker until it applies the correct sink deletion. Kafka compaction can discard old values, but Beam logic must interpret tombstones rather than parsing them as ordinary empty JSON.
Beam CDC consumer
The Beam job reads Kafka with a schema-aware deserializer:
PCollection<ChangeEnvelope> changes = pipeline
.apply("Read CDC",
KafkaIO.<String, byte[]>read()
.withBootstrapServers(options.getKafkaBootstrapServers())
.withTopics(Arrays.asList(
"orders-prod.public.orders",
"orders-prod.public.order_items"))
.withConsumerConfigUpdates(Map.of(
"group.id", "beam-orders-materialized-v1"))
.withKeyDeserializer(StringDeserializer.class)
.withValueDeserializer(ByteArrayDeserializer.class))
.apply("Decode", ParDo.of(new DecodeDebezium()))
.apply("Sequence by row key", ParDo.of(new TagInvalidEnvelope()));
PCollection<KV<String, ChangeEnvelope>> keyed = changes
.apply(MapElements.via(
new SimpleFunction<ChangeEnvelope, KV<String, ChangeEnvelope>>() {
public KV<String, ChangeEnvelope> apply(ChangeEnvelope c) {
return KV.of(c.table() + ":" + c.rowKey(), c);
}
}))
.apply("Enforce dedupe and order",
ParDo.of(new DeduplicateBySourcePosition()));
keyed.apply("Materialize",
ParDo.of(new IdempotentSinkDoFn(options.getSinkName())));
The dedupe transform should be keyed by source row identity and retain the highest committed source version or LSN. Beam state is runner-managed, but state growth must be bounded by key churn and configured cleanup. For an append-only sink, use a unique source identity such as connector, transaction ID, table, operation, and Kafka offset.
For a current-state sink, compare sequence:
INSERT INTO silver_orders (
id, status, source_connector, source_lsn, updated_at
) VALUES (
1842, 'PAID', 'orders-prod', 482910034, '2023-05-18T14:00:00Z'
)
ON CONFLICT (id) DO UPDATE
SET
status = EXCLUDED.status,
source_lsn = EXCLUDED.source_lsn,
updated_at = EXCLUDED.updated_at
WHERE silver_orders.source_lsn < EXCLUDED.source_lsn;
The WHERE is essential. A retry or late lower-LSN event must not replace a newer row.
DLQ policy
Route these categories to separate DLQ partitions or clearly typed fields:
- malformed envelope or converter failure;
- unknown schema version;
- invalid source or row identity;
- incompatible sink operation;
- tombstone or delete-policy failure;
- transient sink exhaustion after a bounded retry policy.
Do not put all transient sink failures into a permanent DLQ immediately. Retry bounded infrastructure failures while the source checkpoint remains retryable. Quarantine deterministic data-contract failures so one poison record does not block a partition indefinitely.
{
"failureId": "orders-prod:orders:4:928102:SCHEMA",
"topic": "orders-prod.public.orders",
"partition": 4,
"offset": 928102,
"sourceLsn": 482910034,
"schemaVersion": 13,
"failureCode": "UNKNOWN_SCHEMA_VERSION",
"pipelineVersion": "beam-orders-2023.05.18-3",
"rawValueBase64": "AQID..."
}
Measure DLQ records and age. A schema rollout can have zero records in a synthetic test but still emit an unknown version under real traffic.
Kubernetes and Beam configuration
Beam on GKE needs predictable resources and durable recovery. A deployment for a worker-oriented runner should set:
apiVersion: batch/v1
kind: Job
metadata:
name: beam-orders-cdc
namespace: data
spec:
backoffLimit: 3
template:
spec:
serviceAccountName: beam-orders
restartPolicy: OnFailure
containers:
- name: pipeline
image: registry.example.com/data/beam-orders:2023.05.18-3
args:
- --runner=PortableRunner
- --job_endpoint=beam-flink-jobserver.data.svc:8099
- --artifacts_dir=gs://example-beam-artifacts/orders
- --streaming=true
- --sdk_worker_parallelism=4
- --save_main_session=true
resources:
requests:
cpu: "1"
memory: 2Gi
limits:
cpu: "2"
memory: 4Gi
env:
- name: GOOGLE_CLOUD_PROJECT
value: example-analytics
- name: KAFKA_BOOTSTRAP_SERVERS
value: cdc-kafka-bootstrap.data.svc:9093
terminationGracePeriodSeconds: 60
Exact Beam portability flags differ by runner. For Flink-on-Kubernetes runners, configure JobManager HA, durable checkpoints, TaskManager slots, pod disruption budgets, and object-storage credentials. For direct/self-managed GKE execution, configure equivalent checkpoint and state storage. Kubernetes liveness must not kill a healthy but temporarily backpressured job more aggressively than the recovery objective permits.
Use network policies and Workload Identity rather than broad static cloud credentials. Beam workers need Kafka TLS trust, artifact/checkpoint access, sink permissions, metrics access, and nothing else.
Snapshot and replay testing
Test the snapshot-to-live transition because it crosses a difficult correctness boundary. Build a repeatable fixture:
- create 10,000
ordersandorder_itemsrows; - deploy Debezium with
snapshot.mode=initial; - start transactions while the snapshot is running;
- delete and update existing rows;
- pause the Connect pod at a recorded source boundary;
- stop the Beam job after its latest completed checkpoint;
- resume Connect and Beam independently;
- compare the source database with the sink.
Reconcile on a deterministic boundary:
SELECT
COUNT(*) AS rows,
COUNT(DISTINCT id) AS unique_ids,
SUM(COALESCE(total_cents, 0)) AS total_cents,
MAX(source_lsn) AS max_source_lsn
FROM silver_orders
WHERE ingest_transaction_id <= 481902;
Do the same aggregate against the authoritative source at a database snapshot corresponding to transaction 481902. Counts alone are weak; include IDs, checksums, deletion counts, and max sequence.
Replay test with an explicit offset range:
@Test
void replayingCdcOffsetsProducesTheSameCurrentState() {
List<ChangeEnvelope> source = fixture("snapshot-plus-replay.json");
TestSink sink = new TestSink();
applyInOrder(sink, source);
applyInOrder(sink, source); // duplicate the full replay
assertEquals(10000, sink.liveRows());
assertEquals(250, sink.deletedRows());
assertEquals(1, sink.maxWriteForEvent("orders:1842:482910034"));
}
Then run the test in a different order within one partition only to reproduce timestamp skew; never reorder events from one database log if the connector and business semantics depend on commit order. Add a test for a tombstone, an older LSN after a newer LSN, and two transactions touching the same row.
Cross-table transaction consistency
Row-level CDC does not automatically create a consistent multi-table sink. Orders and order items published to separate Kafka topics may be consumed at different rates. Do not join by approximate time and call the result transactional.
Use one of three explicit designs:
- consume in-transaction events when the connector and schema expose transaction metadata, then commit the group;
- materialize independent row tables and document that cross-table views are eventually consistent;
- build a transaction envelope on a single ordered stream before fanning out.
If the sink supports atomic transactions, buffer or stage related rows until the transaction end signal, then commit with a deterministic transaction ID. If the sink does not, record transaction status and let readers expose only complete transactions.
Replay and recovery runbook
Replay is an operation with a declared boundary:
- capture connector state, Kafka group offsets, and Beam checkpoint name;
- verify the target Kafka offsets are retained;
- verify the source log position and replication slot health;
- create or version the sink recovery target;
- reset a separately named consumer group or restore a savepoint;
- apply rate limits and monitor database/sink pressure;
- reconcile counts, checksums, deletes, and LSN maxima;
- promote or merge only after the bounded boundary passes.
Never reset a consumer group from earliest as a generic fix. It discards the most precise recovery fact the system has: the saved source position.
Measurable operations
Monitor the whole path:
- PostgreSQL replication-slot lag bytes and oldest retained WAL;
- Connect task state, failed restarts, records by operation, and offset update age;
- Kafka under-replicated partitions, disk use, partition lag, and compaction size;
- Beam backlog seconds, bundle errors, state bytes, worker restarts, and checkpoint age;
- schema conversion and DLQ failures by code and version;
- sink commits, idempotent conflicts, duplicate source positions, and p95 write latency;
- end-to-end freshness from database transaction timestamp to sink visibility.
Useful initial targets are p95 freshness under 60 seconds, zero silent tombstone failures, replication-slot lag below one Kafka retention recovery envelope, failed Connect tasks alerted within two minutes and restored within 15, and a tested full replay that finishes inside the allowed batch outage window. Capacity tests should pause Beam for 30 minutes, then prove that Connect, Kafka, and Beam recover without exhausting database log space.
The central invariant is: every committed source change is represented exactly once in the current-state business result, represented explicitly as a bounded DLQ decision, or retained at a known replayable log position. The diagram and the metrics must expose which state is true.