Skip to content

Extraction Strategies: CDC vs Watermark vs Full Extract

This document explains the three data extraction strategies supported by rust-sql-extractor, when to use each, how they work, and their trade-offs.

Quick Comparison

Strategy Ideal For Performance Complexity Storage When Used
CDC High-volume incremental ⭐⭐⭐ Excellent Medium Moderate Tables with CDC enabled
Change Tracking Medium incremental ⭐⭐⭐ Good Low Low Tables with CT enabled
Watermark Sequential data ⭐⭐ Good Low Minimal Tables with ModifiedDate/UpdatedDate
Full Extract Initial load / resets ⭐ Slow Very Low High First run or state resets

1. Change Data Capture (CDC)

What is CDC?

Change Data Capture is a SQL Server feature that automatically captures all INSERT, UPDATE, and DELETE operations on a table into dedicated change tables. The database continuously publishes the "what changed" without scanning the entire table.

How It Works

  1. Enable at table level: EXEC sys.sp_cdc_enable_net_changes 'dbo', 'YourTable'
  2. SQL Server creates a shadow table (cdc.dbo_YourTable_CT) that stores:
  3. All columns from the source table
  4. __$start_lsn (Log Sequence Number - uniquely identifies the change)
  5. __$seqval (sequence within the LSN for same-transaction operations)
  6. __$operation (1=DELETE, 2=INSERT, 4=UPDATE before, 5=UPDATE after)
  7. __$update_mask (bitmap showing which columns changed)

  8. Incremental extraction uses LSN ranges:

    SELECT ... FROM cdc.fn_cdc_get_all_changes_dbo_YourTable(@start_lsn, @end_lsn, 'all')
    WHERE __$start_lsn > @last_lsn
    

Advantages

  • ✅ Complete history - captures every change with operation type
  • ✅ Minimal load - no table scan, relies on transaction log
  • ✅ Deletes tracked - can identify and merge deletions
  • ✅ Native support - SQL Server manages it transparently
  • ✅ LSN ordering - guaranteed chronological ordering

Disadvantages

  • ❌ Requires setup - must be explicitly enabled by DBA
  • ❌ Storage cost - shadow tables consume disk space
  • ❌ Overhead - log capture jobs consume resources
  • ❌ Not real-time - slight lag depending on capture job frequency
  • ❌ Retention policy - LSN values are eventually purged

When to Use CDC

  • Production OLTP databases with high change velocity
  • Tables requiring comprehensive audit trails
  • When you need to track which rows were deleted
  • Databases where MSSQL CDC is already enabled

Extraction Logic

// Get max LSN for current range
let query = format!(
    "SELECT @max_lsn = sys.fn_cdc_get_max_lsn() ...",
);

// Extract changes between last_lsn and max_lsn
let changes_query = format!(
    "SELECT * FROM cdc.fn_cdc_get_all_changes_{}_{}(@start_lsn, @end_lsn, 'all')
     WHERE __$start_lsn > {} AND __$start_lsn <= {}",
    schema, table, last_lsn, max_lsn
);

// If tracking deletes: operations 2=INSERT, 5=UPDATE-AFTER, 1=DELETE
// MergeDeltaWriter uses __$operation column for upsert/delete logic

2. Change Tracking (CT)

What is Change Tracking?

Change Tracking is a lightweight alternative to CDC. Instead of storing full row copies, SQL Server tracks which rows changed and their version number. The application fetches the actual current data.

How It Works

  1. Enable at table level: ALTER TABLE YourTable ENABLE CHANGE_TRACKING
  2. SQL Server tracks:
  3. Primary key of changed rows
  4. SYS_CHANGE_VERSION (incrementing counter per commit)
  5. SYS_CHANGE_OPERATION (INSERT, UPDATE, DELETE - not before/after values)
  6. Incremental extraction uses version numbers:
    SELECT ... FROM CHANGETABLE(CHANGES YourTable, @last_version) AS T
    WHERE SYS_CHANGE_VERSION > @last_version
    

Advantages

  • ✅ Lightweight - tracks only PK + version, not full rows
  • ✅ Lower overhead - less storage and CPU than CDC
  • ✅ Deletes tracked - identifies deleted rows
  • ✅ Simple setup - lightweight feature with minimal maintenance
  • ✅ Works on standard/express editions - more broadly available

