DEV Community

Cover image for Building a FinOps AI Agent for AWS: Predict, Analyze, and Optimize Cloud Spending
Muhammad Umair Ashraf
Muhammad Umair Ashraf

Posted on

Building a FinOps AI Agent for AWS: Predict, Analyze, and Optimize Cloud Spending

What if your AWS bill could explain itself?

Imagine opening your AWS billing dashboard and discovering that your monthly spending has increased by 40%.

EC2 costs are rising. Data transfer charges look unusual. Your development environment is consuming more resources than expected.

You open AWS Cost Explorer, check CloudWatch, investigate resource utilization, and compare multiple accounts.

Hours later, you finally discover the reason.

Now imagine asking an AI agent:

"Why did my AWS spending increase, what will my bill look like next month, and how can I reduce costs without affecting production?"

Instead of manually investigating multiple dashboards, the agent analyzes spending, identifies unusual patterns, investigates potential causes, forecasts future costs, and recommends optimization opportunities.

That's the idea behind building a FinOps AI Agent for AWS.

In this article, we'll explore an AWS-native architecture using Amazon Bedrock, AWS Cost Explorer, Cost Anomaly Detection, Cost Optimization Hub, Compute Optimizer, Lambda, EventBridge, and Amazon S3.

1. What Is a FinOps AI Agent?

A FinOps AI Agent is an intelligent assistant that helps organizations understand, predict, and optimize cloud spending.

Traditional monitoring tells us:

"Your EC2 spending increased by 25%."

An AI-powered FinOps agent should explain:

"EC2 spending increased because additional instances were launched in the development account. Several instances show consistently low utilization. Review their configurations and consider scheduled shutdown policies."

The difference is that the agent connects financial information with operational context.

Its main responsibilities include:

  • Analyzing AWS spending across accounts, services, and Regions.
  • Detecting unexpected cost increases.
  • Investigating potential cost drivers.
  • Forecasting future cloud expenditure.
  • Identifying optimization opportunities.
  • Generating reports for engineering and finance teams.
  • Supporting approved cost optimization workflows.

2. AWS Architecture

The architecture combines AWS-native financial intelligence services with an AI reasoning layer.

High-level architecture

flowchart TD
    A["AWS Accounts and Workloads"] --> B["AWS Cost Explorer"]
    A --> C["Cost Anomaly Detection"]
    A --> D["Compute Optimizer"]
    A --> E["Cost Optimization Hub"]
    A --> F["CloudTrail"]

    B --> G["Cost Intelligence Layer"]
    D --> G
    E --> G

    C --> H["Amazon EventBridge"]
    H --> I["AWS Lambda"]

    G --> J["AWS Lambda Tools"]
    I --> K["Amazon Bedrock"]
    J --> K

    K --> L["FinOps AI Agent"]

    L --> M["Cost Analysis"]
    L --> N["Cost Forecasting"]
    L --> O["Optimization Recommendations"]
    L --> P["Conversational Interface"]

    M --> Q["Amazon S3 Reports"]
    N --> Q
    O --> R["Human Approval"]

    R --> S["Controlled AWS Actions"]

    L --> T["Amazon SNS"]
    L --> U["Amazon CloudWatch"]

Key AWS services

AWS Service Responsibility
Amazon Bedrock AI reasoning and conversational interaction
AWS Cost Explorer Historical cost and usage analysis
Cost Anomaly Detection Detect unusual spending
AWS Budgets Monitor financial thresholds
Cost Optimization Hub Consolidated optimization opportunities
AWS Compute Optimizer Resource optimization recommendations
AWS CloudTrail Infrastructure change investigation
Amazon EventBridge Event-driven workflows
AWS Lambda Controlled agent tools and processing
Amazon S3 Historical reports and cost data
Amazon Athena SQL-based cost analysis
AWS Glue Data cataloging
Amazon SNS Alerts and notifications
Amazon CloudWatch Operational monitoring

3. Workflow One: Intelligent Cost Analysis

The first responsibility of the agent is understanding where the money is going.

A user might ask:

"Show me our AWS spending for the last 30 days and identify the three most expensive services."

The agent calls a controlled Lambda function that retrieves cost data from AWS Cost Explorer.

It can group spending by service, account, Region, or other supported dimensions.

Example response:

AWS COST ANALYSIS

Period: Last 30 Days

Total Spending: $8,450

Top Services:

Amazon EC2       $3,200
Amazon RDS       $1,850
Amazon S3        $1,100
Other Services   $2,300

Key Observation:

