5: Maintaining and automating data workloads

    Optimizing resources. Considerations include

    Resource optimization on Google Cloud is not a single dial. It is a portfolio of choices about pricing model, cluster lifetime, autoscaling envelopes, storage tiering, and query physics. The exam tests whether a candidate can pick the correct lever for a stated business outcome rather than apply a blanket policy. A workload that runs nightly for forty minutes and never overlaps with another tenant is optimized differently from a streaming pipeline that backfills history every weekend.

    How it works

    The optimization unit must match the billing unit of the underlying service:

    • slot-hours for BigQuery capacity-based pricing
    • vCPU-seconds for Dataflow workers
    • vCPU-hours for Dataproc nodes
    • byte-seconds for Cloud Storage and BigQuery storage
    • seconds of execution for Cloud Functions and Workflows

    The decision framework reduces to four questions. First, is the workload steady-state or spiky? Steady-state workloads benefit from committed capacity and reservations; spiky workloads benefit from on-demand or autoscaling envelopes. Second, is the workload SLA-bound? An analyst dashboard query bounded by a one-second latency target must hold a baseline of slots; an overnight reconciliation pipeline tolerating four hours of execution can share idle slots opportunistically. Third, what is the dominant cost driver? Compute, storage, network egress, and managed service overhead each respond to different tuning. Fourth, where does data live? Reads against Cloud Storage from another region multiply egress; reads against a co-located BigQuery dataset cost nothing in network.

    Optimization also lives in pipeline shape, not only in price model. Pushing a join into BigQuery from a Dataflow batch reduces total cost when the data already sits in BigQuery. Materializing an expensive aggregation as a materialized view shifts the read cost from every query to one refresh. Tuning a Pub/Sub subscription to use ordering keys correctly stops the downstream consumer from over-scaling to compensate for shuffle.

    Minimizing costs per required business need for data

    Cost minimization begins with the storage layer. BigQuery storage offers two billing models per dataset:

    • logical storage, billed on uncompressed bytes
    • physical storage, billed on compressed bytes

    Physical storage typically costs about twice as much per gigabyte but is often less than half the size after compression, which makes physical the cheaper choice for highly compressible columnar workloads.

    Set the billing model with ALTER SCHEMA acme_curated SET OPTIONS (storage_billing_model = 'PHYSICAL').

    Long-term storage discounts apply automatically to partitions not modified for ninety days, dropping the per-byte rate by about half. Partition expiration purges old partitions without manual intervention.

    ALTER TABLE acme_curated.events_facts
    SET OPTIONS (
     partition_expiration_days = 540,
     description = "Web events, retained 18 months for finance reconciliation"
    );
    

    Cloud Storage costs respond to storage class transitions. Object Lifecycle Management moves objects from Standard to Nearline at thirty days, to Coldline at ninety days, and to Archive at three hundred and sixty-five days for the common cold-data tiering pattern.

    The minimum storage duration for each class applies: deleting a Nearline object before thirty days still charges thirty days; Coldline charges ninety; Archive charges three hundred and sixty-five. Choose Autoclass for buckets where access patterns are unpredictable, since Autoclass tiers based on access rather than age and avoids early-deletion charges.

    {
     "lifecycle": {
     "rule": [
     {
     "action": {"type": "SetStorageClass", "storageClass": "NEARLINE"},
     "condition": {"age": 30, "matchesStorageClass": ["STANDARD"]}
     },
     {
     "action": {"type": "SetStorageClass", "storageClass": "COLDLINE"},
     "condition": {"age": 90, "matchesStorageClass": ["NEARLINE"]}
     },
     {
     "action": {"type": "Delete"},
     "condition": {"age": 1825}
     }
     ]
     }
    }
    

    Key points

    Compute optimization in BigQuery starts with the on-demand versus capacity-based decision.

    On-demand pricing charges per terabyte scanned and is bounded by an organization-wide ceiling of two thousand concurrent slots per project, with bursts up to higher values when free capacity is available across the region.

    Capacity-based pricing through Editions binds workloads to slot reservations that autoscale within a baseline and maximum envelope.

    For a workload that scans more than four hundred terabytes per month, capacity-based pricing through Standard or Enterprise edition is almost always cheaper than on-demand.

    For a workload that scans fewer than five terabytes per month, on-demand is usually cheaper because the slot baseline cannot be set low enough to match the variable workload.

    💡 Exam Trap: A scenario that reports "queries scan ninety percent of a wide table" is almost always asking about partitioning and clustering, not about pricing model. Switching from on-demand to capacity does not reduce scan volume; the scan must be filtered by a partition column and the columns used in predicates must be clustered.

    📊 Limit: BigQuery long-term storage discount applies when a table or partition has not been modified for ninety consecutive days. Any modification, including a partial update or schema change to that partition, resets the timer.

    ⚠️ Anti-Pattern: Setting partition_expiration_days on a partitioned table whose downstream consumers depend on full history. Partition expiration deletes data with no recovery beyond fail-safe; once both time travel and fail-safe windows close, the data is gone.

    Dataflow cost optimization rides on three levers.

    • Streaming Engine offloads shuffle and state from worker VMs to a Google-managed backend, which usually reduces worker count by thirty to sixty percent at the cost of a per-streaming-unit charge.
    • FlexRS, the Flexible Resource Scheduling mode for batch jobs, schedules the job within six hours and uses a mix of preemptible and standard workers at roughly forty percent cost reduction, suitable for non-urgent batch.
    • Worker autoscaling, enabled with --autoscaling_algorithm=THROUGHPUT_BASED, allows the runner to scale workers up and down within the --num_workers and --max_num_workers envelope as backlog grows and shrinks.
    gcloud dataflow flex-template run acme-events-ingest \
     --template-file-gcs-location=gs://acme-templates/events_ingest.json \
     --region=us-central1 \
     --parameters=enableStreamingEngine=true,numWorkers=2,maxNumWorkers=20,workerMachineType=n2-standard-4
    

    Dataproc costs respond to cluster lifetime, machine selection, and preemptibility.

    • Standard workers carry the full Compute Engine price.
    • Secondary workers configured as preemptible cost about twenty percent of the standard price but receive thirty-second termination notices.

    Local SSD adds throughput for shuffle-heavy jobs but raises cost; configure it only when the job profile demonstrates a shuffle bottleneck.

    Cluster autoscaling policies grow and shrink secondary workers based on YARN pending memory; primary workers remain pinned because losing them tears down the cluster.

    Ensuring that enough resources are available for business-critical data processes

    The mirror image of cost minimization is capacity guarantee for business-critical processes.

    The mechanism on BigQuery is the reservation with a non-zero baseline. A reservation with slot_capacity = 500 and autoscale.max_slots = 2000 guarantees five hundred slots at all times, billed at the slot-hour rate even when idle, and bursts to two thousand under load.

    Critical workloads sit in their own reservation with a baseline that covers the peak demand of the SLA-bound queries; lower-priority workloads sit in a separate reservation with a zero baseline and a maximum that allows opportunistic bursting.

    gcloud bigquery reservations create acme-finance-critical \
     --location=US \
     --edition=ENTERPRISE \
     --slot-capacity=500 \
     --autoscale-max-slots=2000 \
     --ignore-idle-slots=false
    

    Reservation assignments route projects to reservations by job type. The job types are:

    • QUERY for interactive queries
    • PIPELINE for load and export jobs and DTS
    • BACKGROUND for vector search index maintenance and metadata jobs
    • CONTINUOUS for continuous queries

    A finance project assigned to acme-finance-critical with type QUERY runs its interactive queries inside the guaranteed reservation, while load jobs into the same project can be assigned to a separate PIPELINE reservation to keep them from competing with the interactive queries.

    gcloud bigquery reservations assignments create \
     --location=US \
     --reservation-id=acme-finance-critical \
     --assignee-id=projects/acme-finance \
     --assignee-type=PROJECT \
     --job-type=QUERY
    

    💡 Exam Trap: A query that does not match any reservation assignment runs as on-demand and is billed by bytes scanned, regardless of the organization's broader Editions purchase. This is the most common cost surprise after migrating to capacity-based pricing; verify with INFORMATION_SCHEMA.JOBS.reservation_id that no critical query is unintentionally on-demand.

    Dataflow guarantees responsiveness through worker minimums and Streaming Engine.

    A streaming pipeline with --num_workers=10 --max_num_workers=50 holds ten workers as the floor; backlog spikes scale within the envelope.

    Dataflow Prime offers Vertical Autoscaling which adjusts worker machine size in addition to count, which is the appropriate setting when a job is memory-bound for short bursts.

    Pub/Sub subscriptions backing a streaming Dataflow pipeline should set messageRetentionDuration to at least the maximum acceptable downstream outage; the default is seven days, which is sufficient for most production pipelines.

    gcloud pubsub subscriptions update acme-events-sub \
     --message-retention-duration=604800s \
     --ack-deadline=600
    

    Dataproc capacity guarantees come from explicit primary worker sizing.

    Workflow templates pin cluster shape per job: gcloud dataproc workflow-templates create defines the primary worker count, secondary worker count, machine types, and disk size.

    A workflow template invoked through gcloud dataproc workflow-templates instantiate provisions the cluster, runs the job, and tears the cluster down without dependency on a long-lived control plane.

    Ephemeral cluster per job avoids resource contention with other tenants because each job operates in its own VM fleet.

    🎯 Scenario: A media company runs a Spark batch job that must complete in forty-five minutes for a downstream advertising auction. They have tried autoscaling clusters that resize too slowly, missing the SLA by ten minutes. The correct response is a workflow template that creates a fixed-size ephemeral cluster sized for the historical peak, runs the Spark job, and tears down on completion. Cluster startup takes about ninety seconds; deterministic sizing removes the autoscaler latency from the SLA budget.

    Deciding between persistent or job-based data clusters (e.g., Dataproc)

    Dataproc supports two cluster lifecycle patterns.

    • Persistent clusters stay up for hours or days and serve a stream of jobs, sharing HDFS, the YARN resource manager, and the Hive metastore.
    • Job-based clusters, also called ephemeral clusters, exist only for the duration of a single workflow and tear down on completion.

    The choice between them is one of the most frequently tested optimization questions on the Professional Data Engineer exam.

    In practice

    Persistent clusters fit teams that submit many small interactive Spark or Hive jobs, share a Jupyter notebook environment, or use the cluster's HDFS as a working scratch space.

    The advantage is no startup latency: a job submission goes straight to the running cluster and starts within a few seconds.

    The disadvantages are wasted spend when the cluster is idle, contention between jobs, and the operational burden of patching the cluster on Dataproc image upgrades.

    Persistent clusters benefit from Dataproc autoscaling, which adjusts only secondary workers and only based on YARN pending containers.

    Job-based clusters fit batch pipelines with deterministic shape, especially when the pipeline runs in scheduled bursts.

    Each Dataproc job gets its own cluster, sized exactly for the workload, with no contention.

    The startup overhead of about ninety seconds is amortized over the job's full execution. Job-based clusters are the right choice when:

    • the team runs fewer than ten jobs per hour
    • each job runs longer than ten minutes

    Below those thresholds, the startup cost dominates.

    📊 Limit: Dataproc cluster creation reaches the ready state within ninety seconds in most cases. The actual measured time depends on image version, initialization actions, and metadata server warm-up.

    Dataproc Serverless for Spark is the third option and pushes the ephemeral pattern further. Instead of provisioning a cluster, the developer submits a batch workload that Google Cloud schedules onto a Spark execution environment managed end to end.

    There is no cluster to size or to tune. Billing is per Data Compute Unit second of execution, which collapses idle time to zero.

    Dataproc Serverless suits scheduled batch jobs that lack steady demand and benefit from no operations overhead. The trade-off is reduced control over the runtime: initialization actions, custom YARN configuration, and Jupyter notebook attachment are not directly supported.

    gcloud dataproc batches submit spark \
     --region=us-central1 \
     --jar=gs://acme-jobs/etl-events.jar \
     --properties=spark.executor.memory=4g,spark.executor.cores=2 \
     --batch=acme-events-2025-q4-load
    

    The decision flow for Dataproc lifetime maps to a small set of signals: job frequency, job duration, contention tolerance, and notebook usage.

    Decision Tree: Persistent versus Job-Based Dataproc

    ⚠️ Anti-Pattern: Running a persistent Dataproc cluster twenty-four hours per day for a single nightly job. The cluster sits idle for twenty-three hours; the ephemeral or serverless alternative removes the idle waste entirely.

    💡 Exam Trap: A persistent Dataproc cluster does not protect data when it tears down, because HDFS lives on local disk. Any pipeline that uses Dataproc must read from and write to Cloud Storage through the Cloud Storage connector for Hadoop. Treat HDFS as scratch space only.

    Decision Anchor: Choose persistent clusters when the team submits many short jobs per hour, shares notebooks, or runs custom YARN configuration that requires initialization actions; choose job-based clusters when the workload runs in scheduled bursts with deterministic shape; choose Dataproc Serverless for Spark when the workload is scheduled batch without custom YARN tuning and the team wants zero operations.


    Continue with the interactive course

    Track your progress, jump into practice questions and use the Shark AI tutor inside the GCP - Professional Data Engineer learning hub.