9 minute read

Spark Structured Streaming gives a continuous application a dataframe interface and a durable query-progress model. Dataproc supplies Spark workers, logging, and cluster lifecycle. Neither guarantees an end-to-end delivery contract: that contract comes from the source connector, checkpoint, output semantics, sink transaction boundary, and the way the job is restarted.

Spark Structured Streaming on Dataproc architecture

Pick a source and define what replay means

The source determines the unit of replay:

Source Recovery unit Useful constraint
Kafka topic, partition, and offset connector and Kafka client versions must be compatible
Pub/Sub subscription acknowledgement plus connector-managed stream state the connector cannot infer a business delivery key
GCS files discovered object or file path small files, incomplete objects, and late arrival need policy

With Kafka, the query checkpoint is the authoritative consumed offset. A Kafka consumer group is not a safe substitute. startingOffsets=latest matters only when the checkpoint has no prior batch; on a normal restart, committed offsets in GCS win.

With Pub/Sub, retain and replay by the subscription’s backlog and retention, not by an arbitrary worker. Acknowledgement behavior must align with batch commit. Use a connector package supported by the selected Dataproc image and Scala version, and prove that a crashed executor does not acknowledge a message before the query considers that message durable.

For GCS, create a file-input directory where producers write a temporary object and then promote it atomically. Spark’s file source tracks discovered files in its checkpoint. If a producer updates an existing object name, the checkpoint may not treat that as a new event. The recommended GCS shape is append-only, immutable files with a bounded naming and arrival convention:

gs://example-stream/incoming/orders/
  date=2021-03-29/hour=13/part-00001-d6a.parquet
  date=2021-03-29/hour=13/part-00002-a9c.parquet

Before selecting GCS as a stream transport, quantify file rate. One million tiny object creations are an object-listing and file-discovery workload, not a healthy micro-batch stream.

Establish durable GCS checkpoints

Every logical query needs a unique checkpoint path:

gs://example-checkpoints/orders-stream/v3/

The path stores offsets, query metadata, state, and commit evidence. Version the path with a semantic query version: source subscription or topics, schema, event-time window, and stateful operator shape. A new business version can use a new path, but it must also define the starting offset or timestamp and migration output destination.

Protect the checkpoint bucket from lifecycle deletion and broad principal access. Enable object versioning if the operational model can use it, but versioning is not a substitute for a backup and restore procedure. A malformed manual edit can be automatically preserved as a newer bad object.

Validate checkpoint durability by moving a running Dataproc job:

  1. stop it gracefully;
  2. delete or drain the old worker group;
  3. submit the same application with the same checkpoint;
  4. verify source offsets resume at the last committed batch and lag converges.

Provision dependencies reproducibly

Do not add a connector JAR interactively. Store the application, connector, and checksum in a versioned GCS prefix. The Kafka connector is included with many Spark distributions, but its package may vary by Dataproc image. Pub/Sub and GCS-specific connectors must be selected against the exact Spark and Scala binary version.

A controlled artifact layout is:

gs://example-code/spark/
  apps/orders_stream.py
  connectors/spark-sql-kafka-0-10_2.12-3.0.1.jar
  connectors/pubsub-spark-connector.jar
  checksums.sha256

The driver code and JARs should be released together through CI. Reject a deploy if the Dataproc image label or connector Scala suffix changes without a compatibility test.

Build a Kafka streaming query

The following application parses events, applies a watermark, writes recoverable partitioned Parquet, and exposes progress to the log. Replace the Kafka endpoint and trust settings with the organization’s private cluster settings.

import argparse
import json

from pyspark.sql import SparkSession, functions as F
from pyspark.sql.types import (
    LongType,
    StringType,
    StructField,
    StructType,
)

parser = argparse.ArgumentParser()
parser.add_argument("--checkpoint", required=True)
parser.add_argument("--output", required=True)
args = parser.parse_args()

spark = (
    SparkSession.builder.appName("orders-structured-stream")
    .config("spark.sql.shuffle.partitions", "120")
    .config("spark.sql.streaming.stopGracefullyOnShutdown", "true")
    .getOrCreate()
)

schema = StructType([
    StructField("order_id", StringType()),
    StructField("customer_id", StringType()),
    StructField("amount_cents", LongType()),
    StructField("event_epoch_ms", LongType()),
    StructField("region", StringType()),
])

