Databricks Field Guide

Processing · Chapter 10

Databricks change data capture (CDC) and real-time data

Reviewed by TechFabric engineers. How we write this guide →

Change data capture (CDC) on Databricks means reading the change log a source database already keeps and applying each insert, update and delete to a Delta table, instead of re-copying the whole table. A Lakeflow Connect connector does the capture for SQL Server, MySQL, PostgreSQL and other sources, and an AUTO CDC flow in a Lakeflow pipeline applies the changes in the right order, as current state (SCD type 1) or full history (SCD type 2). Real-time mode and Zerobus Ingest cover the cases where seconds matter.

This chapter is how we'd get data in when the source is an operational database or a stream of events and the business wants freshness in minutes rather than hours. Product statuses are as of October 2026.

The short version

Most business reporting runs on data that was copied overnight, which is fine until somebody needs to act on what happened an hour ago. Change data capture is the technique that makes that affordable. Instead of copying a whole table every time, the platform reads the log that the source database already keeps of every insert, update, and delete, and applies just those changes to a copy on the analytics side. The copy stays close to current without the source system being hammered by repeated full extracts. The awkward parts are rarely the technical ones. Deletes are easy to miss, a record arriving out of order can quietly overwrite a newer one, and the freshness a business asks for is usually more than any decision actually needs. We'd treat that last point as the important one and settle it before building anything.

Decide the latency tier before anything else #

Batch, micro-batch, and continuous streaming form a ladder of cost and complexity, where every rung up buys freshness in exchange for operational attention. We'd ask a team to name the decision that changes when the data is fresher, because the answer usually lands one or two rungs below the first request.

Daily is a scheduled job with no long-lived compute, no checkpoint drift, and a full day to recover a failure before anyone notices. It stays right for finance reporting, regulatory submissions, and anything a human reads once a morning.

Hourly is the same architecture on a tighter schedule, where the meaningful change is that a failed run has to be noticed and retried inside the hour, so alerting must work and someone must be accountable during working hours.

Minutes is where micro-batch streaming earns its place. You now own checkpoints, offsets, state, and the question of what happens when a source goes quiet, and compute runs most of the time rather than briefly.

Seconds is a genuine engineering commitment, implying continuous compute, on-call ownership, state stores that need tuning as volumes grow, and consumers able to handle data changing while they read it. We'd build it where it drives an automated action such as fraud interdiction, and resist it where the destination is a dashboard somebody opens twice a day.

yes, in seconds

no

yes

no

yes

no

Does a system act
automatically on it

Continuous stream
on-call ownership

Does a person act
within the hour

Micro-batch
every few minutes

Is the answer
read intraday

Hourly scheduled
incremental job

Daily batch

Working down the latency ladder to the cheapest tier that meets the need

Real-time mode, the tier below seconds #

Below the four tiers sits a Structured Streaming trigger of its own. Real-time mode has been generally available since 19 March 2026, and Databricks' own figure for it is sub-100ms processing. It gets there by running long batches (five minutes by default), scheduling every stage of the query at once, and passing data between stages through a streaming shuffle as it's produced.

The source and sink list is the first thing to check, because it rules out most medallion work. Per the real-time mode reference, sources are Kafka, Event Hubs through its Kafka endpoint, Kinesis and MSK; sinks are Kafka, Event Hubs and arbitrary foreach writers. Delta tables are supported as neither, and only update output mode works. So the shape is event in, decision out:

# Classic compute, Runtime 16.4 LTS+, autoscaling and Photon off,
# spark.databricks.streaming.realTimeMode.enabled = true in the cluster's Spark config
from pyspark.sql import functions as F

scored = (spark.readStream.format("kafka")
    .option("kafka.bootstrap.servers", brokers)
    .option("subscribe", "payments")
    .load()
    .select(F.col("key"), F.col("value")))   # replace with the scoring logic

(scored.writeStream.format("kafka")
    .option("kafka.bootstrap.servers", brokers)
    .option("topic", "payment_scores")
    .option("checkpointLocation", "/Volumes/payments_prd/streaming/checkpoints/payment_scores")
    .outputMode("update")
    .trigger(realTime="5 minutes")
    .start())

