Cloud Cost Management: FinOps Practices, Rightsizing and Spot Instances

Our AWS bill hit $47,000 in a single month last year for a platform that should have cost half that. There was no single incident, no massive traffic spike, no rogue crypto miner. It was the slow accumulation of m5.xlarge instances provisioned for peak load that never arrived, unattached EBS volumes left by Terraform destroy failures, and three separate development environments running on-demand pricing 24/7. That bill was the moment our team stopped treating cost optimization as a finance problem and started treating it as an infrastructure engineering problem. If you are managing infrastructure with code, you already have the best lever for controlling cost — you just need to wire cost awareness directly into your pipelines, your modules, and your operational habits.

Why Cloud Bills Spike Even With Infrastructure as Code Discipline

In my experience, teams that adopt Terraform or Pulumi often assume their costs will naturally stabilize because everything is now versioned and reviewable. In reality, IaC makes it faster to provision, which can mean faster to overspend if you don't build in guardrails. A single reusable module that defaults to m5.2xlarge can be instantiated dozens of times across workspaces before anyone questions whether that size was justified in the first place. The problem compounds when that module is consumed by application teams who don't have visibility into pricing.

The Illusion of Codified Efficiency

Codified infrastructure is efficient to deploy, not necessarily efficient to run. I have audited Terraform repositories where every EC2 instance was defined with explicit instance types and storage, all properly formatted, all passing terraform validate, and all oversized by 300%. The code was clean; the utilization was not. Cloud providers charge for allocation, not for usage, and your code declares allocation. Without a feedback loop from runtime metrics back into your configuration, you are flying blind. This is where many organizations miss the core FinOps principle: cost is an engineering metric, not just an accounting one. It needs to be measured, attributed, and acted upon with the same rigor as latency or error rate.

The Drift Between Provisioning and Utilization

Even well-sized infrastructure drifts. An RDS instance provisioned for a launch sustains 15% CPU for eight months because traffic growth never materialized. An autoscaling group set with a minimum of four instances handles its workload comfortably with two. In one cluster I managed, we found that 60% of our EKS worker nodes were averaging under 10% CPU over a 30-day window, while our cluster autoscaler was never configured to scale to zero for dev environments overnight. The Kubernetes Documentation on cluster autoscaling and pod resource management is essential here — CPU requests and limits directly drive node sizing decisions, and if those requests are inflated, your entire node pool is inflated with them. Addressing this requires regular reconciliation between what you declared and what you actually need.

Building a FinOps Feedback Loop Into Your Terraform Workflow

The most effective change we made was to make cost visible at the point where engineers make decisions: the pull request. If cost data only lives in a finance dashboard reviewed monthly, it will never influence a Terraform code review on a Tuesday afternoon. You need to bring it into the developer workflow the same way you bring in linting or security scans.

Embedding Cost Estimates in Pull Requests

We integrated Infracost into our CI pipeline to comment directly on Terraform pull requests with the monthly cost impact of the proposed changes. This is not about blocking every expensive change — sometimes you need a larger database — but about forcing a conversation. When a junior engineer proposes changing an instance type from t3.medium to r5.large, seeing an automated comment that says “+ $212/month” prompts a discussion about whether memory requirements truly justify it. In my experience, about half of those changes get revised after that prompt, without any heavy-handed policy enforcement.

# .github/workflows/infracost.yml - cost estimation on pull request
name: infracost

on:
  pull_request:
    paths:
      - 'terraform/**'

jobs:
  infracost:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      pull-requests: write
    steps:
      - uses: actions/checkout@v4
      - name: Setup Infracost
        uses: infracost/actions/setup@v2
        with:
          api-key: ${{ secrets.INFRACOST_API_KEY }}
      - name: Generate cost diff
        run: |
          infracost breakdown --path=terraform/envs/prod \
            --format=json --out-file=/tmp/infracost.json
          infracost comment github --path=/tmp/infracost.json \
            --repo=$GITHUB_REPOSITORY --pull-request=${{github.event.number}} \
            --behavior=update

This approach works best when your Terraform code is modular. If you are still defining raw resources in every environment folder, you will see noise in every PR. A well-structured module library, as described in Terraform Modules: Design Patterns, Versioning and Registry Publishing, lets you attribute cost to a logical component rather than a single resource, which makes the feedback far more actionable for teams.

Linking Cost Data to State Metadata

Cost allocation becomes difficult when your state is fragmented or inconsistent. We tag every resource with team, environment, service, and terraform_workspace at the provider level so that no resource can be created without attribution. But enforcing that in code is only half the battle; you also need to ensure your state backend preserves that mapping. When we migrated our state to a remote backend with locking, we finally got a reliable source of truth for what was provisioned versus what was billed. The strategies in Terraform State Management: Remote Backends, Locking and State Migration were directly relevant there — without consistent remote state, your cost allocation reports will always have gaps. According to the Terraform Documentation, using default_tags in the AWS provider block is the cleanest way to enforce this globally without relying on developers to remember tags in every resource.

