Skip to main content

Cost Model Documentation

Overview​

The Cost model provides dynamic pricing management and billing report generation for the CODITECT platform. It supports tiered pricing structures, multi-currency billing, and comprehensive cost breakdowns. The model enables accurate cost calculation based on usage volumes and generates detailed billing reports for transparency and financial planning.

Model Structure​

CostModel - Pricing Configuration​

Core Fields​

FieldTypeDescriptionConstraints
cost_model_idUUIDUnique pricing model identifierPrimary key, auto-generated
providerStringService provider nameRequired (e.g., "anthropic", "google")
resource_typeResourceTypeType of resource being pricedForeign key to Usage
pricing_tiersVecVolume-based pricing tiersRequired, at least one tier
effective_dateDateTimeWhen pricing takes effectRequired, auto-set to now
expires_dateDateTime (Optional)When pricing expiresFor limited-time pricing

PricingTier Structure​

FieldTypeDescriptionExample
min_quantityf64Minimum quantity for tier0.0
max_quantityf64 (Optional)Maximum quantity for tier1,000,000.0
price_per_unitf64Unit price in this tier0.000008
currencyStringCurrency code"USD"

BillingReport - Monthly Billing​

Core Fields​

FieldTypeDescriptionConstraints
report_idUUIDUnique report identifierPrimary key, auto-generated
tenant_idUUIDTenant being billedForeign key to Tenant
start_dateDateTimeBilling period startRequired
end_dateDateTimeBilling period endRequired
total_costf64Total amount dueAuto-calculated
currencyStringBilling currencyRequired
cost_breakdownVecDetailed line itemsAuto-populated
generated_atDateTimeReport generation timeAuto-set

CostBreakdown Structure​

FieldTypeDescription
service_typeStringCategory of service
resource_typeStringSpecific resource
quantityf64Amount consumed
unitStringUnit of measurement
unit_costf64Price per unit
total_costf64Line item total
percentage_of_totalf64% of total bill

AggregationLevel Enum​

enum AggregationLevel {
Service, // By service type
Resource, // By resource type
User, // By user
Day, // Daily aggregation
Hour // Hourly aggregation
}

Pricing Examples​

Tiered AI Token Pricing​

{
"cost_model_id": "550e8400-e29b-41d4-a716-446655440000",
"provider": "anthropic",
"resource_type": "ClaudeInputTokens",
"pricing_tiers": [
{
"min_quantity": 0.0,
"max_quantity": 1000000.0,
"price_per_unit": 0.000015,
"currency": "USD"
},
{
"min_quantity": 1000000.0,
"max_quantity": 10000000.0,
"price_per_unit": 0.000012,
"currency": "USD"
},
{
"min_quantity": 10000000.0,
"max_quantity": null,
"price_per_unit": 0.00001,
"currency": "USD"
}
],
"effective_date": "2025-08-01T00:00:00Z",
"expires_date": null
}

Compute Pricing Model​

{
"cost_model_id": "660e8400-e29b-41d4-a716-446655440000",
"provider": "gcp",
"resource_type": "CloudRunCpu",
"pricing_tiers": [
{
"min_quantity": 0.0,
"max_quantity": 1000.0,
"price_per_unit": 0.024,
"currency": "USD"
},
{
"min_quantity": 1000.0,
"max_quantity": null,
"price_per_unit": 0.020,
"currency": "USD"
}
],
"effective_date": "2025-08-01T00:00:00Z",
"expires_date": null
}

Billing Report Example​

Monthly Report​

{
"report_id": "770e8400-e29b-41d4-a716-446655440000",
"tenant_id": "123e4567-e89b-12d3-a456-426614174000",
"start_date": "2025-08-01T00:00:00Z",
"end_date": "2025-08-31T23:59:59Z",
"total_cost": 1247.85,
"currency": "USD",
"cost_breakdown": [
{
"service_type": "AI",
"resource_type": "ClaudeInputTokens",
"quantity": 45000000.0,
"unit": "tokens",
"unit_cost": 0.00001,
"total_cost": 450.00,
"percentage_of_total": 36.05
},
{
"service_type": "AI",
"resource_type": "ClaudeOutputTokens",
"quantity": 15000000.0,
"unit": "tokens",
"unit_cost": 0.00005,
"total_cost": 750.00,
"percentage_of_total": 60.12
},
{
"service_type": "Compute",
"resource_type": "CloudRunCpu",
"quantity": 1500.0,
"unit": "vCPU-hours",
"unit_cost": 0.020,
"total_cost": 30.00,
"percentage_of_total": 2.40
},
{
"service_type": "Storage",
"resource_type": "GcsStorage",
"quantity": 892.5,
"unit": "GB-months",
"unit_cost": 0.02,
"total_cost": 17.85,
"percentage_of_total": 1.43
}
],
"generated_at": "2025-09-01T00:05:00Z"
}