The setup page lists the compute rules in that comment: classic compute on dedicated access mode (standard access mode is Python only), spot instances off, and no serverless notebooks or jobs for a direct query. Lakeflow pipelines can run in real-time mode on classic or serverless through pipeline configuration.

We'd reach for it only when a query drives an immediate action: scoring a payment before it clears, flagging a transaction on an unusual location, firing an offer off a clickstream event. For ETL, medallion promotion and anything feeding a dashboard, stay on micro-batch, which is Databricks' own guidance too.

Two constraints decide whether it's affordable. Scheduling all stages at once means the task slots must equal or exceed the tasks across every stage in the batch, so the compute is dedicated and sized for the whole query graph. And checkpoints happen between batches, so a long batch means longer replays after a failure and later metrics, while a short one checkpoints more often and can cost the latency you switched for. Databricks recommends benchmarking the interval on your own workload, and so would we. Where recovery time matters more than response time, the slower tier is still the right answer.

Which route, by source #

Databricks' ingestion overview sorts Lakeflow Connect by source type. That list tells you what exists, not which one to pick, so this is the table we'd put on the screen in a design review.

Source What we'd use What we'd check first The gotcha
SaaS application (Salesforce, Workday, HubSpot) Managed Lakeflow Connect connector That it covers the objects and custom fields you need API quotas belong to the source, so a full refresh can exhaust the quota the business uses by day
Operational database (SQL Server, Postgres, MySQL, Oracle) Managed database connector with CDC Whether CDC or change tracking can be enabled on the source, and who owns that change Enabling CDC is a change to someone else's production database, and the DBA's answer decides the timeline
Database where CDC is refused Query-based connector (GA since May 2026 for Oracle, Teradata, SQL Server, MySQL, MariaDB and PostgreSQL), or AUTO CDC FROM SNAPSHOT A reliable cursor column such as updated_at, and whether deletes matter A cursor-based read never sees a hard delete; snapshot comparison does, at the cost of a full read
Files landing in object storage Auto Loader Who writes the files, and whether they ever rewrite one in place A file overwritten under the same name is a new file to some modes and invisible to others
Kafka, Event Hubs, Kinesis Structured Streaming, or a streaming connector What decision needs the data within a minute The broker's retention is your recovery window; a pipeline down longer than that loses data
An application that wants to push rows Zerobus Ingest, writing straight into a managed Delta table Regional availability, throughput (100 MB/s per stream by default) and whether the app can retry idempotently Delivery is at-least-once, so the table needs a dedupe key, and you now own the client side of an ingestion contract

The managed rows are where we'd start whenever they fit, because a connector that breaks on a vendor API change is Databricks' ticket rather than yours, and long-term maintenance is the cost that hurts a small team most.

From the field: the client who wanted the row from a minute ago #

Andrey Taran, Senior Databricks Engineer at TechFabric, got this conversation on a B2B product whose clients wanted their own analytics inside the product. The ticket was six lines long, and one of them said the dashboards mustn't slow the application down. On a call the client added a seventh. They wanted the row the application had written a minute earlier on a chart in their portal, and a nightly refresh wouldn't do. There was no data team, and the database was also the application's live store, so "real time" and "no impact on the application" couldn't both be true.

He didn't argue the point up front. Step one was Lakehouse Federation over the application's Azure SQL database, with one connection, one foreign catalog, no copy and no schedule. A dashboard read the row written a moment earlier, and the client had a demo within days. Two Unity Catalog views carried the old Power BI logic, and every later step swapped the layer under those views while the dashboards above them stayed untouched. The cost arrived at production scale. The table behind the main view held 130,000 rows in test and 6.46 million in production, and because pushdown is decided per table rather than per join, a view that filtered one side of a join and not the other had Azure SQL send back 6.46 million rows to show about 800.

What the demo bought was a better question than "real time". How fresh does it need to be, and for which numbers? The answer moved the data into Delta, lookups included, refreshed every 30 minutes on weekdays between 7am and 7pm Eastern, when nearly all the client's users are in, and less often at night and at weekends. That schedule costs about $43 a month, where a warehouse kept running all day would have been closer to $970. A full dashboard load went from around two minutes to 20 seconds. Half-measures didn't pay. With only the main table in Delta and the lookups still federated, a typical query took about two seconds against half a second with everything in Delta, so materialise all of it or none.