Rightsizing in Practice: From CloudWatch Metrics to Terraform Variables

Rightsizing sounds simple: match provisioned capacity to actual need. The execution is where it gets operationally complex, because you need statistically significant data, not just a glance at a dashboard, before you downsize a production database.

Collecting the Right Signals

For EC2 and autoscaling groups, I look at a 30-day window of CloudWatch metrics: Average CPUUtilization, max CPUUtilization, memory utilization via the CloudWatch agent, and NetworkIn/Out for I/O-bound workloads. For RDS, I focus on CPU, freeable memory, and read/write IOPS. For Kubernetes, it's container CPU and memory requests versus actual usage from Metrics Server or Prometheus. The mistake I see most often is rightsizing based on average CPU alone. A service that idles at 5% but spikes to 85% during batch processing every night at 2 AM will be severely under-provisioned if you size to the average. You need p95 and p99 values over your observation window.

We export these metrics to a weekly report that joins them with our Terraform module inputs. For example, if our web_app module is deployed with instance_type = "m5.xlarge" but the underlying hosts never exceed 15% CPU and 30% memory, that module call gets flagged for review. This is not automated downsizing — automated downsizing in production without human approval is risky. It is automated detection with human decision-making.

Translating Metrics Into Module Changes

Once you have the signal, the change itself should be trivial because you are changing a variable, not rewriting infrastructure. That is the payoff of parameterization.

# modules/compute/main.tf - parameterized instance type with sane, reviewable defaults
variable "instance_type" {
  description = "EC2 instance type for the application tier"
  type        = string
  default     = "t3.medium"
  validation {
    condition     = can(regex("^[trmcb]\\d+\\.", var.instance_type))
    error_message = "Instance type must be a valid current-generation family."
  }
}

variable "enable_detailed_monitoring" {
  description = "Enable detailed CloudWatch monitoring for rightsizing analysis"
  type        = bool
  default     = true
}

resource "aws_instance" "app" {
  instance_type = var.instance_type
  monitoring    = var.enable_detailed_monitoring

  root_block_device {
    volume_type = "gp3"
    volume_size = var.volume_size
    # gp3 allows independent tuning of IOPS, a classic rightsizing lever
  }

  tags = merge(var.tags, {
    RightsizeReview = formatdate("YYYY-MM-DD", timeadd(timestamp(), "720h"))
  })
}

# In your environment: terraform/envs/prod/main.tf
module "web_app" {
  source        = "../../modules/compute"
  instance_type = "t3.large" # Downgraded from m5.xlarge after 30-day analysis showed 12% avg CPU
  volume_size   = 40         # Reduced from 100GB after observing 18GB actual usage
  tags          = local.common_tags
}

Notice the RightsizeReview tag that sets a review date 30 days out. This creates a lightweight operational reminder to re-evaluate. I have found that without an explicit review date, rightsized resources slowly creep back up because no one remembers to check again after the initial optimization.

Architecting for Spot and Preemptible Instances Without Sacrificing Reliability

Spot instances can reduce compute costs by 60-90% compared to on-demand pricing, but they come with the operational reality of interruption with two minutes' notice. Treating spot like cheaper on-demand is how you get paged at 3 AM. Treating it as a distinct capacity pool with its own scheduling and fault-tolerance patterns is how you save money safely.

Workload Classification for Interruption Tolerance

Not every workload belongs on spot. I use a simple classification: stateless and interruptible, batch and retryable, and stateful or latency-sensitive. Only the first two are candidates. Stateless web services behind a load balancer, CI runners, async workers pulling from SQS, and Kubernetes batch jobs are ideal. Production databases, single-instance legacy services, and real-time stream processors with local state are not, unless you have explicitly designed for preemption.

A practical starting point is to run your non-production environments entirely on spot. Dev and staging clusters, load-testing environments, and preview environments can tolerate interruptions and give your team operational practice with spot handling before you touch production. Once you are comfortable, move stateless production services to a mixed model.

Kubernetes Patterns for Spot Nodes

For EKS, we use Karpenter and managed node groups with a mixed instance strategy, combined with proper pod disruption budgets and termination handlers. The key is to diversify across instance families and availability zones so that a single spot pool interruption does not take out a large portion of capacity at once.

# karpenter-provisioner-spot.yaml - Karpenter provisioner for spot capacity
apiVersion: karpenter.sh/v1beta1
kind: NodePool
metadata:
  name: general-purpose-spot
