Skip to main content

your deltaLink is a streaming offset

incremental dataverse loads with spark, borrowing the structured streaming mental model.

Updated 10 min readMarkdown
Part of seriesdataverse and spark architecture.

Most dataverse-to-lakehouse data ingestion pipelines have a full reload, atleast in the initial run of its course. A spark job underneath pages the whole table, overwrites the bronze layer data and everything looks sorted on the surface.

Let's consider the case of a table that exponentially grew in data volume overnight pertaining to business actions. The table has, lets say eight million rows now and the nightly schedule of the pipeline that triggers the spark job to overwrite the bronze table, would have to spend a significant amount of compute and time moving data that is unchanged. If the same data ETL pipeline is scheduled sometime in the day as well or has multiple runs scheduled for a single day, the nightly ritual burns through the API capacity. In this case, one might consider bringing in an incremental load setup based on last_modified timestamps, which would work unless deletion logic for rows and the clock skew and long-running transactions make a timestamp watermark leakier than it seems.

Dataverse already has a better answer built in: change tracking. The easiest way to use it well is to stop thinking of it as an API feature and start thinking of it as a streaming source.

A single-loop structured streaming model and why is it relevant?

Spark Structured Streaming is a simple loop:

  1. Read the last committed offset from the checkpoint. Ask the source for everything after that offset. That's the micro-batch. Write the batch to the sink. Commit the new offset to the checkpoint.
  2. Spark's exactly-once guarantee doesn't come from magic. It comes from two properties working together:
  3. A replayable source: given an offset, you can fetch the same data again. An idempotent sink: writing the same data twice leaves the same result.
  4. If a batch fails partway through, Spark replays it from the last committed offset, and the sink absorbs the repeat. Keep those two properties in mind. Everything else in this post is about getting them from Dataverse.

What Dataverse change tracking gives:

Change tracking is switched on per table with the Track changes setting. Once it's enabled for a table, it can't be disabled, so turn it on deliberately.

With it on, you add a header to an ordinary query:

http GET [org]/api/data/v9.2/accounts?$select=accountid,name,modifiedon Prefer: odata.track-changes, odata.maxpagesize=5000

The first response is the full result set, paged with @odata.nextLink as usual. The last page also includes an @odata.deltaLink: a URL with a $deltatoken that marks "now."

Later, you call that deltaLink and get back only what changed since then, plus a new deltaLink. Deleted rows don't disappear silently. They come back as stub entries whose @odata.context ends in $deletedEntity, with the record's id and a reason of deleted. In each response, new and updated records come first, followed by the deleted ones.

One subtle point matters a lot: change tracking is state-based, not event-based. You learn which rows changed and get their current values. You don't get every intermediate edit. If a record was updated five times since your last run, you see it once, in its latest state. That's exactly what a lakehouse mirror needs. If you need full history, use auditing instead.

Now check the two properties.

Is the source replayable? Mostly, yes. A delta token marks a point in the table's version history, so calling the same deltaLink again returns changes since that point. The replay isn't byte-for-byte identical: a later call also includes anything that changed in the meantime, so it's a superset of the original batch. It's worth testing in your own environment, but that superset behavior is fine as long as the sink is idempotent.

Is the sink idempotent? It is if you make it so: MERGE on the primary key, keep only the newest version of each row, and treat deleting an already-deleted row as a no-op.

Together, those give you effectively exactly-once results, which is all a mirror table needs.

The golden rule: data first, offset second

The most important line in an incremental pipeline is the order of two writes.

Right: write the changes to Delta, then save the new deltaLink. If the job dies in between, the next run replays from the old link, and MERGE absorbs the duplicates. Nothing is lost.

Wrong: save the new deltaLink, then write the changes. If the write fails, the next run starts after changes that never landed. They're gone, and nothing will tell you.

Structured Streaming enforces this order for you. If you build the loop by hand, you have to enforce it yourself.

Where the analogy breaks

A good mental model also tells you where it stops working. Three places matter here.

  1. It's a single cursor. Kafka topics have partitions, so a stream can read them in parallel. A Dataverse delta can't be split: $filter, $orderby, $expand and $top aren't supported alongside Prefer: odata.track-changes. Every delta read is serial. That's usually fine, since a day's changes are a small slice of the table, but it's why the initial load needs a different strategy (below).
  2. Offsets expire. Kafka retention is something you configure and size. Dataverse change-tracking tokens are only good for a default of seven days, controlled by the organization's ExpireChangeTrackingInDays setting. If your last unprocessed change is older than that window, the call fails with an error. A pipeline that's paused for a long weekend plus a holiday can fall off the edge, and there's no catching up. You need a full-resync path from day one.
  3. Permissions are broader than you might expect. The calling identity needs organization-level read access to the table, or the request fails with a privilege check error. Scoped-down service accounts that work for normal queries can fail here.

Bootstrapping: getting your first offset without a serial full load

The deltaLink only appears on the last page of a track-changes query, and that query can't be filtered or range-partitioned. Paging eight million rows serially just to get a starting token is exactly the slow job we were trying to avoid.

The way out is to separate getting the token from loading the data:

