ivanshamaev/de-agent-skills/de-cost-optimization

Claude Code and agent skill by ivanshamaev/de-agent-skills

Trust tier 3
  • community
Source check pending

Checking that the SKILL.md file is still in the repository.

DE cost optimization — query cost analysis (Trino/Spark/ClickHouse/BigQuery), compute right-sizing, storage tier recommendations, spot/preemptible instances, partition pruning, Z-order/clustering, materialized view economics, data lifecycle policies, FinOps tagging, cost attribution, budget alerts

Install

npx vskill@latest install ivanshamaev/de-agent-skills/de-cost-optimization

SKILL.md

The same SKILL.md was published earlier as ivanshamaev/de-agent-skills/de-cost-optimization.

DE Cost Optimization

When to Use

Load this skill when the user needs to:

  • Review a cloud bill and identify which pipelines, queries, or clusters drive cost
  • Right-size a Spark, Trino, ClickHouse, or Airflow cluster (instance type, memory, core count)
  • Reduce query scan costs via partition pruning, Z-order clustering, or file compaction
  • Move data to cheaper storage tiers (S3-IA, Glacier, ClickHouse cold volumes)
  • Implement spot/preemptible instances for Spark executors or Airflow workers
  • Decide whether to materialize a view or a summary table (refresh cost vs query savings)
  • Define or enforce a data lifecycle and retention policy
  • Set up AWS/GCP budget alerts, FinOps tagging, or per-team cost attribution
  • Run a FinOps review and produce a prioritized cost reduction plan

1. Cost Model Overview

Every data engineering cloud bill breaks down into three levers. Attack them in this order — storage is cheapest per GB, but compute at scale dominates the total.

LeverDriverTypical ShareFirst Action
ComputevCPU-hours × instance price50-70%Right-size + spot instances
StorageGB-months × tier price20-35%Tiering + compaction + lifecycle rules
Data transferGB egressed across AZs/regions5-15%Co-locate compute with storage; avoid cross-region reads
How Each Scales
  • Compute scales with cluster lifetime × size. A cluster that is 2× over-provisioned and never auto-scales burns double money even when idle. Idle Spark clusters during off-peak hours are the single most common waste category.
  • Storage scales with raw data volume × replication factor × tier. Columnar + compressed formats (Parquet/zstd) reduce this 5-10× vs raw JSON/CSV.
  • Data transfer is often invisible until bill arrives. Reading Parquet on S3 from a same-region EMR cluster is free; reading it cross-region costs $0.02/GB and can exceed compute cost on large jobs.
Which to Attack First
Priority 1 — Compute
├─ Idle clusters / always-on servers with <20% avg CPU
├─ Fixed-size clusters that could be spot + auto-scale
└─ Over-provisioned executor memory
Priority 2 — Storage
├─ Raw JSON/CSV on S3 Standard (should be Parquet + tiered)
├─ Small files (<10 MB) causing excess LIST/GET API calls
└─ Data past retention policy still sitting in S3 Standard
Priority 3 — Data Transfer
├─ Queries on cross-region tables
└─ Shuffles writing to S3 between EMR and Glue in different AZs

2. Query Cost Analysis

2.1 Trino / Presto
Reading EXPLAIN (TYPE DISTRIBUTED)
sql
EXPLAIN (TYPE DISTRIBUTED)
SELECT customer_id, SUM(amount) AS revenue
FROM orders
WHERE order_date >= DATE '2024-01-01'
AND region = 'US'
GROUP BY customer_id;

Key tokens to look for in the output:

TokenMeaningCost Signal
TableScanRows and bytes read from storageHigh bytes → missing partition filter
FilterPushed down to connector vs applied in TrinofilterPushdown=false → scan waste
RemoteExchange REPARTITIONNetwork shuffleMany reshuffles → expensive join
Estimates: {rows=..., cpu=..., network=..., memory=...}Planner estimatesCross-check with actual

Partition filter pushdown is confirmed when the TableScan node shows partitionedBy columns in its predicate. If your WHERE order_date = ... clause does NOT appear in the TableScan predicate, it means the filter is not pushed down — you are scanning the whole table and filtering in memory.