Andrey's write-up starts at Embedded analytics on Databricks, part 1, and the slides from his talk at the Dnipro Databricks User Group on 26 September 2026 cover all eight steps.

Managed CDC connectors #

Lakeflow Connect's database connectors read relational sources including SQL Server, MySQL, PostgreSQL and Oracle with change data capture. Where one covers your source we'd take it over anything hand-built, because the parts most likely to break become Databricks' problem rather than yours. The decision that's still yours is operational, and it comes from how the pieces fit together in the gateway-based design.

A Connection holds the source credentials as a Unity Catalog securable object, so access is granted and audited like any other object rather than living in a job configuration.

The Ingestion Gateway connects to the source and extracts snapshots, change logs, and the metadata describing them. It runs continuously on classic compute, which makes it the one piece with a cluster you size yourself.

Staging Storage is a Unity Catalog volume holding extracted data before it is applied. Treat it as a buffer, never as an archive.

The Ingestion Pipeline moves data from staging into the destination on serverless compute. Databricks' SQL Server FAQ recommends scheduling it at least five minutes apart, since serverless start-up takes some of that.

Destination Tables are streaming tables in Unity Catalog, so everything downstream treats them like any other table.

Source database
MySQL, Postgres, SQL Server

Ingestion Gateway
classic compute

Connection
credentials in UC

Staging volume
a buffer, not an archive

Ingestion Pipeline
serverless

Destination
streaming tables

The five components of a managed CDC connector

MySQL without a gateway: the integrated CDC pipeline #

For MySQL there's now a second design. The integrated CDC pipeline, GA since 15 October 2026, does extraction and apply inside one pipeline update, so there's no always-on gateway to size or keep running. It's triggered rather than continuous (continuous mode is Beta), each extraction runs for at least ten minutes, and Databricks suggests starting at an hourly schedule. The source needs binlog_format=ROW, binlog_row_image=FULL and an empty binlog_row_value_options, and binlog retention still has to outlast the gap between runs, or the affected tables need a full refresh. For an hourly-or-slower feed we'd pick it over a gateway, since the gateway is the piece that costs money while idle; for anything tighter, the gateway design is still the one that keeps up.

Sources without a managed connector #

Plenty of important sources have no managed connector. Azure Cosmos DB is the one we'd expect to meet most, because it sits underneath so many production applications.

Cosmos DB maintains a change feed for each container, an ordered and persistent record of changes to the items in it. The Spark connector, azure-cosmos-spark, exposes that feed as a Structured Streaming source through spark.cosmos.changeFeed options, so the read looks like any other stream. We'd land it in a bronze streaming table as received, then fold the changes into silver with AUTO CDC.

(spark.readStream
  .format("cosmos.oltp.changeFeed")
  .option("spark.cosmos.accountEndpoint", endpoint)
  .option("spark.cosmos.database", "orders")
  .option("spark.cosmos.container", "order_events")
  .option("spark.cosmos.changeFeed.startFrom", "Now")  # all-versions mode can't start from Beginning
  .option("spark.cosmos.changeFeed.mode", "AllVersionsAndDeletes")
  .option("spark.cosmos.changeFeed.itemCountPerTriggerHint", "50000")
  .option("spark.cosmos.throughputControl.enabled", "true")
  .option("spark.cosmos.throughputControl.targetThroughputThreshold", "0.25")
  .load())

startFrom is Now on purpose. The connector defaults to Beginning, and all-versions-and-deletes mode can't read from the beginning of the container or from a point in time, only from now or from a saved checkpoint. The history therefore comes from a one-off batch read in latest-version mode, and the order matters: start the stream first and let it write its first checkpoint, then take the snapshot, and fold both into silver with AUTO CDC. _ts alone can't sequence them, because it has one-second precision and a snapshot row and a later update can share it, so sequence by struct(_ts, lsn): the change's log sequence number from the all-versions feed metadata, and 0 for every snapshot row. A change made while the snapshot ran is then applied after the older copy rather than lost. Snapshot first and stream second leaves a gap in which an update or a delete is never seen. The mode also needs continuous backup on the account, and the connector's configuration reference still calls it experimental and suggests it for non-production use, which we'd weigh before relying on it for deletes.

