Skip to main content

Budget Management

Manage budgets for API usage, scraping costs, and monitor spending across platforms.

Endpoints

Create Budget

POST /api/budget

Get Budget

GET /api/budget/{budgetId}

List Budgets

GET /api/budget

Update Budget

PATCH /api/budget/{budgetId}

Allocate Cost

POST /api/budget/{budgetId}/allocate

Get Analytics

GET /api/budget/analytics

Create Budget

Request

name
string
required
Budget name (e.g., “Q1 2026 API Budget”)
description
string
Budget description
budgetType
string
required
Budget type: MONTHLY, QUARTERLY, YEARLY, PROJECT, UNLIMITED
totalAmount
number
required
Total budget amount in USD
startDate
string
required
Budget start date (ISO 8601)
endDate
string
required
Budget end date (ISO 8601)
autoRenewal
boolean
default:"false"
Automatically renew for next period
allocations
array
Budget allocations by service

Response

success
boolean
Indicates if budget was created
data
object

Get Budget Details

Response

Extends the basic budget object with additional analytics:
data
object

Allocate Cost

Request

budgetId
string
required
Budget ID
platform
string
required
Platform name
serviceType
string
required
Service type enum
costAmount
number
required
Cost amount in USD
description
string
Cost description
costDate
string
Date of cost (defaults to now)
apiUsageId
string
Link to ApiUsage record
apifyRunId
string
Link to ApifyRunMetrics record

Budget Analytics

Response

data
object

Examples

Create Monthly Budget

import { BudgetManager } from '@/lib/services/budget-manager';
import { prisma } from '@/lib/prisma';

const budgetManager = new BudgetManager(prisma);

const budget = await budgetManager.createBudget({
  name: 'March 2026 API Budget',
  description: 'Monthly budget for API and scraping costs',
  budgetType: 'MONTHLY',
  totalAmount: 1000.00,
  startDate: new Date('2026-03-01'),
  endDate: new Date('2026-03-31'),
  autoRenewal: true,
  allocations: [
    {
      platform: 'Apify',
      serviceType: 'SCRAPING',
      allocatedAmount: 500.00,
      priority: 'HIGH'
    },
    {
      platform: 'OpenAI',
      serviceType: 'API',
      allocatedAmount: 300.00,
      priority: 'MEDIUM'
    },
    {
      platform: 'Anthropic',
      serviceType: 'API',
      allocatedAmount: 200.00,
      priority: 'MEDIUM'
    }
  ]
});

console.log(`Created budget: ${budget.id}`);

Track API Costs

// After making an API call
const apiCost = 0.05; // $0.05 per request

await budgetManager.allocateCost({
  budgetId: 'budget_123',
  platform: 'OpenAI',
  serviceType: 'API',
  costAmount: apiCost,
  description: 'GPT-4 API call',
  apiUsageId: 'usage_456',
  metadata: {
    model: 'gpt-4',
    tokens: 1250,
    endpoint: '/v1/chat/completions'
  }
});

// Check budget status
const summary = await budgetManager.getBudget('budget_123');
if (summary.spentPercentage > 90) {
  console.warn(`Budget at ${summary.spentPercentage}% - ${summary.totalRemaining} remaining`);
}

Monitor Spending

// Get budget analytics
const analytics = await budgetManager.getBudgetAnalytics();

console.log('Budget Overview:');
console.log(`  Total Allocated: $${analytics.totalAllocated.toFixed(2)}`);
console.log(`  Total Spent: $${analytics.totalSpent.toFixed(2)}`);
console.log(`  Utilization: ${analytics.averageSpentPercentage.toFixed(1)}%`);
console.log(`  Budgets Exceeded: ${analytics.budgetsExceeded}`);
console.log(`  Budgets Near Limit: ${analytics.budgetsNearLimit}`);

console.log('\nTop Spending Platforms:');
analytics.topSpendingPlatforms.forEach((platform, index) => {
  console.log(`  ${index + 1}. ${platform.platform}: $${platform.totalSpent.toFixed(2)} (${platform.percentage.toFixed(1)}%)`);
});

