---
title: "Charge for a queued job"
description: "Price a job in credits: the queue holds them when the job joins the line, so the person learns at once if they can afford it, charges them when it starts, and refunds them when it fails or stalls."
canonical_url: "https://nuxt-backend.dev/docs/build/ai/jobs/credits"
---
# Charge for a queued job

> Price a job in credits: the queue holds them when the job joins the line, so the person learns at once if they can afford it, charges them when it starts, and refunds them when it fails or stalls.

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

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.

- **You get:** a fixed price per job, refused at the door when the balance is short, charged when it starts and refunded when it fails; and what each job cost you, per customer, in Polar.
- **Powered by:** Polar's credit meters, usage events and Cost Insights.
- **The package adds:** a hold that lasts as long as the job waits, the charge as the job's first durable step, the refund, idempotency keys on both, and a cost event per job.

A job is priced up front, in credits, like a product: 5 credits a panel, whatever its model calls cost. The queue holds the credits the moment the job joins the line, so someone who cannot afford it hears so before they wait. It charges them when the job starts, and refunds them if the job fails. A hold, or reservation, takes credits from the balance without charging them yet. A metered action reserves for a few minutes at most. A job can wait in line for an hour, so its hold lasts as long as the job waits.

## Price a job

`meter` and `cost` on `jobs.define` set the price:

```ts [backend/strips.ts]
export const render = jobs.define({
  meter: 'credits',
  cost: ({ panels }) => panels * 5,
  args: { stripId: v.id('strips'), idea: v.string(), panels: v.number() },
  handler: async (job, args) => {
    // …
  },
})
```

- **meter** is a sum meter from your catalog. A refund is a negative usage event, which a count meter cannot take, so a count meter throws where the job is defined.
- **cost** is a number, or `(args) => number` read once when the job joins. It must be a finite number above zero.
- **meter: false** makes the job free: no hold and no usage event, only the line. Its `cost`, `1` when you set none, still counts against a tier's budget.

A job's price is fixed, unless it charges by what it made ([Charge for what a job made](#charge-for-what-a-job-made)). Its model calls are not metered one by one: the queue charges what you priced, not what the gateway reported. What each job cost you reaches Polar beside the charge ([Report what each job cost you](#report-what-each-job-cost-you)), so you can check the price stays above it.

## Charge for what a job made

Some jobs only know their price at the end: a strip of up to six panels, of which the model drew four. `charge: 'output'` holds `cost` as the most the job may cost, and the handler charges what it made with `job.charge(n)`:

```ts [backend/strips.ts]
export const render = jobs.define({
  meter: 'credits',
  charge: 'output',
  cost: ({ panels }) => panels * 5,
  args: { stripId: v.id('strips'), idea: v.string(), panels: v.number() },
  handler: async (job, { stripId, idea, panels }) => {
    let drawn = 0
    for (let panel = 1; panel <= panels; panel++) {
      const { ok } = await job.run(internal.strips.drawPanel, { stripId, idea, panel })
      if (ok) drawn++
    }
    await job.charge(drawn * 5)
  },
})
```

- **The hold** is taken when the job joins, and again as its first step: a no-op while it stands, so a balance read for the first time, or a hold past its week, is taken before any model is called.
- **job.charge(n)** is one usage event of `n` credits, never more than the hold: a larger `n` charges the hold and logs `ai.cost_over_reservation`. The rest of the hold goes back to the balance in the same step, never billed. It carries the hold's id as its idempotency key, so a step run again never bills twice. A second call changes nothing.
- **job.charge(n, { metadata })** adds string metadata of your own to the usage event, such as the id of what the job made: `job.charge(drawn * 5, { metadata: { stripId } })`. The queue's own `userId` (the member who started the job) and `job` (its kind) go on every charge, and win over keys of the same name. Polar takes 50 keys on an event, so yours are 47 at most beside the queue's two and the meter's amount. Each key is 1 to 40 ASCII characters and starts with neither `_`, which Polar keeps for its own keys such as `_cost` and `_llm`, nor `$`. Each value is a string of at most 500 characters. `job.charge` throws a `TypeError` for metadata past those limits, which fails the job before anything is charged, since Polar would refuse that charge on every try.
- **A job that fails after job.charge** is refunded what it was charged, under the hold's id with `-refund` added: a refund tried again never gives back twice.
- **A job that ends without job.charge**, fails or stalls before it, or is canceled before it, costs nothing: its hold is released.

