Skip to content
BuildBase

Quotas

Enforce per-plan usage limits for API calls, storage, exports, and more.

Quotas enforce per-plan usage limits - API calls, storage, exports, video renders. Record usage server-side and show quota status in your app.

Recording is the check. Where the quota is a hard allowance (overage off, or the workspace is trialing) the server refuses a unit past it with 402 QUOTA_EXHAUSTED (with quotaSlug and resetsAt) and records nothing. The error bb.usage.record throws carries that status as err.status; in @buildbase/sdk 0.0.90 it does not carry the server's code, which it does from SDK 1.0.0, so branch on status === 402. A bad request is a 400, so record before doing the work rather than reading the status first. quantity is a whole number from 1 to 1000000 in each report, and in each item of a batch; a fraction or a larger amount is a 400 and nothing is recorded, so send a larger amount as several reports. Where overage is on, the unit is recorded and billed, up to any spend cap the workspace or person set. An unlimited quota reads -1 for included and available.

When a plan bills overage, the units above what it includes reach the invoice through Stripe Billing Meters: BuildBase keeps one meter per quota in your Stripe account, reports each overage unit to it as a meter event for the subscription's Stripe customer, and Stripe adds the total to the subscription's next invoice at the plan's overage price.

import BuildBase from '@buildbase/sdk';

const bb = BuildBase({ serverUrl, orgId, getSessionId });

// Record usage in an API route, before doing the work
export async function POST(req) {
  let usage;
  try {
    usage = await bb.usage.record(workspaceId, {
      quotaSlug: 'api-calls',
      quantity: 1,
      // A string, or left out: a null key is refused with 400.
      idempotencyKey: req.headers.get('x-request-id') ?? undefined,
    });
  } catch (err) {
    // A hard allowance (no overage, or a trial) refuses the unit itself.
    // On the usage routes only that refusal answers 402.
    if (err.status === 402) {
      return Response.json({ error: 'Quota exceeded' }, { status: 429 });
    }
    throw err;
  }

  // -1 means unlimited; past the allowance with overage on, the unit is billed
  const remaining = usage.available === -1 ? null : usage.available;
  return Response.json({ remaining });
}

Before you start

Create the quota in the console first: Billing > Products, then Create product with Type set to Quota. Then give it a value on each plan version that includes it, in the version editor's card Quotas: included, per N & overage (Billing > Plans, the plan, then its version).

Set up a quota in the console

Open products in the console

(opens the console in a new tab)

1. Create the quota

In Billing > Products, press Create product and choose Type Quota. Its slug is what your code records usage against (Create a Quota product).

The Create quota dialog with Type Quota

2. Give it a value on the plan

In a draft plan version (Billing > Plans, Manage versions, Edit on the draft), press Add item under Subscription items and tick the quota. Its table on the card Quotas: included, per N & overage sets:

  • Included: what a workspace can use each month, for subscribers on each interval.
  • Per N units: how many units each overage price buys.
  • Over-usage allowed: on, a workspace past its allowance keeps going and the rest is billed at the overage price in each currency; off (Hard limit), a unit past the allowance is refused.

Press Save changes, then Publish version (Quotas).

The Reports per month quota: Over-usage allowed on, Included 100 monthly and yearly, Per N units 1, and an overage of 0.50 in EUR and USD

3. Record usage

Your server records each unit with bb.usage.record, as at the top of this page. The allowance resets every month on each subscription's own cycle, whatever its billing interval.

4. What the customer sees

openWorkspaceSettings('usage') opens the usage screen in your app, with a bar for each quota: what is used, the allowance and when it resets.

The app's Usage screen for Jordan Lee's Workspace: when usage resets, and the Reports per month bar at 42 of 100 highlighted as step 4

5. What you see

In the console, open the workspace (User management > Workspaces, then its row). The card Workspace quotas & credits lists each quota's Allowance, Used, Remaining and Over used. Its row buttons add or take one unit, reset the usage to 0, or Set value.

Workspace quotas & credits: Reports per month, Allowance 100, Used 42, Remaining 58, with Set value highlighted as step 5

6. Correct the usage

Set value opens Edit usage: type the usage for this period and press Save, for a correction or a goodwill reset. The allowance itself comes from the plan.

Edit usage - Reports per month with the Usage field at 42 highlighted as step 6, and Save

Check that it worked

A recorded unit adds to Used in the console and to the bar in your app. With Hard limit, the unit past the allowance is refused with 402 QUOTA_EXHAUSTED.

Things to watch out for

  • Allowances reset every month, on each subscription's own cycle, whatever the billing interval; a yearly subscriber's allowance is still monthly.
  • A free plan cannot bill overage: its quotas are a Hard limit (free plans cannot bill overage).
  • Overage needs a price in every billing currency while Over-usage allowed is on, or publishing is refused.
  • A trial is always held to the allowance, overage or not.
  • Publishing is refused until each quota has Included for at least one interval: "Quota "x": set Included (≥ 0) for at least one interval".

Showing quota status

import { useQuotaUsageStatus } from '@buildbase/sdk/react';

function UsageMeter({ workspaceId }) {
  const { status } = useQuotaUsageStatus(workspaceId, 'api-calls');
  if (!status) return null;

  // -1 is unlimited: there is no bar to fill
  if (status.included === -1) {
    return <p>{status.consumed} API calls used (unlimited)</p>;
  }

  const pct =
    status.included > 0
      ? Math.round((status.consumed / status.included) * 100)
      : 100;

  return (
    <div>
      <p>
        {status.consumed} / {status.included} API calls used
      </p>
      <div className="bg-muted h-2 rounded">
        <div
          className="bg-primary h-2 rounded"
          style={{ width: `${Math.min(pct, 100)}%` }}
        />
      </div>
    </div>
  );
}

Conditional components

import {
  WhenQuotaAvailable,
  WhenQuotaExhausted,
  WhenQuotaThreshold,
} from '@buildbase/sdk/react';

function APISection() {
  return (
    <>
      <WhenQuotaAvailable slug="api-calls">
        <Playground />
      </WhenQuotaAvailable>

      <WhenQuotaExhausted slug="api-calls">
        <p>Quota exhausted. Upgrade for more.</p>
      </WhenQuotaExhausted>

      <WhenQuotaThreshold slug="api-calls" threshold={80}>
        <p>Over 80% of API calls used.</p>
      </WhenQuotaThreshold>
    </>
  );
}
ComponentPropsRenders when
WhenQuotaAvailableslugHas remaining units
WhenQuotaExhaustedslugFully consumed
WhenQuotaOverageslugIn overage
WhenQuotaThresholdslug, thresholdUsage percentage at or above threshold

Batch recording

For high-throughput scenarios, record multiple events at once:

const result = await bb.usage.recordBatch(workspaceId, {
  items: [
    { quotaSlug: 'api-calls', quantity: 1, idempotencyKey: 'req-1' },
    { quotaSlug: 'storage-mb', quantity: 5, idempotencyKey: 'upload-1' },
  ],
});

Pre-built usage screen

openWorkspaceSettings('usage') shows a built-in usage dashboard with per-quota progress bars.

Next Steps

  • Spend caps - Cap overage, alert at a percentage and cap each project.
  • Feature Flags - Gate features by plan or user.
  • Billing - Subscription plans and checkout.