DEV Community

Ayi NEDJIMI
Ayi NEDJIMI

Posted on

Building a cost-aware architecture on AWS/GCP without a dedicated team

Cloud bills have a way of growing quietly until they explode. You deploy a few new services, forget to clean up a test environment, and three months later someone from finance sends you a screenshot of a $12,000 AWS bill. Without a dedicated FinOps team — which most engineering teams do not have — cost awareness has to be built into the architecture itself.

This article covers practical patterns you can implement today to keep your AWS or GCP spending visible, predictable, and under control.

The usual suspects

Before adding tooling, it helps to know where money typically leaks:

  • Idle compute: EC2 or GCE instances left running after a load test or a cancelled project
  • Unattached storage: EBS volumes, persistent disks, and snapshots that outlive their instances
  • Data transfer costs: inter-region traffic, NAT gateway charges, and accidental public egress
  • Over-provisioned instances: a t3.xlarge doing the work of a t3.small

The common thread: none of these require a production incident to notice. They require visibility.

Start with automated cost reporting

The first step is making costs visible to the team that creates them. AWS Cost Explorer has an API; GCP has the Cloud Billing API. Here is a minimal Python script that pulls daily spend per service and sends a Slack-formatted summary:

import boto3
from datetime import date, timedelta

def get_daily_costs_by_service():
    client = boto3.client("ce", region_name="us-east-1")
    today = date.today().isoformat()
    yesterday = (date.today() - timedelta(days=1)).isoformat()

    response = client.get_cost_and_usage(
        TimePeriod={"Start": yesterday, "End": today},
        Granularity="DAILY",
        Metrics=["UnblendedCost"],
        GroupBy=[{"Type": "DIMENSION", "Key": "SERVICE"}],
    )

    results = []
    for group in response["ResultsByTime"][0]["Groups"]:
        service = group["Keys"][0]
        amount = float(group["Metrics"]["UnblendedCost"]["Amount"])
        if amount > 0.5:  # skip noise below 50 cents
            results.append((service, round(amount, 2)))

    return sorted(results, key=lambda x: x[1], reverse=True)

if __name__ == "__main__":
    costs = get_daily_costs_by_service()
    for service, cost in costs:
        print(f"  {service}: ${cost}")
Enter fullscreen mode Exit fullscreen mode

Run this as a daily cron job and pipe the output to a Slack webhook or email. It takes about 20 minutes to set up and immediately gives your team a habit of looking at costs.

Enforce tagging at the infrastructure level

Cost reports are only useful if you can tell which team or project owns the spend. That requires consistent resource tagging — and consistent tagging requires enforcement.

In AWS, Service Control Policies (SCPs) can deny resource creation if mandatory tags are missing. Here is a minimal SCP that blocks EC2 and RDS instance creation without a tag:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "RequireProjectTag",
      "Effect": "Deny",
      "Action": [
        "ec2:RunInstances",
        "rds:CreateDBInstance"
      ],
      "Resource": "*",
      "Condition": {
        "Null": {
          "aws:RequestTag/project": "true"
        }
      }
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode

Apply this at the organizational unit level and your team will never again wonder which service owns a cluster of mystery instances.

On GCP, the equivalent is Organization Policy constraints combined with label enforcement via policy libraries.

Detect and kill idle resources automatically

Visibility and tagging catch new waste. You also need to handle the backlog: resources that exist but should not. This Python script uses boto3 to identify EC2 instances with average CPU below 5% over the last 14 days:

import boto3
from datetime import datetime, timedelta, timezone

def find_idle_instances(threshold_pct=5.0):
    ec2 = boto3.client("ec2", region_name="eu-west-1")
    cw = boto3.client("cloudwatch", region_name="eu-west-1")

    instances = ec2.describe_instances(
        Filters=[{"Name": "instance-state-name", "Values": ["running"]}]
    )

    idle = []
    end = datetime.now(timezone.utc)
    start = end - timedelta(days=14)

    for reservation in instances["Reservations"]:
        for inst in reservation["Instances"]:
            iid = inst["InstanceId"]
            stats = cw.get_metric_statistics(
                Namespace="AWS/EC2",
                MetricName="CPUUtilization",
                Dimensions=[{"Name": "InstanceId", "Value": iid}],
                StartTime=start,
                EndTime=end,
                Period=86400,
                Statistics=["Average"],
            )
            if not stats["Datapoints"]:
                idle.append((iid, "no data"))
                continue
            avg_cpu = sum(d["Average"] for d in stats["Datapoints"]) / len(stats["Datapoints"])
            if avg_cpu < threshold_pct:
                idle.append((iid, f"{avg_cpu:.1f}% avg CPU"))

    return idle

if __name__ == "__main__":
    for iid, reason in find_idle_instances():
        print(f"  Candidate for shutdown: {iid} — {reason}")
Enter fullscreen mode Exit fullscreen mode

Do not auto-terminate based on CPU alone — disk I/O and network activity matter too. Use this as an alert, not an executor. The engineer who owns the tag gets a weekly digest of their idle resources and decides what to shut down.

Budget alerts as a safety net

All of the above is proactive. Budget alerts are your reactive backstop. Both AWS Budgets and GCP Budget Alerts let you set thresholds on actual or forecasted spend, with notifications to email or a webhook.

Set three tiers: 80%, 100%, and 120% of your monthly budget. The 80% alert is a signal to review; the 100% alert is a stop-the-line conversation; the 120% alert means something automated is spending money unexpectedly. That last one is the one that saves you from infrastructure runaway bugs.

For teams running security-sensitive workloads, the same infrastructure governance mindset applies to your hardening posture — free architecture and security checklists can help you apply the same systematic approach to both cost and security controls.

The takeaway

You do not need a dedicated FinOps team to avoid cloud cost surprises. You need three things working together: visibility (daily cost reports per service), attribution (enforced resource tags), and idle detection (automated weekly scans).

None of these require significant engineering effort to set up. The harder part is building the habit — making cost a first-class metric alongside latency and error rate. Once your team checks the daily cost digest the same way they check the deployment dashboard, the surprises stop.


I run AYI NEDJIMI Consultants, a cybersecurity consulting firm. We publish free security hardening checklists — PDF and Excel.

Top comments (0)