5/7
Technical Architecture & AI Engineering · 7 min read

Cloud FinOps and Unit Economics: Cost-Per-Tenant Modeling and LLM Token Routing

Turn cloud and AI bills into architectural unit metrics, cut non-production and log storage waste, and route LLM traffic by task complexity.

Why This Matters at Engineering Leadership Scale

As a Team Lead, you optimize latency and delivery speed. At Head of Engineering or L6/L7 level, you also own cost per customer, cost per 1,000 requests, and gross margin. Finance does not read flame graphs; they track whether cloud and AI spend scales slower or faster than revenue.

In B2B SaaS and AI products, infrastructure bills quietly double when verbose debug logs stay active in hot search indexes, unindexed queries force oversized RDS instances, or product squads route every simple classification call through a frontier LLM. Treating cost as a first-class architectural metric prevents panic-driven cloud freezes and lets you spot unprofitable enterprise tenants early.

Core Mental Model & Architecture

Four high-leverage architectural levers typically capture 80% of cloud and AI FinOps savings without hurting customer latency.

FinOps LeverPrimary Cost DriverTypical SavingsMechanismLatency Impact
Unit-Cost TelemetryUnattributed shared infraUnlocks 15% to 35% cutsTag compute and log tokens by tenant_id and feature_nameNone (async)
Right-Sizing & Non-Prod SchedulesIdle dev/staging clusters40% to 60% non-prodOff-hours auto-pause, Spot batch workers, tuned pod requestsNone in prod
Storage & Log Lifecycle TieringVerbose prod logs in hot SSD50% to 75% loggingDrop DEBUG, cap metric cardinality, move logs >14d to S3/GlacierNone (hot triage stays 14d)
LLM Routing & Prompt CachingFrontier models on simple tasks65% to 90% AI spendRoute classify/extract to small models + enable prompt cachingImproves p95 latency

Never optimize raw bill totals in isolation. Track unit cost per active tenant and cost per 1,000 requests: if cloud spend grows 20% while billable transactions grow 60%, your architecture is winning.

Step-by-Step Implementation Tutorial

1. Instrument tenant_id and feature_name on Cost Boundaries

Propagate tenant_id and feature_name through API middleware, async worker envelopes, and LLM gateway telemetry. For shared databases, allocate baseline compute proportionally by request share rather than chasing penny-exact attribution.

2. Ship a Weekly Unit-Cost Rollup Query

Join AWS Cost and Usage Reports (CUR) with LLM token usage events in ClickHouse, BigQuery, or Postgres so engineering leaders inspect unit economics every week.

sql
WITH llm_costs AS (
  SELECT
    tenant_id,
    feature_name,
    COUNT(*) AS reqs,
    SUM(
      (prompt_tokens / 1e6) * input_usd_per_1m
      + (completion_tokens / 1e6) * output_usd_per_1m
      - (cached_prompt_tokens / 1e6) * (input_usd_per_1m * 0.90)
    ) AS llm_usd
  FROM llm_usage_events
  WHERE event_ts >= NOW() - INTERVAL '7 days'
  GROUP BY 1, 2
)
SELECT
  l.tenant_id,
  l.feature_name,
  l.reqs,
  ROUND(l.llm_usd + COALESCE(i.infra_usd, 0), 2) AS weekly_total_usd,
  ROUND(((l.llm_usd + COALESCE(i.infra_usd, 0)) / NULLIF(l.reqs, 0)) * 1000, 4) AS usd_per_1k_reqs
FROM llm_costs l
LEFT JOIN tenant_infra_allocations i
  ON l.tenant_id = i.tenant_id AND i.week_start = DATE_TRUNC('week', NOW())
ORDER BY weekly_total_usd DESC
LIMIT 20;

3. Implement Tiered LLM Model Routing and Prompt Caching

Reserve frontier models strictly for complex synthesis. Route deterministic classification and JSON extraction to fast, lightweight models (cutting token cost 80% to 90%) and enable provider prompt caching for repeated system instructions.

typescript
type TaskTier = "classify" | "extract" | "synthesize";

const ROUTING_POLICY: Record<TaskTier, { model: string; maxTokens: number; cachePrefix: boolean }> = {
  classify: { model: "haiku-or-gpt4o-mini", maxTokens: 128, cachePrefix: true },
  extract: { model: "haiku-or-gpt4o-mini", maxTokens: 512, cachePrefix: true },
  synthesize: { model: "sonnet-or-frontier", maxTokens: 1500, cachePrefix: true },
};

