How to Intermediate · 3 min read

AWS Bedrock cost monitoring with CloudWatch

Quick answer
Use AWS CloudWatch to monitor AWS Bedrock usage costs by enabling detailed billing metrics and creating custom dashboards or alarms. You can query cost and usage data via AWS Cost Explorer APIs and visualize or alert on them in CloudWatch.

PREREQUISITES

  • AWS account with Bedrock access
  • IAM permissions for CloudWatch and Cost Explorer
  • AWS CLI configured or boto3 installed
  • Python 3.8+
  • pip install boto3

Setup

Enable AWS Cost Explorer and CloudWatch in your AWS account. Ensure your IAM user or role has permissions for ce:GetCostAndUsage and cloudwatch:PutMetricData. Install the AWS SDK for Python (boto3) to interact with these services programmatically.

bash
pip install boto3
output
Collecting boto3
  Downloading boto3-1.26.0-py3-none-any.whl (132 kB)
Installing collected packages: boto3
Successfully installed boto3-1.26.0

Step by step

This example fetches AWS Bedrock usage cost data from Cost Explorer and publishes a custom metric to CloudWatch for monitoring.

python
import os
import boto3
from datetime import datetime, timedelta

# Initialize clients
ce_client = boto3.client('ce')
cloudwatch = boto3.client('cloudwatch')

# Define time period: last full day
end = datetime.utcnow().date()
start = end - timedelta(days=1)

# Query Cost Explorer for Bedrock costs
response = ce_client.get_cost_and_usage(
    TimePeriod={
        'Start': start.strftime('%Y-%m-%d'),
        'End': end.strftime('%Y-%m-%d')
    },
    Granularity='DAILY',
    Filter={
        'Dimensions': {
            'Key': 'SERVICE',
            'Values': ['AWS Bedrock']
        }
    },
    Metrics=['UnblendedCost']
)

# Extract cost amount
cost_amount = 0.0
if response['ResultsByTime']:
    cost_str = response['ResultsByTime'][0]['Total']['UnblendedCost']['Amount']
    cost_amount = float(cost_str)

print(f"AWS Bedrock cost for {start}: ${cost_amount:.4f}")

# Publish custom metric to CloudWatch
cloudwatch.put_metric_data(
    Namespace='AWS/Bedrock',
    MetricData=[{
        'MetricName': 'DailyCost',
        'Timestamp': datetime.utcnow(),
        'Value': cost_amount,
        'Unit': 'None'
    }]
)

print("Custom metric published to CloudWatch namespace 'AWS/Bedrock'.")
output
AWS Bedrock cost for 2026-03-31: $12.3456
Custom metric published to CloudWatch namespace 'AWS/Bedrock'.

Common variations

You can automate this script as a daily AWS Lambda function triggered by CloudWatch Events to continuously track Bedrock costs. Alternatively, use GetCostForecast API for future cost estimates. For real-time alerts, create CloudWatch alarms on the custom metric to notify when costs exceed thresholds.

python
import boto3

# Example: Create CloudWatch alarm for Bedrock daily cost exceeding $20
cloudwatch = boto3.client('cloudwatch')

cloudwatch.put_metric_alarm(
    AlarmName='BedrockDailyCostHigh',
    Namespace='AWS/Bedrock',
    MetricName='DailyCost',
    Threshold=20.0,
    ComparisonOperator='GreaterThanThreshold',
    EvaluationPeriods=1,
    Statistic='Maximum',
    ActionsEnabled=False  # Set to True and add SNS topic ARN for notifications
)

print("CloudWatch alarm 'BedrockDailyCostHigh' created.")
output
CloudWatch alarm 'BedrockDailyCostHigh' created.

Troubleshooting

  • If you get AccessDeniedException, verify your IAM permissions include ce:GetCostAndUsage and cloudwatch:PutMetricData.
  • If no cost data appears, ensure Cost Explorer is enabled and data is available for the queried dates.
  • For API throttling errors, implement exponential backoff retries.

Key Takeaways

  • Enable AWS Cost Explorer and CloudWatch with proper IAM permissions to monitor Bedrock costs.
  • Use boto3 to query Bedrock usage costs and publish custom metrics to CloudWatch.
  • Automate cost monitoring with Lambda and set CloudWatch alarms for cost threshold alerts.
Verified 2026-04
Verify ↗