spec:
  template:
    spec:
      requirements:
        - key: karpenter.sh/capacity-type
          operator: In
          values: ["spot"]
        - key: karpenter.k8s.aws/instance-category
          operator: In
          values: ["c", "m", "r"]
        - key: karpenter.k8s.aws/instance-cpu
          operator: In
          values: ["4", "8"]
        - key: topology.kubernetes.io/zone
          operator: In
          values: ["us-east-1a", "us-east-1b", "us-east-1c"]
      taints:
        - key: workload-type
          value: "spot"
          effect: NoSchedule
---
# Deployment tolerating spot taint and handling interruption gracefully
apiVersion: apps/v1
kind: Deployment
metadata:
  name: api-worker
spec:
  replicas: 6
  template:
    spec:
      tolerations:
        - key: workload-type
          operator: Equal
          value: "spot"
          effect: NoSchedule
      terminationGracePeriodSeconds: 120
      affinity:
        podAntiAffinity:
          preferredDuringSchedulingIgnoredDuringExecution:
            - weight: 100
              podAffinityTerm:
                labelSelector:
                  matchLabels:
                    app: api-worker
                topologyKey: topology.kubernetes.io/zone
      containers:
        - name: worker
          image: registry.example.com/api-worker:1.8.3
          resources:
            requests:
              cpu: "500m"
              memory: "1Gi"
            limits:
              cpu: "1000m"
              memory: "2Gi"
          lifecycle:
            preStop:
              exec:
                command: ["/bin/sh", "-c", "sleep 15 && /app/drain.sh"]
---
# Terraform for mixed ASG - on-demand base capacity + spot overflow
resource "aws_autoscaling_group" "app" {
  min_size         = 4
  max_size         = 20
  desired_capacity = 6
  vpc_zone_identifier = var.private_subnet_ids

  mixed_instances_policy {
    instances_distribution {
      on_demand_base_capacity                  = 2  # Always keep 2 on-demand for stability
      on_demand_percentage_above_base_capacity = 0  # Remaining 100% is spot
      spot_allocation_strategy                 = "price-capacity-optimized"
    }
    launch_template {
      launch_template_specification {
        launch_template_id = aws_launch_template.app.id
        version            = "$Latest"
      }
      override {
        instance_type     = "m6i.large"
        weighted_capacity = "2"
      }
      override {
        instance_type     = "m6a.large"
        weighted_capacity = "2"
      }
      override {
        instance_type     = "m5.large"
        weighted_capacity = "2"
      }
    }
  }
}

That Terraform mixed instances policy is worth explaining. on_demand_base_capacity = 2 ensures you always have a stable core, even if all spot capacity is reclaimed simultaneously. The price-capacity-optimized allocation strategy is generally superior to lowest-price because it balances cost with interruption frequency based on AWS's own capacity signals. Combined with pod anti-affinity across zones, this setup has let us run 70% of our Kubernetes workload on spot with no measurable impact on availability over the last year.

Tagging, Allocation and Showback: Making Costs Visible to Engineering Teams

If engineers cannot see what their team is spending, they cannot be expected to optimize it. Finance can send a monthly CSV, but that is already a month out of date and disconnected from the code changes that caused it. Effective showback means cost data that is timely, tagged at the resource level, and mapped to the same boundaries your code uses: team, service, environment, and component.

Enforcing Tagging Standards at Plan Time

We enforce mandatory tags with a policy check in CI using OPA/Conftest. If a Terraform plan creates a resource without team, service, environment, and cost_center, the pipeline fails. This is far more effective than trying to fix tags after the fact with a Lambda that retroactively tags untagged resources. The provider-level default_tags approach catches most cases, but policy as code catches the edge cases where a module author bypasses the provider or uses a resource type that does not inherit default tags.

We also use AWS Cost Allocation Tags and activate them for billing. User-defined tags not activated in the billing console will not appear in Cost Explorer, which is a common oversight. After activating, it takes 24 hours for them to appear, so you need to plan for that delay when building reports. From there, we sync CUR data into a warehouse and build Grafana dashboards that mirror our Terraform workspace structure — production, staging, and per-team sandboxes. When a team sees its sandbox costs doubled after a change to retain 14 days of logs instead of 3, the feedback is immediate and concrete.

Building Team-Level Dashboards

The decision between showback and chargeback is cultural, not technical. Chargeback, where costs are actually billed back to a team budget, creates strong incentives but can lead to perverse behavior if teams start under-provisioning critical shared services to save their own budget. We started with showback: dashboards are visible, costs are attributed, but no money moves. That was enough to drive a 22% reduction in three months because the visibility alone prompted cleanup of idle resources. Now we are moving toward chargeback for our larger platform teams, with guardrails that prevent optimization from compromising reliability budgets like SLO error budgets.

Automating Waste Detection With Policy as Code and Scheduled Jobs

