python
"""
Per-Request Cost Attribution Middleware for FastAPI
This middleware provides:
- **Estimation**: Compute (CPU time), Memory (RSS usage), IO (req+resp sizes)
- **Tagging**: Via `X-Cost-Tag` header (defaults to 'untagged')
- **Budget Alerts**: In-memory tracking with console alerts at 90% threshold
- Set budgets via `/set-budget/{tag}?budget=100.0`
- View spend via `/spend`
Caveats:
- CPU/Memory attribution uses process totals delta during request → approximate for concurrent loads (over-attributes if multi-request).
- Ideal for low-concurrency or dedicated containers.
- For high-concurrency/prod: Integrate perf counters, cgroups, or sampling (e.g., Prometheus).
- IO uses `Content-Length` headers → excludes chunked/unset.
- Costs are configurable rates (AWS/GCP-inspired examples).
- In-memory state → restarts reset. Prod: Use Redis/DB.
- Exceptions: Partial attribution skipped for simplicity.
Install: `pip install fastapi uvicorn psutil`
Run: `uvicorn main:app --reload`
Test:
- `curl -H "X-Cost-Tag: project1" http://localhost:8000/hello`
- `curl "http://localhost:8000/set-budget/project1?budget=10.0"`
- `curl http://localhost:8000/spend`
"""
import os
import time
import psutil
from typing import Dict
from fastapi import FastAPI, Request, Response, HTTPException, Query
from fastapi.responses import JSONResponse
app = FastAPI(title="Cost Attribution Demo")
# Configurable cost rates (USD; adjust for your cloud provider)
CPU_COST_PER_SECOND_USD: float = 0.00005 # e.g., ~$0.05/core-hour / 3600
MEMORY_COST_PER_GB_HOUR_USD: float = 0.010 # e.g., ~$10/TB-hour scaled
IO_COST_PER_GB_USD: float = 0.0001 # e.g., egress ~$0.10/GB scaled
# State (in-memory; prod: Redis)
BUDGETS: Dict[str, float] = {}
SPEND: Dict[str, float] = {}
ALERT_THRESHOLD: float = 0.9
# Cache process handle
process = psutil.Process(os.getpid())
@app.middleware("http")
async def cost_attribution_middleware(request: Request, call_next):
"""
Core middleware: Track, estimate, tag, alert, annotate response.
"""
# Pre-request snapshot
start_wall = time.perf_counter()
start_cpu = process.cpu_times()
start_mem_gb = process.memory_info().rss / (1024 ** 3)
req_size_bytes = int(request.headers.get("content-length", 0))
tag = request.headers.get("X-Cost-Tag", "untagged")
try:
response: Response = await call_next(request)
except Exception as exc:
# On error: minimal attribution (wall-time proxy)
wall_time_s = time.perf_counter() - start_wall
_accumulate_and_alert(tag, wall_time_s * CPU_COST_PER_SECOND_USD, wall_time_s / 3600)
raise
else:
# Post-request metrics
end_wall = time.perf_counter()
end_cpu = process.cpu_times()
end_mem_gb = process.memory_info().rss / (1024 ** 3)
wall_time_s = end_wall - start_wall
cpu_user_delta = end_cpu.user - start_cpu.user
cpu_sys_delta = end_cpu.system - start_cpu.system
cpu_time_s = cpu_user_delta + cpu_sys_delta
avg_mem_gb = (start_mem_gb + end_mem_gb) / 2
mem_gb_hours = avg_mem_gb * (wall_time_s / 3600)
resp_size_bytes = int(response.headers.get("content-length", 0))
total_io_gb = (req_size_bytes + resp_size_bytes) / (1024 ** 3)
# Cost breakdown
cost_cpu = cpu_time_s * CPU_COST_PER_SECOND_USD
cost_mem = mem_gb_hours * MEMORY_COST_PER_GB_HOUR_USD
cost_io = total_io_gb * IO_COST_PER_GB_USD
total_cost = cost_cpu + cost_mem + cost_io
# Track & alert
_accumulate_and_alert(tag, total_cost)
# Annotate response headers
response.headers["X-Cost-Tag"] = tag
response.headers["X-Cost-Estimate-USD"] = f"{total_cost:.6f}"
response.headers["X-Cost-Compute-USD"] = f"{cost_cpu:.6f}"
response.headers["X-Cost-Memory-USD"] = f"{cost_mem:.6f}"
response.headers["X-Cost-IO-USD"] = f"{cost_io:.6f}"
response.headers["X-Cost-Wall-S"] = f"{wall_time_s:.3f}"
response.headers["X-Cost-CPU-S"] = f"{cpu_time_s:.3f}"
return response
def _accumulate_and_alert(tag: str, cost: float):
"""Accumulate spend and check budget."""
if tag not in SPEND:
SPEND[tag] = 0.0
SPEND[tag] += cost
if tag in BUDGETS and SPEND[tag] > BUDGETS[tag] * ALERT_THRESHOLD:
alert_msg = (
f"BUDGET ALERT [{tag}]: "
f"${SPEND[tag]:.4f} > {ALERT_THRESHOLD*100}% of ${BUDGETS[tag]:.4f} "
f"(over by ${(SPEND[tag] - BUDGETS[tag]):.4f})"
)
print(alert_msg)
# TODO: Integrate Slack/Discord/email (e.g., via httpx.post to webhook)
# Admin endpoints
@app.post("/set-budget/{tag}")
async def set_budget(tag: str, budget: float = Query(..., description="USD budget")):
"""Set budget for a tag (e.g., /set-budget/project1?budget=100.0)"""
BUDGETS[tag] = budget
return {"status": "ok", "tag": tag, "budget": budget}
@app.delete("/clear-budget/{tag}")
async def clear_budget(tag: str):
BUDGETS.pop(tag, None)
SPEND.pop(tag, None)
return {"status": "ok", "tag": tag}
@app.get("/spend")
async def get_spend():
"""Get all tag spends."""
return {"budgets": BUDGETS, "spend": SPEND}
@app.get("/spend/{tag}")
async def get_spend_tag(tag: str):
return {
"tag": tag,
"budget": BUDGETS.get(tag, 0.0),
"spend": SPEND.get(tag, 0.0),
"pct_used": (SPEND.get(tag, 0.0) / BUDGETS.get(tag, 1.0)) * 100 if tag in BUDGETS else 0.0
}
# Demo endpoint
@app.get("/hello")
@app.post("/hello")
async def hello():
"""Demo endpoint with simulated compute/IO."""
time.sleep(0.05) # Simulate CPU
data = {"message": "Hello from cost-tracked endpoint!", "data": [i for i in range(1000)]}
return data
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)