Finding Expensive Queries via system tables
sql
-- Top 20 most expensive queries in the last 24 hours (Trino)
SELECT
query_id,
LEFT(query, 120) AS query_snippet,
user,
source,
state,
CAST(read_data_size AS VARCHAR) AS scanned,
-- Estimate cost at $5/TB scanned (Athena pricing proxy)
ROUND(read_data_size / 1e12 * 5.0, 4) AS est_cost_usd,
DATE_DIFF('second', created, "end") AS wall_sec,
peak_memory_bytes / 1e9 AS peak_memory_gb,
cpu_time_ms / 1000.0 AS cpu_sec
FROM system.runtime.query_history
WHERE created >= NOW() - INTERVAL '24' HOUR
AND state = 'FINISHED'
ORDER BY read_data_size DESC
NULLS LAST
LIMIT 20;
sql
-- Aggregate cost per source (team / application) over last 7 days
SELECT
source,
COUNT(*) AS query_count,
ROUND(SUM(read_data_size) / 1e12, 3) AS total_tb_scanned,
ROUND(SUM(read_data_size) / 1e12 * 5.0, 2) AS est_total_cost_usd,
ROUND(AVG(DATE_DIFF('second', created, "end")), 1) AS avg_wall_sec
FROM system.runtime.query_history
WHERE created >= NOW() - INTERVAL '7' DAY
AND state = 'FINISHED'
GROUP BY source
ORDER BY total_tb_scanned DESC;
File Size Optimization
  • Too-small files (<10 MB): excessive S3 LIST + GET overhead; Trino opens one reader thread per file, so 10,000 files × overhead > reading one 1 GB file.
  • Too-large files (>1 GB): cannot be split across workers in parallel; one task processes the whole file.
  • Sweet spot: 128–512 MB per file after compression.
sql
-- Find partitions with small-file problem (Iceberg metadata)
SELECT
partition,
COUNT(*) AS file_count,
AVG(file_size_in_bytes) / 1e6 AS avg_file_mb,
SUM(file_size_in_bytes) / 1e9 AS total_gb
FROM "catalog"."schema"."table$files"
GROUP BY partition
HAVING COUNT(*) > 100 OR AVG(file_size_in_bytes) < 10e6
ORDER BY file_count DESC
LIMIT 30;
2.2 Spark (EMR / Databricks / Self-Hosted)
Spark UI Cost Signals

Navigate: Jobs → select expensive job → Stages → sort by Duration descending.

Key indicators:

  • Shuffle Read/Write size: A stage with 500 GB shuffle write followed by a stage with 500 GB shuffle read means you are moving 500 GB over the network. Each GB shuffled costs executor CPU time + network I/O + potential spill to disk.
  • GC time % > 10%: executors spending >10% in garbage collection → memory is too low for the data size; increase spark.executor.memory or reduce partition size.
  • Task skew: longest task 10× median → one partition is much larger than others (data skew). Fix with salting or AQE.
  • Spill (Memory) / Spill (Disk): non-zero spill means tasks ran out of memory and wrote to disk → slower and wastes I/O.
EXPLAIN COST
python
spark.sql("""
EXPLAIN COST
SELECT customer_id, SUM(amount) AS revenue
FROM orders
WHERE order_date >= '2024-01-01'
GROUP BY customer_id
""").show(truncate=False)

Look for Statistics(sizeInBytes=..., rowCount=...). If estimates are wildly wrong, run ANALYZE TABLE orders COMPUTE STATISTICS FOR ALL COLUMNS to refresh them — bad statistics cause the planner to choose wrong join strategies (BroadcastHashJoin vs SortMergeJoin).