Disadvantages

  • ⚠️ No before/after - doesn't capture pre-update values
  • ⚠️ Schema changes - tracking disabled on ALTER TABLE
  • ⚠️ Version sync - all changes share same version (can batch large updates)
  • ❌ Retention - versions are purged after cleanup cycles
  • ❌ Current data only - must join to get actual column values

When to Use Change Tracking

  • Tables with moderate change velocity
  • When storage is a concern (vs CDC)
  • Databases that can't enable CDC (permissions, editions)
  • When you don't need pre-update values
  • Tables with frequent bulk updates (CT batches them)

Extraction Logic

// Get current version
let current_version = self.connector.get_current_version().await?;

// Extract changes since last_version
let changes_query = format!(
    "SELECT * FROM CHANGETABLE(CHANGES [{}].[{}], {}) AS T
     WHERE SYS_CHANGE_VERSION > {}",
    schema, table, last_version, last_version
);

// If tracking deletes: SYS_CHANGE_OPERATION tells if it's DELETE
// MergeDeltaWriter uses SYS_CHANGE_OPERATION column for merge

3. Watermark (Datetime-based Incremental)

What is Watermark?

Watermark extraction tracks changes via a continuously-incrementing datetime column (e.g., ModifiedDate, UpdatedAt). Each run extracts rows where the datetime is greater than the previous extraction's max datetime.

How It Works

  1. Require a datetime column that:
  2. Updates automatically on INSERT/UPDATE (via trigger or computed column)
  3. Is indexed for performance
  4. Has a common naming pattern (*Modified*, *Updated*, *Changed*, *Timestamp*)

  5. Auto-detection scans column types and names:

    SELECT column_name, data_type 
    FROM INFORMATION_SCHEMA.COLUMNS 
    WHERE data_type IN ('datetime', 'datetime2', 'datetimeoffset', ...)
      AND column_name LIKE '%Modified%' OR '%Updated%'
    

  6. Incremental extraction uses WHERE clause:

    SELECT * FROM [dbo].[YourTable] 
    WHERE [ModifiedDate] > '2024-01-15 10:32:17'
    ORDER BY [ModifiedDate]
    

Advantages

  • ✅ Works everywhere - no special SQL Server features needed
  • ✅ Simple logic - straightforward WHERE clause
  • ✅ Low overhead - standard indexed scan
  • ✅ Self-tuning - index on datetime improves performance automatically
  • ✅ Portable - logic works on other databases (PostgreSQL, MySQL, Oracle)

Disadvantages

  • ❌ Requires schema change - must add/maintain datetime column
  • ⚠️ Deletes invisible - deleted rows disappear, can't be tracked
  • ⚠️ Datetime precision - microsecond vs millisecond differences matter
  • ⚠️ Clock skew - multi-server setups need synchronized clocks
  • ⚠️ Gap risk - very high update rates can cluster at same timestamp
  • ❌ Update-only - can't distinguish INSERT from UPDATE

When to Use Watermark

  • Tables without CDC/CT enabled
  • Incremental loads where delete tracking isn't required
  • High-velocity tables (watermark is simpler than scanning)
  • Data mart/warehouse scenarios (inserts dominate)
  • Tables that already have a ModifiedDate column
  • Multi-database environments

Extraction Logic

// First run: no state → full extract
if state.is_none() {
    return self.extract_full(advice, options, writer).await;
}

// Subsequent runs: use last watermark value
let where_clause = match watermark_type {
    WatermarkType::DateTime => {
        let last_value = "2024-01-15 10:32:17";
        format!("WHERE [ModifiedDate] > '{}'", last_value)
    }
    WatermarkType::Identity => {
        let last_value = "12345";
        format!("WHERE [ID] > {}", last_value)
    }
};

let query = format!(
    "SELECT * FROM [{}].[{}] {} ORDER BY [{}]",
    schema, table, where_clause, column
);

4. Full Extract

What is Full Extract?

A complete scan of the entire table, used for initial loads or when state is reset.

How It Works

SELECT * FROM [schema].[table]

Advantages

  • ✅ Simple - no prerequisites or configuration
  • ✅ Guaranteed complete - every row captured
  • ✅ Works everywhere - no SQL Server features needed

Disadvantages

  • ❌ Slow - must read entire table
  • ❌ Resource-intensive - locks, I/O, memory
  • ❌ High network traffic - all rows transmitted
  • ❌ Not incremental - every run duplicates prior data
  • ❌ Delete handling - if using hash-based merge, only compares via PK+hash