An administrator's retry of a job charged by output never runs on the old charge: the rerun takes a fresh hold and charges what it makes. A charge whose refund gave up is given back first: that retry tries the refund again, and a retry once it lands runs the job.

### When the billing provider refuses the charge

A job charged by output has done its work by the time it charges: the strip is drawn. When the billing provider refuses `job.charge` for a passing reason, the job does not fail and the person keeps what it made. A passing reason is one of these: the provider did not answer, it answered `408`, `429` or a `5xx`, or the workspace has no billing customer yet. The charge is owed instead:

1. **The job runs on and ends done**, its result kept. `onJobEnd` hears it with `owed: n`, the credits still owed, and `charged: 0`. `jobs.get` and `getJob` read `owed: { credits: n, givenUp: false }`.
2. **Its credits stay held** under the job's hold id, so the person cannot spend them again while the charge is owed. A refused try keeps `n` of the hold and gives the rest back in one transaction (`settleSpend`'s `keepReservation`). The hold is never let go and taken again between tries, so no other spend can take those credits meanwhile.
3. **The queue tries the charge again in the background**, a minute later, then two, doubling, eight tries in all, about two hours. Each try settles under the same idempotency key as the first, so the provider bills the job once, however many tries reach it.
4. **Once it lands**, `charged` reads `n`, `owed` is gone, and `onOwedCharge` hears `status: 'charged'`.
5. **After the last try** the charge is given up: the hold goes back, the job stays `done` and uncharged, `owed` reads `givenUp: true`, `onOwedCharge` hears `status: 'given_up'`, and `ai.job_charge_given_up` is logged. The Queue tab shows the job with the credits it was never charged, and its **Retry the charge** button (`retryJob`) owes the charge again, holds its credits again and tries it at once, recording `job.charge_retried`. A second press while that try runs changes nothing.

A provider that refuses the charge itself, with any other `4xx`, would refuse every try: a revoked access token (`401`), a product or meter it does not have (`403`, `404`). These are an operator's mistakes, never the person's, so the job still ends `done` and keeps what it made, and the charge is given up at once, with no try in the background. The hold goes back, `owed` reads `givenUp: true`, `onOwedCharge` hears `status: 'given_up'`, and `ai.job_charge_refused` is logged as an error. Fix what it names, then press **Retry the charge**. A background try that meets such a refusal gives up the same way, without the tries left. A charge at start refused this way still fails its job with `unavailable` (reason `provider_refused`), its hold back.

A balance short of the credits is no passing refusal: the job still fails with `insufficient_credits`. Metadata past the provider's limits never reaches it: `job.charge` throws first. A job that fails or is refunded after its charge was owed owes nothing, whether the charge's tries still run or gave up while the job ran: its owed charge is dropped, its hold goes back, and its retry from the dead letters runs the job again. A try already on its way when the job fails may still land; it is then refunded at once, under the hold's id with `-refund`. A job canceled without a refund keeps its owed charge, as it would keep a charge that landed.

Hear how an owed charge ended with `onOwedCharge`, an internal mutation or action of yours taking `vOwedCharge`, beside `onJobEnd`:

```ts [backend/jobs.ts]
export const jobs = defineJobQueue(components, {
  ai,
  onJobEnd: internal.strips.ended,
  onOwedCharge: internal.strips.charged,
})
```

```ts [backend/strips.ts]
import { vOwedCharge } from 'nuxt-backend/ai'

export const charged = internalMutation({
  args: vOwedCharge,
  handler: async (ctx, { args, status, credits }) => {
    const { stripId } = args as { stripId: Id<'strips'> }
    // Your record of what the strip was billed; never move credits here.
    await ctx.db.patch(stripId, status === 'charged' ? { billed: credits } : { billing: 'unpaid' })
  },
})
```

It runs once per owed charge that ends. A charge that lands while the job still runs is heard before `onJobEnd`, which then reports no `owed`; one an administrator retries after it gave up is heard again, `charged` after `given_up`: let the later one win.

