The user wants a "per-request cost attribution middleware" for some system (likely a web server or API gateway).
The key components requested are:
Compute/Memory/IO Estimation: Measuring or estimating resource usage per request.
Tagging: Associating metadata (like user ID, endpoint, tenant) with the cost.
Budget Alerts: Notifying when spending exceeds a threshold.
Context & Scope:
Since the user didn't specify a language or framework, I should choose a popular, readable, and versatile one. Python (using FastAPI or Flask) or Node.js (using Express) are good candidates. I'll choose Python with FastAPI because its async nature makes handling middleware and background tasks easier, and the ecosystem for metrics is strong.
High-Level Architecture:
Middleware: Intercepts incoming requests and outgoing responses.
Measurement (The Hard Part):
Time: Easy (wall clock time).
CPU/Memory: Harder in a portable way within a Python process without external tools. resource module (Unix) or psutil are options.
IO: Counting bytes read/written or database calls.
Estimation: Real-time low-level monitoring adds overhead. Often, it's better to use a "model-based" approach (e.g., "This endpoint usually takes X CPU") or a lightweight sampler. However, to make this code functional and illustrative, I will implement a sampling approach using psutil or resource to get diffs of process-wide resources, divided by concurrent requests (rough estimation), or just measure wall time + database query counts as a proxy for IO.
Decision: I'll use time for compute duration and a mock/simplified counter for IO/DB calls. True CPU/Memory profiling per request in a high-concurrency async server is complex and often requires eBPF or external agents. I will simulate the logic of a cost estimator.
Attribution/Tagging: Extracting data from headers, JWTs, or path parameters.
Storage/Aggregation: Storing these metrics. I shouldn't build a full database schema, but I should show how to emit metrics (e.g., to a log, a global dictionary for demonstration, or a StatsD client).
Budgeting: Checking cumulative costs against a limit.
Drafting the Solution (Mental Code Structure):
Input: Request object.
Process:
Start Timer.
Identify User/Tenant (Tagging).
Check Current Budget (Pre-flight check? Or just alerting? usually alerting).
Process Request (yield control to next handler).
Stop Timer.
Collect Metrics (Memory usage diff, DB queries executed).
Refining the "Cost Model":
Realistically, cost attribution usually involves:
Compute: Wall time × CPU cost.
Memory: Peak RSS × duration (hard to get per-request in Python without tracemalloc, which is slow). I'll approximate this or use a fixed overhead. Let's stick to Wall Time + IO counts for the code example to keep it runnable.
IO: Number of DB queries or External API calls.
Step-by-Step Implementation Plan:
Setup: FastAPI app.
Mock Infrastructure: A simple in-memory database for "Budgets" and "Usage".
The Middleware:
dispatch function.
Start timer.
Run request.
Capture metrics.
Calculate cost.
Alert logic.
Cost Logic: A class that converts metrics to "Credits" or "USD".
Alerting: A simple print/logger statement or mock email sender.
Self-Correction/Edge Cases:
Concurrency: If I measure global process memory, it changes for all threads. Per-request memory measurement in Python is notoriously difficult.
Fix: I will implement a "Resource Estimator" that uses tracemalloc (if feasible) or simpler heuristics (like counting specific function calls or just using duration). I'll define an interface for the Cost Model so the user can swap it.
Budgets: Need a way to define budgets. A simple tenant_id -> limit map.
Finalizing the Code Structure:
I will provide a Python solution using FastAPI. It is modular and easy to understand.
CostModel: Handles the math.
BudgetManager: Checks limits.
ResourceMonitor: The tricky part. I'll use time and a context manager to track DB calls.
Middleware: The glue.
Let's write the code.
Key features to highlight in the explanation:
Wall-clock time vs. CPU time.
The difficulty of per-request memory attribution in managed languages (GC pauses).
The difference between "Metering" (counting) and "Rating" (pricing).
Code Outline:
python
from fastapi import FastAPI, Request, HTTPException
import time
import psutil # For CPU/Memory (globally)
import asyncio
from collections import defaultdict
# 1. Configuration & Constants
# 2. Mock Resource Monitor (Context Manager)
# 3. Budget Store
# 4. Middleware Logic
# 5. Example Routes
Let's refine the "Memory/IO" estimation.
Since this is a "middleware", it wraps the request.
Compute:end_time - start_time.
IO: I need a way to track DB calls during the request.
Technique: Dependency Injection or a global request context variable. I'll simulate this by having a RequestContext that the DB layer updates.
Memory: I'll use psutil to get the RSS diff, but add a disclaimer that this is process-wide, not per-request. A better approach for the example is just to count "objects allocated" or fixed overhead, but let's stick to psutil with a big fat warning comment or just use request duration as the primary cost driver for simplicity in the demo.
Actually, let's use resource.getrusage(resource.RUSAGE_SELF) to show how it's done, but acknowledge the limitations.
Revised Plan for the "Cost Attribution Middleware" implementation:
Tagging: Extract API Key or Tenant ID.
Measurement:
Compute: Wall time (ms).
IO: A mock counter that increments when "external services" are called.
Memory: Current RSS (simplistic).
Calculation: Apply a pricing matrix.
Alerting: If total_usage > budget, trigger a webhook/log.
I will generate a robust, production-style Python class structure.
Code Structure:
CostAttributionConfig: Pricing rates.
BudgetTracker: In-memory store (replaceable with Redis).
CostMiddleware: The Starlette/FastAPI middleware.
UsageContext: A context var to track IO calls inside the request.
Let's add a "Budget Check" decorator or middleware phase. If a user is over budget, do we reject? The prompt asks for "Alerts", not necessarily rejection, but usually "Budget Blocks" are implied in production. I will implement "Soft Limits" (Alerts) and "Hard Limits" (Block).
Self-Correction during coding:psutil might not be installed in the user's environment. I should write the code to handle import errors or stick to standard libraries (time, resource) where possible, noting psutil is preferred. I'll use standard resource module for CPU/Context switches (Unix only) to make it run "everywhere" Linux/Mac, and mock the rest.
Let's proceed with the Python/FastAPI implementation. It is the most expressive for this architectural pattern.
This is a comprehensive implementation of a Per-Request Cost Attribution Middleware in Python using FastAPI.
This solution is designed to be modular, covering resource estimation (CPU/Memory/IO), contextual tagging (Tenant/User), and enforcement of budgets with alerts.
Architecture Overview
Metering Layer: Wraps the request lifecycle to measure duration and estimate resource usage.
Context Layer: Extracts metadata (User ID, Tenant, Endpoint) to attribute costs to specific entities.
Pricing Engine: Converts raw usage metrics into a normalized "Cost" (either monetary or abstract "credits").
Budget Enforcer: Checks accumulated costs against thresholds (Soft Limit = Alert, Hard Limit = Block).
The Implementation
You will need fastapi, uvicorn, and psutil installed.
bash
pip install fastapi uvicorn psutil
Here is the complete main.py:
python
Key Concepts Explained
1. Compute/Memory/IO Estimation
Accurate per-request measurement in a managed language like Python is difficult because of the Garbage Collector and shared memory.
Compute: We use time.perf_counter for high-precision wall-clock time. In a production async environment, you ideally want CPU time (process.cpu_times()), but wall-clock is a standard proxy for "occupancy" cost.
Memory: The middleware measures the RSS (Resident Set Size) delta. Note: In a thread-pool or heavy concurrency, attributing shared memory to a single request is inaccurate. A common pattern is to sample memory at the start/end of the request or simply charge a fixed "footprint" tax per request based on average profile.
IO: It is hard to transparently intercept IO calls. The example uses a heuristic (checking the URL), but in a real enterprise system, you would use Dependency Injection (passing a metered_db_client to your routes) that increments a counter whenever a query is executed.
2. Tagging Strategy
The _extract_context method is crucial. Costs are useless if they aren't attributed to an owner.
Identity: We extract Tenant-ID and User-ID from headers. In production, this would likely come from decoding a JWT token.
Granularity: We also tag the endpoint. This allows you to answer questions like "Which endpoint is costing the most?".
3. Budget Enforcement
We implement a Two-Phase Budget:
Hard Limit (Pre-check): Before executing the request logic, we check if the tenant is already over the limit. If so, we return HTTP 429 immediately to save resources.
Soft Limit (Alerting): If the request pushes the tenant over a warning threshold (e.g., 80% of budget), we log an alert. This could be a webhook to Slack or an email in a real system.
Trigger Alert:
Modify BUDGET_LIMITS in the code to be very low (e.g., 0.0001) and restart. Hitting the endpoint again will trigger the alert_log warning in your console.
import asyncio
import time
import psutil
import logging
from typing import Callable, Optional, Dict, Any
from fastapi import FastAPI, Request, Response, HTTPException
from fastapi.concurrency import iterate_in_threadpool
from collections import defaultdict
from dataclasses import dataclass, field
# --- Configuration & Constants ---
# Pricing Model (Abstract Units per Unit of Resource)
# In production, this would come from a config file or DB.
PRICING_RATES = {
"compute_cost_per_ms": 0.00001, # Cost per millisecond of CPU time
"memory_cost_per_mb": 0.00005, # Cost per MB of RAM allocated
"io_cost_per_call": 0.001, # Cost per I/O operation (DB call, API fetch)
}
# Budget Limits (in abstract cost units)
BUDGET_LIMITS = {
"tenant_A": {"hard_limit": 100.0, "soft_limit": 80.0},
"default": {"hard_limit": 50.0, "soft_limit": 40.0}
}
# --- Domain Models ---
@dataclass
class UsageMetrics:
compute_time_ms: float = 0.0
memory_rss_mb: float = 0.0
io_operations: int = 0
def to_cost(self) -> float:
"""Convert raw metrics to monetary/cost value"""
cost = (
(self.compute_time_ms * PRICING_RATES["compute_cost_per_ms"]) +
(self.memory_rss_mb * PRICING_RATES["memory_cost_per_mb"]) +
(self.io_operations * PRICING_RATES["io_cost_per_call"])
)
return cost
@dataclass
class RequestContext:
tenant_id: str
user_id: str
endpoint: str
tags: Dict[str, str] = field(default_factory=dict)
# --- Mock Services ---
# In-memory store for budget tracking (Use Redis in production)
budget_store = defaultdict(float)
alert_log = logging.getLogger("budget_alerts")
alert_log.setLevel(logging.INFO)
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
alert_log.addHandler(handler)
# --- Middleware Components ---
class CostAttributionMiddleware:
def __init__(self, app: FastAPI):
self.app = app
async def __call__(self, request: Request, call_next: Callable) -> Response:
# 1. Context Extraction (Tagging)
context = self._extract_context(request)
# 2. Pre-Check Budget (Fail fast if over hard limit)
current_spend = budget_store.get(context.tenant_id, 0.0)
limits = BUDGET_LIMITS.get(context.tenant_id, BUDGET_LIMITS["default"])
if current_spend >= limits["hard_limit"]:
raise HTTPException(status_code=429, detail="Budget Exceeded: Hard limit reached.")
# 3. Start Metering
process = psutil.Process()
mem_start = process.memory_info().rss / (1024 * 1024) # MB
cpu_start = process.cpu_times()
start_time = time.perf_counter()
# Track IO (Simplified: using a context var or global hook is complex,
# so we simulate/estimate IO based on request type here for demonstration)
estimated_io = 1 if "db" in request.url.path else 0
# 4. Process Request
response = await call_next(request)
# 5. Stop Metering & Calculate
end_time = time.perf_counter()
mem_end = process.memory_info().rss / (1024 * 1024)
# Calculate diffs
duration_ms = (end_time - start_time) * 1000
mem_delta = max(0, mem_end - mem_start) # simplistic delta
metrics = UsageMetrics(
compute_time_ms=duration_ms,
memory_rss_mb=mem_delta,
io_operations=estimated_io
)
request_cost = metrics.to_cost()
# 6. Attribution & Storage
budget_store[context.tenant_id] += request_cost
# 7. Budget Alerts (Post-Request)
new_spend = budget_store[context.tenant_id]
if new_spend >= limits["soft_limit"] and current_spend < limits["soft_limit"]:
alert_log.warning(f"ALERT: Tenant {context.tenant_id} crossed soft limit ({limits['soft_limit']}). Current: {new_spend:.4f}")
# 8. Inject Attribution Headers (Debug/Info)
response.headers["X-Cost-Value"] = f"{request_cost:.6f}"
response.headers["X-Tenant-ID"] = context.tenant_id
return response
def _extract_context(self, request: Request) -> RequestContext:
"""Extract tagging info from Headers or JWT"""
# Mock extraction
tenant = request.headers.get("X-Tenant-ID", "default")
user = request.headers.get("X-User-ID", "anonymous")
return RequestContext(
tenant_id=tenant,
user_id=user,
endpoint=request.url.path
)
# --- Application Setup ---
app = FastAPI()
app.add_middleware(CostAttributionMiddleware)
# --- Routes for Testing ---
@app.get("/")
async def root():
return {"message": "Hello World"}
@app.get("/expensive/compute")
async def expensive_compute():
# Simulate CPU load
sum(i * i for i in range(100000))
return {"status": "done", "load": "high"}
@app.get("/db/read")
async def db_read():
# This endpoint triggers IO estimation in the middleware logic above
await asyncio.sleep(0.1) # Simulate IO wait
return {"data": "some_db_row"}
@app.get("/admin/budgets")
async def get_budgets():
return dict(budget_store)
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)