Skip to main content

Monitoring & Alerts

Configure alerts and monitoring for API usage, budget thresholds, Apify runs, and data quality.

Endpoints

Get Monitoring Dashboard

GET /api/monitoring/dashboard

Get Active Alerts

GET /api/monitoring/alerts

Create Alert Rule

POST /api/monitoring/alerts/rules

Resolve Alert

PATCH /api/monitoring/alerts/{alertId}/resolve

Get Apify Usage

GET /api/monitoring/apify/usage

Monitoring Dashboard

Response

success
boolean
Indicates if the request was successful
data
object

Active Alerts

Request

type
string
Filter by alert type: BUDGET, API, APIFY, DATA_QUALITY, PERFORMANCE
severity
string
Filter by severity: LOW, MEDIUM, HIGH, CRITICAL
isResolved
boolean
default:"false"
Include resolved alerts

Response

data
object

Create Alert Rule

Request

name
string
required
Alert rule name
type
string
required
Alert type: BUDGET, API, APIFY, DATA_QUALITY, PERFORMANCE
conditions
object
required
Alert trigger conditions
severity
string
default:"MEDIUM"
Alert severity
notifications
object
required
Notification configuration
enabled
boolean
default:"true"
Whether the rule is enabled

Apify Usage

Monitor Apify account usage and costs.

Response

Implemented by ApifyMonitoringService in /lib/services/apify-monitoring-service.ts:109-310:
data
object

Examples

Get Monitoring Dashboard

async function getMonitoringDashboard() {
  const response = await fetch(
    'https://your-domain.com/api/monitoring/dashboard',
    {
      headers: {
        'Authorization': `Bearer ${process.env.API_KEY}`
      }
    }
  );

  const { data } = await response.json();
  return data;
}

const dashboard = await getMonitoringDashboard();

console.log('API Usage:');
console.log(`  Requests: ${dashboard.apiUsage.totalRequests}`);
console.log(`  Cost: $${dashboard.apiUsage.totalCost.toFixed(2)}`);
console.log(`  Error Rate: ${dashboard.apiUsage.errorRate.toFixed(2)}%`);

console.log('\nApify Usage:');
console.log(`  Compute Units: ${dashboard.apifyUsage.usage.computeUnits.utilization.toFixed(1)}%`);
console.log(`  Monthly Cost: $${dashboard.apifyUsage.costs.monthly.toFixed(2)}`);

console.log('\nBudgets:');
console.log(`  Active: ${dashboard.budgets.activeBudgets}`);
console.log(`  Spent: $${dashboard.budgets.totalSpent.toFixed(2)} / $${dashboard.budgets.totalAllocated.toFixed(2)}`);
console.log(`  Near Limit: ${dashboard.budgets.budgetsNearLimit}`);

Create Budget Alert

// Create alert when budget reaches 80%
const response = await fetch(
  'https://your-domain.com/api/monitoring/alerts/rules',
  {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${apiKey}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      name: 'Budget 80% Alert',
      type: 'BUDGET',
      conditions: {
        budgetId: 'budget_123',
        threshold: 80,
        metric: 'spentPercentage'
      },
      severity: 'MEDIUM',
      notifications: {
        email: ['[email protected]'],
        slack: {
          webhookUrl: 'https://hooks.slack.com/services/YOUR/WEBHOOK',
          channel: '#alerts'
        }
      },
      enabled: true
    })
  }
);

Monitor Apify Usage

import { ApifyMonitoringService } from '@/lib/services/apify-monitoring-service';

const monitor = new ApifyMonitoringService(process.env.APIFY_API_KEY);

const usage = await monitor.getFullMonitoringData();

// Check for high utilization
if (usage.usage.computeUnits.utilization > 90) {
  console.error('🚨 Compute units at 90%!');
  
  // Get platform spending to identify culprit
  const spending = await monitor.getPlatformSpending();
  const topPlatform = Object.entries(spending.platformBreakdown)
    .sort(([,a], [,b]) => b.estimatedCost - a.estimatedCost)[0];
  
  console.log(`Top spender: ${topPlatform[0]} ($${topPlatform[1].estimatedCost.toFixed(2)})`);
}

// Check for active alerts
if (usage.alerts.length > 0) {
  console.warn(`Active alerts: ${usage.alerts.length}`);
  usage.alerts.forEach(alert => {
    console.log(`  ${alert.type}: ${alert.message}`);
  });
}

Response Example

Monitoring Dashboard

{
  "success": true,
  "data": {
    "apiUsage": {
      "totalRequests": 12543,
      "totalCost": 67.89,
      "avgResponseTime": 324,
      "errorRate": 1.2,
      "byPlatform": {
        "OpenAI": {
          "requests": 8234,
          "cost": 45.67,
          "avgResponseTime": 412
        },
        "Anthropic": {
          "requests": 4309,
          "cost": 22.22,
          "avgResponseTime": 198
        }
      }
    },
    "apifyUsage": {
      "account": {
        "username": "your-account",
        "plan": "STARTER",
        "isVerified": true
      },
      "stats": {
        "actors": 8,
        "datasets": 156,
        "runs": 423,
        "builds": 12
      },
      "usage": {
        "computeUnits": {
          "current": 1750,
          "limit": 2000,
          "utilization": 87.5
        },
        "storage": {
          "current": 4294967296,
          "limit": 10737418240,
          "utilization": 40.0
        }
      },
      "costs": {
        "monthly": 39.00,
        "daily": 1.30,
        "projected": 40.30
      },
      "alerts": [
        {
          "type": "warning",
          "resource": "Compute Units",
          "message": "Warning: 87.5% of compute units used",
          "utilization": 87.5
        }
      ]
    },
    "budgets": {
      "activeBudgets": 3,
      "totalAllocated": 5000.00,
      "totalSpent": 2145.67,
      "budgetsNearLimit": 1
    },
    "systemHealth": {
      "database": "healthy",
      "cache": "healthy",
      "apify": "healthy"
    }
  }
}

Alert Types

Budget Alerts

Defined in Prisma schema at /prisma/schema.prisma:614-636:
  • THRESHOLD_80: Budget at 80%
  • THRESHOLD_90: Budget at 90%
  • THRESHOLD_100: Budget at 100%
  • BUDGET_EXCEEDED: Budget exceeded
  • SPENDING_SPIKE: Unusual spending pattern
  • LOW_BUDGET: Low remaining balance
  • ALLOCATION_DEPLETED: Allocation exhausted

API Alerts

Defined in /prisma/schema.prisma:305-327:
  • RATE_LIMIT_WARNING: Approaching rate limit (80%)
  • RATE_LIMIT_CRITICAL: At rate limit (95%)
  • COST_WARNING: Unexpected cost increase
  • COST_CRITICAL: Cost threshold exceeded
  • ERROR_RATE_HIGH: High error rate (>5%)

Apify Alerts

Defined in /prisma/schema.prisma:504-520:
  • FAILURE_RATE: High failure rate
  • COST_SPIKE: Unexpected cost increase
  • DATA_QUALITY: Data quality issues
  • NO_RUNS: No recent runs (stale data)

Next Steps

Budget Management

Manage your budgets

API Reference

Explore all endpoints

Build docs developers (and LLMs) love