Executor Sizing Formula
spark.executor.memory = 4–8 GB per executor core (memory-heavy ETL)
spark.executor.cores = 4–5 cores per executor (limits context switches)
Total executors = (Total vCPUs allocated) / spark.executor.cores
Example for r5.2xlarge (8 vCPU, 64 GB):
spark.executor.cores = 4
spark.executor.memory = 12g (leaving 4g for OS + overhead)
spark.executor.memoryOverhead = 2g
Executors per node = 2
Dynamic Allocation vs Fixed: Cost Comparison
python
# Fixed cluster: 10 executors running for 8 hours
fixed_cost = 10 * 8 * instance_cost_per_hour # e.g. 10 * 8 * $0.50 = $40
# Dynamic allocation: average 3 executors over 8 hours
dynamic_cost = 3 * 8 * instance_cost_per_hour # $12 → 70% savings
# Enable dynamic allocation
spark = (
SparkSession.builder
.config("spark.dynamicAllocation.enabled", "true")
.config("spark.dynamicAllocation.minExecutors", "1")
.config("spark.dynamicAllocation.maxExecutors", "50")
.config("spark.dynamicAllocation.initialExecutors", "2")
.config("spark.dynamicAllocation.executorIdleTimeout", "120s")
.config("spark.dynamicAllocation.schedulerBacklogTimeout", "30s")
.config("spark.shuffle.service.enabled", "true") # required for dynamic alloc
.getOrCreate()
)
Reading EMR Utilization from CloudWatch
python
import boto3
from datetime import datetime, timedelta
def get_cluster_cpu_utilization(cluster_id: str, days: int = 7) -> float:
"""Return average YARNMemoryAvailablePercentage over last N days."""
cw = boto3.client("cloudwatch", region_name="us-east-1")
resp = cw.get_metric_statistics(
Namespace="AWS/ElasticMapReduce",
MetricName="YARNMemoryAvailablePercentage",
Dimensions=[{"Name": "JobFlowId", "Value": cluster_id}],
StartTime=datetime.utcnow() - timedelta(days=days),
EndTime=datetime.utcnow(),
Period=3600,
Statistics=["Average"],
)
datapoints = resp["Datapoints"]
if not datapoints:
return 0.0
avg = sum(d["Average"] for d in datapoints) / len(datapoints)
return round(100 - avg, 1) # invert: available% → used%
2.3 ClickHouse
Identifying Expensive Queries
sql
-- Top 20 most expensive queries by bytes read, last 24 hours
SELECT
query_id,
user,
LEFT(query, 100) AS query_snippet,
read_bytes / 1e9 AS read_gb,
read_rows,
memory_usage / 1e9 AS memory_gb,
query_duration_ms / 1000.0 AS duration_sec,
-- Mark queries that could benefit from projection
result_rows < read_rows / 100 AS high_reduction_ratio
FROM system.query_log
WHERE event_time >= NOW() - INTERVAL 1 DAY
AND type = 'QueryFinish'
AND query_kind = 'Select'
ORDER BY read_bytes DESC
LIMIT 20;
sql
-- Aggregate read cost by user over last 7 days
SELECT
user,
COUNT(*) AS query_count,
ROUND(SUM(read_bytes) / 1e12, 3) AS total_tb_read,
ROUND(AVG(query_duration_ms) / 1000, 1) AS avg_sec,
ROUND(SUM(memory_usage) / 1e12, 3) AS total_memory_tb
FROM system.query_log
WHERE event_time >= NOW() - INTERVAL 7 DAY
AND type = 'QueryFinish'
AND query_kind = 'Select'
GROUP BY user
ORDER BY total_tb_read DESC;
Verifying Projection Usage
sql
-- Check whether a projection is being used for a specific query
-- Run EXPLAIN SELECT ... and look for "ReadFromMergeTree (projection: <name>)"
EXPLAIN
SELECT region, SUM(amount)
FROM orders
WHERE order_date >= '2024-01-01'
GROUP BY region;
-- List all projections in a table
SELECT
name,
part_name,
rows,
data_compressed_bytes / 1e6 AS compressed_mb
FROM system.projection_parts
WHERE table = 'orders'
ORDER BY data_compressed_bytes DESC;
Cold vs Hot Data Cost Model (TTL MOVE)
sql
-- Configure tiered storage: hot data on NVMe, cold data on S3
ALTER TABLE events
MODIFY TTL
event_date + INTERVAL 30 DAY TO VOLUME 'cold_s3', -- move to S3 after 30d
event_date + INTERVAL 365 DAY DELETE; -- delete after 1 year
-- Estimate cost: if S3 = $0.023/GB-month vs NVMe = $0.10/GB-month
-- Moving 10 TB of 31-90 day data from NVMe to S3 saves ~$0.077/GB-month = $770/month
2.4 BigQuery
Finding Expensive Queries

This is the start of the file. Read the full SKILL.md on GitHub.

Security

  • Security scanPassed, 95 of 100Pattern checks on the skill's files.
  • Model reviewPassed

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

7-day trend score
0

Not refreshed yet.

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Cursor
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/ivanshamaev/de-agent-skills/de-cost-optimization/badge)](https://verified-skill.com/skills/ivanshamaev/de-agent-skills/de-cost-optimization)

Something wrong with this skill or its page? Tell us.