Get the token cheaply. Run the track-changes query with $select set to just the primary key. It still pages serially, but each page is tiny. Save the deltaLink from the last page. Load the data in parallel. Use range-partitioned $filter queries on an immutable column like createdon, spread across Spark executors (see my earlier post on why nextLink is a cursor, not a partition). Start incremental runs from the token in step 1.

Step 1 must finish before step 2 starts. Then any change made during the full load is either captured by the load itself or shows up in the first delta, and often both. MERGE makes the overlap harmless.

There's one catch: the deltaLink remembers the $select it was created with. So the key-only token from step 1 only returns key columns in later deltas. To get full rows in deltas, run step 1 with the same $select you want for incremental loads. It's slower than key-only but still much cheaper than a full extraction, because you can discard rows as you page instead of writing them anywhere. If that's still too slow for a very wide table, accept the serial bootstrap once and parallelize everything after it.

A scheduled micro-batch with a control table:

The simplest implementation is a scheduled job that runs the streaming loop once per run.

The control table is your checkpoint:

CREATE TABLE IF NOT EXISTS ops.dataverse_offsets ( 
entity STRING, 
delta_link STRING, 
committed_at TIMESTAMP, 
rows_upserted BIGINT, 
rows_deleted BIGINT ) USING DELTA;

Reading the changes:

import time
from pyspark.sql import functions as F, Window
from delta.tables import DeltaTable

def read_changes(session, delta_link):
    """Follow a deltaLink to the end. Returns upserts, deletes, and the next offset."""
    upserts, deletes = [], []
    url, next_link = delta_link, None
    while url:
        r = session.get(url)
        if r.status_code == 429:
            time.sleep(int(r.headers.get("Retry-After", "5")))
            continue
        r.raise_for_status()
        body = r.json()
        for row in body["value"]:
            if row.get("@odata.context", "").endswith("$deletedEntity"):
                deletes.append((row["id"],))
            else:
                upserts.append((row["accountid"], row.get("name"), row["modifiedon"]))
        url = body.get("@odata.nextLink")
        next_link = body.get("@odata.deltaLink", next_link)
    return upserts, deletes, next_link

Applying the micro-batch, then committing the offset:

ENTITY, TARGET, CTRL = "accounts", "bronze.accounts", "ops.dataverse_offsets"

last_link = (spark.table(CTRL).filter(F.col("entity") == ENTITY)
                  .first()["delta_link"])
upserts, deletes, next_link = read_changes(session, last_link)

tgt = DeltaTable.forName(spark, TARGET)

if upserts:
    w = Window.partitionBy("accountid").orderBy(F.col("modifiedon").desc())
    latest = (spark.createDataFrame(upserts, "accountid string, name string, modifiedon string")
                   .withColumn("rn", F.row_number().over(w))
                   .filter("rn = 1").drop("rn"))
    (tgt.alias("t").merge(latest.alias("s"), "t.accountid = s.accountid")
        .whenMatchedUpdateAll(condition="s.modifiedon >= t.modifiedon")
        .whenNotMatchedInsertAll()
        .execute())

if deletes:
    dels = spark.createDataFrame(deletes, "accountid string")
    (tgt.alias("t").merge(dels.alias("d"), "t.accountid = d.accountid")
        .whenMatchedDelete()
        .execute())

# Data is committed. Only now advance the offset.
(spark.createDataFrame(
    [(ENTITY, next_link, len(upserts), len(deletes))],
    "entity string, delta_link string, rows_upserted long, rows_deleted long")
  .withColumn("committed_at", F.current_timestamp())
  .createOrReplaceTempView("new_offset"))

spark.sql(f"""
  MERGE INTO {CTRL} c USING new_offset n ON c.entity = n.entity
  WHEN MATCHED THEN UPDATE SET *
  WHEN NOT MATCHED THEN INSERT *
""")

Data is committed. Only now advance the offset.

Dedupe before merging. A replayed superset batch can contain more than one version of a row, so keep only the newest per key. The modifiedon >= condition stops an older replayed version from overwriting a newer one already in the table. Upserts before deletes matches the order Dataverse returns them in. Reading on the driver is fine here. The cursor is serial anyway. If your deltas are large, write each page to a staging location as you go instead of holding lists in memory.

Have a resync runbook. When a token expires, or the schema changes in a way you can't patch, the fix is the bootstrap again: new token, parallel full load, resume. If it's automated and tested, an expired token costs an hour of compute instead of a day of firefighting.

Plan for schema changes. Because the deltaLink remembers its $select, adding a column to the mirror means getting a new token with the new column list and backfilling that column. Treat it like a migration, not a config tweak.

Track multiple tables separately. One offset per table, one row per table in the control table (or one checkpoint per stream). Never share a deltaLink between pipelines.

Takeaways

Treat the deltaLink as a streaming offset, your control table or checkpoint as the offset log, and MERGE as an idempotent sink. Exactly-once comes from replay plus idempotency, not from avoiding failure. Commit data before the offset, every time. Change tracking is a single, serial, state-based cursor: no $filter, no history, and tokens that expire after seven days by default. Bootstrap once, load in parallel, then let deltas take over. Monitor offset age and keep a tested resync path, because sooner or later a token will expire.

The useful part of the streaming model isn't the API. It's the discipline: know where your offset is, make replays harmless, and never let the offset move ahead of the data.

Sources:

No comments yet. Be the first to comment.