Two constraints matter more than anything else there. The change feed in its standard latest-version mode gives you the most recent version of each changed item rather than every intermediate version, so an item updated five times between reads arrives once carrying its final state. That is fine for a silver table of current state and wrong if you are reconstructing a full audit history.

Reading the change feed consumes request units on the source container, so this ingestion has a real cost on the Cosmos side as well as on Databricks. The connector's throughput control settings cap that consumption, and we'd treat them as mandatory, because an unbounded backfill will starve the application depending on that container.

Message brokers #

Kafka, Azure Event Hubs through its Kafka-compatible endpoint, Amazon Kinesis, and Google Pub/Sub are all first-class Structured Streaming sources, differing mainly in connection options.

The mechanics are the same across all of them. The checkpoint holds the offsets recording what has been consumed, so it determines behaviour on restart and belongs with the target table rather than in a scratch location. Broker retention sets how long a stopped pipeline can stay stopped before data is lost, and it should be compared against your worst realistic outage.

The setting that most often changes the bill is Trigger.AvailableNow, which processes everything currently available and then stops. You keep streaming semantics, offsets, and exactly-once bookkeeping while paying for compute only while the batch runs, which is streaming code on batch economics and suits an event stream feeding an hourly report.

Applying changes with AUTO CDC #

Once changes are in bronze, a Lakeflow pipeline turns that log into a table of current state with AUTO CDC, the replacement for APPLY CHANGES (which still works with the same syntax).

CREATE OR REFRESH STREAMING TABLE silver_orders;

CREATE FLOW orders_changes AS AUTO CDC INTO silver_orders
FROM STREAM(bronze_order_changes)
KEYS (order_id)
APPLY AS DELETE WHEN operation = 'DELETE'
SEQUENCE BY STRUCT(commit_ts, log_position)
COLUMNS * EXCEPT (operation, commit_ts, log_position)
STORED AS SCD TYPE 1;

The keys identify the row, the sequencing expression establishes the true order of changes, and the delete condition marks removals. Two sequencing columns go in a STRUCT: it orders by the first field and breaks ties with the second.

SCD type 2: keeping history with AUTO CDC #

Change STORED AS SCD TYPE 1 to SCD TYPE 2 and the same input produces history: each version of a row gets __START_AT and __END_AT columns taken from the sequencing value, and the current version is the one whose __END_AT is NULL. TRACK HISTORY ON limits which column changes open a new version, so a churning last_seen_at doesn't multiply rows:

CREATE OR REFRESH STREAMING TABLE silver_customers_history;

CREATE FLOW customers_history AS AUTO CDC INTO silver_customers_history
FROM STREAM(bronze_customer_changes)
KEYS (customer_id)
APPLY AS DELETE WHEN operation = 'DELETE'
SEQUENCE BY STRUCT(commit_ts, log_position)
COLUMNS * EXCEPT (operation, commit_ts, log_position)
STORED AS SCD TYPE 2
TRACK HISTORY ON * EXCEPT (last_seen_at);

The Python equivalent is dp.create_auto_cdc_flow() after from pyspark import pipelines as dp, with the same options as arguments (keys, sequence_by, apply_as_deletes, stored_as_scd_type, track_history_except_column_list). Where the source can only give you periodic full extracts, AUTO CDC ... FROM SNAPSHOT compares consecutive snapshots and derives the changes itself.

We'd insist on this over a hand-written MERGE because of out-of-order arrival, which broker partitioning, retries and multi-node sources all produce. A merge applying whatever arrived last will silently overwrite a newer value with an older one, and the table looks entirely plausible afterwards, which is what makes the bug expensive.

Building the same change pipeline on each platform

