---
title: "Spend credits in your functions"
description: "Spend credits from your own server code, in one call or as reserve, run and settle so a failed run costs nothing, hold them for a queued job, let a plan with usage pricing go past the balance, and give credits back on a sum meter."
canonical_url: "https://nuxt-backend.dev/docs/build/billing/credits/spending"
---
# Spend credits in your functions

> Spend credits from your own server code, in one call or as reserve, run and settle so a failed run costs nothing, hold them for a queued job, let a plan with usage pricing go past the balance, and give credits back on a sum meter.

Version: nuxt-backend 0.6.x · Tab: Build · Kind: how-to · Status: stable

Every page: [llms.txt](https://nuxt-backend.dev/llms.txt) · Skill for coding agents: [nuxt-backend](https://nuxt-backend.dev/.well-known/skills/nuxt-backend/SKILL.md)

Commands use npm; use your project's package manager.

- [Try it live in the playground](https://nuxt-backend.dev/playground/strips)
- [API reference](https://nuxt-backend.dev/docs/reference/api/billing)
- [Source](https://github.com/qruto/nuxt-backend/blob/main/src/convex/integrations/billing/credits.ts)

You spend credits from your own server code, in the function that does the paid work, and never from the browser. One call charges at once. The three-step form reserves the credits first, runs the work, and charges only when it succeeded, so a failed generation costs nothing.

- **Polar does natively:** it ingests usage events, deduplicates them by `external_id`, subtracts them from the meter balance, and bills what goes past it on a metered price (checked on 2026-10-25).
- **The package adds:** a balance check in the same Convex transaction as the reservation, so two spends at once can never both pass, plus settle and release, refunds on a sum meter, and the caller checks billing makes everywhere.

```ts [backend/strips.ts]
import { v } from 'convex/values'
import { action } from './_generated/server'
import { billing } from './billing'

export const generatePanel = action({
  args: { prompt: v.string() },
  handler: async (ctx, { prompt }) => {
    // The billing entity (the active workspace, or the user with billTo: 'user') resolves from the session.
    await billing.spendCredits(ctx, { meter: 'credits', value: 1 })
    return drawPanel(prompt)
  },
})
```

`drawPanel` is your own code. `spendCredits(ctx, event)` takes a `SpendCreditsEvent`:

- `meter`, a catalog key, or a raw `meterId`;
- `value`, `1` by default;
- `name`, the provider's event name, by default the meter's `eventName` or key;
- `userId`, to spend for an entity your server code chose;
- `allowOverage`, to let the balance go below zero (the pay-as-you-go case below; off by default);
- `metadata` and `timestamp`;
- `externalId`, the idempotency key, a random UUID by default.

Every amount must be a finite number above zero: `value` here and in `refundCredits`, and a reservation's `value` when it settles. A settle's `finalAmount` is zero or more. Anything else throws before the cached balance or the provider sees it: a negative spend would credit the balance, and a `NaN` would leave a balance every later check waves through. The cache's own mutations refuse the same amounts, and a balance that is not a number refuses spends.

<note>

The scaffolded [`ai.ts`](https://nuxt-backend.dev/docs/build/ai/metered-actions) wraps these spends into `ai.meteredAction` and `ai.stream`, with rate limiting and `ctx.usage`. Reach for those before you write spends by hand.

</note>

## Reserve, run, settle

A spend is three steps, and `spendCredits` is the one-call form of them:

1. **reserveCredits** takes the credits off the cached balance inside the component, in one atomic step. Convex mutations serialize, so two concurrent spends can never both pass, and the spend path never waits on the provider. A balance that is too low throws `insufficient_credits` with `balance` and `need` ([Errors](https://nuxt-backend.dev/docs/reference/backend/errors#insufficient_credits)). Credits stay strictly prepaid unless the spend passes `allowOverage: true`. A cache that was granted credits but never synced heals itself once from an action's context; `allowRefresh: false` skips that from a mutation.
2. **settleSpend** ingests the usage event at the provider, the only durable record, which the customer sees in the provider's portal, and closes the reservation. Pass `finalAmount` when the real cost came in under the estimate: the rest goes back to the balance in the same transaction. It is capped at the reservation, since settling above it would be a second, unguarded charge. A `finalAmount` of `0` ingests nothing and hands the whole reservation back. A failed ingest releases the whole reservation.
3. **releaseSpend** undoes a reservation whose work failed. Nothing is charged.

When `settleSpend` can't reach the provider, it releases the reservation and throws, so the run is not charged. To charge it anyway, call `settleSpend` again with the same reservation: the provider drops an event whose `externalId` it already has, so a retry never charges twice, and the cached balance catches up on the provider's next update. A `spendCredits` call that you retry gets a new `externalId` each time unless you pass your own.

When you will retry, pass `keepReservation: true`. A refused settle then keeps what it would have charged held, under the same id, and gives only the rest back, in one transaction. No other spend can take those credits between your tries, as it could if the reservation were released and then taken again. Call `releaseSpend` when you stop trying. The job queue settles an owed charge this way ([When the billing provider refuses the charge](https://nuxt-backend.dev/docs/build/ai/jobs/credits#when-the-billing-provider-refuses-the-charge)).

The split lets work run between the check and the charge. `setupAi` reserves before it runs a model and settles only after success, and its streaming endpoint settles in a different function than the one that reserved:

```ts [backend/strips.ts]
const reservation = await billing.reserveCredits(ctx, { meter: 'credits', value: 5 })
try {
  const panel = await drawPanel(prompt)
  await billing.settleSpend(ctx, reservation)
  return panel
}
catch (error) {
  await billing.releaseSpend(ctx, reservation)
  throw error
}
```

A `SpendReservation` is plain serializable data (`entityId`, `externalId`, `reserved`, `meter`, `meterId`, `value`), so it can cross function boundaries. Because it can, `settleSpend` checks its `value` again rather than ingesting on its word.

A reservation holds for 10 minutes unless you pass `hold`. A flow that crashed between reserving and settling heals itself: its reservation lapses, and the balance syncs from the provider again.

## Hold credits for a queued job

A strip that waits in a generation queue can wait longer than 10 minutes. Pass `hold`, in milliseconds and a week at most, to keep the reservation until a worker picks the job up. Reserve when the job is queued, settle when it starts, and give the credits back when it fails.

```ts [backend/stripQueue.ts]
import { HOUR } from 'nuxt-backend/rate-limit'
import { billing } from './billing'

// When the job is queued: refuse a short balance now, and hold the credits.
const reservation = await billing.reserveCredits(ctx, { meter: 'credits', value: 50, hold: 6 * HOUR })

// When a worker starts it: charge.
await billing.settleSpend(ctx, reservation)

// When it fails before it starts: let the hold go.
await billing.releaseSpend(ctx, reservation)

// When it fails after the charge: give the credits back on a sum meter.
await billing.refundCredits(ctx, { meter: 'credits', value: 50, externalId: `${reservation.externalId}:refund` })
```

Store the reservation on the job's row, since it is plain data. A held reservation counts against the balance until you settle or release it, or until `hold` runs out. `defineJobQueue` from `nuxt-backend/ai` does all of this for you: it reserves at enqueue, charges at dispatch and refunds a failed run ([Charge for a queued job](https://nuxt-backend.dev/docs/build/ai/jobs/credits)). A cancelled job that already started stays charged.

## Sum meters vs count meters

A meter's aggregation decides what one event spends and whether credits can be given back:

<table>
<thead>
  <tr>
    <th>
      
    </th>
    
    <th>
      <code>
        aggregation: 'sum'
      </code>
      
       (default)
    </th>
    
    <th>
      <code>
        aggregation: 'count'
      </code>
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      One event means
    </td>
    
    <td>
      <code>
        metadata[property]
      </code>
      
       credits (default property <code>
        amount
      </code>
      
      )
    </td>
    
    <td>
      exactly 1 credit
    </td>
  </tr>
  
  <tr>
    <td>
      Multi-credit spends
    </td>
    
    <td>
      <code>
        value: 5
      </code>
      
       in one event
    </td>
    
    <td>
      throws: spend <code>
        1
      </code>
      
       per event
    </td>
  </tr>
  
  <tr>
    <td>
      Refunds
    </td>
    
    <td>
      <code>
        refundCredits
      </code>
      
       ingests a compensating negative event
    </td>
    
    <td>
      not possible
    </td>
  </tr>
</tbody>
</table>

```ts [backend/strips.ts]
// Give credits back on a sum meter, for a generation the person rejected
await billing.refundCredits(ctx, { meter: 'credits', value: 5 })
```

The cached balance shows a refund at once, and holds it for five minutes: Polar applies the event a moment after it takes it, so a read of Polar in that time, by a webhook or a sync, may not count it yet, and never takes the meter below the cached balance. A meter the cache does not list yet is added with the refund. A second refund under the same `externalId` is one Polar drops, and the cache credits it once.

## Who may spend

A spend without a `userId` checks its caller the way the billing reads do: signed in, a member of the workspace that pays (read fresh), and never an administrator impersonating someone. Pass `userId` only for an entity your server code chose itself, from a cron or a queued job, never an id a caller sent.

Each spend is a usage event on the entity's customer at the provider: the provider's portal and dashboard show it, `useUsage()` lists it, and a metered price on the plan bills what went past the allowance ([Charge for usage beyond the plan](https://nuxt-backend.dev/docs/build/billing/subscriptions/overage)).

## What happens when…

<table>
<thead>
  <tr>
    <th>
      Case
    </th>
    
    <th>
      Result
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      The balance is too low
    </td>
    
    <td>
      <a href="https://nuxt-backend.dev/docs/reference/backend/errors#insufficient_credits">
        <code>
          insufficient_credits
        </code>
      </a>
      
       with <code>
        balance
      </code>
      
       and <code>
        need
      </code>
      
      ; nothing is reserved or charged
    </td>
  </tr>
  
  <tr>
    <td>
      An amount is zero, negative or not a number
    </td>
    
    <td>
      A throw before the cache or Polar sees it
    </td>
  </tr>
  
  <tr>
    <td>
      A count meter is asked for <code>
        value: 5
      </code>
    </td>
    
    <td>
      A throw: spend <code>
        1
      </code>
      
       per event, or switch the meter to <code>
        sum
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      Polar is unreachable at settle
    </td>
    
    <td>
      The reservation is released, or kept with <code>
        keepReservation
      </code>
      
      , and <code>
        settleSpend
      </code>
      
       throws; retry with the same reservation to charge it once
    </td>
  </tr>
  
  <tr>
    <td>
      A flow crashes between reserve and settle
    </td>
    
    <td>
      The reservation lapses after 10 minutes, and the balance syncs from Polar again
    </td>
  </tr>
  
  <tr>
    <td>
      A caller is no longer a member, or is an impersonating admin
    </td>
    
    <td>
      <code>
        forbidden
      </code>
      
      , as for every billing call (<a href="https://nuxt-backend.dev/docs/build/billing/setup#who-may-buy-for-a-workspace">
        Who may buy for a workspace
      </a>
      
      )
    </td>
  </tr>
</tbody>
</table>

## Limits

- **Prepaid unless you say otherwise.** Only `allowOverage: true` lets a balance go below zero, and only a plan with a usage price bills for it.
- **Refunds need a sum meter.** A count meter has no negative event.
- **A usage price's cap is Polar's, not yours.** Past the cap, Polar bills nothing more, so refuse in your own function before reserving when a customer should stop ([Charge for usage beyond the plan](https://nuxt-backend.dev/docs/build/billing/subscriptions/overage)).
- **Ten minutes per reservation, a week with hold.** A hold that runs out lets the reservation lapse, and the balance syncs from the provider again.

## Test it

A spend checks its caller first, so a test needs no Polar to prove who may spend. `asUser` signs a caller in as a real session would:

```ts [backend/strips.test.ts]
import { getBackendError } from 'nuxt-backend/functions'
import { asUser, defineBackendTestApp } from 'nuxt-backend/test'
import { expect, test } from 'vitest'
import { api } from './_generated/api'
import schema from './schema'

const testApp = defineBackendTestApp(schema, import.meta.glob('./**/*.ts'))

test('an impersonating admin may not spend a workspace\'s credits', async () => {
  const support = await asUser(testApp(), { impersonatedBy: 'admin_1' })
  const refusal = await support.action(api.strips.generatePanel, { prompt: 'A cat in a cape' }).catch(getBackendError)
  expect(refusal).toMatchObject({ code: 'forbidden', data: { reason: 'impersonating' } })
})
```

Then spend for real on Polar's sandbox, and watch the event arrive in `useUsage()` and the sandbox dashboard ([Develop with real sandboxes](https://nuxt-backend.dev/docs/develop/sandboxes#billing-on-polars-sandbox)).

## Related

- [Polar](https://nuxt-backend.dev/docs/services/polar): meters, usage events and the sandbox.
- [Sell credits and top-ups](https://nuxt-backend.dev/docs/build/billing/credits): balances, packs and the low-balance notice.
- [Meter an AI action](https://nuxt-backend.dev/docs/build/ai/metered-actions): `ai.meteredAction` and `ai.stream`, built on these spends.
- [Charge for a queued job](https://nuxt-backend.dev/docs/build/ai/jobs/credits): the hold the job queue takes for you.
- [Billing API reference](https://nuxt-backend.dev/docs/reference/api/billing): `SpendCreditsEvent` and `SpendReservation`.


## Sitemap

See the full [sitemap](https://nuxt-backend.dev/sitemap.md) for all pages.