// Plot monthly trend
console.log('\nMonthly Trend:');
analytics.monthlyTrend.forEach(month => {
  console.log(`  ${month.month}: $${month.totalSpent.toFixed(2)} (${month.budgetUtilization.toFixed(1)}% utilization)`);
});

Response Example

Budget Summary

{
  "success": true,
  "data": {
    "budget": {
      "id": "budget_123",
      "name": "March 2026 API Budget",
      "budgetType": "MONTHLY",
      "totalAmount": 1000.00,
      "spentAmount": 456.78,
      "remainingAmount": 543.22,
      "status": "ACTIVE",
      "startDate": "2026-03-01T00:00:00Z",
      "endDate": "2026-03-31T23:59:59Z",
      "alertThreshold80": true,
      "alertThreshold90": true,
      "alertThreshold100": true,
      "autoRenewal": true
    },
    "allocations": [
      {
        "id": "alloc_1",
        "platform": "Apify",
        "serviceType": "SCRAPING",
        "allocatedAmount": 500.00,
        "spentAmount": 289.50,
        "remainingAmount": 210.50,
        "priority": "HIGH"
      },
      {
        "id": "alloc_2",
        "platform": "OpenAI",
        "serviceType": "API",
        "allocatedAmount": 300.00,
        "spentAmount": 123.28,
        "remainingAmount": 176.72,
        "priority": "MEDIUM"
      },
      {
        "id": "alloc_3",
        "platform": "Anthropic",
        "serviceType": "API",
        "allocatedAmount": 200.00,
        "spentAmount": 44.00,
        "remainingAmount": 156.00,
        "priority": "MEDIUM"
      }
    ],
    "totalSpent": 456.78,
    "totalRemaining": 543.22,
    "spentPercentage": 45.68,
    "alerts": [],
    "projectedEndDate": "2026-03-21T14:30:00Z",
    "burnRate": 76.13
  }
}

Budget Analytics

{
  "success": true,
  "data": {
    "totalBudgets": 5,
    "activeBudgets": 3,
    "totalAllocated": 5000.00,
    "totalSpent": 2145.67,
    "totalRemaining": 2854.33,
    "averageSpentPercentage": 42.91,
    "budgetsExceeded": 0,
    "budgetsNearLimit": 1,
    "topSpendingPlatforms": [
      {
        "platform": "Apify",
        "totalSpent": 1245.80,
        "percentage": 58.06
      },
      {
        "platform": "OpenAI",
        "totalSpent": 678.42,
        "percentage": 31.62
      },
      {
        "platform": "Anthropic",
        "totalSpent": 221.45,
        "percentage": 10.32
      }
    ],
    "monthlyTrend": [
      {
        "month": "2026-01",
        "totalSpent": 876.34,
        "budgetUtilization": 58.42
      },
      {
        "month": "2026-02",
        "totalSpent": 812.55,
        "budgetUtilization": 54.17
      },
      {
        "month": "2026-03",
        "totalSpent": 456.78,
        "budgetUtilization": 45.68
      }
    ]
  }
}

Budget Alerts

Alerts are automatically created when thresholds are reached:
  • 80% Threshold: Warning alert
  • 90% Threshold: Critical alert
  • 100% Threshold: Budget exceeded alert
Implementation in /lib/services/budget-manager.ts:400-445:
private async checkBudgetAlerts(budgetId: string): Promise<void> {
  const budget = await this.prisma.budget.findUnique({
    where: { id: budgetId },
    include: { budgetAlerts: { where: { isResolved: false } } }
  });

  const spentPercentage = (budget.spentAmount / budget.totalAmount) * 100;

  if (budget.alertThreshold80 && spentPercentage >= 80) {
    await this.prisma.budgetAlert.create({
      data: {
        budgetId: budget.id,
        alertType: 'THRESHOLD_80',
        threshold: 80,
        currentSpent: budget.spentAmount,
        budgetTotal: budget.totalAmount,
        message: `Budget "${budget.name}" has reached ${spentPercentage.toFixed(1)}% of allocated amount`
      }
    });
  }
}

Next Steps

Monitoring Alerts

Configure budget alerts and notifications

Budget Management

Learn about cost optimization and forecasting

Build docs developers (and LLMs) love