Capability Databricks AWS Azure GCP
Database CDC capture Lakeflow Connect connectors for SQL Server, MySQL, Postgres, Oracle and more DMS to S3 or Kinesis Data Factory CDC, or Debezium onto Event Hubs Datastream for MySQL, Postgres, Oracle
Applying changes to a table AUTO CDC, declarative, SCD type 1 or 2 Glue or EMR job you write and maintain Data Flow mapping or a custom Spark merge Dataflow template, or BigQuery merge you write
Out-of-order handling Built in through the sequencing column Your merge logic Your merge logic Your merge logic
Streaming and batch code One API, one set of tables Kinesis plus Flink, separate from batch Stream Analytics, separate from batch Dataflow spans both with separate sinks
Governance over the feed Unity Catalog from the connection onwards Lake Formation after cataloguing Purview plus per-service access IAM per service
Lag as a first-class metric Pipeline event log plus table history CloudWatch per service Monitor per service Cloud Monitoring per service

Datastream and DMS are genuinely good at capture. The difference is what happens after capture, because elsewhere the apply step is code somebody writes and owns, whereas here it is a declarative flow with ordering and deletes handled by the framework.

Operating stateful streams #

A stream that filters rows or renames columns remembers nothing between micro-batches, so its memory profile stays flat for years. That stops the moment you group by a customer, count over a window, deduplicate, or join two streams, because the engine must now hold something about every key it has seen to answer correctly when the next batch arrives. That memory is the state, it lives alongside the checkpoint rather than in the table, and unbounded growth in it is the characteristic failure of the seconds tier. It never announces itself, because the pipeline keeps succeeding while each batch takes slightly longer than the last, until one misses the trigger interval and the lag stops recovering.

A watermark is how you tell the engine it may forget. Setting one with withWatermark on an event time column declares a bound on how late a record may arrive and still be counted, and Databricks is careful about what that promises, in that records arriving inside the threshold are always processed while records arriving outside it may still be processed but are not guaranteed to be. Once the largest event time seen moves far enough past a window, the state for that window can be dropped and its result emitted, which makes state size a function of the watermark rather than of how long the stream has run. What you pay is completeness, because a row later than the bound is dropped or, in a design that cares, routed to a side table. We'd pick the threshold from the observed lateness of the source rather than a round number that felt generous, and watch numRowsDroppedByWatermark, so what we chose to sacrifice stays visible.

streams/orders_agg.pypython
from pyspark.sql import functions as F

orders = (spark.readStream.table("silver_orders")
    .withWatermark("order_ts", "30 minutes"))

shipments = (spark.readStream.table("silver_shipments")
    .withWatermark("ship_ts", "2 hours"))

hourly_value = (orders
    .groupBy(F.window("order_ts", "1 hour"), "region")
    .agg(F.sum("order_value").alias("region_value")))

# Both sides watermarked, and the join bounded in time, so state can be released.
fulfilled = orders.join(shipments, F.expr("""
    order_id = shipment_order_id
    AND ship_ts >= order_ts
    AND ship_ts <= order_ts + INTERVAL 2 HOURS
"""))

The state is held per key by a state store committed with every batch, and the provider matters as soon as the keyspace is wide. RocksDB is the production answer, because it keeps state on local disk with an in-memory cache rather than on the JVM heap, which is what stops a large keyspace from turning into garbage collection pauses. It is the default from Databricks Runtime 17.3 onwards and is selected below that through spark.sql.streaming.stateStore.providerClass. Two numbers deserve a dashboard from the first day rather than the first incident. One is state size, reported per stateful operator as numRowsTotal and memoryUsedBytes in the streaming progress metrics, where a line that never flattens means no watermark is doing its job. The other is batch duration against the trigger interval, because a stream is healthy while batches finish comfortably inside their trigger and is in trouble when they creep towards it.

Stream-stream joins are the strictest case, needing a watermark on both sides and a condition bounding the two event times against each other, as in the interval above, with outer joins requiring the watermarks rather than merely benefiting from them. Without both halves the engine can never conclude that a row will not find a partner later, so it keeps every unmatched row for as long as the stream runs, and the join looks fine in testing because a single day of data gives nothing time to go wrong.

