🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Cloud Data Cost Control: Compute, Storage, Warehouses

Data EngineeringCost Optimization⭐ Premium

Cloud Data Cost Control: Compute, Storage, Warehouses

Difficulty: Senior Level | Companies: Netflix, Uber, Airbnb, Spotify, Stripe

Cloud data bills are unusual because the people who create the cost and the people who receive the invoice are usually different teams. An analyst adds a join on an unpartitioned table, a pipeline runs hourly instead of every six hours, a cluster stays warm overnight, and by the end of the quarter finance is asking questions nobody in the data team can answer. Cost control is therefore an ownership problem first and a technical problem second.

Prerequisites

  • !Object storage lifecycle policies
  • !Cluster sizing and auto-scaling basics
  • !How warehouse credit billing works

What You'll Learn

  • 1Break a data bill into compute, storage and egress components
  • 2Apply spot instances, auto-scaling and idle shutdown safely
  • 3Design storage tiering and compaction policies
  • 4Run a tagging and budget practice that assigns spend to a team

Where the money actually goes

Three buckets dominate. Compute is transient processing: Spark or EMR clusters, Kubernetes pods, warehouse credits and serverless query time. Storage is the persistent footprint: object storage, warehouse local storage and database volumes, which grow steadily and are almost never cleaned up. Egress and API charges are the movement of data between services, regions and clouds, and they are the category most teams discover only after a cross-region replication bill arrives.

The proportions matter for where to invest effort. For most analytics-heavy organizations compute is sixty to eighty percent of the bill and storage is the long tail, so the biggest wins come from running less compute rather than squeezing bytes. Egress is small until someone enables cross-region replication without a traffic estimate, at which point it can dwarf everything else within a week. Start by pulling thirty days of billing by service and by tag, because arguing about optimization without that split is guesswork.

Cost driverTypical shareMain leverCommon mistake
Warehouse or query credits40 to 60 percentRight-sizing, auto-suspend, pruningOne large warehouse for all workloads
Batch clusters15 to 30 percentSpot mix, auto-scaling, schedulingFixed cluster size all day
Object storage5 to 15 percentTiering, compression, compactionMillions of tiny files, no lifecycle
Data transfer1 to 10 percentKeep traffic inside one regionUnplanned cross-region replication
Orchestration and overheadUnder 5 percentConsolidationOne DAG per trivial task

Compute: spot, autoscaling and keeping clusters lean

Spot instances are the single largest compute discount available, typically sixty to ninety percent off on-demand, in exchange for the possibility of interruption. The rule that makes them safe is to place interruption-tolerant work on spot: shuffle-heavy Spark stages, batch transforms and backfills can recompute from a checkpoint. Keep the driver or master node on-demand so the control plane survives, and always keep some on-demand capacity as a floor for jobs that cannot be interrupted mid-stage.

python
class CostOptimizedCluster:
    @staticmethod
    def config():
        return {
            "Master": {"InstanceType": "m5.xlarge", "Market": "ON_DEMAND"},
            "Core": {"InstanceType": "r5.2xlarge", "Market": "SPOT", "BidPrice": "0.30"},
            "Task": {"InstanceType": "m5.4xlarge", "Market": "SPOT", "InstanceCount": 10},
            "Configurations": [
                {
                    "Classification": "spark-defaults",
                    "Properties": {
                        "spark.dynamicAllocation.enabled": "true",
                        "spark.shuffle.service.enabled": "true",
                        "spark.sql.adaptive.enabled": "true",
                    },
                }
            ],
        }

    @staticmethod
    def estimate(on_demand_hours: int, spot_hours: int) -> dict:
        on_demand = on_demand_hours * 0.50
        spot = spot_hours * 0.15
        return {
            "on_demand_cost": round(on_demand, 2),
            "spot_cost": round(spot, 2),
            "savings": round(on_demand - spot, 2),
            "savings_percent": round((on_demand - spot) / on_demand * 100, 1),
        }

Pair spot with dynamic allocation and an aggressive idle timeout. The second-largest compute waste is a cluster that finishes its work at two in the morning and then waits for the next scheduled run with everything still reserved. Five-minute idle termination and a scheduler that starts clusters on demand rather than pre-warming them remove that waste with no code changes to any job.