## Run one job for free

`jobs.enqueue(ctx, job, args, { free: true })` runs one job of a metered kind for nothing: it holds no credits, is never charged, and counts in no tier's budget. `job.charge` does nothing in it, and `onJobEnd` and `jobs.get` report `free: true`. Your mutation decides who gets it, such as a plan's monthly free generation. Record the use in the same mutation that puts the job in line: two strips started at once then cannot both run free, since Convex runs one of the two mutations again against what the other wrote:

```ts [backend/strips.ts]
const month = new Date().toISOString().slice(0, 7)
const used = await ctx.db.query('freeRenders')
  .withIndex('by_workspace_and_month', q => q.eq('workspaceId', ctx.workspace.id).eq('month', month))
  .unique()
if (!used) await ctx.db.insert('freeRenders', { workspaceId: ctx.workspace.id, month })
const { jobId } = await jobs.enqueue(ctx, internal.strips.render, args, { free: !used })
```

## When credits move

<table>
<thead>
  <tr>
    <th>
      The job
    </th>
    
    <th>
      Its credits
    </th>
    
    <th>
      At the billing provider
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      Joins the line
    </td>
    
    <td>
      Held: the balance drops at once
    </td>
    
    <td>
      Nothing yet
    </td>
  </tr>
  
  <tr>
    <td>
      Is refused at the door
    </td>
    
    <td>
      Never held, and never counted against the tier's budget
    </td>
    
    <td>
      Nothing
    </td>
  </tr>
  
  <tr>
    <td>
      Starts
    </td>
    
    <td>
      Charged
    </td>
    
    <td>
      A usage event on the meter, for the member who started it
    </td>
  </tr>
  
  <tr>
    <td>
      Finishes
    </td>
    
    <td>
      Stay charged
    </td>
    
    <td>
      
    </td>
  </tr>
  
  <tr>
    <td>
      Finishes, its charge by output refused for now
    </td>
    
    <td>
      Stay held while the charge is owed: charged once it lands, back to the balance if it is given up
    </td>
    
    <td>
      The same usage event, under the same key, once a try lands
    </td>
  </tr>
  
  <tr>
    <td>
      Finishes, its charge by output refused for good (<code>
        401
      </code>
      
      , <code>
        403
      </code>
      
      , <code>
        404
      </code>
      
      )
    </td>
    
    <td>
      Back to the balance at once: the charge is given up until an administrator retries it
    </td>
    
    <td>
      Nothing until that retry lands
    </td>
  </tr>
  
  <tr>
    <td>
      Is canceled before it starts
    </td>
    
    <td>
      The hold is released, and its cost goes back to the budget window
    </td>
    
    <td>
      Nothing
    </td>
  </tr>
  
  <tr>
    <td>
      Is canceled while it runs
    </td>
    
    <td>
      Stay charged: the steps it finished were real work. A kind charged by output canceled before <code>
        job.charge
      </code>
      
       is never charged
    </td>
    
    <td>
      
    </td>
  </tr>
  
  <tr>
    <td>
      Fails or stalls
    </td>
    
    <td>
      Refunded, and its cost goes back to the budget window
    </td>
    
    <td>
      A negative usage event that gives them back
    </td>
  </tr>
</tbody>
</table>