EC2 represents approximately 38%
of total AWS spending.

Recommended Investigation:

Review EC2 utilization, instance
families, and non-production workloads.
Enter fullscreen mode Exit fullscreen mode

These figures are illustrative.

The agent should also explain which cost metric it uses, such as unblended cost or amortized cost, to ensure meaningful comparisons.

4. Workflow Two: AI-Powered Cost Anomaly Investigation

Unexpected spending is one of the biggest cloud financial challenges.

Imagine an application that normally generates $120 in daily AWS costs.

Suddenly, daily spending increases to $260.

AWS Cost Anomaly Detection identifies the unusual spending pattern and sends an event to Amazon EventBridge.

EventBridge triggers a Lambda investigation workflow.

sequenceDiagram
    participant CAD as Cost Anomaly Detection
    participant EB as EventBridge
    participant L as Lambda
    participant CE as Cost Explorer
    participant CT as CloudTrail
    participant AI as Amazon Bedrock
    participant SNS as Amazon SNS

    CAD->>EB: Anomaly detected
    EB->>L: Trigger investigation
    L->>CE: Retrieve cost breakdown
    L->>CT: Retrieve relevant activity
    CE-->>L: Cost information
    CT-->>L: Infrastructure events
    L->>AI: Submit investigation context
    AI-->>L: Generate findings
    L->>SNS: Send investigation report

The agent investigates which services experienced increased spending, which accounts and Regions were affected, which usage types contributed to the increase, and whether relevant infrastructure changes occurred.

Example report:

COST ANOMALY INVESTIGATION

Detected Increase: 116%

Affected Service: Amazon EC2
Account: Development
Region: us-east-1

Potential Contributors:

- Additional EC2 instances launched.
- Increased compute consumption.
- Development workloads running overnight.

Recommended Actions:

- Review newly launched instances.
- Check CPU and memory utilization.
- Review development shutdown policies.
- Validate workloads with their owners.

Status: Awaiting Engineering Review
Enter fullscreen mode Exit fullscreen mode

An anomaly is a signal, not proof of a root cause. The agent must distinguish confirmed findings from potential explanations.

5. Workflow Three: Predict Future AWS Spending

Knowing yesterday's spending is useful.

Knowing what you might spend next month is even more valuable.

The agent can retrieve AWS Cost Explorer forecasts to estimate future expenditure.

Example:

CLOUD SPENDING FORECAST

Current Monthly Spending: $8,450

Forecast for Next Month: $10,200

Expected Increase: 20.7%

Potential Cost Drivers:

- Increasing EC2 usage.
- Growing database consumption.
- Higher data transfer.
- Increased storage usage.

Recommended Action:

Review projected growth with
engineering and finance teams.
Enter fullscreen mode Exit fullscreen mode

These figures are illustrative.

The forecasting workflow can combine historical cost data, AWS-generated forecasts, workload growth assumptions, seasonal usage patterns, and planned infrastructure deployments.

This helps teams understand not only how much they might spend but also why their spending could increase.

Forecasts are estimates, not guaranteed bills. The agent should communicate uncertainty and avoid presenting predictions as facts.

6. Workflow Four: Intelligent Resource Optimization

This is where the FinOps agent becomes especially useful.

AWS Cost Optimization Hub consolidates optimization opportunities, while AWS Compute Optimizer provides resource-level recommendations for supported workloads.

The agent can investigate:

EC2 Rightsizing

Identify instances that may be larger than their workloads require.

Idle Resources

Find resources that may no longer be needed.

EBS Optimization

Review unattached volumes and suitable storage configuration changes.

Amazon RDS

Evaluate available database optimization recommendations.

Amazon S3

Review lifecycle policies and suitable storage classes based on access patterns.

NAT Gateway

Investigate data processing charges and unnecessary network traffic.

Savings Plans and Reserved Instances

Evaluate purchasing commitments using actual utilization, coverage, and expected workload stability.

Example recommendation:

OPTIMIZATION OPPORTUNITY

Resource: i-0abc123example

Current Configuration: m5.2xlarge

Recommended Configuration: m5.xlarge

Estimated Monthly Savings: $85

Estimated Annual Savings: $1,020

Risk Assessment:

Validate CPU, memory, network,
and application requirements.

Status: Approval Required
Enter fullscreen mode Exit fullscreen mode

The resource and savings figures are hypothetical.

The agent should retrieve actual recommendations from AWS services instead of inventing savings estimates.

It should also avoid double-counting overlapping optimization opportunities.

7. Building the Agent with Amazon Bedrock

