# Cost Optimization Examples

Reduce infrastructure costs through intelligent resource allocation and scheduling.

## Resource Right-Sizing

Match instance types to actual workload requirements:

```nickel
{
  cost_optimization = {
    # Analyze current usage and recommend right-sized instances
    right_sizing = {
      enabled = true,
      analysis_period_days = 30,
      metrics = ["cpu", "memory", "disk", "network"]
    },

    # Current (oversized) configuration
    current_servers = [
      {
        name = "web-01",
        instance_type = "t3.2xlarge",  # 8 vCPU, 32GB memory
        actual_usage = {
          cpu_avg = "15%",
          memory_avg = "20%",
          network_avg = "10%"
        }
      },
      {
        name = "api-01",
        instance_type = "c5.4xlarge",  # 16 vCPU, 32GB memory
        actual_usage = {
          cpu_avg = "25%",
          memory_avg = "30%",
          network_avg = "20%"
        }
      }
    ],

    # Optimized configuration (right-sized)
    optimized_servers = [
      {
        name = "web-01",
        instance_type = "t3.medium",  # 2 vCPU, 4GB memory - 75% cost reduction
        expected_savings_percent = 75
      },
      {
        name = "api-01",
        instance_type = "c5.large",  # 2 vCPU, 4GB memory - 87.5% cost reduction
        expected_savings_percent = 87.5
      }
    ]
  }
}
```

## Reserved Instances and Savings Plans

Commit to long-term pricing for discounts:

```nickel
{
  cost_optimization = {
    reserved_instances = {
      enabled = true,
      strategy = "blended",  # Mix on-demand and reserved

      reservations = [
        {
          instance_type = "t3.large",
          count = 5,
          term = "3-year",
          payment = "all-upfront",
          discount_percent = 72,  # 72% discount vs on-demand
          annual_cost = 1200
        },
        {
          instance_type = "c5.2xlarge",
          count = 3,
          term = "1-year",
          payment = "partial-upfront",
          discount_percent = 34,
          annual_cost = 2400
        }
      ]
    },

    # Savings Plans
    savings_plans = {
      enabled = true,
      compute_savings_plan = {
        commitment = "$10,000/year",
        term = "3-year",
        discount_percent = 33,
        flexibility = "cross-region"  # Use across any region
      }
    },

    # Cost tracking
    cost_tracking = {
      monthly_budget = 15000,
      budget_alerts = [
        { threshold: 80, alert_type: "warning" },
        { threshold: 100, alert_type: "critical" }
      ]
    }
  }
}
```

## Spot Instances and Preemptible VMs

Use low-cost, interruptible instances for fault-tolerant workloads:

```nickel
{
  cost_optimization = {
    # AWS Spot Instances
    aws_spot = {
      enabled = true,
      interruption_tolerance = true,

      worker_pools = [
        {
          name = "batch-workers",
          instance_type = "t3.large",
          use_spot = true,
          spot_price_limit = 0.035,  # Max willing to pay
          capacity = 5,
          savings_percent = 70,

          # Diversification to reduce interruption risk
          instance_families = ["t3", "t2", "m5", "m6i"],
          availability_zones = ["us-east-1a", "us-east-1b", "us-east-1c"]
        }
      ]
    },

    # GCP Preemptible VMs
    gcp_preemptible = {
      enabled = true,
      preemptible_count = 10,
      regular_count = 2,  # Always maintain some regular instances
      savings_percent = 80  # 80% discount vs regular
    },

    # Azure Spot VMs
    azure_spot = {
      enabled = true,
      eviction_policy = "deallocate",
      max_price = 0.05,
      savings_percent = 90
    }
  }
}
```

## Auto-Scaling for Cost Efficiency

Scale resources based on demand:

```nickel
{
  auto_scaling = {
    enabled = true,

    # Kubernetes cluster autoscaler
    cluster_autoscaler = {
      enabled = true,
      scale_down = {
        enabled = true,
        delay_after_add = "10m",
        delay_after_failure = "3m",
        unneeded_time = "10m"
      }
    },

    # Pod auto-scaling
    hpa_policies = [
      {
        workload = "api-service",
        min_replicas = 2,
        max_replicas = 10,
        metrics = [
          {
            type = "cpu",
            target_average = "70%"
          },
          {
            type = "memory",
            target_average = "80%"
          },
          {
            type = "custom",
            metric = "http_requests_per_second",
            target_average = 1000
          }
        ]
      },
      {
        workload = "batch-processor",
        min_replicas = 1,
        max_replicas = 5,
        metrics = [
          {
            type = "custom",
            metric = "queue_depth",
            target_average = 100
          }
        ]
      }
    ]
  }
}
```

## Scheduling and Time-Based Scaling

Stop unused resources during off-hours:

```nushell
#!/usr/bin/env nu

# Schedule-based resource management
def scale_by_schedule [hour day_of_week] {
  let is_business_hours = ($hour >= 9 and $hour <= 17)
  let is_weekday = ($day_of_week < 5)

  if ($is_business_hours and $is_weekday) {
    # Business hours - full capacity
    print "Business hours: Scaling to full capacity"
    provisioning scale --min 3 --max 10 --target-utilization 70
  } else if ($hour >= 18 and $hour < 22) {
    # Evening - reduced capacity
    print "Evening: Scaling to reduced capacity"
    provisioning scale --min 1 --max 5 --target-utilization 80
  } else {
    # Night/weekend - minimal capacity
    print "Night/weekend: Scaling to minimal capacity"
    provisioning scale --min 1 --max 2 --target-utilization 90
  }
}

# Run on schedule (via cron or orchestrator)
let now = (date now)
let hour = ($now | format date "%H" | into int)
let day_of_week = ($now | format date "%w" | into int)

scale_by_schedule $hour $day_of_week
```

## Database Optimization

Reduce database costs through optimization:

```nickel
{
  database_optimization = {
    # Use multi-AZ only for production
    multi_az = {
      production = true,     # Full HA: 2-3x cost
      staging = false,       # Single AZ: lower cost
      development = false
    },

    # Connection pooling
    connection_pooling = {
      enabled = true,
      pool_size_min = 5,
      pool_size_max = 20,
      idle_connection_timeout = "900s"  # Close idle connections
    },

    # Backup strategy (cost vs retention)
    backups = {
      production = {
        retention_days = 35,   # Keep for 35 days
        backup_window = "03:00-04:00"
      },
      staging = {
        retention_days = 7,    # Keep for 7 days only
        backup_window = "04:00-05:00"
      },
      development = {
        retention_days = 1,    # Keep for 1 day only
        backup_window = "05:00-06:00"
      }
    },

    # Index optimization
    query_optimization = {
      slow_query_threshold = "100ms",
      analyze_frequency = "daily",
      auto_create_indexes = false  # Manual control for cost
    }
  }
}
```

## Storage Tiering

Move data to cheaper storage tiers based on access patterns:

```nickel
{
  storage = {
    s3_tiering = {
      enabled = true,
      buckets = [
        {
          name = "application-data",
          lifecycle_rules = [
            {
              name = "recent-data",
              filter = { prefix = "current-month/" },
              storage_class = "STANDARD",
              days = 0
            },
            {
              name = "old-data",
              filter = { prefix = "archive/" },
              transitions = [
                { days: 30, storage_class: "STANDARD_IA" },
                { days: 90, storage_class: "GLACIER" },
                { days: 365, storage_class: "DEEP_ARCHIVE" }
              ]
            }
          ]
        }
      ]
    },

    # EBS volume optimization
    ebs_optimization = {
      enabled = true,
      rules = [
        {
          filter = { usage_percent = "< 20" },
          action = "downsize_or_delete"
        }
      ]
    }
  }
}
```

## CDN and Edge Caching

Reduce bandwidth costs with caching:

```nickel
{
  cdn = {
    enabled = true,
    provider = "cloudflare",

    caching = {
      # Static assets: cache for 1 year
      static_assets = {
        path = "/static/**",
        ttl = "31536000s",  # 1 year
        compression = "gzip",
        cache_on_cookie = false
      },

      # API responses: cache based on cache-control headers
      api = {
        path = "/api/**",
        ttl = "3600s",  # 1 hour
        cache_by_cookie = ["session_id"]
      },

      # HTML: short cache with revalidation
      html = {
        path = "/**",
        ttl = "300s",  # 5 minutes
        cache_control = "public, max-age=300"
      }
    },

    # WAF rules to prevent expensive requests
    waf = {
      enabled = true,
      rules = [
        {
          name = "rate-limit",
          rate_limiting = { requests: 100, period: "10s" }
        }
      ]
    }
  }
}
```

## Cost Monitoring and Alerts

Track and control costs:

```bash
#!/usr/bin/env nu

# Cost monitoring script
def monitor-costs [] {
  # Get current monthly cost
  let current_cost = (
    provisioning cost estimate --month $(date +%Y-%m) |
    from json | get total
  )

  # Compare to budget
  let budget = 15000
  let percent_of_budget = ($current_cost / $budget * 100)

  print $"Current cost: $($current_cost)"
  print $"Budget: $($budget)"
  print $"Usage: ($percent_of_budget)%"

  # Alert if exceeding threshold
  if $percent_of_budget > 100 {
    # Critical alert
    http post $env.SLACK_WEBHOOK \
      --data { text: "⚠️  COST ALERT: Over budget by $($current_cost - $budget)" }
  } else if $percent_of_budget > 80 {
    # Warning alert
    http post $env.SLACK_WEBHOOK \
      --data { text: "⚠️  Cost warning: ($percent_of_budget)% of budget used" }
  }

  # Breakdown by service
  let breakdown = (provisioning cost breakdown | from json)
  $breakdown | each { | service |
    print $"  ($service.name): $($service.cost)"
  }
}

# Run daily cost check
monitor-costs
```

## Related Documentation

- [Multi-Cloud Deployment](./multi-cloud.md)
- [Auto-Scaling](../features/orchestrator.md)
- [Monitoring](./monitoring-examples.md)
- [Workspace Management](./workspace-examples.md)