The hold is a reservation on the cached balance, as a [metered action's](https://nuxt-backend.dev/docs/build/billing/credits/spending#reserve-run-settle) is, kept for as long as the job waits. Two jobs that join at the same moment can never hold the same credits. Too few credits refuses the job with `insufficient_credits`, carrying `balance` and `need`, before anything joins the line. A balance this deployment has never read, such as a new account's first credits, cannot be refreshed from your mutation: the job joins holding nothing yet, and its first step reads the balance and takes the hold, or fails the job with `insufficient_credits` before any model is called, at once, when the balance is short. A balance read without the credit meter, an owner with no credits at all, is refused at the door with `not_ready`, as before. `onJobEnd` and `jobs.get` report what a job was `charged`. A tier's daily budget, when it has one, is checked before the hold, and counts the same `cost` ([Cap what an owner spends per day](https://nuxt-backend.dev/docs/build/ai/jobs/priority#cap-what-an-owner-spends-per-day)).

Billing that has not caught up yet is waited for, never read as a shortfall. A balance read with no credit meter yet (the provider grants a new plan's credits a moment after it starts), or an owner with no billing customer yet, is `not_ready` at the job's hold or its charge at start: the step waits five seconds, then ten, doubling, six waits in all, about five minutes, reading the balance again each time, and logs `ai.job_billing_wait`. A charge at start keeps its hold taken while it waits, so no other spend takes those credits meanwhile; a job canceled or failed during the wait gets the hold back. The job runs once billing has caught up, and fails with that `not_ready` refusal (reason `not_synced` or `no_customer`) if it never does. Only a balance short of the credits fails it with `insufficient_credits`.

The charge is the job's first durable step. If the billing provider cannot record it, the job fails with nothing spent, and the hold is released. The charge and the refund carry the job's hold id as their idempotency key, so a step that runs again after a timeout never bills or refunds twice.

## Show the balance

`useCredits` reads the balance live, and it already counts the hold: a queued strip's credits are gone from the balance the moment it joins. A refund shows up when the billing provider confirms it, a few seconds after the job fails.

```vue [app/pages/strips/new.vue]
<script setup lang="ts">
import { api } from '#backend/api'

const credits = useCredits({ meter: 'credits' })
const create = useMutation(api.strips.create)
const idea = ref('')

async function start() {
  try {
    const stripId = await create({ idea: idea.value, panels: 4 })
    await navigateTo(`/strips/${stripId}`)
  }
  catch (error) {
    if (getBackendError(error)?.code === 'insufficient_credits') await navigateTo('/pricing')
  }
}
</script>

<template>
  <p>{{ credits.balance.value ?? '…' }} credits. A four-panel strip costs 20.</p>
  <input v-model="idea" placeholder="A fox who wants to fly">
  <button @click="start">
    Draw the strip
  </button>
</template>
```

[Out of credits](https://nuxt-backend.dev/docs/build/billing/credits#out-of-credits) shows how to offer the pack that covers what a refused job needed.

## What a failed job costs you

A refund gives the person back their credits, not your bill. The gateway still bills every model call a failed job made before it failed, and every step it retried. That is the price of promising your users that a failed job costs them nothing. Keep it small by failing early: check the input in your mutation before `jobs.enqueue`, and throw a catalog error from a step for what a retry cannot fix ([Which errors fail a job](https://nuxt-backend.dev/docs/build/ai/jobs/model-limits#which-errors-fail-a-job)).

## Report what each job cost you

When a job ends, done or failed, the package sends one more event to Polar: a child of the job's charge, carrying Polar's Cost Insights fields. It never carries the prompt or the result:

<table>
<thead>
  <tr>
    <th>
      Field
    </th>
    
    <th>
      What it holds
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        _cost
      </code>
    </td>
    
    <td>
      What the job's model calls cost, in US cents, at sub-cent precision, as the gateway reported them
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        _llm
      </code>
    </td>
    
    <td>
      The vendor and model of the job's calls, and their input, output and cached tokens
    </td>
  </tr>
</tbody>
</table>

Polar's Costs dashboard then shows cost per customer, gross margin and cashflow next to your revenue, with no table of yours. A failed job's cost is reported too, although its credits were refunded, because you paid for its calls. The event carries the member who started the job, so Polar can show the cost per member of a workspace. A call through your own provider key reports no cost, and its event carries tokens only. See Polar's [Cost Insights](https://polar.sh/docs/features/cost-insights/introduction) (checked on 2026-10-25).

## Related

- [Polar](https://nuxt-backend.dev/docs/services/polar): the meters, the usage events and Cost Insights.
- [Run generation jobs](https://nuxt-backend.dev/docs/build/ai/jobs): the queue and the job's statuses.
- [Spend credits in your functions](https://nuxt-backend.dev/docs/build/billing/credits/spending): reserve, settle and refund underneath.
- [Credits & top-ups](https://nuxt-backend.dev/docs/build/billing/credits): balances, packs and the low-balance notice.


## Sitemap

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