We are building a backend cost observability dashboard. The goal is to map compute, storage, and egress costs to services and customers.
We need to design a system that can track and report costs at a granular level (per service, per customer) and provide a dashboard for visualization.
Steps:
-
Data Collection:
- We need to collect cost data from cloud providers (AWS, GCP, Azure, etc.) or from our own infrastructure if we are managing our own data centers.
- We can use cloud provider APIs (e.g., AWS Cost Explorer, Google Cloud Billing API) to get cost breakdowns by service, but we need to map these to our own services and customers.
-
Cost Allocation Model:
- We need a way to assign costs to services and then to customers. This might involve:
a. Tagging resources (with service name, customer id, environment, etc.) so that we can split costs by tags.
b. Using a hierarchical model: costs are first allocated to services (which might be shared across customers) and then services are split among customers (e.g., by usage, by fixed split, etc.)
-
Data Processing:
- We need to ingest the raw cost data, enrich it with our tagging and allocation model, and then aggregate by service and customer.
-
Storage:
- We need to store the processed cost data for historical analysis and dashboarding.
-
Dashboard:
- We need a frontend dashboard that can show:
- Total cost over time (by service, by customer)
- Breakdown of costs (compute, storage, egress) per service and customer.
- Comparative views (e.g., this month vs last month, by customer, etc.)
- We might use a BI tool (like Grafana, Tableau, or a custom solution) that can query our stored data.
-
Real-time vs. Batch:
- Cost data is typically updated daily (from cloud providers) so near real-time (daily) is acceptable.
Proposed Architecture:
-
Data Collection:
- Use cloud provider APIs to fetch cost data on a daily basis (or more frequently if needed). We can use AWS Cost Explorer for AWS, and similar for others.
- We can set up a scheduled job (e.g., Airflow, cron) to run daily and fetch the data.
-
Data Processing (ETL):
- We have raw cost data from cloud providers, which includes:
- Service (e.g., EC2, S3, etc.)
- Resource IDs, tags, etc.
- Cost (in USD or other currency)
- Time period (daily, hourly, etc.)
- We need to map these to our internal services and customers. We can have a mapping table (or service) that maps cloud tags (or resource names) to our service and customer.
- Example:
- AWS resource tagged with
service: auth-service and customer: acme-corp -> we allocate to service "auth" and customer "acme".
- If a resource doesn't have a customer tag, it might be shared (e.g., infrastructure). We need to split shared costs (e.g., by customer usage or by fixed percentages).
-
Storage:
-
We can store the processed data in a relational database (PostgreSQL) or a time-series database (if we want to focus on time series) or a data warehouse (if the volume is large).
-
The table could look like:
Table: daily_costs
- date (date)
- service_id (foreign key to services table)
- customer_id (foreign key to customers table)
- cost_type (enum: compute, storage, egress, or maybe we have separate columns)
- amount (numeric)
- cloud_provider (optional: if we have multiple)
- cloud_service (optional: the raw cloud service name)
But note: we might want to break down by cost type (compute, storage, egress). However, cloud providers break down by their own services. We might need to map cloud services to our cost types.
Alternatively, we can have:
Table: daily_cost_breakdown
- date
- service_id
- customer_id
- compute_cost
- storage_cost
- egress_cost
But this limits the cost types we track. We might want to track more types in the future.
Another alternative: have a table with:
- date
- service_id
- customer_id
- cost_category (string, e.g., 'compute', 'storage', 'egress', or even more granular like 'ec2', 's3')
- amount
Then we can aggregate by category.
However, we must note that cloud providers might not break down by exactly our categories. For example, AWS RDS might have both compute and storage. We need to split RDS cost into compute and storage? Or we can define our own mapping.
It might be easier to start with the cloud's service breakdown and then map each cloud service to our cost category.
Example mapping:
AWS EC2 -> compute
AWS RDS (the instance part) -> compute
AWS RDS (storage) -> storage
AWS S3 -> storage
AWS Data Transfer -> egress
... etc.
We can create a mapping table:
cloud_provider | cloud_service | cost_category
Then when we process the raw cost data, we assign a cost_category for each line.
Then our daily_cost_breakdown table can be:
date, service_id, customer_id, cost_category, amount
Then we can pivot in the dashboard to show compute, storage, egress.
-
Processing Steps:
a. Fetch raw cost data for a given date (or date range) from cloud providers.
b. For each line item in the raw data:
- Extract the tags (or other metadata) to get service and customer.
- If no customer tag, then we mark as shared (customer_id = NULL or a special shared customer id?).
- Map the cloud service to a cost category (compute, storage, egress, etc.) using our mapping table.
c. Aggregate by date, service_id, customer_id, cost_category -> sum(amount)
But wait: we might have shared costs that need to be allocated to multiple customers. How do we handle that?
Option 1: In the raw data, we have two types of costs:
- Direct costs: tagged with a customer -> allocated to that customer.
- Shared costs: not tagged with a customer -> we split these among all customers (or by some rule).
How to split shared costs?
We can have a separate process that, after aggregating direct costs, takes the shared costs and splits them by a predefined allocation key (e.g., by customer's usage of the service, or equally, or by some other metric).
But note: the raw cost data from cloud providers might already have the cost broken down by resource. We are tagging resources. So if a resource is shared (like a shared database server), we tag it with multiple customers? That's not typical.
Alternatively, we can tag shared resources with a service (e.g., "shared-infra") and then split the cost of that service among customers by a rule (e.g., by the proportion of their direct usage of that service?).
This is complex. We might need to design an allocation model.
Simplified approach for now:
- All costs are either direct (tagged with a customer) or shared (not tagged with a customer).
- We create a "shared" bucket for each service (or for the whole account) and then split the shared costs equally among all customers? Or by the customer's proportion of total direct costs?
But note: the dashboard is for our internal teams and customers. We might have internal services that are not charged to customers, and customer-specific services.
Let's define:
- We have a list of customers (some might be internal, some external).
- We have a list of services (each service is owned by a team, and might be used by one or more customers).
We can have a table that maps services to customers (many-to-many). Then, for a shared service (a service that is used by multiple customers) we split the cost of that service by a rule.
But wait: the raw cost data is at the resource level. We tag resources with service and (optionally) customer. So if a service is shared, we might have resources that are tagged with the service but without a customer. Then we need to split the cost of those resources among the customers that use that service.
How do we know which customers use a shared service? We might have a separate table that lists the customers for each service (for shared services). For example:
-
Tables:
We need:
Table: customers
- id
- name
Table: services
- id
- name
Table: service_customer
- service_id
- customer_id
- allocation_weight (optional, default 1.0) -> if we want to split by weight.
Table: cloud_service_mapping
- cloud_provider (e.g., 'aws')
- cloud_service (e.g., 'AmazonEC2')
- cost_category (e.g., 'compute')
- service_id (optional: if we want to map cloud service to our service by default, but we are using tags for service so this might be used as fallback)
But note: we are using tags to get the service. So we don't need to map every cloud service to our service. We only need to map the cloud service to a cost_category.
Actually, we might have two mappings:
a. From (cloud_provider, cloud_service) to cost_category.
b. From tags to service_id and customer_id.
So we can have:
Table: cost_category_mapping
- cloud_provider
- cloud_service
- cost_category
And then we have a separate process that maps tags to service and customer.
But we also need to map a cloud service to a default service (if the tag is missing). We can have:
Table: default_service_mapping
- cloud_provider
- cloud_service
- service_id
So if a resource doesn't have a service tag, we use the default mapping to assign a service.
Similarly for customer? We might not have a default customer. So if a resource doesn't have a customer tag, it's shared.
-
Processing Flow:
For each raw cost line:
cloud_provider = ...
cloud_service = ...
amount = ...
tags = { ... }
cost_category = lookup in cost_category_mapping(cloud_provider, cloud_service)
service_id =
if tags contain 'service' and that service exists in our services table -> that service_id
else if there is a default_service_mapping for (cloud_provider, cloud_service) -> that service_id
else -> assign to a default 'unallocated' service (or skip?).
customer_id =
if tags contain 'customer' and that customer exists in our customers table -> that customer_id
else -> NULL (shared)
Then, if customer_id is not NULL, we record:
(date, service_id, customer_id, cost_category, amount) as direct cost.
If customer_id is NULL, we record:
(date, service_id, NULL, cost_category, amount) as shared cost.
After processing all lines:
We have two sets: direct_costs and shared_costs (by date, service_id, cost_category).
For each (date, service_id, cost_category) in shared_costs:
total_shared = sum(amount) for that group.
Get the list of customers for that service from service_customer table.
Let n = number of customers for that service.
For each customer in the list:
allocated_shared = total_shared / n (or by weight)
Then add to the customer's cost: (date, service_id, customer_id, cost_category, allocated_shared)
Then combine direct and allocated shared.
-
Storage:
We can store the final daily cost breakdown in a table:
daily_costs:
- date (date)
- service_id (integer, foreign key to services)
- customer_id (integer, foreign key to customers, nullable? but we are allocating shared so it should not be null in the final table)
- cost_category (string)
- amount (numeric)
But note: we might want to break down by cloud provider? We can add a column for cloud_provider if we want to see costs by cloud.
Alternatively, we can have:
daily_costs:
- date
- service_id
- customer_id
- cloud_provider (if we want to keep that dimension)
- cost_category
- amount
But then we are duplicating the service_id per cloud provider? Actually, a service might run on multiple cloud providers.
We might want to see total cost per service (across clouds) and also break down by cloud.
So let's keep cloud_provider as a dimension.
But note: the same service might be running on multiple clouds? Then we would have multiple rows for the same service and customer on the same day, but different cloud_provider.
That's acceptable.
-
Dashboard:
We need to query the daily_costs table and aggregate by:
- Time (day, week, month, etc.)
- Service
- Customer
- Cost category
We can use a SQL query or a BI tool that connects to the database.
Example queries:
Total cost per customer per month:
SELECT
customer_id,
DATE_TRUNC('month', date) as month,
SUM(amount) as total_cost
FROM daily_costs
GROUP BY customer_id, month
Cost breakdown by category for a customer in a month:
SELECT
customer_id,
DATE_TRUNC('month', date) as month,
cost_category,
SUM(amount) as cost
FROM daily_costs
WHERE customer_id = ?
GROUP BY customer_id, month, cost_category
We can also join with customers and services tables to get names.
-
Implementation:
We can build a Python application that:
- Runs daily (via Airflow or cron) to:
1. Fetch raw cost data from cloud providers (using boto3 for AWS, etc.)
2. Process the data as above.
3. Store the results in the database.
We can use a task queue (like Celery) if the processing is heavy, but for a single day it might be manageable.
Alternatively, we can use AWS Glue or Google Dataflow for processing if we are in the cloud.
But for simplicity, we can start with a Python script.
-
Dashboard:
We can use Grafana (which can connect to PostgreSQL) and create dashboards with the queries we need.
Alternatively, build a simple Flask/Django app with charts using Chart.js or similar.
But using a BI tool might be faster.
-
Additional Considerations:
- Data retention: how long do we keep daily data? We might want to aggregate older data (e.g., monthly) and delete daily to save space.
- Currency conversion: if we have multiple cloud providers in different currencies, we need to convert to a base currency. We can use a daily exchange rate table.
- Tags consistency: we must enforce tagging policies. We can have a process that checks for resources without required tags and alerts.
-
Summary of Tables:
customers: id, name, ...
services: id, name, ...
service_customer: service_id, customer_id, allocation_weight (default 1.0)
cost_category_mapping: cloud_provider, cloud_service, cost_category
default_service_mapping: cloud_provider, cloud_service, service_id
daily_costs: date, service_id, customer_id, cloud_provider, cost_category, amount
-
Example:
Raw AWS cost data:
Date: 2024-01-01
Service: AmazonEC2
Tags: service=auth, customer=acme
Cost: $100
Mapping:
cost_category_mapping: ('aws', 'AmazonEC2') -> 'compute'
So we get:
date: 2024-01-01
service_id: (lookup by tag 'auth' -> say 1)
customer_id: (lookup by tag 'acme' -> say 1)
cloud_provider: 'aws'
cost_category: 'compute'
amount: 100
Another line:
Date: 2024-01-01
Service: AmazonS3
Tags: service=storage, (no customer)
Cost: $50
Mapping:
cost_category_mapping: ('aws', 'AmazonS3') -> 'storage'
Then:
service_id: (lookup by tag 'storage' -> say 2)
customer_id: NULL
Then after processing shared costs for service_id=2:
Suppose service_storage (id=2) has customers: [acme (1), beta (2)]
Then we split $50 equally:
acme: $25
beta: $25
So we create two records:
(2024-01-01, 2, 1, 'aws', 'storage', 25)
(2024-01-01, 2, 2, 'aws', 'storage', 25)
-
Edge Cases:
-
A resource might have multiple customer tags? Then we need to split? But typically a resource is used by one customer. We can take the first or log an error.
-
A service might have no customers? Then it's an internal service and we don't split the cost to customers. We might want to track internal costs separately.
We can have a flag in services: is_internal. If is_internal, then even if there are shared costs, we don't allocate to customers. We just keep it as a cost for that service (with customer_id NULL?).
But our final table daily_costs has non-null customer_id? We said we allocate shared costs to customers. But for internal services, we might not want to allocate to customers.
So we can change:
In step 4, we only allocate shared costs to customers for services that are not internal.
For internal services, we keep the shared cost with customer_id NULL? But then our dashboard might not show it.
Alternatively, we can have a special customer for internal (like "internal") and then allocate the shared cost of internal services to that customer.
But then we are double counting? Because the internal service cost is already in the direct costs for that service (if it's used by internal teams) and then we allocate the shared part to internal.
Actually, we might have:
-
Direct costs for internal service: tagged with an internal customer (e.g., "engineering") -> then it's direct and goes to that customer.
-
Shared costs for internal service: resources without a customer tag, and the service is internal -> then we allocate to the internal customer (or multiple internal customers?).
It's getting complex.
Let's simplify:
We have two types of customers: external and internal.
We want to see:
- Cost per external customer (what we bill them)
- Cost per internal service (for our own accounting)
So we can:
In the service_customer table, we only list external customers for services that are external.
For internal services, we don't have any entries in service_customer.
Then, when we have a shared cost for an internal service, we don't allocate it to any customer (we leave customer_id NULL). Then we can query:
Total cost for internal services:
SELECT service_id, SUM(amount)
FROM daily_costs
WHERE customer_id IS NULL
GROUP BY service_id
But note: the direct costs for internal services are already with an internal customer? We might have tagged internal resources with an internal customer (like "engineering"). Then they are direct and we see them under that customer.
So we have two ways to track internal:
Option A: Tag internal resources with an internal customer (e.g., "engineering") and then they are direct. And for shared internal resources (without customer tag) we leave them unallocated (customer_id NULL). Then we can see:
- Engineering team cost: all costs for customer "engineering" (direct and allocated from shared internal? but we are not allocating shared internal to engineering because service_customer doesn't have engineering for internal services?).
This is inconsistent.
Option B: We treat internal services as having a special internal customer (e.g., "internal") and we include that customer in the service_customer table for internal services? Then we allocate shared costs to that internal customer.
But then we are allocating shared costs of internal services to the internal customer, which might be multiple teams? We might have multiple internal customers (engineering, product, etc.) and we want to split internal service costs among them.
So we might need to have:
service_customer for internal services: list of internal customers that use that internal service.
Then the same allocation model works.
So we can have:
Customers table includes both external and internal.
Then for an internal service, we list the internal teams that use it in service_customer.
Then the dashboard can filter by customer type (external vs internal) if we have a flag in customers.
-
Revised Tables:
customers:
id (PK)
name
is_external (boolean)
services:
id (PK)
name
service_customer:
service_id (FK to services)
customer_id (FK to customers)
allocation_weight (numeric, default 1.0) -- for weighted allocation
cost_category_mapping:
cloud_provider (string)
cloud_service (string)
cost_category (string)
default_service_mapping:
cloud_provider (string)
cloud_service (string)
service_id (FK to services)
daily_costs:
date (date)
service_id (FK to services)
customer_id (FK to customers)
cloud_provider (string) -- optional, but recommended
cost_category (string)
amount (numeric)
-
Implementation Steps:
Step 1: Set up the database with the above tables.
Step 2: Populate:
- customers (both internal and external)
- services
- service_customer (which customers use which services, and their weights)
- cost_category_mapping (for each cloud service we use, map to cost_category)
- default_service_mapping (for cloud services that don't have a tag, map to a default service)
Step 3: Write a script that:
- Fetches raw cost data for a given date and cloud provider.
- For each line item:
a. Get cost_category from cost_category_mapping.
b. Get service_id from tags (if present) or from default_service_mapping.
c. Get customer_id from tags (if present). If not, mark as shared (customer_id NULL).
d. If service_id is not found, assign to a default 'unallocated' service (we must have a service for unallocated).
- Group by (date, service_id, customer_id, cost_category, cloud_provider) and sum(amount) for direct costs.
- For shared costs (customer_id NULL), group by (date, service_id, cost_category, cloud_provider) and sum(amount).
- For each shared cost group:
- Get the list of customers for that service from service_customer.
- For each customer, allocate: (shared_amount / total_weight) * customer_weight, where total_weight = sum of allocation_weight for all customers of that service.
- Create records for each customer with the allocated amount.
- Combine direct and allocated shared records and insert into daily_costs.
Step 4: Schedule the script to run daily for each cloud provider.
Step 5: Set up a dashboard (Grafana or custom) that queries daily_costs and aggregates as needed.
-
Dashboard Queries:
We might want to see:
- Total cost per customer (external only) for a given period.
SELECT
c.name as customer_name,
SUM(dc.amount) as total_cost
FROM daily_costs dc
JOIN customers c ON dc.customer_id = c.id
WHERE c.is_external = true
AND dc.date BETWEEN '2024-01-01' AND '2024-01-31'
GROUP BY c.id, c.name
ORDER BY total_cost DESC;
- Cost breakdown by category for a customer:
SELECT
dc.cost_category,
SUM(dc.amount) as cost
FROM daily_costs dc
WHERE dc.customer_id = ?
AND dc.date BETWEEN ? AND ?
GROUP BY dc.cost_category;
- Cost by service for a customer:
SELECT
s.name as service_name,
SUM(dc.amount) as cost
FROM daily_costs dc
JOIN services s ON dc.service_id = s.id
WHERE dc.customer_id = ?
AND dc.date BETWEEN ? AND ?
GROUP BY s.id, s.name;
- Total cost by service (across all customers) for a period:
SELECT
s.name as service_name,
SUM(dc.amount) as cost
FROM daily_costs dc
JOIN services s ON dc.service_id = s.id
WHERE dc.date BETWEEN ? AND ?
GROUP BY s.id, s.name;
- We can also break down by cloud provider:
SELECT
dc.cloud_provider,
SUM(dc.amount) as cost
FROM daily_costs dc
WHERE dc.date BETWEEN ? AND ?
GROUP BY dc.cloud_provider;
-
Future Improvements:
- Support for more granular cost categories (e.g., by specific cloud service if needed).
- Support for more allocation methods (e.g., by usage data from application logs).
- Predictions and forecasting.
- Alerts when cost exceeds budget.
-
Code Structure:
We can have:
config.py: for database connection, cloud provider credentials, etc.
models.py: for SQLAlchemy models (if using ORM) or just table definitions.
fetch_costs.py: for fetching from cloud providers.
process_costs.py: for processing the raw data and allocating shared costs.
store_costs.py: for storing the processed data.
main.py: orchestrates the daily run.
Or we can have a single script.
-
Example Code Snippet (Python with PostgreSQL and AWS):
We'll use boto3 for AWS.
Steps:
import boto3
from datetime import datetime, timedelta
import psycopg2
# Connect to DB
conn = psycopg2.connect(...)
cur = conn.cursor()
# Fetch raw cost data from AWS Cost Explorer for yesterday
client = boto3.client('ce', region_name='us-east-1')
response = client.get_cost_and_usage(
TimePeriod={
'Start': (datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d'),
'End': datetime.now().strftime('%Y-%m-%d')
},
Granularity='DAILY',
Metrics=['BlendedCost'],
GroupBy=[
{
'Type': 'DIMENSION',
'Key': 'SERVICE'
},
{
'Type': 'TAG',
'Key': 'service'
},
{
'Type': 'TAG',
'Key': 'customer'
}
]
)
# Then process the response...
Note: AWS Cost Explorer can group by tags and service. We can get:
For each group (service, service_tag, customer_tag) we get the amount.
But note: the grouping might return multiple lines for the same service if there are multiple tags? Actually, it returns one line per combination of the group by keys.
Example:
SERVICE: AmazonEC2, service: auth, customer: acme -> amount: $100
SERVICE: AmazonEC2, service: auth, customer: (null) -> amount: $50 (shared)
Then we can process each group.
However, note: the same service (AmazonEC2) with the same service tag but different customer tags are separate groups.
We can do:
for group in response['ResultsByTime'][0]['Groups']:
service = group['Keys'][0] # e.g., "AmazonEC2"
service_tag = group['Keys'][1] # e.g., "auth"
customer_tag = group['Keys'][2] # e.g., "acme" or None
amount = group['Metrics']['BlendedCost']['Amount']
Then we map:
cost_category = lookup cost_category_mapping for (cloud_provider='aws', cloud_service=service)
service_id =
if service_tag:
lookup services table by name=service_tag
else:
lookup default_service_mapping for (aws, service) -> service_id
customer_id =
if customer_tag:
lookup customers table by name=customer_tag
else:
None
Then we have a record.
Then we aggregate and allocate shared.
But note: the AWS response might have multiple services that are the same but with different tags? We are already grouping by service and tags.
This should work.
-
Challenges:
-
The AWS Cost Explorer API has limits (on the number of groups returned). We might need to paginate.
-
We might have multiple cloud providers. We can run the same process for each.
-
We need to handle multiple currencies? We can convert to USD using a daily exchange rate.
-
We need to handle the fact that the same service (e.g., EC2) might have multiple cost categories (compute and storage? Actually, EC2 is mainly compute, but EBS volumes are storage). In AWS, EBS is a separate service.
So our mapping should map each AWS service to a cost category.
Example:
AmazonEC2 -> compute
AmazonEBS -> storage
AmazonS3 -> storage
AWSDataTransfer -> egress
We can build this mapping manually.
-
Conclusion:
This is a high-level design. We need to implement the ETL and set up the dashboard.
Let's start by creating the database and then writing the processing script.
We can iterate and improve.
For the dashboard, we can start with a simple Flask app that shows tables and charts, or use Grafana.
Given the complexity, we might want to start with a simpler model:
- Only direct costs (no allocation of shared costs) and then manually allocate shared costs later.
But the requirement is to map to customers, so we need allocation.
Alternatively, we can enforce tagging so that every resource has a customer tag. Then we don't have shared costs.
But in reality, there will be shared infrastructure.
So we need allocation.
We'll go with the above design.
I'll design a comprehensive backend cost observability dashboard that maps cloud/ infrastructure costs to services and customers. Here's a complete architecture:
System Architecture Overview
┌─────────────────────────────────────────────────────────────┐
│ COST OBSERVABILITY DASHBOARD │
├─────────────┬─────────────┬─────────────┬─────────────────┤
│ Data │ Processing │ Storage │ Dashboard │
│ Sources │ Layer │ Layer │ & API │
├─────────────┴─────────────┴─────────────┴─────────────────┤
│ │
│ ┌─────────┐ ┌─────────┐ ┌──────────┐ ┌─────────────┐│
│ │Cloud │ │ETL/ │ │Time- │ │Grafana/ ││
│ │Providers│ │Transform│ │Series │ │Custom UI ││
│ │(AWS, │ │Pipeline │ │DB │ │+ REST API ││
│ │GCP, Azure)│ │ │ │(Prom/ │ │ ││
│ └─────────┘ └─────────┘ │InfluxDB) │ └─────────────┘│
│ │ └──────────┘ │ │
│ ▼ ▼ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ TAG/ATTRIBUTE ENRICHMENT LAYER │ │
│ │ • Service Mapping (kubernetes_labels, aws_tags) │ │
│ │ • Customer Mapping (tenant_id, project_id) │ │
│ │ • Cost Allocation Rules Engine │ │
│ └─────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
1. Data Model
Core Tables (PostgreSQL/Snowflake/BigQuery)
-- Customers Table
CREATE TABLE customers (
customer_id VARCHAR(50) PRIMARY KEY,
name VARCHAR(255),
tier VARCHAR(50), -- enterprise, pro, free
billing_contact JSONB,
created_at TIMESTAMP
);
-- Services Table
CREATE TABLE services (
service_id VARCHAR(100) PRIMARY KEY,
name VARCHAR(255),
team VARCHAR(100),
owner_email VARCHAR(255),
cost_center VARCHAR(50),
is_internal BOOLEAN DEFAULT false,
service_type VARCHAR(50) -- 'api', 'worker', 'database', etc.
);
-- Service-Customer Relationship (Many-to-Many)
CREATE TABLE service_customers (
id SERIAL PRIMARY KEY,
service_id VARCHAR(100) REFERENCES services(service_id),
customer_id VARCHAR(50) REFERENCES customers(customer_id),
allocation_method VARCHAR(50) DEFAULT 'proportional', -- 'proportional', 'fixed', 'usage'
weight DECIMAL(5,2) DEFAULT 1.0, -- for proportional allocation
created_at TIMESTAMP
);
-- Daily Cost Facts Table
CREATE TABLE daily_costs (
id BIGSERIAL PRIMARY KEY,
date DATE NOT NULL,
service_id VARCHAR(100) REFERENCES services(service_id),
customer_id VARCHAR(50) REFERENCES customers(customer_id),
cloud_provider VARCHAR(50), -- aws, gcp, azure, onprem
cost_type VARCHAR(50), -- 'compute', 'storage', 'network_egress', 'managed_service'
cost_subtype VARCHAR(100), -- 'ec2', 's3', 'rds', 'cloud_run', etc.
amount DECIMAL(12,2) NOT NULL,
currency VARCHAR(3) DEFAULT 'USD',
units_consumed DECIMAL(12,2), -- optional: GB-hours, requests, etc.
raw_cost_data JSONB, -- store original provider data
created_at TIMESTAMP DEFAULT NOW(),
INDEX idx_date (date),
INDEX idx_service_date (service_id, date),
INDEX idx_customer_date (customer_id, date),
INDEX idx_cost_type (cost_type)
);
-- Hourly Aggregates for Fast Queries
CREATE TABLE hourly_costs (
id BIGSERIAL PRIMARY KEY,
timestamp TIMESTAMP NOT NULL,
service_id VARCHAR(100),
customer_id VARCHAR(50),
cost_type VARCHAR(50),
amount DECIMAL(12,2),
INDEX idx_timestamp (timestamp),
INDEX idx_service_timestamp (service_id, timestamp)
);
Tag Mapping Rules Table
CREATE TABLE tag_mapping_rules (
id SERIAL PRIMARY KEY,
rule_name VARCHAR(100),
provider VARCHAR(50),
tag_key VARCHAR(100),
tag_value_pattern VARCHAR(200), -- regex pattern
target_field VARCHAR(50), -- 'service_id' or 'customer_id'
target_value VARCHAR(200),
priority INT DEFAULT 100,
is_active BOOLEAN DEFAULT true
);
2. ETL Pipeline Design
# Example Airflow DAG structure
from airflow import DAG
from airflow.operators.python import PythonOperator
from datetime import datetime, timedelta
default_args = {
'owner': 'cost-observability',
'depends_on_past': False,
'start_date': datetime(2024, 1, 1),
'email_on_failure': True,
'retries': 3,
}
dag = DAG(
'daily_cost_processing',
default_args=default_args,
schedule_interval='0 5 * * *', # Run daily at 5 AM
catchup=True
)
def fetch_cloud_costs(execution_date, **context):
"""Fetch costs from all cloud providers"""
# AWS Cost Explorer API
# GCP Billing Export (BigQuery)
# Azure Cost Management API
# On-prem monitoring (Prometheus, custom scripts)
pass
def enrich_with_tags(raw_costs):
"""Apply tag mapping rules to identify services/customers"""
# Load tag mapping rules from DB
# Apply regex patterns to resource names/tags
# Default assignments for unmapped resources
pass
def allocate_shared_costs(enriched_costs):
"""Allocate shared infrastructure costs"""
# Identify shared services (k8s cluster, VPC, etc.)
# Apply allocation rules (proportional by usage, fixed splits)
pass
def aggregate_and_store(processed_costs):
"""Aggregate to daily granularity and store"""
# Group by: date, service_id, customer_id, cost_type
# Insert into daily_costs table
# Rollup to hourly/monthly aggregates
pass
tasks = [
PythonOperator(task_id='fetch_costs', python_callable=fetch_cloud_costs, dag=dag),
PythonOperator(task_id='enrich_tags', python_callable=enrich_with_tags, dag=dag),
PythonOperator(task_id='allocate_shared', python_callable=allocate_shared_costs, dag=dag),
PythonOperator(task_id='aggregate_store', python_callable=aggregate_and_store, dag=dag),
]
for i in range(len(tasks)-1):
tasks[i] >> tasks[i+1]
3. Tagging Strategy
Mandatory Tags for All Resources:
# Kubernetes/Cloud Resources
tags:
- cost-center: "team-xyz" # Maps to service/team
- environment: "prod|staging|dev"
- customer-id: "cust_123" # External customer ID (if applicable)
- service-name: "api-gateway" # Internal service name
- allocation-method: "direct|shared|proportional"
Fallback Rules:
-
Service Detection:
- Kubernetes:
app.kubernetes.io/name, k8s-app
- AWS:
aws:cloudformation:stack-name, Name tag patterns
- GCP:
goog-k8s-name, resource.labels.*
-
Customer Detection:
- Primary:
customer-id tag
- Secondary: Resource name contains customer prefix (e.g.,
acme-api-, beta-db-)
- Default:
unallocated-customer
4. API Design (REST)
# Cost Aggregation API
GET /api/v1/costs?
start_date=2024-01-01&
end_date=2024-01-31&
group_by=service,customer&
cost_type=compute,storage,egress&
customer_id=acme_corp&
service_id=auth-service
Response:
{
"metadata": {
"period": "2024-01-01 to 2024-01-31",
"currency": "USD",
"total_cost": 45678.90
},
"breakdown": [
{
"service_id": "auth-service",
"service_name": "Authentication API",
"customer_id": "acme_corp",
"customer_name": "Acme Corporation",
"costs": {
"compute": 12345.67,
"storage": 2345.67,
"network_egress": 567.89,
"managed_services": 890.12
},
"total": 16149.35
}
]
}
# Service Cost Breakdown
GET /api/v1/services/{service_id}/costs?
start_date=2024-01-01&
end_date=2024-01-31&
granularity=day|hour
# Customer Cost Report
GET /api/v1/customers/{customer_id}/costs?
start_date=2024-01-01&
end_date=2024-01-31&
include_shared=true
# Trend Analysis
GET /api/v1/trends?
metric=cost_per_request&
service_id=auth-service&
period=weekly
5. Dashboard Views (Grafana/Custom UI)
View 1: Executive Summary
┌─────────────────────────────────────────────┐
│ Total Monthly Cost: $456,789 │
│ ▲12.3% vs last month │
├─────────────────────────────────────────────┤
│ Top 5 Customers by Cost: │
│ 1. Acme Corp $123,456 (27%) │
│ 2. Beta Inc $98,765 (22%) │
│ 3. Gamma LLC $76,543 (17%) │
│ ... │
├─────────────────────────────────────────────┤
│ Cost by Type: │
│ ████ Compute 65% │
│ ██ Storage 25% │
│ █ Egress 8% │
│ █ Managed 2% │
└─────────────────────────────────────────────┘
View 2: Service Drill-Down
- Service selector dropdown
- Time series charts:
- Daily cost trend (with forecast)
- Cost per request/transaction
- Cost breakdown by component (compute/storage/network)
- Cost allocation table:
Service: auth-service
┌───────────────┬─────────────┬──────────────┬─────────────┐
│ Customer │ This Month │ Last Month │ % Change │
├───────────────┼─────────────┼──────────────┼─────────────┤
│ Acme Corp │ $45,678 │ $41,234 │ +10.8% │
│ Beta Inc │ $32,145 │ $29,876 │ +7.6% │
│ Shared (alloc)│ $12,345 │ $11,234 │ +9.9% │
└───────────────┴─────────────┴──────────────┴─────────────┘
View 3: Anomaly Detection
- Cost spikes visualization (threshold-based alerts)
- Unexpected growth detection (statistical deviations)
- Idle resource detection (low utilization high cost)
View 4: Forecast & Budget
- Monthly forecast vs budget
- Burn rate calculations
- What-if scenarios (e.g., "What if we double Acme Corp's usage?")
6. Cost Allocation Algorithms
def allocate_shared_costs(shared_costs, service_customers, method='proportional'):
"""
Allocate shared infrastructure costs to customers
Args:
shared_costs: Dict of {cost_type: amount} for shared service
service_customers: List of customers using this service with weights
method: 'proportional', 'fixed', 'usage_based'
Returns:
Dict of {customer_id: {cost_type: amount}}
"""
allocations = {}
if method == 'proportional':
total_weight = sum(c['weight'] for c in service_customers)
for customer in service_customers:
share = customer['weight'] / total_weight
allocations[customer['customer_id']] = {
cost_type: amount * share
for cost_type, amount in shared_costs.items()
}
elif method == 'fixed':
# Pre-defined fixed splits from service_customers.fixed_amount
total_fixed = sum(c.get('fixed_amount', 0) for c in service_customers)
for customer in service_customers:
share = customer.get('fixed_amount', 0) / total_fixed
allocations[customer['customer_id']] = {
cost_type: amount * share
for cost_type, amount in shared_costs.items()
}
return allocations
7. Technology Stack Recommendations
| Component | Recommended Tools | Alternatives |
|---|
| Data Storage | PostgreSQL + TimescaleDB | Snowflake, BigQuery |
| Time Series | InfluxDB, Prometheus | TimescaleDB |
| ETL/Orchestration | Airflow, Prefect | Dagster, Luigi |
| Dashboard | Grafana + Custom Plugins | Superset, Metabase |
| API | FastAPI (Python) | Go, Node.js |
| Alerting | Prometheus Alertmanager | Grafana Alerts, PagerDuty |
| Cloud Cost APIs | AWS Cost Explorer, GCP Billing API, Azure Cost Management | CloudHealth, CloudHealth |
8. Implementation Roadmap
Phase 1: Foundation (Weeks 1-4)
- Set up data warehouse with core tables
- Implement AWS cost ingestion (most critical)
- Basic tagging enforcement
- Simple dashboard (service-level costs)
Phase 2: Multi-Cloud (Weeks 5-8)
- Add GCP/Azure ingestion
- Implement customer mapping
- Shared cost allocation logic
- Basic forecasting
Phase 3: Advanced Features (Weeks 9-12)
- Anomaly detection
- Cost per request metrics
- Budget alerts
- API for integration with billing systems
Phase 4: Optimization (Weeks 13-16)
- Predictive forecasting
- What-if scenarios
- Cost optimization recommendations
- Customer self-service portal
9. Alerting & Monitoring
# Example alert rules for Prometheus/Alertmanager
alerts:
- alert: CostSpike
expr: increase(daily_costs[1d]) > 1.5 * avg_over_time(daily_costs[7d])
for: 2h
labels:
severity: warning
annotations:
summary: "Cost spike detected for {{ $labels.service_id }}"
description: "Cost increased by {{ $value | humanizePercentage }} vs 7-day average"
- alert: BudgetExceeded
expr: monthly_cost / monthly_budget > 0.9
for: 24h
labels:
severity: critical
annotations:
summary: "Budget threshold exceeded for {{ $labels.customer_id }}"
10. Cost Optimization Recommendations Engine
class CostOptimizer:
def find_idle_resources(self, service_id, days=7):
"""Find underutilized resources"""
# Query: CPU < 10% AND Memory < 20% for 7 days
pass
def find_overprovisioned(self, service_id):
"""Find resources that can be downsized"""
# Compare utilization vs instance size
pass
def reserved_instance_coverage(self, service_id):
"""Check RI/Savings Plans coverage"""
pass
def generate_recommendations(self, customer_id=None):
"""Generate actionable recommendations"""
recommendations = []
for service in services:
if customer_id and service not in customer_services:
continue
idle = self.find_idle_resources(service.id)
if idle:
recommendations.append({
'service': service.name,
'type': 'idle_resource',
'savings': self.calculate_savings(idle),
'action': 'Terminate or resize'
})
return recommendations
11. Security & Access Control
RBAC Roles:
- finance_team: view_all_costs, export_reports
- service_owner: view_own_service_costs, view_customer_breakdown
- customer_success: view_assigned_customers_costs
- engineering: view_service_costs, view_own_cost_breakdown
- admin: all permissions + configuration
Row-Level Security (PostgreSQL):
CREATE POLICY service_owner_policy ON daily_costs
USING (service_id IN (
SELECT service_id FROM service_owners
WHERE user_email = current_user
));
12. Sample Queries
Top 10 Costliest Services This Month:
SELECT
s.name,
s.team,
SUM(dc.amount) as total_cost,
COUNT(DISTINCT dc.customer_id) as customer_count
FROM daily_costs dc
JOIN services s ON dc.service_id = s.service_id
WHERE dc.date >= DATE_TRUNC('month', CURRENT_DATE)
GROUP BY s.service_id, s.name, s.team
ORDER BY total_cost DESC
LIMIT 10;
Customer Cost Trend:
SELECT
c.name,
DATE_TRUNC('week', dc.date) as week,
SUM(dc.amount) as weekly_cost,
LAG(SUM(dc.amount), 1) OVER (
PARTITION BY c.customer_id
ORDER BY DATE_TRUNC('week', dc.date)
) as prev_week_cost
FROM daily_costs dc
JOIN customers c ON dc.customer_id = c.customer_id
WHERE dc.customer_id = 'acme_corp'
AND dc.date >= CURRENT_DATE - INTERVAL '90 days'
GROUP BY c.customer_id, c.name, DATE_TRUNC('week', dc.date)
ORDER BY week;
Cost Per Request (if request metrics available):
WITH requests AS (
SELECT service_id, DATE(date) as day, COUNT(*) as request_count
FROM request_logs
WHERE date >= '2024-01-01'
GROUP BY service_id, DATE(date)
),
costs AS (
SELECT service_id, DATE(date) as day,
SUM(CASE WHEN cost_type='compute' THEN amount ELSE 0 END) as compute_cost
FROM daily_costs
WHERE date >= '2024-01-01'
GROUP BY service_id, DATE(date)
)
SELECT
r.service_id,
s.name,
r.day,
r.request_count,
c.compute_cost,
c.compute_cost / NULLIF(r.request_count, 0) as cost_per_request
FROM requests r
JOIN costs c ON r.service_id = c.service_id AND r.day = c.day
JOIN services s ON r.service_id = s.service_id
ORDER BY cost_per_request DESC;
13. Deployment Considerations
-
Data Freshness:
- Raw costs: 24-48 hours delay from cloud providers
- Processed costs: 5 AM daily (post-processing)
- Near-real-time metrics: 5-15 min latency
-
Scalability:
- Partition
daily_costs by date (monthly partitions)
- Index heavily on
(service_id, date) and (customer_id, date)
- Use materialized views for common aggregations
-
Data Retention:
- Raw data: 2 years
- Daily aggregates: 5 years
- Hourly aggregates: 90 days
- Archive old data to S3/GS cold storage
-
Cost of System:
- Estimate: $500-2000/month for medium-sized org (100+ services, 1000+ customers)
- Main cost: Data warehouse storage/compute
14. Quick Start Script
#!/bin/bash
# setup_cost_dashboard.sh
# 1. Initialize database
docker-compose up -d postgres
psql -h localhost -U postgres -f schema.sql
# 2. Configure cloud providers
cat > config/aws_config.json <<EOF
{
"access_key": "...",
"secret_key": "...",
"account_id": "123456789",
"regions": ["us-east-1", "us-west-2"]
}
EOF
# 3. Set up Airflow
docker-compose up -d airflow
airflow dags import cost_processing_dag.py
# 4. Initialize Grafana
docker-compose up -d grafana
# Import dashboard JSON from dashboards/
# 5. Run initial backfill
python -m etl.backfill --start-date 2024-01-01 --end-date 2024-01-31
This design provides:
- ✅ Granular cost mapping to services and customers
- ✅ Flexible allocation for shared infrastructure
- ✅ Multi-cloud support (AWS/GCP/Azure/on-prem)
- ✅ Historical analysis with trend data
- ✅ Anomaly detection and alerts
- ✅ Self-service for service owners
- ✅ Export capabilities for billing reconciliation
- ✅ Scalable architecture for enterprise scale
Would you like me to elaborate on any specific component, provide Terraform configurations for deployment, or design the detailed schema for a particular cloud provider?