export function resolveModel(tier: TaskTier, tenantId: string, feature: string) {
  return { ...ROUTING_POLICY[tier], tags: { tenant_id: tenantId, feature_name: feature } };
}

4. Enforce Log Lifecycle Tiering and Non-Prod Auto-Pause

Drop DEBUG logs in production, reject high-cardinality metric tags (user_id, request_id), move audit logs >14 days old from hot OpenSearch to S3/Glacier, and schedule dev/staging clusters to scale to zero nights and weekends.

Worked Production Scenario: Before vs. After

A multi-tenant portfolio-reporting and compliance platform serving 350 enterprise tenants hit $18,000/month in AWS RDS, OpenSearch, and LLM bills growing 15% quarterly. Rather than chasing micro-optimizations, the platform squad executed three changes over six weeks:

  1. Added composite Postgres indexes (tenant_id, event_date DESC) and PgBouncer pooling (80 active connections), eliminating RDS vertical scaling.
  2. Tiered raw audit logs >14 days from OpenSearch NVMe to S3/Glacier and enabled off-hours auto-pause on dev/staging clusters.
  3. Routed ticket classification and entity extraction to small models with prompt caching.
MetricBefore FinOps InitiativeAfter 6 WeeksNet Impact
Monthly Cloud + LLM Spend$18,000 / month$11,200 / month-38% ($6,800/mo saved)
Unit Cost per Active Tenant$51.43 / tenant / mo$32.00 / tenant / mo-38% unit cost
Hot OpenSearch Retention90 days SSD14 days hot + S3 cold-72% logging spend
LLM Cost per 1,000 Workflows$14.20$4.10-71% AI inference spend
Monday Peak p95 Latency4.5s190ms23x faster while cheaper

Common Failure Modes & Anti-Patterns

1. Chasing Penny-Level Attribution Perfection

The trap: Spending two months attributing shared NAT gateway pennies across tenants before cutting obvious waste. The structural fix: Follow 80/20 attribution. Directly meter the top three drivers (LLM tokens, DB/compute share, log volume) and allocate baseline networking proportionally by request volume.

2. Cutting Resilience Guardrails to Hit a Cost Target

The trap: Disabling Multi-AZ database failover or slashing peak autoscaling headroom to reduce AWS bills. The structural fix: Eliminate waste (idle non-prod, verbose logs, oversized LLM models) first. Never trade SLO reliability for minor infra savings without explicit executive sign-off.

3. Unbounded Metric Cardinality Explosions

The trap: Adding tenant_id or order_id as a custom Prometheus or Datadog metric label, multiplying active series 100x overnight. The structural fix: Block unbounded labels via OpenTelemetry collector drop-rules and CI lint checks; keep high-cardinality IDs in structured logs, traces, and warehouse billing tables.

How to Handle Pushback in the Room

VP of Engineering: "Finance is flagging our cloud bill growth. Which two changes actually move the needle this quarter, and what is the expected dollar impact?"

Calm Executive Response: "Bottom line: unit cost per tenant rose 22% because hot log storage and frontier LLM calls scaled linearly with volume. Two changes cut 35% of our monthly spend ($6,800/month) in four weeks with zero latency risk: tiering logs older than 14 days from OpenSearch to S3, and routing classification prompts to small models with prompt caching. I will share a weekly cost-per-tenant scorecard every Friday."

Product Manager: "Won't routing AI steps to a smaller model hurt answer quality for enterprise customers?"

Calm Executive Response: "We are keeping the frontier model for final customer synthesis and only shifting deterministic classification and extraction to lightweight models. We will benchmark both models on our golden eval set first and only shift live traffic if accuracy stays within 1% of baseline."

Key Takeaways & This Week's Action Rep

  • Track unit economics, not raw bills: Report cost per active tenant and cost per 1,000 requests alongside latency SLOs.
  • Execute the four high-ROI levers first: Unit-cost telemetry, non-prod off-hours pause, hot-to-cold log tiering, and small-model routing + prompt caching.
  • Never cut reliability reserves as "FinOps": Eliminate idle waste and verbose logs before touching Multi-AZ redundancy.
  • Gate model routing with evals: Prove quality parity offline before shifting production prompts to cheaper models.
  • This Week's Action Rep: Compute last month's total infrastructure + LLM cost divided by active tenants for your main service, and pitch one storage, non-prod, or model-routing optimization worth >20% savings.