9 minute read

A streaming delivery pipeline has two jobs: prove the transformation behaves correctly and prove the deployed job can preserve or deliberately migrate its state. Unit tests cover the first only partially; a green connector test does not prove a Flink savepoint can be restored, a Beam watermark can close a window, or a Spark checkpoint accepts a schema change.

Production confidence comes from a pyramid: deterministic tests around pure logic, event-time tests around windows and timers, contract tests around schemas, integration tests around actual state and brokers, replay tests around retained data, and controlled failure tests around recovery. CI/CD then promotes the same immutable artifact through these gates.

Delivery, state, and recovery testing diagram

Test the behavior, not framework liveness

Divide application code so that most business behavior is testable without a cluster. Parsing, key construction, enrichment policy, joins within bounded state, validation, aggregation, and routing should accept explicit values and return explicit outcomes.

For Java, model outcomes instead of logging and swallowing errors:

public sealed interface EnrichmentResult
    permits EnrichmentResult.Accepted, EnrichmentResult.Rejected {
  record Accepted(OrderEnriched event) implements EnrichmentResult {}
  record Rejected(String eventId, String reason) implements EnrichmentResult {}
}

The framework adapter transforms a runner context into this domain function. A test can then cover a malformed amount, stale reference data, duplicate event ID, event before source creation, and a valid update without starting Kafka.

Keep external time as a parameter:

Payment transform(Payment payment, ReferenceData reference, Instant processingTime) {
  if (payment.getEventTime().isAfter(processingTime.plusSeconds(1))) {
    throw new ClockSkewException(payment.getId());
  }
  return payment.normalize(reference, processingTime);
}

Passing processingTime is not a perfect model of a runner, but it makes normal and boundary cases deterministic and avoids tests that call Instant.now() and sleep.

Make unit and property tests deterministic

Use fixed input, fixed clocks, explicit watermark assumptions, and content-based assertions. A test that validates “at least one element” is weak; validate keys, values, timestamps, pane labels, state, and dead-letter reason.

Property-based tests are useful for streaming normalization:

  • reprocessing the same event ID produces the same logical key;
  • a valid input is never both accepted and rejected;
  • ordering an input permutation does not change a commutative aggregate when event keys and times are fixed;
  • decoding and re-encoding preserves the schema version and required fields;
  • state transitions never move backward except after a documented replay.

Keep generated values bounded. A random timestamp 1,000 years in the future can produce an unhelpful failure unrelated to the actual retention horizon.

Test event time explicitly

Processing-time tests are easier but answer the wrong question for late events, out-of-order events, windows, and timers. A meaningful test controls:

  1. event-time timestamp;
  2. watermark;
  3. arrival order;
  4. allowed lateness;
  5. trigger mode;
  6. expected pane or timer firing.

For an hourly window, include an event at 12:00, one at 12:59:59, one at 13:00, an early record at 12:30, a watermark past 13:00, and a late record before and after the late-data limit.

For Flink, use its test harness to deliver elements and timers:

KeyedOneInputStreamOperatorTestHarness<String, Click, Long> harness =
    new KeyedOneInputStreamOperatorTestHarness<>(
        new CountClicks(),
        Click::getAccountId,
        Types.STRING);

harness.open();
harness.processElement(new Click("a", 10L), 10L);
harness.processWatermark(new Watermark(60_000L));
harness.processElement(new Click("b", 30L), 30L);
harness.setProcessingTime(120_000L);
harness.close();

The exact harness constructor depends on Flink’s version. More important than the syntax is the assertion: late input and timer firing are driven by controlled values, never by wall-clock sleeps.

Use Beam TestStream for windows and triggers

Beam’s TestStream can encode processing time, event time, and watermark progression:

TestStream<Payment> events = TestStream.create(PaymentCoder.of())
    .addElements(
        TimestampedValue.of(payment("p-1", 10), Instant.ofEpochSecond(10)))
    .advanceWatermarkTo(new Instant(60_000))
    .addElements(
        TimestampedValue.of(payment("p-2", 40), Instant.ofEpochSecond(40)))
    .advanceProcessingTime(Duration.standardMinutes(1))
    .advanceWatermarkToInfinity();

PCollection<KV<String, Long>> actual = p.apply(events)
    .apply(Window.<Payment>into(FixedWindows.of(Duration.standardMinutes(1)))
        .withAllowedLateness(Duration.standardMinutes(5)))
    .apply("Count per account", Count.perKey());

