---
title: "Queue work with a workpool"
description: "Run many actions a few at a time on Convex's workpool component, retry the ones that ask for it, and hear back when each one ends."
canonical_url: "https://nuxt-backend.dev/docs/build/data/jobs/workpool"
---
# Queue work with a workpool

> Run many actions a few at a time on Convex's workpool component, retry the ones that ask for it, and hear back when each one ends.

Version: nuxt-backend 0.6.x · Tab: Build · Kind: recipe · 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.

Import a feed for each of a reader's 20 subscriptions without sending 20 requests at once to a service that allows three. Scheduled one by one with `ctx.scheduler.runAfter`, all of them start together. A workpool from the official [`@convex-dev/workpool`](https://www.convex.dev/components/workpool) component queues them instead: it runs at most `maxParallelism` at a time, retries the actions that ask for it, and calls a mutation of yours as each one ends. Your app imports it directly.

## Queue feed imports

The scaffold already mounts one pool, `workpool`, which the package's own billing and generation jobs share. Give your work a pool of its own, so its limit is yours alone:

```bash
npm install @convex-dev/workpool
```

<code-tree default-value="backend/imports.ts">

```ts [backend/convex.config.ts]
import workpool from '@convex-dev/workpool/convex.config'

// The scaffold's `app.use(workpool)` stays. Add a mount for your own queue:
app.use(workpool, { name: 'feedImports' })
```

```ts [backend/imports.ts]
import { Workpool } from '@convex-dev/workpool'
import { backendError } from 'nuxt-backend/functions'
import { v } from 'convex/values'
import { components, internal } from './_generated/api'
import { internalAction } from './_generated/server'
import { authed } from './functions'

const pool = new Workpool(components.feedImports, { maxParallelism: 3 })

export const importFeed = internalAction({
  args: { url: v.string() },
  handler: async (_ctx, { url }) => {
    const response = await fetch(url)
    if (!response.ok) throw new Error(`${url} answered ${response.status}`)
    return (await response.text()).length
  },
})

export const importFeeds = authed.mutation({
  args: { urls: v.array(v.string()) },
  handler: async (ctx, { urls }) => {
    if (urls.length > 20) throw backendError('invalid_input', { field: 'urls', message: 'Import up to 20 feeds at once.' })
    await pool.enqueueActionBatch(ctx, internal.imports.importFeed, urls.map(url => ({ url })), { retry: true })
  },
})
```

</code-tree>

The pool fetches whatever it is given, so the public mutation that fills it is behind a tier and bounded.

<table>
<thead>
  <tr>
    <th>
      Option
    </th>
    
    <th>
      Default
    </th>
    
    <th>
      Effect
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        maxParallelism
      </code>
    </td>
    
    <td>
      <code>
        10
      </code>
    </td>
    
    <td>
      Items running at once; the rest wait their turn. The platform's own limit on concurrent functions applies on top
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        retryActionsByDefault
      </code>
    </td>
    
    <td>
      <code>
        false
      </code>
    </td>
    
    <td>
      Retry every action that fails, without <code>
        retry: true
      </code>
      
       on each enqueue. Turn it on only for a pool of actions that are safe to run twice
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        defaultRetryBehavior
      </code>
    </td>
    
    <td>
      <code>
        { maxAttempts: 5, initialBackoffMs: 250, base: 2 }
      </code>
    </td>
    
    <td>
      How an action that asks for retries is retried: five attempts in all, 250 ms before the second, doubling after
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        logLevel
      </code>
    </td>
    
    <td>
      <code>
        'REPORT'
      </code>
    </td>
    
    <td>
      Warnings, errors and a periodic report in the deployment's logs; <code>
        'INFO'
      </code>
      
       adds each item's start and end
    </td>
  </tr>
</tbody>
</table>

## Enqueue work

Enqueue from a mutation or an action. Each call returns the item's `WorkId` at once, and the item runs later, in its turn:

- `enqueueAction`, `enqueueMutation` and `enqueueQuery` take one function and its arguments.
- `enqueueActionBatch`, `enqueueMutationBatch` and `enqueueQueryBatch` take one function over an array of arguments.
- Each takes `retry` (actions only), `onComplete` with its `context`, `runAfter` or `runAt`, and `name` for the logs.

## Retries

An action runs once unless it asks for more: one that charged a card or sent an email must never run twice by accident. Pass `retry: true` for an action that is safe to repeat, such as a read from an outside API. A retried action waits `initialBackoffMs`, then that times `base` before each attempt after, with some jitter, until `maxAttempts` is spent.

An action that knows it cannot succeed, a feed that is gone for good, throws `NonRetryableError` from `@convex-dev/workpool`. The item ends at once as `failed`, with no attempt left to run. The pool never retries a mutation: the platform already retries one that conflicts with another.

## Hear back when an item ends

`pool.defineOnComplete` defines the mutation the pool calls once per item, with your `context` and the item's `result`: `{ kind: 'success', returnValue }`, `{ kind: 'failed', error }` after the last attempt, or `{ kind: 'canceled' }`.

```ts [backend/imports.ts]
import type { DataModel } from './_generated/dataModel'

export const feedImported = pool.defineOnComplete<DataModel>({
  context: v.object({ feedId: v.id('feeds') }),
  handler: async (ctx, { context, result }) => {
    await ctx.db.patch('feeds', context.feedId, result.kind === 'success'
      ? { status: 'imported', size: result.returnValue as number }
      : { status: result.kind })
  },
})
// Enqueue with: { retry: true, onComplete: internal.imports.feedImported, context: { feedId } }
```

Writing the outcome to your own table is also how a page follows it: a query over that table updates as each item lands. `pool.status(ctx, workId)` reads where one item is, `pool.cancel(ctx, workId)` cancels one, and `pool.cancelAll(ctx)` every item not yet finished. An attempt already running is not stopped.

## In tests

Register the component with `@convex-dev/workpool/test` beside `defineBackendTestApp` from `nuxt-backend/test`, under the name you mounted it by. Enqueued work runs through the scheduler, so drain it with fake timers, and stub `fetch` so the test never reaches the network ([Testing](https://nuxt-backend.dev/docs/develop/testing)).

## Related

- [Background work](https://nuxt-backend.dev/docs/build/data/jobs): when to reach for a workpool, a workflow or a cron.
- [Run a durable workflow](https://nuxt-backend.dev/docs/build/data/jobs/workflows): several steps that must all happen.
- [Cache expensive actions](https://nuxt-backend.dev/docs/build/data/jobs/action-cache): an action called again with the same arguments.
- The [workpool component](https://www.convex.dev/components/workpool): every method and option.


## Sitemap

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