Database Schema​

Primary Storage Patterns​

# Cost models by provider and resource
Key: /cost_models/{provider}/{resource_type}/{effective_date}
Value: JSON serialized CostModel

# Active cost models
Key: /active_cost_models/{provider}/{resource_type}
Value: cost_model_id

# Billing reports
Key: /{tenant_id}/billing_reports/{YYYY-MM}/{report_id}
Value: JSON serialized BillingReport

# Historical pricing
Key: /cost_model_history/{provider}/{resource_type}/{effective_date}
Value: JSON serialized CostModel

Secondary Indexes​

# Reports by status
/billing_reports_by_status/{status} -> [report_ids]

# Reports by amount
/billing_reports_by_amount/{YYYY}/{amount_range} -> [report_ids]

# Overdue reports
/overdue_billing_reports -> [report_ids]

Cost Calculation​

Tiered Pricing Logic​

impl CostModel {
pub fn calculate_cost(&self, quantity: f64) -> Option<f64> {
// For simple tiered pricing (entire quantity at tier rate)
for tier in &self.pricing_tiers {
if quantity >= tier.min_quantity &&
tier.max_quantity.map_or(true, |max| quantity <= max) {
return Some(quantity * tier.price_per_unit);
}
}
None
}

pub fn calculate_cost_graduated(&self, quantity: f64) -> f64 {
// For graduated pricing (each tier gets its rate)
let mut total_cost = 0.0;
let mut remaining = quantity;

for tier in &self.pricing_tiers {
let tier_max = tier.max_quantity.unwrap_or(f64::MAX);
let tier_quantity = (tier_max - tier.min_quantity).min(remaining);

if tier_quantity > 0.0 {
total_cost += tier_quantity * tier.price_per_unit;
remaining -= tier_quantity;
}

if remaining <= 0.0 {
break;
}
}

total_cost
}
}

Volume Discounts​

struct VolumeDiscount {
threshold: f64,
discount_percent: f64,
applicable_to: Vec<ResourceType>
}

// Apply volume discount
let base_cost = cost_model.calculate_cost(quantity)?;
let discount = get_applicable_discount(resource_type, quantity);
let final_cost = base_cost * (1.0 - discount.discount_percent / 100.0);

Source Files​

  • Models:
    • /src/models/cost.rs - Cost model definitions
    • /src/models/usage.rs - ResourceType enum
  • Services:
    • /src/services/pricing_service.rs - Pricing calculations
    • /src/services/billing_service.rs - Report generation
  • Repositories:
    • /src/db/repositories/cost_repository.rs
    • /src/db/repositories/billing_repository.rs
  • API Handlers:
    • /src/api/handlers/billing_handlers.rs
  • Tests:
    • /src/models/tests/cost_tests.rs

Key Methods​

impl CostModel {
fn new(provider: String, resource_type: ResourceType, pricing_tiers: Vec<PricingTier>) -> Self
fn calculate_cost(&self, quantity: f64) -> Option<f64>
fn get_unit_price(&self, quantity: f64) -> Option<f64>
fn is_active(&self) -> bool
}

impl BillingReport {
fn new(tenant_id: Uuid, start_date: DateTime<Utc>, end_date: DateTime<Utc>, currency: String) -> Self
fn add_cost_item(&mut self, breakdown: CostBreakdown)
fn recalculate_percentages(&mut self)
fn apply_credits(&mut self, credits: Vec<Credit>)
fn finalize(&mut self) -> Result<()>
}

API Endpoints​