raw = (
    spark.readStream.format("kafka")
    .option(
        "kafka.bootstrap.servers",
        "kafka-0.internal:9092,kafka-1.internal:9092,kafka-2.internal:9092",
    )
    .option("subscribe", "orders.v1")
    .option("startingOffsets", "latest")
    .option("failOnDataLoss", "true")
    .option("maxOffsetsPerTrigger", "500000")
    .load()
)

parsed = (
    raw.selectExpr(
        "CAST(value AS STRING) AS json_value",
        "topic",
        "partition",
        "offset",
    )
    .select(
        F.from_json("json_value", schema).alias("payload"),
        "topic",
        "partition",
        "offset",
    )
    .select("payload.*", "topic", "partition", "offset")
)

events = (
    parsed.withColumn(
        "event_time",
        F.to_timestamp(F.col("event_epoch_ms") / F.lit(1000.0)),
    )
    .withWatermark("event_time", "15 minutes")
    .withColumn("event_date", F.to_date("event_time"))
)

query = (
    events.writeStream.format("parquet")
    .outputMode("append")
    .option("checkpointLocation", args.checkpoint)
    .option("path", args.output)
    .partitionBy("event_date", "region")
    .trigger(processingTime="20 seconds")
    .start()
)

while query.isActive:
    query.awaitTermination(30)
    progress = json.loads(query.lastProgress) if query.lastProgress else None
    if progress:
        print(json.dumps({
            "batchId": progress.get("batchId"),
            "inputRows": progress.get("numInputRows"),
            "inputRate": progress.get("inputRowsPerSecond"),
            "processedRate": progress.get("processedRowsPerSecond"),
            "triggerMs": progress.get("durationMs", {}).get("triggerExecution"),
        }))

The code sets failOnDataLoss=true. If retention expires while the job is down, Spark fails instead of silently skipping an unknown offset range. Treat that failure as an incident requiring backfill, not as a prompt to disable the setting.

maxOffsetsPerTrigger is a safety valve for a large backlog. It protects the first recovering batch from consuming every historical record at once, but it also extends catch-up time. Size it with the measured per-batch processing rate and the recovery deadline.

Use Pub/Sub or GCS inputs where they fit

Pub/Sub is a good native event boundary when producers and consumers already use Google Cloud. A supported Spark Pub/Sub connector generally has to provide Spark rows containing payload bytes, attributes, message ID, and publish time. The application contract then resembles Kafka:

raw = (
    spark.readStream.format("pubsub")
    .option("projectId", "PROJECT_ID")
    .option("subscription", "projects/PROJECT_ID/subscriptions/orders-stream")
    .load()
)

events = raw.select(
    F.from_json(F.col("data").cast("string"), schema).alias("payload"),
    F.col("messageId"),
    F.col("publishTime"),
).select("payload.*", "messageId", "publishTime")

This is intentionally connector-oriented rather than universal: validate option names and message fields against the packaged connector. Test deduplication on messageId or, preferably, a producer-stable order_event_id. Pub/Sub at-least-once semantics can redeliver messages during retries, so a downstream unique key is part of correctness.

A GCS file source works without a broker:

files = (
    spark.readStream.schema(schema)
    .option("maxFilesPerTrigger", "500")
    .option("latestFirst", "false")
    .json("gs://example-stream/incoming/orders")
)

Use explicit schema, maxFilesPerTrigger, and a late-file policy. A producer should publish objects after all bytes are committed. A query consuming partially written JSON can repeatedly fail or admit malformed lines, depending on the reader’s corruption behavior.

Choose sinks by transaction requirement

A plain Parquet sink is convenient and scalable, but its file writes and the stream checkpoint are not one transaction. A retried micro-batch can overwrite predictable output locations or can produce duplicate logical records if the sink is append-only. Spark’s checkpoint prevents one normal committed batch from being committed twice by that query, but it does not roll back arbitrary external side effects.

GCS/object output

Use append mode for immutable events, partition on low-cardinality event-time dimensions, and test file size. For replay, build an output manifest from batch IDs and atomically expose it to readers. If consumers require one final result per key, use a table format or foreachBatch merge rather than raw files.

BigQuery output

BigQuery is useful as a serving sink, but every writer still needs an idempotency key. With foreachBatch, write the batch to a staging table and run an idempotent merge:

def merge_bigquery(batch_df, batch_id):
    tagged = batch_df.withColumn("spark_batch_id", F.lit(batch_id))
    tagged.write.format("bigquery") \
        .option("table", "PROJECT_ID.analytics_stage.order_events_stage") \
        .option("temporaryGcsBucket", "example-dataproc-temp") \
        .option("writeMethod", "direct") \
        .mode("overwrite") \
        .save()

    # Execute a BigQuery MERGE with BigQuery's client after the stage load.
    # The target key is (source_id, event_id), not the Spark batch ID alone.

