{
  "version": 1,
  "id": "finops-foundations",
  "title": "FinOps Foundations",
  "summary": "The inform, optimise, operate lifecycle and the cultural rules that make cloud cost an engineering concern.",
  "estimatedMinutes": 15,
  "prerequisites": [],
  "source": "courses-notebook CLD303_finops_cloud_cost 01_finops_foundations",
  "quiz": [
    {
      "prompt": "The FinOps lifecycle cycles through which three phases?",
      "options": [
        "Plan, Build, Deploy",
        "Inform, Optimize, Operate",
        "Detect, Respond, Recover",
        "Buy, Sell, Trade"
      ],
      "answer": 1
    },
    {
      "prompt": "The FinOps golden rule emphasizes:",
      "options": [
        "Finance owns all cost decisions",
        "Engineers who build it pay for (and own) it",
        "Cost is reviewed only quarterly",
        "Tags are optional"
      ],
      "answer": 1
    }
  ],
  "lesson": "Understand the FinOps framework lifecycle, the FOCUS billing specification, and unit economics \u2014 then build a Python billing data aggregator that simulates a cloud cost report.\n\n## The FinOps Framework\n\nThe FinOps Foundation defines three phases executed in a continuous loop:\n\n| Phase | Goal | Key Activities |\n|---|---|---|\n| **Inform** | Visibility & allocation | Cost dashboards, tagging, showback reports |\n| **Optimize** | Reduce waste & maximize value | Rightsizing, RI/SP purchasing, scheduling |\n| **Operate** | Embed discipline in culture | Budgets, alerts, cost reviews, KPIs |\n\n### FinOps Personas\n\n| Persona | Primary Concern | Key Metric |\n|---|---|---|\n| Engineering | Build reliable, cost-efficient systems | Cost per deployment |\n| Finance | Forecast and budget cloud spend | Variance vs budget |\n| Product | Understand cost per feature/user | Cost per active user |\n| Leadership | Unit economics, margin | Cloud as % of revenue |\n\n### FinOps Maturity Model\n\n| Stage | Characteristics |\n|---|---|\n| **Crawl** | Reactive \u2014 basic tagging, monthly cost reviews |\n| **Walk** | Proactive \u2014 showback, anomaly alerts, RI coverage |\n| **Run** | Predictive \u2014 unit economics, real-time optimization, FinOps RACI |\n\n## The FOCUS Billing Specification\n\n**FOCUS** (FinOps Open Cost & Usage Specification) is a vendor-neutral schema for cloud billing data, standardizing field names across AWS (CUR), GCP (BigQuery billing), and Azure (Cost Management exports).\n\n### Core FOCUS Columns\n\n| Column | Type | Description |\n|---|---|---|\n| `BillingPeriodStart` | datetime | Start of billing window |\n| `BillingPeriodEnd` | datetime | End of billing window |\n| `ServiceName` | string | Cloud service (EC2, S3, BigQuery) |\n| `ServiceCategory` | string | Compute, Storage, Network, Database |\n| `ResourceId` | string | Unique resource identifier |\n| `RegionName` | string | Cloud region |\n| `BilledCost` | float | Actual charged amount (USD) |\n| `ListCost` | float | On-demand list price before discounts |\n| `EffectiveCost` | float | Amortized cost including commitments |\n| `Tags` | map | Key-value resource tags |\n| `ProviderName` | string | AWS, GCP, Azure |\n\nFOCUS enables multi-cloud cost analysis without custom ETL per provider.\n\n## Unit Economics\n\nUnit economics connects cloud spend to business outcomes:\n\n| Unit Metric | Formula | Target |\n|---|---|---|\n| Cost per Active User (CPAU) | Total cloud cost / MAU | Decreasing as you scale |\n| Cost per API Request | Total cost / Request count | < $0.001 for most APIs |\n| Cost per Transaction | Total cost / Transactions | Depends on domain |\n| Cloud Margin | 1 \u2212 (Cloud cost / Revenue) | Should grow over time |\n| Waste Ratio | Waste cost / Total cost | Target < 10% |\n\nWithout unit economics, cost reduction efforts are disconnected from business value.\n\n```python\n# Cell 1: FOCUS-compliant billing record model and data generator\nfrom dataclasses import dataclass, field\nfrom datetime import date, timedelta\nfrom typing import Dict, List, Optional\nimport random\nimport json\n\n\n@dataclass\nclass BillingRecord:\n    \"\"\"A single FOCUS-compliant billing line item.\"\"\"\n    billing_period_start: date\n    billing_period_end: date\n    service_name: str\n    service_category: str  # Compute, Storage, Network, Database\n    resource_id: str\n    region_name: str\n    billed_cost: float\n    list_cost: float\n    effective_cost: float\n    provider_name: str\n    tags: Dict[str, str] = field(default_factory=dict)\n\n    @property\n    def discount_pct(self) -> float:\n        \"\"\"Percentage discount vs list price.\"\"\"\n        if self.list_cost == 0:\n            return 0.0\n        return round((1 - self.billed_cost / self.list_cost) * 100, 2)\n\n\ndef generate_billing_dataset(days: int = 30, seed: int = 42) -> List[BillingRecord]:\n    \"\"\"Generate a synthetic FOCUS-compliant cloud billing dataset.\"\"\"\n    random.seed(seed)\n\n    services = [\n        ('EC2',         'Compute',  1.0,  True),\n        ('RDS',         'Database', 0.8,  True),\n        ('S3',          'Storage',  0.02, False),\n        ('EKS',         'Compute',  0.5,  True),\n        ('CloudFront',  'Network',  0.05, False),\n        ('Lambda',      'Compute',  0.1,  False),\n        ('ElastiCache', 'Database', 0.3,  True),\n        ('DataTransfer','Network',  0.09, False),\n    ]\n\n    teams = ['platform', 'data', 'product', 'ml', 'infra']\n    envs  = ['prod', 'staging', 'dev']\n    regions = ['us-east-1', 'us-west-2', 'eu-west-1']\n\n    records: List[BillingRecord] = []\n    start = date(2024, 1, 1)\n\n    for day_offset in range(days):\n        period_start = start + timedelta(days=day_offset)\n        period_end   = period_start + timedelta(days=1)\n\n        for svc_name, svc_cat, base_cost, has_ri in services:\n            team   = random.choice(teams)\n            env    = random.choices(envs, weights=[0.6, 0.25, 0.15])[0]\n            region = random.choice(regions)\n\n            # Weekend effect \u2014 lower compute on weekends\n            day_of_week = period_start.weekday()\n            weekend_factor = 0.4 if day_of_week >= 5 and svc_cat == 'Compute' else 1.0\n\n            list_cost = round(base_cost * random.uniform(0.8, 1.3) * weekend_factor, 4)\n\n            # RI/SP discount applies to on-demand-eligible services\n            if has_ri and env == 'prod':\n                discount = random.uniform(0.30, 0.72)  # 30-72% discount\n                billed_cost = round(list_cost * (1 - discount), 4)\n            else:\n                billed_cost = list_cost\n\n            effective_cost = round(billed_cost * random.uniform(0.95, 1.05), 4)\n\n            resource_id = f'arn:aws:{svc_name.lower()}:{region}:123456:{team}-{env}-001'\n\n            records.append(BillingRecord(\n                billing_period_start=period_start,\n                billing_period_end=period_end,\n                service_name=svc_name,\n                service_category=svc_cat,\n                resource_id=resource_id,\n                region_name=region,\n                billed_cost=billed_cost,\n                list_cost=list_cost,\n                effective_cost=effective_cost,\n                provider_name='AWS',\n                tags={\n                    'team':        team,\n                    'environment': env,\n                    'cost-center': f'CC-{1000 + teams.index(team) * 100}',\n                },\n            ))\n\n    return records\n\n\nrecords = generate_billing_dataset(days=30)\nprint(f'Generated {len(records)} billing records')\nprint(f'Sample record:')\nr = records[0]\nprint(f'  {r.billing_period_start}  {r.service_name:12s}  '\n      f'list=${r.list_cost:.4f}  billed=${r.billed_cost:.4f}  discount={r.discount_pct:.1f}%')\n```\n\n```python\n# Cell 2: Billing aggregator \u2014 cost by service, team, environment\nfrom collections import defaultdict\nfrom typing import Callable, Tuple\n\n\ndef aggregate_costs(\n    records: List[BillingRecord],\n    group_by: Callable[[BillingRecord], str],\n) -> Dict[str, float]:\n    \"\"\"Aggregate billed_cost grouped by an arbitrary key function.\"\"\"\n    totals: Dict[str, float] = defaultdict(float)\n    for r in records:\n        totals[group_by(r)] += r.billed_cost\n    return dict(sorted(totals.items(), key=lambda x: x[1], reverse=True))\n\n\ndef print_cost_table(title: str, data: Dict[str, float], total: float) -> None:\n    print(f'\\n=== {title} ===')\n    print(f'  {\"Group\":<20s}  {\"Cost (USD)\":>12s}  {\"Share\":>8s}')\n    print('  ' + '-' * 44)\n    for group, cost in data.items():\n        share = cost / total * 100 if total > 0 else 0\n        print(f'  {group:<20s}  ${cost:>11.2f}  {share:>7.1f}%')\n    print(f'  {\"TOTAL\":<20s}  ${total:>11.2f}  {100.0:>7.1f}%')\n\n\ntotal_billed = sum(r.billed_cost for r in records)\ntotal_list   = sum(r.list_cost   for r in records)\ntotal_savings = total_list - total_billed\n\nprint(f'30-Day Cloud Bill Summary')\nprint(f'  On-demand (list):  ${total_list:.2f}')\nprint(f'  Actual billed:     ${total_billed:.2f}')\nprint(f'  Commitment savings:${total_savings:.2f}  ({total_savings/total_list*100:.1f}%)')\n\nby_service = aggregate_costs(records, lambda r: r.service_name)\nby_team    = aggregate_costs(records, lambda r: r.tags.get('team', 'untagged'))\nby_env     = aggregate_costs(records, lambda r: r.tags.get('environment', 'untagged'))\nby_category= aggregate_costs(records, lambda r: r.service_category)\n\nprint_cost_table('By Service',     by_service,  total_billed)\nprint_cost_table('By Team',        by_team,     total_billed)\nprint_cost_table('By Environment', by_env,      total_billed)\nprint_cost_table('By Category',    by_category, total_billed)\n```\n\n## Key Takeaways\n\n- The FinOps cycle (Inform \u2192 Optimize \u2192 Operate) is continuous, not a one-time project\n- FOCUS standardizes billing columns across providers, enabling multi-cloud analytics\n- Tags are the foundation of cost allocation \u2014 without them, showback is impossible\n- Unit economics (CPAU, cost per request) links cloud spend to business outcomes\n- Commitment discounts (RI/SP) can reduce on-demand costs by 30\u201372%\n"
}