PAssert.that(actual).containsInAnyOrder(
    KV.of("acct-1", 2L));
p.run();

TestStream is especially useful for distinguishing:

  • an event that arrived late but remains within the allowed-lateness horizon;
  • an event whose window and watermark closed;
  • an on-time aggregation versus a late pane;
  • timer behavior versus processing-time behavior.

Do not assert after an unbounded watermark unless you intend to test final output. A Direct Runner test can validate Beam SDK logic, but it does not validate Dataflow, Flink Runner, or Spark Runner serialization, state, and recovery behavior.

Treat schema and contracts as a release boundary

Store schemas and generated types in versioned source. CI should run:

  • compatibility check against the registered latest production schema;
  • required-field and timestamp semantic checks;
  • generated-code or build check;
  • sample decode for at least two historical major/minor versions;
  • dead-letter tests for unknown required versions;
  • sink contract tests for nullability, precision, and allowed enum values.

A schema registry compatibility mode is a guardrail, not a correctness proof. “Backward compatible” says consumers can read previous data under the registry’s rules. It does not prove that a changed field’s business meaning, units, or timezone is compatible.

Prefer additive and explicitly versioned changes:

{
  "type": "record",
  "name": "OrderPaid",
  "namespace": "com.example.events.v3",
  "fields": [
    {"name": "event_id", "type": "string"},
    {"name": "order_id", "type": "string"},
    {"name": "event_time_ms", "type": "long"},
    {"name": "amount_minor", "type": "long"},
    {"name": "currency", "type": "string"},
    {"name": "risk_score", "type": ["null", "double"], "default": null}
  ]
}

Contract tests should reject unit changes such as replacing a decimal currency amount with floating point, even if both happen to serialize as numbers.

Build integration tests with real boundaries

Run short-lived integration tests in CI where practical:

  • broker startup with actual producer and consumer;
  • schema registry or a faithful compatible test service;
  • real state backend with RocksDB for Flink;
  • checkpoint or savepoint restore;
  • idempotent or transactional sink behavior;
  • output reconciliation from an independent assertion query.

Avoid a suite that starts a full cloud deployment for every commit. Split:

  • per commit: unit, contract, lint, and fast local event-time tests;
  • per pull request: container build, security scan, short broker integration, and compatibility check;
  • pre-release: real runner, real object store, checkpoint/restart, replay, and canary;
  • scheduled: long state, high-volume skew, regional failure, and upgrade rehearsal.

Use testcontainers or an ephemeral cluster where supported, but remember that one local broker cannot reproduce replica loss, multi-zone networking, or managed-service throttling. Label each test with the failure modes it actually covers.

Add replay and golden-data tests

Choose a versioned, access-safe sample that represents realistic distribution:

  • normal, duplicate, out-of-order, late, tombstone, and invalid records;
  • one hot key and many cold keys;
  • historical schema versions;
  • null and boundary values;
  • source partitions with known offset ranges.

Replay the dataset twice. Expected outputs should be identical for a deterministic transformation, aside from documented generated metadata such as job ID. Reprocessing should not create sink duplicates when the same event identity is used.

For stateful jobs, record a checkpoint midway through the replay and validate:

  1. restore completes from the chosen checkpoint;
  2. no pre-checkpoint events are re-emitted incorrectly;
  3. sink duplicates are idempotent;
  4. in-flight state produces the expected subsequent window/timer;
  5. source offsets and output watermark match the expected recovery point.

A golden file is useful but should not contain secrets or production personal data. Store a small fixture with a cryptographic digest and an explicit license and privacy classification.

Inject failure at each guarantee boundary

Failure injection should target assumptions:

Fault Expected behavior
worker or executor termination checkpoint/savepoint restore and bounded catch-up
broker or source partition interruption lag rises; no output gap; resume from durable offset
sink timeout after commit retry does not duplicate logical output
schema-registry outage job uses a documented cache policy or fails closed
checkpoint upload failure alert; continued processing only inside the accepted RPO
hot partition backpressure and skew signal without data loss
clock skew future-event policy routes or bounds the record
poison event bounded retry then DLQ; partition does not stall indefinitely

For a canary, inject a single documented fault and stop if the canary fails its rollback conditions. Do not terminate stateful workers to “see what happens” in production without an owner, recovery objective, and verified savepoint.

CI pipeline example

An application-agnostic GitHub Actions workflow can run lightweight gates on every change:

name: streaming-pipeline-ci
on:
  pull_request:
  push:
    branches: [main]