The merge itself must be implemented against a unique event key and published in code with the application version. Overwriting a staging table and then failing the merge is recoverable. Appending to the final table and then marking the batch in a separate store is not reliably atomic.

Kafka output

Kafka output works when the value is a serialized record and the business key is stable. Kafka’s producer can provide idempotent behavior, but a Spark sink batch still needs the surrounding replay and deduplication contract. Keep one event ID in the key or payload and have consumers enforce the uniqueness semantics required.

Size Dataproc for sustained lag

The steady-state condition is:

p95 micro-batch duration < trigger interval

That leaves room for GC, source bursts, and state compaction. If the trigger is 20 seconds and the normal batch takes 18 seconds, there is no recovery headroom. Target 50 to 60 percent utilization at steady state, leaving capacity to catch up.

For stateful joins or windows, profile RocksDB or in-memory state, shuffle, Python memory, and checkpoint history. Spark Structured Streaming state on each executor must be durable through GCS checkpoints, but executors still rebuild it and need enough temporary disk and network time. A preemptible fleet is acceptable only if restart and state rebuild still fit the lag SLO.

Size one or more partitions per executor core and cap source records per trigger. A Kafka backlog with 20 million records should not be accepted as one giant first batch. For Pub/Sub, backpressure and connector fetch settings need the same measurement.

Submit and monitor on Dataproc

Create a stable cluster or submit to an existing streaming pool:

gcloud dataproc clusters create streaming-jobs \
  --region=us-central1 \
  --zone=us-central1-a \
  --image-version=2.0-debian10 \
  --master-machine-type=n2-standard-4 \
  --worker-machine-type=n2-highmem-8 \
  --num-workers=6 \
  --no-address \
  --subnet=projects/PROJECT_ID/regions/us-central1/subnetworks/data

gcloud dataproc jobs submit pyspark \
  gs://example-code/spark/apps/orders_stream.py \
  --region=us-central1 \
  --cluster=streaming-jobs \
  --jars=gs://example-code/spark/connectors/pubsub-spark-connector.jar \
  --properties='spark.executor.instances=12,spark.executor.cores=4,spark.executor.memory=12g,spark.executor.memoryOverhead=3g,spark.sql.shuffle.partitions=120' \
  -- \
  --checkpoint=gs://example-checkpoints/orders-stream/v3/ \
  --output=gs://example-lake/silver/orders/

Do not use an ephemeral cluster that an orchestrator terminates while the streaming job is still considered healthy. Restart policy must distinguish a bad event loop from intended deployment. Send a graceful termination signal where possible, so the query stops accepting a new micro-batch and completes current work.

Export and alert on:

  • numInputRows, input rate, and processed rate;
  • trigger, add-batch, and get-offset duration;
  • source start/end offsets or Pub/Sub backlog age;
  • state operator rows and memory use;
  • malformed records routed to a dead-letter path;
  • output rows and unique event keys;
  • batch gap, job restart count, and end-to-end event age.

Input rate alone is not lag: pair it with source end offsets and the checkpoint’s committed position. Processed rate alone is not health: a source outage can make it zero while a dashboard shows no errors.

Recover, replay, and upgrade

Restart from the same checkpoint with the same semantic application. If a release changes schema or stateful behavior, use a separately versioned checkpoint and a documented starting boundary.

For a controlled replay:

starting_offsets = """
{
  "orders.v1": {
    "0": 850000,
    "1": 820000,
    "2": 830000
  }
}
"""

Use that value only with a new checkpoint and new or idempotent sink. Starting offsets are ignored when the existing checkpoint contains an offset log. After replay, reconcile record counts, unique event IDs, and aggregate totals before switching consumers.

The recovery runbook should include:

  1. Stop new deployments and record the active checkpoint and application image.
  2. Inspect the last query progress and last committed source offset.
  3. Determine whether source retention still covers that offset.
  4. Restart the same query on healthy capacity.
  5. Confirm checkpoint advancement, sink uniqueness, and event-age recovery.
  6. For an incompatible release, roll back to the previous image or start a new query version with an explicit source boundary.

Exercise malformed JSON, worker termination, connector loss, GCS checkpoint unavailability, and a full cluster replacement. A production-ready stream is not the query that never failed in a test; it is the query whose known failures have bounded outcomes and an executable recovery path.