Streaming Backfill Safety: Watermark Shifts, Retractions, and Correctness Tests
1. Overview
1.1 Purpose
This document outlines safety mechanisms and testing strategies for streaming backfill operations in our event-time stream processing pipelines (e.g., based on Apache Flink or Kafka Streams). Backfill involves ingesting historical data into a live streaming topology to reconstruct or update downstream state (e.g., aggregates, materialized views).
Key challenges:
Watermark shifts : Backfill data may have event timestamps (ET) older than the current watermark (WM), causing WM stalls, lateness, or jumps.
Retractions : Changelog streams (e.g., upserts/deletes) during backfill can retract prior values, risking incorrect final state if not handled idempotently.
Correctness : Ensuring exactly-once semantics, no data loss/duplication, and accurate state post-backfill.
1.2 Scope
Applies to production topologies with bounded-out-of-orderness (Ooo) assumptions.
Assumes Flink-like semantics: event-time processing, watermarks, timers, side-outputs for late data.
Non-goals: Schema evolution, partitioning changes.
1.3 Key Principles
Idempotency : Backfills must be repeatable without side effects.
Atomicity : Backfill + live stream transition must be seamless.
Observability : Metrics for WM progress, retraction counts, lateness.
Rollback : Ability to pause/resume backfill with state snapshots.
2. Watermark Shifts
2.1 Risks
WM stall : Historical data ET < current WM → no progress until caught up.
WM jump : Injecting sorted historical data → sudden WM advance, dropping live late data.
Ooo violations : Backfill data exceeds bounded Ooo → dropped or side-outputted incorrectly.
2.2 Safety Mechanisms
Pre-backfill WM Alignment :
Pause live ingestion.
Compute global min/max ET from backfill dataset.
Retract WM to min_backfill_ET - bounded_ooo via a synthetic "WM retraction event".
Phased Injection :
code Copy code
Phase 1: Historical data (ET <= cutoff_ts)
- Sort backfill by ET.
- Inject in micro-batches (e.g., 1h windows).
- Update WM incrementally: `new_wm = max(current_wm, max_batch_et)`.
Phase 2: Transition (cutoff_ts < ET <= live_wm)
- Gap-filling with watermarks only (no events).
Phase 3: Resume live stream.
Batch size: Adaptive, based on throughput (e.g., < 10% WM lag).
Lateness Handling :
Configure allowedLateness to 2 * bounded_ooo.
Side-output late events to DLQ for manual inspection.
Metric: backfill_wm_lag = live_wm - backfill_wm.
Guards :
Circuit breaker: If WM lag > threshold (e.g., 1d), pause backfill.
Dual-WM mode: Track backfill_wm and live_wm separately until convergence.
2.3 Configuration
Param Default Description backfill.ooo_bound5m Max allowed lateness during backfill backfill.batch_size1h ET window per batch backfill.wm_retract_threshold1d Max WM retraction allowed
3. Retractions
3.1 Risks
State thrashing : Rapid insert/delete cycles during backfill → incorrect aggregates.
Non-idempotent backfills : Duplicate retractions → over-deletion.
Live interference : Backfill retractions affecting live state prematurely.
3.2 Safety Mechanisms
Changelog Deduplication :
Pre-process backfill: Group by primary key, resolve to final state (e.g., latest upsert).
Emit only net changes: +value for inserts/upserts, -value for deletes.
Transaction Boundaries :
Wrap backfill batches in Flink transactions (exactly-once).
Use Kafka transactional producers for changelog topics.
Retract Filtering :
code Copy code
if (event.type == RETRACT && event.et < backfill_cutoff) {
// Buffer and emit only if matching +insert exists in backfill
buffer.put(key, event);
}
Post-backfill: Flush buffered retractions.
Idempotency via Checkpoints :
Backfill from last successful checkpoint.
Use key-state versioning: Increment on each update, ignore stale.
Metrics :
backfill_retractions_total
backfill_net_changes (inserts - deletes)
4. Correctness Tests
4.1 Test Categories
Unit Tests : Operator-level (e.g., watermark assigner, retract handler).
Integration Tests : End-to-end backfill in local Flink mini-cluster.
Chaos Tests : Inject faults (WM shifts, network partitions) in Kubernetes.
4.2 Test Scenarios
Use JUnit + Flink Test Harness. Generate synthetic datasets with ScalaTest or custom generators.
Scenario Inputs Assertions Coverage WM Shift Forward Backfill ET: [T-1d, T], live WM=T+1h Final WM = T+1h, no drops WatermarkAssigner WM Retract Backfill min ET = T-2d, live WM=T WM retracts to T-2d-ooo, all data processed Global WM sync Late Data During Backfill Mix late events (ET=T-1h) with backfill Lateness side-output, state correct Lateness handling Retraction Cycles Key: +10, -5, +3 (net +8) Final state = 8, idempotent on rerun Changelog resolver Partial Backfill Failover Kill task mid-batch Resume from checkpoint, no duplicates Exactly-once Ooo Violation Event ET < WM - ooo_bound Dropped + alert Bounds check Chaos: Partition Loss Drop 50% backfill events Detect via checksum, retry batch Resilience
4.3 Test Framework
scala Copy code
class BackfillSafetyTest extends FlinkTestSuite {
@Test
def testWmShift(): Unit = {
val backfill = generateEvents(minEt = Instant.now().minus(1, DAYS))
injectBackfill(topology, backfill)
assertEquals(expectedState, readState())
assertWmConverged()
}
}
Golden Datasets : Pre-defined input/output pairs (e.g., 1M events, 10% retractions).
Property-Based : ScalaCheck for random ET distributions.
CI Integration : Run on every PR, full chaos nightly.
4.4 Success Criteria
100% unit/integration coverage.
Chaos tests: 99% success rate over 100 runs.
Post-test validation: State checksum == expected (e.g., CRC32).
5. Rollout Plan
Alpha : Local dev clusters.
Beta : Staging with 10% traffic shadow.
Prod : Canary (1 partition), monitor for 24h, full rollout.
Monitoring : Prometheus alerts on WM lag > 1h, retraction spikes.
6. Open Questions
Integration with CDC sources (e.g., Debezium)?
Handling unbounded backfills (e.g., full history)?
Cost estimates for large-scale (PB-scale) backfills?
Draft v0.1 - Feedback welcome. Owner: Streaming Team.