For aggregations, deduplication, and joins, Databricks recommends the built-in operators over custom logic and we'd agree, because that is where watermarks, state cleanup, and recovery are already handled correctly. The escape hatch, transformWithState and its pandas counterpart transformWithStateInPandas, available from Databricks Runtime 16.2, earns its place when the logic really is a state machine rather than an aggregate, meaning named state variables per key, timers that fire on time rather than on the arrival of a row, or a time-to-live on individual values.

Resizing state partitions without rebuilding the checkpoint #

The shuffle partition count baked into a stateful query's checkpoint used to be permanent. Change spark.sql.shuffle.partitions and a query with an existing checkpoint ignores it, so the only way to apply a new count was a fresh checkpoint, which means abandoning the accumulated state and backfilling. On-demand state repartitioning, generally available since 13 October 2026, removes that trade. Set a different configuration key, restart, and the query redistributes its state into the new partition count.

query.stop()
spark.conf.set("spark.sql.streaming.stateStore.partitions", "100")
query = df.writeStream.start()

For stateful queries spark.sql.streaming.stateStore.partitions takes precedence over spark.sql.shuffle.partitions. After the restart, the query finishes the last planned microbatch, runs the repartition, and then resumes processing, so plan for a pause rather than a background migration. The requirements are Databricks Runtime 18 LTS and above and the RocksDB state store provider, which is the default from DBR 17.3 on.

We'd treat this as a reason to stop over-provisioning partitions on day one. The old incentive was to guess high, because guessing low was expensive to fix; now the fix is a restart. What we'd watch is the pause itself. Databricks notes that larger state sizes can increase repartition time, and the duration shows up in StreamingQueryProgress under durationMs as controlBatch.REPARTITION, so we'd read that metric on a non-critical stream first to learn what the pause costs at our state size before scheduling one against a feed with a latency commitment. On an estate still on an older runtime, the partition count remains a day-one decision.

Advanced concerns #

Schema drift in the source happens without notice. A column added upstream should reach bronze and surface as an alert, and a column whose type changes should fail loudly rather than being coerced. We'd keep bronze permissive and silver strict, so drift is captured before it is interpreted.

The initial snapshot plus catch-up is where double counting begins. The snapshot represents a point in time while the change stream starts from an offset, and if the two do not line up you either lose changes in the gap or reapply changes already in the snapshot. Managed connectors handle this, whereas hand-built pipelines need the change stream started before the snapshot is taken and the sequencing column to resolve the overlap.

Idempotent merges matter more than delivery semantics. Teams spend a great deal of energy chasing exactly-once delivery when at-least-once delivery plus an idempotent apply gives the same outcome with far less fragility. If applying the same change twice produces the same table, duplicate delivery stops being an incident.

Backfill alongside a live stream should run as a separate flow into the same target, with the live stream continuing throughout. Stopping the stream to backfill creates a gap somebody has to remember to close, and the sequencing column ensures the backfill cannot overwrite newer records.

Multi-region sources need a decision about where changes are applied, because cross-region egress on a high-volume feed is a meaningful line on a cloud bill, and clock skew between regions makes a wall-clock sequencing column unsafe. We'd use a monotonic source-side sequence such as a log position instead.

Lag is the metric that matters, measured from source commit time to the moment the change is queryable in the target, rather than whether the job succeeded. A pipeline can succeed every run while falling steadily further behind, and only lag reveals it. We'd publish lag per feed against a threshold agreed with the business, as described in Observability.

Where we'd start on a new feed #

For a new CDC feed, the sequence we'd follow is short. Write down the decision the freshness serves and pick the tier from the ladder above. Check the source's log retention against the longest outage you'd tolerate, and have the DBA enable CDC or change tracking before anyone builds anything. Use the managed connector if one covers the source, land the changes in bronze as received, and apply them with an AUTO CDC flow sequenced by a log position, not a wall clock. Put lag, from source commit to queryable row, on a dashboard on day one with an alert at the agreed threshold. And if the feed carries an aggregation or a stream join, set the watermark and plot state size before it goes live, because that's the one decision that's cheap only at the start.

The declarative framework hosting these flows is covered in Medallion Architecture, and the cost consequences of continuous compute in Cost and Performance.