Pricing Management​

  • GET /api/pricing - Get current pricing
  • GET /api/pricing/{provider}/{resource} - Get specific pricing
  • POST /api/admin/pricing - Create new pricing model
  • PUT /api/admin/pricing/{cost_model_id} - Update pricing

Billing Reports​

  • GET /api/billing/current - Current month's usage
  • GET /api/billing/reports - List billing reports
  • GET /api/billing/reports/{report_id} - Get specific report
  • POST /api/billing/reports/generate - Generate ad-hoc report

Cost Estimation​

  • POST /api/billing/estimate - Estimate costs
  • GET /api/billing/calculator - Interactive calculator
  • GET /api/billing/forecast - Cost forecasting

Pricing Strategies​

Standard Pricing Tiers​

  1. Free Tier: First N units free
  2. Standard Tier: Regular pricing
  3. Volume Tier: Discounted bulk rates
  4. Enterprise Tier: Negotiated rates

Special Pricing Models​

  1. Committed Use: Pre-purchase discounts
  2. Spot Pricing: Variable market rates
  3. Reserved Capacity: Guaranteed availability
  4. Pay-as-you-go: Standard on-demand

Billing Workflows​

Monthly Billing Cycle​

Day 1-25: Usage accumulation
Day 26: Usage forecast email
Day 28: Final usage warning
Day 30: Generate billing report
Day 31: Send invoice
Day 1 (next): Payment processing
Day 5: Late payment reminder
Day 10: Service suspension warning

Report Generation Process​

  1. Aggregate usage data by service/resource
  2. Apply current pricing models
  3. Calculate tiered pricing
  4. Apply discounts/credits
  5. Generate line items
  6. Calculate taxes if applicable
  7. Create PDF invoice
  8. Send notifications

Cost Optimization​

Recommendations Engine​

struct CostOptimization {
resource_type: ResourceType,
current_usage: f64,
current_cost: f64,
recommended_action: String,
potential_savings: f64
}

// Example recommendations
- Switch to volume pricing tier
- Use reserved capacity
- Optimize resource usage patterns
- Consolidate similar workloads

Budget Alerts​

struct BudgetAlert {
tenant_id: Uuid,
budget_amount: f64,
period: BudgetPeriod,
alert_thresholds: Vec<f64>, // e.g., [50.0, 80.0, 100.0]
notification_channels: Vec<NotificationChannel>
}

Financial Integration​

Invoice Structure​

struct Invoice {
invoice_number: String,
billing_report: BillingReport,
tax_details: Option<TaxDetails>,
payment_terms: PaymentTerms,
due_date: DateTime<Utc>,
status: InvoiceStatus
}

enum InvoiceStatus {
Draft,
Sent,
Paid,
Overdue,
Disputed,
Cancelled
}

Payment Processing​

  • Credit card auto-charge
  • ACH bank transfers
  • Wire transfers
  • Purchase orders
  • Credits and adjustments

Compliance & Audit​

Audit Requirements​

  • Immutable billing records
  • Complete pricing history
  • Usage-to-cost traceability
  • Adjustment audit trail

Data Retention​

  • Cost models: Permanent
  • Billing reports: 7 years
  • Usage data: 90 days detailed, 7 years aggregated
  • Payment records: 7 years

Performance Considerations​

Caching Strategy​

  • Cache active pricing models
  • Pre-calculate common quantities
  • Store monthly aggregates
  • Materialized report views

Optimization​

  • Batch cost calculations
  • Async report generation
  • Compress historical data
  • Archive old reports

Future Enhancements​

Advanced Features​

  1. Multi-currency Support: Real-time exchange rates
  2. Tax Integration: Automated tax calculation
  3. Cost Allocation: Department/project charging
  4. Marketplace Billing: Third-party service integration

Analytics Improvements​

  1. Cost Trends: Historical analysis
  2. Anomaly Detection: Unusual spending alerts
  3. What-if Analysis: Pricing scenario modeling
  4. ROI Calculations: Value metrics

Automation​

  1. Auto-scaling Budgets: Dynamic budget adjustment
  2. Smart Credits: Automatic credit application
  3. Dispute Resolution: Automated handling
  4. Collection Automation: Dunning management

Last Updated: 2025-08-29 Version: 1.0