Even with good hygiene, waste accumulates. People create an EBS volume for debugging and forget it. A feature branch environment is spun up for a demo and never torn down. A NAT Gateway sits idle in a VPC that has not had traffic in months. Manual reviews will not catch this consistently; you need automated detection that runs on a schedule and creates actionable tickets or, where safe, takes automatic action.

We run a nightly job that scans for common waste signals: unattached volumes, unattached Elastic IPs, idle load balancers with zero healthy hosts, old EBS snapshots, and non-running instances that have been stopped for more than 30 days. For Kubernetes, we scan for PersistentVolumeClaims not bound to a pod and LoadBalancer services with no endpoints. Results are posted to Slack and, for high-confidence waste like volumes unattached for more than 7 days, we open a Jira ticket assigned to the team tag. Low-risk cleanup, like deleting untagged Elastic IPs that have been unassociated for 30 days, happens automatically after a notification period.

Integrating this with your IaC workflow matters. If you simply delete a resource manually that is still declared in Terraform, your next terraform apply will recreate it. So our waste detector checks state first — if the resource is managed by Terraform, it flags the Terraform code location rather than deleting it directly, so the fix happens in code. This keeps your state and your reality aligned. For resources that are intentionally unmanaged, the automation can act directly. The distinction between managed and unmanaged waste is something I did not appreciate until we had an automated cleanup recreate 20 volumes that were correctly deleted manually but still declared in a forgotten workspace.

This pairs naturally with declarative deployment patterns. If you are using GitOps for Kubernetes, your waste detection can also reconcile declared versus actual resources in the cluster, a topic covered well in GitOps with ArgoCD and Flux: Declarative Kubernetes Deployment. When your desired state is fully declared in Git, identifying orphaned resources becomes a diff problem, not a hunting expedition.

EC2 Pricing Model Discount vs On-Demand Commitment Interruption Risk Ideal Workload Profile
On-Demand Baseline (0%) None None Short-lived, unpredictable, or production workloads that cannot tolerate interruption
Spot Instances 60-90% None High — 2-minute warning Stateless web tiers, CI/CD workers, batch jobs, fault-tolerant microservices
Reserved Instances (Standard 1yr) ~35-40% 1 or 3 years, capacity reservation None Steady-state baselines like databases and always-on services
Savings Plans (Compute) ~30-35% (1yr Compute) 1 or 3 years, flexible across instance family/region None Variable but predictable compute across many services

Choosing between Savings Plans and Reserved Instances often comes down to flexibility. Savings Plans apply across instance families, regions, and even Lambda and Fargate, while Standard RIs give you capacity reservations in a specific AZ. In my experience, most teams over-commit to RIs early and then struggle when their architecture shifts. We now cover our stable baseline with a 1-year Compute Savings Plan and handle peaks with spot, leaving on-demand only for the small remainder that cannot tolerate interruption or commitment.

Frequently Asked Questions

How long should I observe metrics before rightsizing a production workload?

For steady-state services, observe at least one full business cycle, typically 14 to 30 days, including any batch windows or end-of-month spikes. For seasonal workloads, you need longer — I have seen teams downsize based on a quiet August only to get caught by Black Friday traffic. Capture p95 and p99 utilization, not just averages, and always cross-reference CPU with memory and I/O. If you run Kubernetes, check pod resource requests and actual usage from Prometheus over the same window before adjusting node pool sizes.

Can I run stateful services or databases on spot instances?

Generally, no. Databases that store state locally should remain on on-demand or reserved capacity. The exception is if you have engineered for spot interruption — for example, a replicated database like Elasticsearch or CockroachDB where loss of a single node does not cause data loss and the cluster can rebalance quickly. Even then, keep a core of on-demand nodes for quorum. A safer pattern is to keep the data plane on reserved capacity and run the stateless query or ingest tiers on spot.

What is the difference between rightsizing and autoscaling, and do I need both?

Rightsizing sets the correct size for a single instance or node — the instance type, memory, and disk. Autoscaling adjusts the number of instances in response to demand. You need both. Rightsizing without autoscaling leaves you over-provisioned during off-peak hours. Autoscaling without rightsizing means you are scaling the wrong size horizontally, paying more per unit of capacity than necessary. Start with rightsizing your instance family, then implement autoscaling on top of the optimized size.

How do we handle Terraform state when cost optimization changes require replacing resources?

Some rightsizing changes, like changing an EC2 instance type, can be done in place with a short interruption. Others, like switching from gp2 to gp3 or changing RDS instance classes, may require replacement depending on your provider configuration and lifecycle blocks. Always check terraform plan for forced replacement, use create_before_destroy where appropriate to avoid downtime, and ensure your remote state backend is locked during the apply. Test the change in a staging workspace first, because a replacement that drops and recreates a stateful resource without a snapshot can cause data loss.

Related Articles

References & Standards: Kubernetes Documentation · Docker Documentation · Terraform Documentation