Storage: tiering, compaction and file layout

Object storage gets cheaper per gigabyte the less frequently you read it, so lifecycle policies that move cold data to infrequent-access or archive classes after thirty, ninety or three hundred and sixty-five days pay for themselves on any dataset nobody queries. Apply them by prefix or by tag rather than globally, because a blanket policy will happily archive the table someone needs at tax time.

Compaction is the other storage lever, and it is really a compute lever wearing a storage costume. A directory with forty thousand sixty-kilobyte files costs more to plan and read than one directory with two hundred files of a hundred and twenty megabytes each, because every query pays a per-file overhead before reading a single row.

python
class StorageOptimizer:
    TIER_RULES = [
        (365, "GLACIER"),
        (90, "STANDARD_IA"),
        (30, "STANDARD_IA"),
    ]

    def __init__(self, spark, target_mb=256):
        self.spark = spark
        self.target_mb = target_mb

    def compact(self, path: str) -> None:
        self.spark.sql(f"OPTIMIZE delta.`{path}` ZORDER BY (event_date)")

    def report(self, path: str) -> dict:
        files = self.spark.read.parquet(path).inputFiles()
        sizes = [self.spark._jvm.java.io.File(f).length() for f in files]
        small = [s for s in sizes if s < self.target_mb * 1024 * 1024]
        return {
            "file_count": len(files),
            "avg_mb": round(sum(sizes) / len(sizes) / 1024 / 1024, 1),
            "small_file_count": len(small),
        }

    def apply_lifecycle(self, bucket: str, prefix: str) -> int:
        transitions = 0
        for age_days, tier in self.TIER_RULES:
            transitions += self._transition_matching(bucket, prefix, age_days, tier)
        return transitions

Revisit partitioning while you are here. Partitioning by a low-cardinality column such as year creates a handful of enormous files; partitioning by a high-cardinality column such as user id creates millions of useless ones. The goal is partitions that are selective for the common query and few enough that the catalog stays small.

Warehouse sizing for Snowflake and BigQuery

Elastic warehouses solve a real problem and create a new one: a warehouse sized for the busiest minute of the day burns credits in every quiet hour. Auto-suspend with a short idle window, a small default warehouse for dashboards, and a separate larger warehouse for heavy transformations is the pattern that keeps both latency and cost predictable. Separating workloads is more valuable than tuning any single one, because a dashboard query queued behind a six-hour transformation is a cost problem and an experience problem at the same time.

python
class WarehouseAdvisor:
    def recommend(self, metrics: list) -> dict:
        queue = sum(m["queue_ms"] for m in metrics) / len(metrics)
        runtime = sum(m["run_ms"] for m in metrics) / len(metrics)
        if queue > 5000:
            action = "SCALE_UP"
        elif runtime < 1000 and queue < 1000:
            action = "SCALE_DOWN"
        else:
            action = "HOLD"
        return {
            "avg_queue_ms": round(queue),
            "avg_runtime_ms": round(runtime),
            "recommendation": action,
            "config": {
                "auto_suspend_seconds": 60,
                "auto_resume": True,
                "min_clusters": 1,
                "max_clusters": 4,
                "scaling_policy": "ECONOMY",
            },
        }

Read the queue time before touching size. Long queue time with short runtime means you are undersized at peak; short queue time with long runtime means you are oversized everywhere. They call for opposite fixes, and conflating them is how teams end up paying double for the same workload.

Budgets, tags and anomaly alerts

You cannot manage spend you cannot attribute. Tag every resource at creation time with team, project and environment, enforce the tags through infrastructure policy rather than through documentation, and refuse to provision untagged resources. Once attribution exists, set per-team monthly budgets and alert at seventy-five and ninety percent so there is time to react before the month closes.

