Introduction
After wiring agents to OLTP databases, streams/CDC, and data-quality workflows, the next operational pressure is cost and performance of the analytics warehouse/lakehouse (Snowflake, BigQuery, Redshift, Databricks SQL, Fabric). This article delivers a practical Cost & Performance Optimization Agent that monitors spend and latency, diagnoses query patterns, proposes bounded remediations (clustering/partitioning tweaks, materializations, slot/warehouse rightsizing, result-cache policies), and executes only with receipts (change tickets, job run IDs, PR IDs).
The Use Case
Analytic platforms excel at elasticity—but without discipline, costs rise and SLAs drift. Human reviews (monthly cost meetings) lag reality; ad-hoc fixes don’t stick. The agent continuously ingests billing/usage telemetry and query traces, correlates spikes with models/dashboards, ranks optimization opportunities by $/benefit and risk, and proposes safe, reversible actions behind feature flags. No success claim is made without a downstream receipt.
Prompt Contract (agent interface)
# file: contracts/warehouse_cost_perf_v1.yaml
role: "CostPerfAgent"
scope: >
Monitor warehouse/lakehouse cost and latency; propose and execute bounded optimizations.
Ask once if critical fields are missing (platform, project/account, telemetry windows).
Never assert success without a receipt (ticket id, PR id, job id).
inputs:
platform: enum["snowflake","bigquery","redshift","databricks","fabric"]
lookback_days: integer
sla_ms_p95: integer
budget_monthly_usd: number
output:
type: object
required: [summary, hotspots, proposals, impact_model, citations, next_steps, tool_proposals]
properties:
summary: {type: string, maxWords: 100}
hotspots:
type: array
items:
type: object
required: [owner, object, type, cost_usd, p95_ms, calls_7d]
properties:
owner: {type: string}
object: {type: string} # table/view/query_tag/model/dashboard
type: {type: string} # "table","model","dashboard","job","warehouse"
cost_usd: {type: number}
p95_ms: {type: number}
calls_7d: {type: integer}
proposals:
type: array
items:
type: object
required: [action, target, est_saving_usd, est_p95_ms_delta, risk, preconditions]
properties:
action: {type: string, enum: ["cluster","partition","materialize","result_cache","job_rewrite","rightsizing","schedule_shift","auto_suspend","slot_quota"]}
target: {type: string}
est_saving_usd: {type: number}
est_p95_ms_delta: {type: number}
risk: {type: string, enum: ["low","medium","high"]}
preconditions: {type: array, items: string}
impact_model:
type: object
required: [current_month_usd, projected_month_usd, projected_p95_ms]
properties:
current_month_usd: {type: number}
projected_month_usd: {type: number}
projected_p95_ms: {type: number}
citations: {type: array, items: string} # query ids, job ids, object names
next_steps: {type: array, items: string, maxItems: 6}
tool_proposals:
type: array
items:
type: object
required: [name, args, preconditions, idempotency_key]
properties:
name:
type: string
enum: [IngestUsage, IngestQueryLog, DetectHotspots, Simulate, OpenTicket,
ApplyRightsizing, SetAutoSuspend, CreateMaterialization, UpdatePartitioning,
EnableResultCache, SubmitPR]
args: {type: object}
preconditions: {type: string}
idempotency_key: {type: string}
policy_id: "warehouse_cost_policy.v2"
citation_rule: "Minimal-span references to object names and query/job ids."
Tool Interfaces (typed, with receipts)
# tools.py
from pydantic import BaseModel
from typing import Optional, Dict, List
class IngestUsageArgs(BaseModel):
platform: str
lookback_days: int
class IngestQueryLogArgs(BaseModel):
platform: str
lookback_days: int
tag_filter: Optional[str] = None
class DetectHotspotsArgs(BaseModel):
usage: Dict
queries: Dict
sla_ms_p95: int
class SimulateArgs(BaseModel):
proposal: Dict # {action,target,params}
class OpenTicketArgs(BaseModel):
title: str
description: str
owners: List[str]
severity: str
class ApplyRightsizingArgs(BaseModel):
target: str # e.g., "wh.etl_large"
size: str # "S","M","L","XL" or slots
autosuspend_sec: int
class SetAutoSuspendArgs(BaseModel):
target: str
autosuspend_sec: int
class CreateMaterializationArgs(BaseModel):
model: str
schedule: str # cron or window
ttl_hours: int
class UpdatePartitioningArgs(BaseModel):
table: str
partition_by: str
class EnableResultCacheArgs(BaseModel):
scope: str # "project"|"schema"|"query_tag"
enabled: bool
class SubmitPRArgs(BaseModel):
repo: str
branch: str
message: str
diff: str
class ToolReceipt(BaseModel):
tool: str
ok: bool
ref: str # ticket id, job id, pr id
message: str = ""
data: Optional[Dict] = None
# adapters.py (demo logic; wire to platform SDKs/APIs in production)
from tools import *
def ingest_usage(a: IngestUsageArgs) -> ToolReceipt:
return ToolReceipt(tool="IngestUsage", ok=True, ref=f"usage-{a.lookback_days}", data={"total_usd": 48231.17})
def ingest_query_log(a: IngestQueryLogArgs) -> ToolReceipt:
return ToolReceipt(tool="IngestQueryLog", ok=True, ref=f"qlog-{a.lookback_days}", data={"queries": [{"id":"q-991","p95_ms":4200,"cost_usd":612,"object":"model.sales_orders_daily","tag":"dash:revenue_core","calls_7d":1800}]})
def detect_hotspots(a: DetectHotspotsArgs) -> ToolReceipt:
hs = [{"owner":"bi@sales","object":"model.sales_orders_daily","type":"model","cost_usd":3200,"p95_ms":4200,"calls_7d":1800},
{"owner":"etl@data","object":"wh.etl_large","type":"warehouse","cost_usd":19000,"p95_ms":1800,"calls_7d":400}]
return ToolReceipt(tool="DetectHotspots", ok=True, ref="hot-1", data={"hotspots": hs})
def simulate(a: SimulateArgs) -> ToolReceipt:
# toy simulator
p = a.proposal
if p["action"]=="materialize":
return ToolReceipt(tool="Simulate", ok=True, ref="sim-1", data={"saving_usd": 2400, "p95_ms_delta": -2200})
if p["action"]=="rightsizing":
return ToolReceipt(tool="Simulate", ok=True, ref="sim-2", data={"saving_usd": 6000, "p95_ms_delta": +80})
return ToolReceipt(tool="Simulate", ok=True, ref="sim-0", data={"saving_usd": 0, "p95_ms_delta": 0})
def open_ticket(a: OpenTicketArgs) -> ToolReceipt:
return ToolReceipt(tool="OpenTicket", ok=True, ref="COST-1742", message="Optimization ticket opened")
def apply_rightsizing(a: ApplyRightsizingArgs) -> ToolReceipt:
return ToolReceipt(tool="ApplyRightsizing", ok=True, ref=f"chg-{a.target}", message="Warehouse resized")
def set_autosuspend(a: SetAutoSuspendArgs) -> ToolReceipt:
return ToolReceipt(tool="SetAutoSuspend", ok=True, ref=f"sus-{a.target}", message="Auto-suspend set")
def create_materialization(a: CreateMaterializationArgs) -> ToolReceipt:
return ToolReceipt(tool="CreateMaterialization", ok=True, ref=f"job-mat-{a.model}", message="Materialization scheduled")
def update_partitioning(a: UpdatePartitioningArgs) -> ToolReceipt:
return ToolReceipt(tool="UpdatePartitioning", ok=True, ref=f"ddl-{a.table}", message="Partitioning updated")
def enable_result_cache(a: EnableResultCacheArgs) -> ToolReceipt:
return ToolReceipt(tool="EnableResultCache", ok=True, ref=f"rc-{a.scope}", message="Result cache toggled")
def submit_pr(a: SubmitPRArgs) -> ToolReceipt:
return ToolReceipt(tool="SubmitPR", ok=True, ref="PR-983", message="PR submitted")

Join the conversation! Your thoughts help the community grow.