Amazon Bedrock provides the reasoning layer for the FinOps assistant.

The agent should not receive unrestricted AWS access.

Instead, expose specific functions through AWS Lambda.

Suggested tools:

Tool Responsibility
get_cost_summary Retrieve cost breakdowns
get_cost_forecast Retrieve future cost estimates
get_cost_anomalies Retrieve anomaly information
get_optimization_recommendations Retrieve savings opportunities
get_resource_metrics Retrieve utilization metrics
get_cloudtrail_activity Investigate infrastructure changes
generate_finops_report Generate cost reports
create_approval_request Submit recommendations for review

Each tool should have a clearly defined input schema and output format.

Example: AWS Cost Explorer Lambda function

The following simplified Python example retrieves daily spending grouped by service.

import boto3
import json
from datetime import date, timedelta

ce = boto3.client("ce", region_name="us-east-1")

def lambda_handler(event, context):

    end_date = date.today()
    start_date = end_date - timedelta(days=30)

    response = ce.get_cost_and_usage(
        TimePeriod={
            "Start": start_date.isoformat(),
            "End": end_date.isoformat()
        },
        Granularity="DAILY",
        Metrics=["UnblendedCost"],
        GroupBy=[
            {
                "Type": "DIMENSION",
                "Key": "SERVICE"
            }
        ]
    )

    results = []

    for period in response["ResultsByTime"]:

        for group in period["Groups"]:

            results.append({
                "date": period["TimePeriod"]["Start"],
                "service": group["Keys"][0],
                "cost": float(
                    group["Metrics"]["UnblendedCost"]["Amount"]
                ),
                "unit": group["Metrics"]["UnblendedCost"]["Unit"]
            })

    return {
        "statusCode": 200,
        "body": json.dumps(results)
    }
Enter fullscreen mode Exit fullscreen mode

This is a starting example, not a complete production implementation.

A production implementation should validate input parameters, enforce account-level authorization, handle API pagination and throttling, manage errors, and use an appropriate cost metric.

Example agent instructions

You are an AWS FinOps AI Agent.

Your responsibilities:

1. Analyze AWS cost and usage data.
2. Identify unusual spending patterns.
3. Explain potential cost drivers.
4. Retrieve optimization recommendations.
5. Forecast future spending.
6. Generate FinOps reports.

Rules:

- Use authorized AWS tools for cost data.
- Never invent spending figures.
- Distinguish estimates from actual costs.
- Explain the evidence behind recommendations.
- Consider application performance and availability.
- Never modify infrastructure without approval.
- Protect sensitive account information.
- Escalate uncertain or high-risk decisions.
Enter fullscreen mode Exit fullscreen mode

The key principle is that the AI interprets the data, while AWS services remain the source of truth.

8. Building a Historical Cost Intelligence Layer

Organizations managing multiple AWS accounts may need deeper analysis than standard API queries provide.

AWS Data Exports can deliver cost and usage datasets to Amazon S3.

AWS Glue can catalog the data, and Amazon Athena can query it using SQL.

flowchart LR
    A["AWS Cost and Usage Data"] --> B["AWS Data Exports"]
    B --> C["Amazon S3"]
    C --> D["AWS Glue Data Catalog"]
    D --> E["Amazon Athena"]
    E --> F["FinOps Lambda Tools"]
    F --> G["Amazon Bedrock"]
    G --> H["AI Cost Insights"]

For example, a SQL query could aggregate spending by AWS service and account:

SELECT
    line_item_product_code,
    line_item_usage_account_id,
    SUM(line_item_unblended_cost) AS total_cost
FROM finops_cost_data
WHERE year = '2026'
  AND month = '11'
GROUP BY
    line_item_product_code,
    line_item_usage_account_id
ORDER BY total_cost DESC;
Enter fullscreen mode Exit fullscreen mode

The table and column names are illustrative and must match the exported dataset schema.

This architecture enables application-level cost attribution, team-level spending analysis, monthly comparisons, cost per transaction, and chargeback or showback reporting.

9. Human Approval and Safe Optimization

A FinOps agent should not automatically make every change it recommends.

An EC2 instance with low CPU utilization might still be handling important workloads during specific business hours.

A production database might require additional capacity for seasonal traffic.

A purchasing commitment might create a financial obligation that is unsuitable for an unpredictable workload.

A safer workflow is:

flowchart TD
    A["AI Identifies Opportunity"] --> B["Collect Supporting Metrics"]
    B --> C["Estimate Savings and Risk"]
    C --> D["Generate Recommendation"]
    D --> E["Human Approval"]
    E -->|Approved| F["Execute Controlled Change"]
    E -->|Rejected| G["Record Decision"]
    F --> H["Validate Application Health"]
    H --> I["Measure Actual Cost Impact"]

Use separate IAM roles for analysis and infrastructure changes.

Require approval for production rightsizing, resource deletion, and financial commitments.

Record every action and maintain an appropriate rollback strategy.

10. Security and Governance

Financial data can reveal business priorities and infrastructure architecture.

A production FinOps agent should follow strong security controls.

IAM Least Privilege: Give each Lambda function only the permissions needed for its task.

Separate Read and Write Roles: Keep cost analysis tools separate from infrastructure modification tools.

Account-Level Authorization: Validate which AWS accounts and cost centers a user can access.

Encryption: Protect exported cost data and generated reports.

Auditability: Track tool calls, approval decisions, and infrastructure changes.

Prompt Injection Protection: Treat retrieved resource descriptions, tags, and user input as untrusted data. Validate all tool parameters.

Human Oversight: Never allow an AI-generated recommendation alone to authorize a high-impact change.

11. Measuring FinOps Success

The success of the agent should be measured through business outcomes.

KPI What It Measures
Monthly AWS Spend Total cloud expenditure
Cost Anomaly Detection Time Time to identify and investigate unusual spending
Forecast Accuracy Difference between forecast and actual spending
Optimization Adoption Rate Recommendations implemented
Realized Savings Verified reduction in actual spending
Cost per Transaction Infrastructure cost per business transaction
Budget Variance Difference between actual and planned expenditure

One metric deserves special attention: realized savings.

An agent might identify $5,000 in potential monthly savings. That does not mean the organization has actually saved $5,000.

Savings become real only after implementation and financial validation against an appropriate baseline.

12. Custom FinOps Agent vs. AWS FinOps Agent

AWS now offers the AWS FinOps Agent in preview, powered by Amazon Bedrock.

It supports anomaly investigations, natural-language cost inquiries, recurring reports, and optimization recommendations.

For many organizations, this managed capability is an excellent starting point.

A custom agent becomes useful when you need organization-specific approval workflows, internal integrations, custom cost allocation, specialized forecasting, or additional governance controls.

My recommendation is to evaluate the managed AWS FinOps Agent first and build custom capabilities where they provide additional business value.

13. What's Next?

The architecture can evolve into a broader cloud financial intelligence platform.

Imagine integrating FinOps checks into CI/CD pipelines to estimate infrastructure costs before deployment.

Imagine analyzing Amazon EKS workloads to understand Kubernetes resource costs.

Imagine calculating the infrastructure cost of each customer transaction.

Imagine forecasting the financial impact of a new AI workload before launching it.

These capabilities can turn FinOps from a monthly reporting activity into a continuous engineering practice.

Conclusion

Cloud spending is not just a finance problem.

It is an engineering, architecture, operational, and business problem.

By combining Amazon Bedrock with AWS Cost Explorer, Cost Anomaly Detection, AWS Budgets, Cost Optimization Hub, Compute Optimizer, Lambda, EventBridge, and Amazon S3, organizations can build an intelligent system that transforms cloud cost data into actionable decisions.

The objective is not an AI agent that blindly shuts down resources to save money.

It is an intelligent assistant that helps teams understand spending, predict future costs, and optimize infrastructure without compromising reliability or security.

The future of FinOps is not just monitoring cloud spending. It is predicting, explaining, and optimizing it before the bill becomes a surprise.

Official AWS References

AWS #FinOps #AmazonBedrock #GenerativeAI #CloudCostOptimization

Top comments (1)

Collapse
 
userxnom profile image
Abdullah Naseer •

Really strong write-up, Umair — the $120 to $260 a day anomaly example is the part that made this click for me, because that is exactly the shape of surprise that shows up overnight, and your line that an anomaly is a signal, not proof of a root cause, is the bit most agent demos skip.

One thing I would love to see you push further is the loop from recommendation to realized savings. You flag that $5,000 in potential monthly savings is not $5,000 saved until it is implemented and verified against a baseline — so how would you have the agent check back a month later and report whether the m5.2xlarge rightsizing actually delivered the saving it predicted? That verification step feels like the difference between a FinOps report and a FinOps agent.

And of your four "what's next" ideas, which would you build first — the CI/CD cost estimate before deploy, or cost per transaction? My instinct is the CI/CD one, since it catches spend before it exists, but I am curious what you would pick and why.