permissions:
  contents: read
  id-token: write

jobs:
  verify:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-java@v4
        with:
          distribution: temurin
          java-version: '17'
          cache: maven
      - run: mvn -B -DskipITs=false verify
      - name: Check schema compatibility
        env:
          SCHEMA_REGISTRY_URL: $
        run: ./ci/check-schema-compatibility.sh schemas/
      - run: ./ci/run-kafka-integration.sh
      - name: Build immutable image
        run: |
          docker build --label org.opencontainers.image.revision="${GITHUB_SHA}" \
            -t streaming-pipeline:${GITHUB_SHA} .
          docker save streaming-pipeline:${GITHUB_SHA} -o streaming-pipeline.tar
      - name: Test savepoint restore
        run: ./ci/test-state-restore.sh streaming-pipeline:${GITHUB_SHA}

Record all tool and container versions. Do not run a deploy from the same job that built the artifact unless the deployment is intentionally ephemeral. A protected promotion job should identify the image by digest, not rebuild the source.

The YAML intentionally omits cloud-specific registry and secret steps. Add OIDC-based authentication and least-privilege deployment roles in the target environment.

State compatibility is an API

Flink keyed and operator state can become part of the deployment contract. Spark checkpoints reference query plans and state serialization; Beam runner state is also tied to SDK and transform identity. Treat these as compatibility surfaces.

Before a stateful release:

  • name stateful operators and state fields explicitly;
  • use stable logical state types with version evolution where supported;
  • change one schema concern at a time;
  • restore the previous release’s savepoint/checkpoint into the candidate build;
  • process additional events around pending windows and timers;
  • compare state size, key cardinality, output, and DLQ behavior;
  • define how old state is migrated or safely discarded.

A source-code test cannot prove Java serialization compatibility for every object graph. A binary-compatibility plugin plus an actual historical savepoint test is stronger.

For Flink, a canary upgrade may use:

flink savepoint 00000000000000000000000000000000 \
  s3://example/savepoints/orders/candidate --type CANONICAL

flink run -s s3://example/savepoints/orders/candidate/savepoint-... \
  /opt/jobs/orders-candidate.jar

Savepoint location is deployment-specific. Confirm the job ID and exact Flink CLI supported by the target version. Do not treat a trigger command as proof that the savepoint completed; monitor the savepoint response and restore logs.

Promote with evidence

A deployment record should include:

release:
  pipeline: orders-enricher
  imageDigest: sha256:...
  sourceCommit: 012345...
  schemas: [orders.event:42]
  checkpointCompatibility: verified-from-savepoint-sp-104
  goldenReplay: fixture-orders-2022-12
  rollbackMode: restore-previous-savepoint
  maxCanaryLag: 120s
  maxDlqRatio: 0.001
  owner: data-platform

Canary deployment exposes only a controlled partition, source subset, or shadow sink. Compare candidate output with the incumbent without allowing duplicate writes. For exactly-once behavior, understand the sink transaction: a shadow side effect can violate the very guarantee under test.

Rollback correctly

Stopping a candidate job and restarting the old binary is not necessarily rollback. The old binary might not read state written by the candidate, and the source may already have committed new offsets.

Define one of these choices in advance:

  • state rollback: stop candidate, restore the pre-deploy savepoint in the old version, replay from the matching offsets, and use an idempotent sink;
  • forward fix: stop bad writes, deploy a compatible fix, and continue from candidate state;
  • output correction: isolate candidate output partitions, reverse or overwrite them with a controlled correction;
  • data replay: rebuild downstream state in a new versioned namespace, then cut consumers over.

Keep the old checkpoint and old artifact until the rollback horizon expires. Cloud retention policies should not delete the only useful savepoint during a multi-day canary.

Release checklist

  • Pure logic has deterministic unit and property tests.
  • Event-time behavior uses a controlled stream or test harness.
  • Windows, late panes, timers, and DLQ routing have explicit assertions.
  • Schema compatibility is checked independently of code compilation.
  • Integration tests use actual broker/state/sink boundaries.
  • Golden replay covers duplicates, skew, old schemas, and invalid data.
  • Checkpoint/savepoint restore is tested with the prior production state.
  • Failure injection has expected signals and bounded recovery.
  • One immutable artifact moves through environments.
  • Promotion thresholds and a state-aware rollback procedure are documented.

A streaming CI pipeline is successful when a tested artifact can be deployed, observed, restored, and rolled back with evidence. A fast compile is only the beginning.