python
class CostMonitor:
    def __init__(self):
        self.budgets = {}
        self.alerts = []

    def set_budget(self, team: str, monthly_limit: float) -> None:
        self.budgets[team] = monthly_limit

    def check(self, team: str, spend: float) -> dict:
        budget = self.budgets.get(team, float("inf"))
        pct = spend / budget * 100 if budget else 0.0
        if pct > 90:
            self.alerts.append((team, "CRITICAL", f"{pct:.1f}% of budget consumed"))
        elif pct > 75:
            self.alerts.append((team, "WARNING", f"{pct:.1f}% of budget consumed"))
        return {"team": team, "budget": budget, "spend": spend, "remaining": budget - spend, "pct": round(pct, 1)}

    def anomaly(self, team: str, today: float, baseline: float, sigma: float) -> str | None:
        if sigma > 0 and (today - baseline) / sigma > 3:
            return f"{team}: spend {today:.0f} is three sigma above baseline {baseline:.0f}"
        return None

Anomaly detection on daily spend catches the failure that budgets miss: the slowly creeping query that is well within its monthly allowance but has doubled since last month. A single three-sigma rule on the daily series surfaces it within days.

Building a FinOps habit that lasts

Dashboards do not change behaviour on their own. The teams that sustain savings treat cost as an operational signal with the same seriousness as latency: a weekly review of the top ten spenders, a named owner per line item, a documented explanation for any increase above a chosen threshold, and a habit of pairing every new pipeline proposal with a cost estimate.

Make the estimate easy to produce. If estimating the price of a proposed job requires a meeting with the finance team, nobody will do it, so publish a simple calculator based on bytes scanned, cluster hours and storage rate and put it next to the pipeline template. The goal is not a perfect number. The goal is that the person writing the pipeline thinks about the bill before it exists.

✨Sequence the work

Tag and attribute first, because every later decision depends on knowing whose money it is. Then attack idle compute, then spot and right-sizing, then storage tiering. Teams that start with storage because it is easy end up optimizing fifteen percent of the bill while the cluster runs oversized all night.

Common Mistakes

One large warehouse or cluster shared by every workload

Fix: Split interactive dashboards from heavy transformations so each can be sized and suspended independently

Optimizing storage while compute runs idle overnight

Fix: Set idle termination and dynamic allocation before touching anything else

Lifecycle policies applied globally by default

Fix: Tier by prefix or tag so tax-time tables and cold archives are treated differently

Budgets without attribution

Fix: Enforce team, project and environment tags at provisioning time and block untagged resources

Best Practices

  • Pull thirty days of billing by service and by tag before proposing any change
  • Keep masters on-demand and put interruption-tolerant work on spot
  • Separate workloads before tuning any single workload
  • Publish a one-page cost calculator next to the pipeline template
  • Review the top ten spenders weekly with a named owner for each

Interview Questions

Q1: How would you cut a Spark bill by fifty percent without changing business logic?

Move eligible stages to spot, enable dynamic allocation with a short idle timeout, run outside peak hours, add adaptive query execution to shrink shuffles, and compact small files so each job plans fewer tasks.

Q2: Spot or on-demand, how do you decide?

Put checkpoint-recoverable and interruptible work on spot with an on-demand floor and driver kept on-demand. Anything with long non-idempotent state stays on-demand until it is made rerunnable.

Q3: Design cost allocation for a multi-tenant data platform.

Tag at provisioning, propagate tags into job and query metadata, meter usage per tenant by warehouse time and bytes scanned, then charge back with a published rate card and a monthly variance report.

Q4: How do you right-size an elastic warehouse?

Read queue time and runtime separately. High queue with short runtime means scale up at peak; short queue with short runtime means shrink and shorten auto-suspend; long runtime means optimize the query before resizing.

Q5: How do you present cost savings to leadership?

Show dollars, not techniques: baseline monthly spend, the change implemented, measured savings, and the run-rate projection, alongside any latency or reliability trade-off the change introduced.

Key Takeaways

  • Spend splits into compute, storage and egress, and compute usually dominates
  • Attribute cost to a team before attempting to reduce it
  • Spot plus dynamic allocation plus idle shutdown is the biggest and safest win
  • Warehouse separation of workloads beats tuning a single warehouse
  • Storage tiering and compaction matter, but they are rarely the first lever
  • Treat cost as an operational signal with owners and weekly review
🔒

Premium Content

Cloud Data Cost Control: Compute, Storage, Warehouses

You've previewed the first section. Unlock this full lesson and 900+ advanced tutorials with a Premium plan.

đŸŽ¯End-to-end Projects
đŸ’ŧInterview Prep
📜Certificates
🤝Community Access

Already a member? Log in

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-13

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Advertisement