Skip to content
Credits & Usage Metering

Charge for usage, without building a ledger.

Workspaces and people buy credit packs through Stripe or get credits with their plan, and your app spends them with one call that refuses to take the balance below zero. Long jobs can set credits aside first and pay the real cost when they finish, and a balance can top itself up. For included usage there are quotas: a per-plan allowance, then either a bill for the extra or a hard stop, with a spend cap the customer sets.

Your app is an organization in BuildBase. Your users sign in and work inside workspaces - one per team or customer.

You set up

In the console and the SDK

  • Credit packs and their prices, in the console
  • Credits included with a plan, if you want them
  • One call where the paid work happens, like an AI generation

Your users get

Inside their workspace

  • A credit balance on their workspace or their own account
  • A store to buy more credits, through Stripe
  • A clear 'not enough credits' message, never a surprise bill

Usage-based pricing without the ledger work

Balances, buckets, expiry and the Stripe purchase are handled. You call consume where the work happens.

Sell Credit Packs

Set how many credits a pack holds and its price in each currency. Users buy through Stripe from a ready-made store.

Spend Safely

One call takes credits and returns the new balance. A retry never charges twice, and the balance never goes below zero.

Credits With a Plan

Include credits with a plan, once or every month, topped up or reset at renewal.

Oldest Spent First

Credits closest to expiring are used first, and users can see what is about to run out.

A Full History

Every purchase, spend, grant and refund is recorded with the balance after it. You can grant or take back credits per workspace.

Usage Limits by Plan

Give each plan an allowance, like API calls a month. Past it, you either bill the overage or stop the action.

Reserve, Then Settle

Hold credits before long work starts and settle the real amount when it ends, or release the hold, so two jobs never spend the same balance.

Top Up Automatically

Users can have the next pack bought on their saved card when the balance falls below a level they choose, so paid work does not stop mid-month. Not while you collect tax through Stripe Tax: those packs go through checkout.

Spend credits where the work happens

Gate the button with WhenCreditsAvailable and spend from the client, or charge from your API route and return a 402 when the balance runs out.

components/generate-button.tsxTSX
import {
  useConsumeCredits,
  useSaaSAuth,
  useSaaSWorkspaces,
  WhenCreditsAvailable,
  WhenCreditsLow,
} from '@buildbase/sdk/react';

export function GenerateButton() {
  const { currentWorkspace } = useSaaSWorkspaces();
  const { openCreditStore } = useSaaSAuth();
  const { consumeCredits, loading } = useConsumeCredits(currentWorkspace?._id);

  const generate = async () => {
    try {
      await consumeCredits({ amount: 10, description: 'AI generation' });
      // run the generation
    } catch (err: any) {
      if (err.code === 'INSUFFICIENT_CREDITS') openCreditStore();
    }
  };

  return (
    <>
      <WhenCreditsLow threshold={20}>
        <p>Running low on credits.</p>
      </WhenCreditsLow>
      <WhenCreditsAvailable
        min={10}
        fallbackComponent={<button onClick={() => openCreditStore()}>Buy credits</button>}
      >
        <button onClick={generate} disabled={loading}>
          Generate (10 credits)
        </button>
      </WhenCreditsAvailable>
    </>
  );
}
app/api/export/route.tsTSX
import BuildBase from '@buildbase/sdk';
import { cookies } from 'next/headers';

const bb = BuildBase({
  serverUrl: process.env.BUILDBASE_SERVER_URL!,
  orgId: process.env.BUILDBASE_ORG_ID!,
  getSessionId: async () =>
    (await cookies()).get('bb-session-id')?.value ?? null,
});

export async function POST(req: Request) {
  const { workspaceId } = await req.json();

  try {
    const { balanceAfter } = await bb.credits.consume(workspaceId, {
      amount: 50,
      description: 'Batch export',
      idempotencyKey: req.headers.get('x-request-id') ?? undefined,
    });
    // run the export
    return Response.json({ balanceAfter });
  } catch (err: any) {
    if (err.code === 'INSUFFICIENT_CREDITS') {
      return Response.json({ error: 'Not enough credits' }, { status: 402 });
    }
    throw err;
  }
}

Hold credits first, pay the real cost after

An AI call or an agent run doesn't know what it costs until it's done. A hold sets your estimate aside up front and charges the real cost at the end, so two jobs can never spend the same credits.

