Usage Analytics

Track your API consumption, monitor usage patterns, and stay within your plan limits. ComplianceLayer provides comprehensive usage analytics to help you optimize API calls and manage costs.

Why Track Usage?

  • Cost Management: Monitor consumption to avoid unexpected overages
  • Optimization: Identify which endpoints consume the most quota
  • Planning: Historical trends help you choose the right plan
  • Debugging: Detect unusual API activity or integration issues

Usage Summary

Get an overview of your API usage for a specific time period:

GET/usage/summary

Get aggregated usage statistics for your account over a date range.

Query Parameters

ParameterTypeRequiredDescription
start_datestringNoStart date (YYYY-MM-DD format). Defaults to beginning of current billing period.
end_datestringNoEnd date (YYYY-MM-DD format). Defaults to today.
curl "https://api.compliancelayer.net/v1/usage/summary?start_date=2026-03-01&end_date=2026-03-09" \
  -H "Authorization: Bearer cl_YOUR_API_KEY"

plan is a plan slug string such as "free", not an object. endpoints is an object mapping endpoint name to request count for the current month.

Counter scope. The scan figures (scans_this_month, scans_per_month) are authoritative and agree with /usage/limits. The request-level counters — total_requests, requests_today, and the endpoints breakdown — count authenticated API requests from July 29, 2026 onward (no earlier history exists) and are recorded asynchronously, so very recent requests can take a moment to appear. Treat them as informational rather than billing-grade.

Check Limits

Verify your current usage against plan limits before making requests:

GET/usage/limits

Check if you're within your plan's usage limits. Returns detailed quota information and remaining capacity.

curl "https://api.compliancelayer.net/v1/usage/limits" \
  -H "Authorization: Bearer cl_YOUR_API_KEY"

This is the endpoint to check before a batch operation or a scheduled run. usage.scans_remaining is the number that matters, and status.can_run_scan is the boolean form of the same question. There is no usage_percent field — compute it from scans_used and scans_limit if you need one.

The overage block applies to paid plans, which are billed per scan beyond their quota rather than being cut off. On Free, eligible is false, rate_per_scan is null, and running out of quota is a hard stop that returns 429.

Usage by Endpoint

See which API endpoints consume the most of your quota:

GET/usage/by-endpoint

Get a breakdown of API usage by endpoint over the specified time period. Helps identify optimization opportunities.

Query Parameters

ParameterTypeDefaultDescription
daysnumber30Number of days to analyze (1-90)
curl "https://api.compliancelayer.net/v1/usage/by-endpoint?days=7" \
  -H "Authorization: Bearer cl_YOUR_API_KEY"

Entries are sorted by count, highest first, and are grouped by endpoint and method. error_rate is the percentage of calls that returned 4xx or 5xx. There is no percent field; divide count by total_requests yourself.

Depends on request logging. This breakdown is built from API request logs, which are still being instrumented. An empty endpoints array with total_requests: 0 does not mean you made no calls. Use it for a rough picture, not for reconciliation.

Historical Trends

View usage trends over time to identify patterns and plan capacity:

GET/usage/history

Get monthly usage history for trending analysis. Useful for capacity planning and identifying seasonal patterns.

Query Parameters

ParameterTypeDefaultDescription
monthsnumber6Number of months to return (1-12)
curl "https://api.compliancelayer.net/v1/usage/history?months=3" \
  -H "Authorization: Bearer cl_YOUR_API_KEY"

Buckets are calendar months labelled YYYY-MM, oldest first, ending with the current (partial) month. Each bucket has only month, api_requests, and scans — there is no per-bucket plan field and no trends object, so compute averages or projections client-side. current_plan is a plan slug such as "free".

Practical Examples

Monitoring Daily Usage

Check your usage at the start of each day to stay within limits:

async function checkDailyUsage() {
  const response = await fetch(
    'https://api.compliancelayer.net/v1/usage/limits',
    {
      headers: {
        'Authorization': `Bearer ${process.env.API_KEY}`
      }
    }
  );

  const data = await response.json();
  const { scans_used, scans_limit, scans_remaining } = data.usage;
  const usagePercent = (scans_used / scans_limit) * 100;

  console.log(`Plan: ${data.plan.name}`);
  console.log(`Scans used: ${scans_used}/${scans_limit} (${scans_remaining} left)`);
  console.log(`Usage: ${usagePercent.toFixed(1)}%`);

  // Warn if approaching limit
  if (usagePercent > 80) {
    console.warn('⚠️  Approaching monthly scan limit!');
  }

  return data;
}

// Run daily check
await checkDailyUsage();

Identifying Top Endpoints

Find which endpoints you call most frequently:

async function analyzeEndpointUsage(days = 30) {
  const response = await fetch(
    `https://api.compliancelayer.net/v1/usage/by-endpoint?days=${days}`,
    {
      headers: {
        'Authorization': `Bearer ${process.env.API_KEY}`
      }
    }
  );

  const data = await response.json();

  console.log(`Usage analysis for last ${days} days:`);
  console.log(`Total requests: ${data.total_requests}`);
  console.log('\nTop endpoints:');

  data.endpoints.slice(0, 5).forEach((endpoint, i) => {
    const share = data.total_requests
      ? (endpoint.count / data.total_requests * 100).toFixed(1)
      : '0.0';

    console.log(`${i + 1}. ${endpoint.method} ${endpoint.endpoint}`);
    console.log(`   Calls: ${endpoint.count} (${share}%)`);
    console.log(`   Avg response time: ${endpoint.performance.avg_ms.toFixed(0)}ms`);
    console.log(`   Error rate: ${endpoint.error_rate.toFixed(1)}%`);
  });

  return data;
}

await analyzeEndpointUsage(7);

Capacity Planning

Use historical data to predict future usage and plan upgrades:

async function planCapacity() {
  const response = await fetch(
    'https://api.compliancelayer.net/v1/usage/history?months=6',
    {
      headers: {
        'Authorization': `Bearer ${process.env.API_KEY}`
      }
    }
  );

  const data = await response.json();

  // Calculate average monthly scans
  const avgScans = data.history.reduce((sum, month) => sum + month.scans, 0) / data.history.length;

  // Get current plan limit
  const limitsResponse = await fetch(
    'https://api.compliancelayer.net/v1/usage/limits',
    {
      headers: {
        'Authorization': `Bearer ${process.env.API_KEY}`
      }
    }
  );

  const limits = await limitsResponse.json();
  const monthlyLimit = limits.plan.limits.scans_per_month;

  console.log(`Average monthly scans: ${Math.round(avgScans)}`);
  console.log(`Current plan limit: ${monthlyLimit}`);
  console.log(`Capacity utilization: ${((avgScans / monthlyLimit) * 100).toFixed(1)}%`);

  // Recommend upgrade if consistently over 80%
  if ((avgScans / monthlyLimit) > 0.8) {
    console.log('\n💡 Recommendation: Consider upgrading your plan');
    console.log('   You\'re consistently using over 80% of your quota.');
  }

  return data;
}

await planCapacity();

Best Practices

1. Monitor Usage Proactively

  • Check /usage/limits before running batch operations
  • Set up daily cron jobs to track usage trends
  • Alert when usage exceeds 80% of quota

2. Optimize High-Volume Endpoints

  • Use /usage/by-endpoint to identify optimization targets
  • Cache results where appropriate
  • Use webhooks instead of polling for scan status
  • Batch operations where possible

3. Plan Ahead

  • Review /usage/history monthly for trends
  • Upgrade plans before hitting limits, not after
  • Account for seasonal patterns in your usage

4. Build Usage Dashboards

Create internal dashboards that visualize:

  • Current usage vs plan limits (from /usage/limits)
  • Daily/weekly usage trends (from /usage/summary)
  • Top API consumers by endpoint (from /usage/by-endpoint)
  • Cost projections based on historical data

5. Set Up Alerts

async function checkAndAlert() {
  const response = await fetch(
    'https://api.compliancelayer.net/v1/usage/limits',
    {
      headers: {
        'Authorization': `Bearer ${process.env.API_KEY}`
      }
    }
  );

  const data = await response.json();
  const usagePercent = data.usage.scans_used / data.usage.scans_limit * 100;

  if (usagePercent >= 90) {
    // Critical: Send PagerDuty alert
    await notifyPagerDuty({
      severity: 'critical',
      summary: `API quota at ${usagePercent}%`,
      details: data
    });
  } else if (usagePercent >= 80) {
    // Warning: Send Slack notification
    await notifySlack({
      channel: '#engineering',
      text: `⚠️  API usage at ${usagePercent}% of monthly quota`
    });
  }
}

// Run every hour
setInterval(checkAndAlert, 60 * 60 * 1000);

Troubleshooting

Scan Counts Don't Match What I Expected

  • Only completed scans are counted. A scan that failed does not consume quota.
  • Scans triggered indirectly still count: adding a monitored domain runs an immediate scan, every scheduled scan counts, and a batch of N domains counts as N.
  • The period is your entitlement period, which may not start on the first of the calendar month. /usage/limits counts against that period; /usage/history buckets by calendar month.

Request Counters Read Zero

  • Expected for now. Per-request logging is still being instrumented, so total_requests, requests_today, the endpoints map, and /usage/by-endpoint can all be zero or empty on an account that is actively making calls.
  • Scan counts are unaffected and remain accurate.
  • For live rate-limit headroom, read the x-ratelimit-* response headers instead — see Rate Limits.

Historical Data Shows Gaps

  • A month with no activity is still returned, with zeros — gaps are real, not missing data.
  • The newest bucket is the current month and is partial by definition.
  • months defaults to 6.

Related Topics