When to Use Full Extract

  • Initial load - first time extracting a table
  • State reset - when reset_extraction_state() is called
  • Force full - when options.force_full = true
  • Fallback - when watermark has no prior state
  • Recovery - after data loss or corruption

Decision Tree: Choosing Your Strategy

Does the table have CDC enabled?
├─ YES → Use CDC ✅ (best for completeness)
│
└─ NO → Does the table have Change Tracking enabled?
    ├─ YES → Use Change Tracking ✅ (good balance)
    │
    └─ NO → Does the table have a ModifiedDate/UpdatedAt column?
        ├─ YES → Use Watermark ✅ (simple incremental)
        │
        └─ NO → Use Full Extract ❌ (slow, but guaranteed)

Extraction State Reset Behavior

When reset_extraction_state() is called:

For CDC/CT tables (with deletes tracking)

Current behavior: State is cleared, next run extracts from current max LSN/version Problem: Misses all changes that occurred since last extraction Fixed behavior: Should trigger Full Extract to capture current table state

For Watermark tables

Current behavior: Watermark value is cleared Next behavior: First run without state → extracts full table, sets new watermark Note: This is correct - watermark naturally falls back to full

For tables with hashing

Current behavior: _hash column is added in Full extract Next behavior: MergeDeltaWriter compares hashes, upserts only changed rows Result: Deduplication without needing CDC/CT


Implementation Issues & Fixes

Issue 1: DateTime Precision Loss (Watermark)

Problem:

WHERE [ModifiedDate] > '2008-03-11 10:32:17.973333333'
                                                    ↑ Too many decimals!

SQL Server's datetime type supports only 3 decimal places (milliseconds), but JSON serialization may preserve nanosecond precision (9 decimals).

Current code (line 778-781 in data_extractor.rs):

WatermarkType::DateTime => {
    let val = last_value
        .as_str()
        .unwrap_or("")
        .replace('T', " ")
        .replace('Z', "");  // ← Incomplete formatting!
    format!("'{}'", val)
}

Fix: Truncate to milliseconds (3 decimal places):

WatermarkType::DateTime => {
    let val = last_value.as_str().unwrap_or("");
    // Parse ISO datetime and truncate to milliseconds
    if let Ok(dt) = chrono::DateTime::parse_from_rfc3339(val) {
        let truncated = dt.format("%Y-%m-%d %H:%M:%S%.3f").to_string();
        format!("'{}'", truncated)
    } else {
        // Fallback: just remove T and Z
        let clean = val.replace('T', " ").replace('Z', "");
        format!("'{}'", clean)
    }
}

Issue 2: CDC/CT Reset Should Trigger Full Extract

Current problem: Resetting CDC/CT extraction state clears the LSN/version but doesn't force a full extract. The next run starts from the current max LSN (missing all prior changes).

Fix: Add parameter to reset_extraction_state():

pub fn reset_extraction_state(&mut self, force_full_for_incremental: bool) -> &mut Self {
    for entry in &mut self.entries {
        // Reset state
        entry.last_extracted = None;

        // If force_full_for_incremental=true and strategy is CDC/CT:
        // Set a flag or trigger immediate full extract
        if force_full_for_incremental {
            match entry.strategy {
                ExtractionStrategy::Cdc { .. } | ExtractionStrategy::ChangeTracking { .. } => {
                    // Mark for full extract next run
                    entry.force_full_next_run = true; // New field
                }
                _ => {} // Watermark/Full are already stateless
            }
        }
    }
    self
}

Then in extract_table():

if entry.force_full_next_run || options.force_full {
    return self.extract_full_with_state(advice, options, &table_path).await;
}


Summary Table: Strategy Comparison

Aspect CDC Change Tracking Watermark Full Extract
Setup Required DBA enabled DBA enabled Schema add None
Changes captured ✅ All (Insert/Update/Delete) ✅ All ops (no values) ⚠️ Insert/Update only ⚠️ None (baseline)
Before/After values ✅ Yes ❌ No ❌ No ❌ No
Delete tracking ✅ Yes ✅ Yes ❌ No ❌ No (with hash: yes)
Performance ⭐⭐⭐ ⭐⭐⭐ ⭐⭐ ⭐
Complexity Medium Low Low Very low
First load Full table Full table Full table Full table
Incremental LSN ranges Version ranges Datetime filtering N/A
Merge logic __$operation col SYS_CHANGE_OPERATION col PK+hash compare Hash compare