Set the estimate aside

Reserving takes the estimate out of the balance now, and is refused if there isn't enough. If your code sends the same reserve again with the same retry key, it gets back the first hold, never a second one.

Pay what it actually cost

Settle the hold when the work ends. If it cost less, the rest goes back to the balance. If it cost more, the extra is taken too, or refused with the hold left open. Settling at zero gives the whole hold back.

Give it back if the work fails

Releasing a hold returns all of it. On your server, withHold does the lot for you: it reserves, runs your function, charges the cost it returns, and gives everything back if it throws an error.

Holds that expire

A hold nobody closes is given back when its time runs out: 15 minutes by default, up to 24 hours. If the work outlives its hold, withHold on your server still charges for it, as a normal spend.

Balances that count holds

The balance your app reads already leaves out credits on hold, and so do the credit checks. The credits screen shows how much is held.

Events for every hold

Your webhooks and workflows hear when a hold opens, and when it is charged or given back. A charged hold also sends the usual spend event, so anything you built on spending sees held work too.

In your app, useReserveCredits and bb.credits.withHold need @buildbase/sdk 1.0.0 or later.

Top up before the balance runs out

When a balance drops below a level the customer picks, the next credit pack is bought on their saved card, so paid work doesn't stop mid-month. It works for workspaces and for people. It is not available while you collect tax with Stripe Tax, since a saved-card charge can't carry tax yet.

Pick the level, the pack and a limit

Choose the balance to top up at, the pack to buy, and the most top-ups in a month (1 to 50, 2 by default).

Never charged twice

Any spend, hold or expiry that takes the balance under the level can start a top-up, and each drop can charge only once, even if something retries. If the balance is back above the level by then, nothing is bought.

The right card

It uses the card saved for top-ups first, then the customer's default card, then the one the subscription is charged on. A card can be saved without charging it, and buying a pack by hand saves that card too.

Declined cards and bank checks

A declined card is tried again after longer and longer waits, then top-ups pause. If the bank wants the cardholder to confirm (3-D Secure), the customer gets a checkout for the same pack instead of a charge they can't approve.

Pauses that say why

When top-ups pause, the reason is spelled out. The monthly limit was hit, the card kept failing, or the subscription is on its final unpaid notice. Or there's no card, the pack isn't sold any more (or not in that currency), the terms changed since the customer agreed to them, or you started collecting tax.

Told at every step

Your webhooks hear when a top-up starts, when a charge fails and when the credits land. The owner gets an email on the first decline and on any pause.

In your app, useCreditAutoTopUp and its card on the credits screen need @buildbase/sdk 1.0.0 or later.

Every way credits arrive and leave

Packs, plans, grants and refunds all land in one ledger, a running record of every credit in and out. Credits that expire soonest are spent first.

Packs per currency

A pack has a number of credits, a price in each of up to 21 currencies and, if you like, how many days the credits last. Once bought, a pack keeps the credits and expiry it was sold with, whatever you change later.

Credits with a plan

A plan can give a pack's credits once or every billing period, either added to the balance or replacing it. If giving them fails, BuildBase retries on its own and tells you if it still fails.

Grants from your team

Give or take back credits on a workspace from the console. Each one lands in the ledger with who did it.

Soonest to expire, spent first

Credits closest to their expiry date are spent first. Every hour, credits past their date are removed, and your app can show what expires in the next few days.

Refunds and disputes

A refund takes back its share of the credits left in the pack. A chargeback (a dispute) takes back the rest, and winning the dispute gives them back, once. Credits already spent stay spent.

A person's own wallet

Credits can belong to one person instead of a workspace. They're bought on that person's own card and never mixed with a workspace's balance. Every credit hook can read the person's credits instead of a workspace's.

In your app, the person's wallet in the credit hooks ({ user: true }) and bb.me.credits need @buildbase/sdk 1.0.0 or later.

Quotas with extra usage, or a hard stop

A quota is how much a plan includes, such as API calls a month. Your server records usage with one call. Past the quota, the plan either bills the extra (overage) through Stripe or says no.

Extra usage billed by Stripe

Usage past the allowance is reported to Stripe, which adds it to the next invoice at the plan's price for extra units. BuildBase keeps one Stripe Billing Meter per quota for this.

Flat, tiered or in blocks

