Concepts
Queues and concurrency limits
A concurrency limit caps how many runs of a task, or of a group of tasks, execute at once in an environment. The rest wait their turn in the task's queue.
On this page
Every run waits in a queue until it starts. By default each task has a queue of its own with no limit, so its runs start as fast as workers take them. A concurrency limit caps how many of a queue's runs execute at once. Set one to protect what a task talks to: a database that slows down under twenty bulk writers, or an API with a rate limit.
Limit a task#
Add queue with a concurrencyLimit to the task's definition:
{"id": "etl.convert-batch", "kind": "task", "runtime": "node", "entrypoint": "tasks/convert.mjs", "handler": "convertBatch", "queue": {"concurrencyLimit": 10}}At most 10 runs of etl.convert-batch execute at once in each environment. An eleventh waits until one of the ten finishes.
| Field | Meaning |
|---|---|
concurrencyLimit | Optional. At most this many of the queue's runs execute at once in each environment, 1 to 100,000. Without it, no limit. |
name | Optional. A queue that every task naming it shares. 1 to 128 letters, digits and _ - . /, and it may not start with task/. Without it, the task has its own queue, task/<task id>. |
The key is concurrencyLimit, in camel case, as in Trigger.dev. queue is part of the task's definition, like hot and schedule, so changing it takes a new deploy.
Share a queue between tasks#
Tasks that name the same queue share its limit. Here at most 3 runs of orders.import and refunds.import, counted together, write to the database at once:
{"name": "db-writers", "concurrencyLimit": 3}In Node, queue() makes the shared queue once, and each task passes it. In Python, pass the same queue to each task:
import { writeFileSync } from 'node:fs';import { defineTask, queue } from '@bokjoy/sdk'; // At most 10 batches convert at once, in each environment.const convertBatch = defineTask({ id: 'etl.convert-batch', kind: 'task', runtime: 'node', entrypoint: 'tasks/convert.mjs', handler: 'convertBatch', queue: { concurrencyLimit: 10 },}); // One limit for both importers: at most 3 of their runs, together,// write to the database at once.const dbWriters = queue({ name: 'db-writers', concurrencyLimit: 3 }); const importOrders = defineTask({ id: 'orders.import', kind: 'task', runtime: 'node', entrypoint: 'tasks/imports.mjs', handler: 'importOrders', queue: dbWriters,}); const importRefunds = defineTask({ id: 'refunds.import', kind: 'task', runtime: 'node', entrypoint: 'tasks/imports.mjs', handler: 'importRefunds', queue: dbWriters,}); writeFileSync('manifest.json', JSON.stringify({ tasks: [convertBatch, importOrders, importRefunds] }, null, 2));import json from bokjoy import define_task # At most 10 batches convert at once, in each environment.convert_batch = define_task( id="etl.convert-batch", kind="task", runtime="python", entrypoint="tasks/convert.py", handler="convert_batch", queue={"concurrencyLimit": 10},) # One limit for both importers: at most 3 of their runs, together,# write to the database at once.DB_WRITERS = {"name": "db-writers", "concurrencyLimit": 3} import_orders = define_task( id="orders.import", kind="task", runtime="python", entrypoint="tasks/imports.py", handler="import_orders", queue=DB_WRITERS,) import_refunds = define_task( id="refunds.import", kind="task", runtime="python", entrypoint="tasks/imports.py", handler="import_refunds", queue=DB_WRITERS,) with open("manifest.json", "w") as manifest: json.dump({"tasks": [convert_batch, import_orders, import_refunds]}, manifest, indent=2)- One limit per queue. Every task that names a queue must give it the same
concurrencyLimit. Leaving it out on one task counts as a different limit. The deploy is refused, and the error names both tasks:queue "db-writers" is declared with concurrencyLimit 3 by task "orders.import" and concurrencyLimit 5 by task "refunds.import". - Checked twice.
defineTaskanddefine_taskrefuse a bad name or limit when you build the manifest. They see one task at a time, so the shared limit is checked when you deploy.
Choose the queue when you trigger#
A trigger can send its run to another queue the deployment declares, with the queue option:
import { tasks } from '@bokjoy/sdk'; // This batch writes to the database, so it waits in the importers' queue// and counts against their limit instead of its task's own.const handle = await tasks.trigger( 'etl.convert-batch', { batch: 7 }, { idempotencyKey: 'convert-batch-7', queue: 'db-writers' },); console.log(handle.id, handle.status, handle.queue);from bokjoy import tasks # This batch writes to the database, so it waits in the importers' queue# and counts against their limit instead of its task's own.handle = tasks.trigger( "etl.convert-batch", {"batch": 7}, idempotency_key="convert-batch-7", queue="db-writers",) print(handle.id, handle.status, handle.queue)- It names a declared queue. A shared queue's name, such as
db-writers, ortask/<task id>, the own queue of a task without aname. The run then counts against that queue's limit instead of its task's. - It cannot set a limit. The limit always comes from the deployment.
- An unknown queue starts nothing. A queue the run's deployment does not declare is a
ValidationError(400). - The run keeps its queue. Retries wait in the same queue. The handle and the run carry it as
queue. Triggering again with the same idempotency key and a different queue is aConflictError.
Runs a task starts with ctx.trigger, and workflow calls, wait in their own task's queue.
Limit per key#
A concurrency key splits a queue's limit by a value you choose, such as an organization ID. Give the task a limit, "queue": {"concurrencyLimit": 1}, and pass the key when you trigger:
import { tasks } from '@bokjoy/sdk'; // process-user-counts has a limit of 1. With a concurrency key, that limit// applies to each organization apart: one upload at a time per org, while// other orgs' uploads run alongside it.const orgId = 'org_42';const handle = await tasks.trigger( 'process-user-counts', { upload: 9 }, { idempotencyKey: 'user-counts-upload-9', concurrencyKey: orgId },); console.log(handle.id, handle.status, handle.concurrencyKey);from bokjoy import tasks # process-user-counts has a limit of 1. With a concurrency key, that limit# applies to each organization apart: one upload at a time per org, while# other orgs' uploads run alongside it.org_id = "org_42"handle = tasks.trigger( "process-user-counts", {"upload": 9}, idempotency_key="user-counts-upload-9", concurrency_key=org_id,) print(handle.id, handle.status, handle.concurrency_key)- The limit applies per key. Runs with the same key share the limit: here, one upload of
org_42at a time. Runs with another key do not count against it, and there is no cap across keys. - Runs without a key share it too. They count against the limit together, apart from every key.
- It works anywhere you trigger.
concurrencyKey(Python:concurrency_key) ontrigger,triggerAndWaitand eachbatchTriggeritem, and onctx.triggerinside a task. In a workflow,ctx.triggerAndWaitand eachctx.batchTriggerAndWaititem take it too. Over HTTP it isconcurrency_key. - A key is 1 to 128 bytes of UTF-8, with no whitespace at either end and no control, invisible format or line break characters. Spaces inside a key are fine. A zero-width space or a character that reverses text is refused, because it would make two keys look alike in the console. The clients refuse anything else before sending it.
- Keys match exactly. They keep their case and compare byte for byte, as in Trigger.dev:
Org_42andorg_42are two keys, and so are the composed and decomposed forms ofé. Pass an ID, or normalize a name (NFC, and one case) first. - The run keeps its key. Retries keep it, and the handle and the run carry it as
concurrencyKey(Python:concurrency_key). Triggering again with the same idempotency key and a different concurrency key is aConflictError. - A replay keeps it too. Replaying a run, from the console, the CLI or the MCP server, sends its concurrency key, and its queue when its trigger chose one. If the current deployment no longer declares that queue, the replay is refused and says so.
How the limit works#
- A running attempt holds a slot. A run holds one of its queue's slots from the moment an attempt starts until that attempt is over, except while a held wait waits on its children. The oldest waiting run starts first.
- A short sleep keeps its slot. A workflow that sleeps for less than 60 seconds keeps its slot, so nothing else of its queue starts meanwhile, and it goes on at once when it wakes. It keeps the slot even if its next attempt is handed back before it starts.
- Other waits give it back. A workflow call, a wait for an event and a sleep of 60 seconds or more release the slot. So do
ctx.triggerAndWaitandctx.batchTriggerAndWait. When the workflow wakes, it needs a free slot again before it goes on, and it is ahead of runs that arrived later. - A held wait gives it back while its children run. In a plain Node task,
ctx.triggerAndWaitandctx.batchTriggerAndWaitkeep the task's process running but free its slot, so its children can start, even in its own queue with a limit of 1. When they finish, the task needs a free slot again before it goes on, ahead of runs queued behind it. See In a plain task. - Retries give the slot back. A failed attempt gives its slot back. The retry waits out its delay without a slot, so the next run in the queue can start. Then it waits for a free slot like any queued run, behind runs that were already waiting.
- A delayed run holds nothing. A run triggered with a
delayor adebouncetakes no slot and is not counted as queued while it waits for its time. Then it joins the queue as a run triggered at that time would. - An attempt that stops reporting keeps its slot until Bok Joy proves it stopped: its worker reports it, its container is proved gone by the Docker host that ran it, or its machine is destroyed. A worker cut off from the network may still be running the task, so a queue with a limit of 1 never runs two attempts at once. When nothing can prove it, for a worker that never comes back or a task run without a container, an operator who confirms it stopped can release it.
- Per environment. Each environment counts its own runs: a limit of 10 means 10 in
prodand 10 instaging. Every preview counts its own too. - The current deployment sets it. Whenever a deployment becomes current in an environment, its limits apply there, to runs already waiting too. Lower a limit and deploy, and the runs over it wait. A queue the new deployment no longer declares keeps its last limit for the runs still in it.
- Every worker obeys it. Private workers, cloud workers and the warm workers of hot tasks all start a run only when its queue has room.
- Blocked runs start no machines. A new cloud machine starts only for runs their queue would let start.
Move a task to another queue#
A run keeps the queue it was accepted into. When you deploy a task with a different queue (from its own queue to a shared one, say), its runs still pinned to the old deployment stay in the old queue, and new runs use the new one. Each queue's limit applies apart, so for a while both limits can run at once: a limit of 1 on each lets 2 run. If that matters, let the old runs finish, or cancel them, before you move the task.
While a run waits#
The console shows why a queued run has not started, naming its queue and how many of its slots are in use:
Waiting for a slot in queue task/etl.convert-batch, 10 of 10 in use.For a run with a concurrency key, it names the key:
Waiting for a slot in queue task/process-user-counts for key org_42, 1 of 1 in use.A workflow waking from a short sleep holds its slot already, so the console never tells it to wait for one.
The console names every queue by its ID, as the API does: task/<task id> for a task's own queue, and the name for a shared one.
The console's Concurrency limits page lists the environment's queues: each one's limit, its slots in use, its queued runs, the tasks that use it and its busiest concurrency keys. Queues with no limit and nothing in them are left out until you choose Show all queues.
Read queues#
queues.list and queues.retrieve answer in Trigger.dev's shapes:
import { queues } from '@bokjoy/sdk'; // Numbered pages, as Trigger.dev's queues.list answers.const page = await queues.list({ page: 1, perPage: 50 });const { currentPage, totalPages, count } = page.pagination;console.log(`page ${currentPage} of ${totalPages}, ${count} queues`);for (const queue of page.data) { console.log(queue.id, queue.type, queue.concurrencyLimit ?? 'unlimited', queue.running, queue.queued);} // One queue, by its ID, or by type and name as Trigger.dev names it.const writers = await queues.retrieve('db-writers');console.log(`${writers.name}: ${writers.running} of ${writers.concurrencyLimit} running`);const convert = await queues.retrieve({ type: 'task', name: 'etl.convert-batch' });console.log(`${convert.name}: ${convert.queued} waiting`);from bokjoy import queues # Numbered pages, as Trigger.dev's queues.list answers.page = queues.list(page=1, per_page=50)numbers = page.paginationprint(f"page {numbers.current_page} of {numbers.total_pages}, {numbers.count} queues")for queue in page.data: limit = "unlimited" if queue.concurrency_limit is None else queue.concurrency_limit print(queue.id, queue.type, limit, queue.running, queue.queued) # One queue, by its ID, or by type and name as Trigger.dev names it.writers = queues.retrieve("db-writers")print(f"{writers.name}: {writers.running} of {writers.concurrency_limit} running")convert = queues.retrieve(type="task", name="etl.convert-batch")print(f"{convert.name}: {convert.queued} waiting")| Node | Python | Value |
|---|---|---|
id | id | task/<task id> for a task's own queue, else the shared queue's name. A run's queue and the trigger option name a queue by this. |
name | name | The task ID for a task's own queue, else the shared queue's name. |
type | type | task or custom. |
concurrencyLimit | concurrency_limit | The limit, or null for none. |
running | running | Its slots in use: runs executing, and workflows in a sleep of under 60 seconds. |
queued | queued | Its runs waiting. |
paused | paused | Always false. Bok Joy has no paused queues. |
queues.list takes page (from 1) and perPage (Python: per_page), 1 to 200, default 50, and lists the environment's queues ordered by ID. queues.retrieve takes a queue's ID, or a type and a name, and a queue the environment does not have is a NotFoundError. An API key reads its own environment's queues. Over HTTP, see the Queues API.
Not supported yet#
- A limit of 0, which pauses a queue in Trigger.dev.
- Pausing and resuming a queue.
- Overriding a queue's limit while it runs, and resetting an override.
- A queue on a workflow call, or a concurrency key on
ctx.callTask. The child waits in its own task's queue.ctx.triggerAndWaitand batch items take a concurrency key.
Coming from Trigger.dev#
Bok Joy follows Trigger.dev v4's queues, as of SDK 4.5.16. These differ:
| Trigger.dev | Bok Joy |
|---|---|
| Tasks that give one queue different limits: the first wins, with a warning | The deploy is refused. |
| A trigger names a queue no version declares: the run waits for one that does | A ValidationError, and no run starts. |
concurrencyLimit: 0 pauses a queue | 1 to 100,000. Pausing, resuming and overriding a limit are not supported. |
| A short wait keeps its slot while the process stays up | A short sleep keeps its slot too. The process ends while it sleeps, so its machine is free. |
| A retry within about 30 seconds keeps its slot | A retry gives it back, waits out its delay, then waits for a free slot. |
| A delayed run takes no slot until its time | The same. |
| An environment's concurrency limit caps all its runs | No environment-wide limit. The capacity of your workers and machines caps it. |
concurrencyKey makes a copy of the queue per key | The queue counts each key apart, with the same limit. |
| A concurrency key is any string | 1 to 128 bytes, with no whitespace at either end and no control, invisible format or line break characters. |
Runs carry no queue, only ctx.queue | Runs and handles carry queue and concurrencyKey. |
queue on triggerAndWait and in-task triggers | Runs started from a task wait in their own task's queue. ctx.trigger, ctx.triggerAndWait and batch items take a concurrency key. |