Price extra usage at one rate, in tiers where the rate changes with volume, or in blocks of units (say, per 1,000 calls). Set it for each billing period and each currency.

Refused, not overdrawn

With extra usage off, or during a trial, the first unit past the allowance is refused and nothing is recorded. The refusal says which quota ran out and when it resets. Record usage before doing the work, so a refusal stops it.

Counted once

Send each usage report with a key of your choosing. The same key twice, even at the same moment, counts once, so a retry never bills extra usage twice. You can also record many units in one call.

Usage in your app

Read one quota or all of them, page through the usage history, or drop in a ready-made usage screen with a bar for each quota. It's all in the SDK you already have.

Resets on its own

The allowance starts fresh each period, and a refusal says when, so your screen can tell the customer when they can carry on.

In your app, tiered prices on the plan picker and the usage screen need @buildbase/sdk 1.0.0 or later.

The controls customers want before they pay by usage

Caps a workspace sets for itself, a share for each member, and limits on things people create. Each one applies the moment usage is recorded.

Spend caps

A workspace or a person sets how far past its allowance a quota may go. Past that cap, usage is refused just as it is on a plan with no extra usage, so the bill can't run away.

Usage alerts

Pick percentages of the allowance, such as 80% and 100%. Your webhooks hear as each one is passed, once per period.

Caps per project

Record usage with a label (a partition key), such as a project id, and the workspace can cap each label on its own. One busy project can't use up the whole allowance.

Per-member allowances

Give each member of a team plan their own share every period, plus a shared pool to draw on when theirs runs out. The workspace still counts the total.

Limits on things people create

Count things like API keys, projects or installed apps against a limit: take a place when one is created, give it back when it's deleted. If two requests race for the last place, only one gets it, and a retry never takes a second place.

A refusal that says whose plan to raise

When a limit is full, the refusal says whether the workspace's plan or the person's own is the one to upgrade, so your screen can offer the right one.

In your app, a member's own allowance in useLimit, and bb.workspaces.limits for limits on things people create need @buildbase/sdk 1.0.0 or later.

The ledger, the console and the events

What your team sees and what your backend hears, without writing a reporting job.

The credit ledger

One console screen lists every purchase, spend, grant, expiry, take-back, refund and hold across your workspaces, with the balance after each and who did it.

Packs in the console

Create, price and archive credit packs. Archiving stops new sales, and customers keep what they bought.

Webhooks and workflows

Credits bought, given, spent, expired or taken back, and a quota going past its allowance, all reach your webhooks, and all but credits taken back can start a workflow. The ones a person should see also reach your Slack.

Frequently Asked Questions

What people ask about Credits.

Do my users see this?

Yes. They see a credit balance on their workspace, a store to buy more, and a clear message when there are not enough credits.

What is the difference between credits and quotas?

Credits are a balance your users buy or get with a plan, and spend. Quotas are a per-plan allowance, like API calls a month, that resets every month and is either billed as overage or capped.

Can a retry charge twice?

Not if you pass the same idempotency key. The balance also never goes below zero - a short balance is refused, not overdrawn.

Do credits expire?

Purchased credits expire only when the pack has a validity period. Plan credits can also expire when they renew or when the plan changes. Credits closest to expiring are spent first.

Can a long job hold credits before it runs?

Yes. Before an AI call or an agent run, hold the credits you expect it to use. When it ends, charge the real cost, or release the hold if it failed. A hold nobody settles is released when it expires. The balance your app reads already leaves out credits on hold.

Can credits top up automatically?

Yes, as long as you do not collect tax through Stripe Tax. A workspace or person picks a low-balance point, a pack to buy, and the most top-ups a month (1 to 50). When spending takes the balance below that point, the pack is bought on their saved card, once each time it drops below.

What happens to credits when a payment is refunded or disputed?

The credits still in the pack follow the money. A refund takes back its share of them. A dispute (a chargeback) takes back the rest of the pack, and winning the dispute gives them back. Credits already spent stay spent.

Can a customer cap what overage costs them?

Yes. A workspace or person can set a spend cap on a quota: how many units past their allowance they are willing to pay for. Past that, more usage is refused rather than billed. They can also pick the points, as percentages of the allowance, at which your webhooks and workflows are told.

Put a price on your most expensive action

Create a credit pack in the console, then call consumeCredits() where the work happens. Stripe handles the purchase.

Free plan7-day free trial on paid plansNo credit card required