Queue
Durable typed task execution for server-side work that should run through an adapter such as QStash or Vercel Queues.
@tulip-systems/queue is the low-level task execution atom. Use it when the application wants to say: do this work later, durably, and with retries handled by the adapter.
Queue tasks are command-like. A task represents an instruction, not a fact that already happened.
When to use Queue
Use Queue for work such as:
- sending an email
- processing an import
- syncing a file provider
- dispatching an event listener
- running slow side effects outside the request path
Do not use Queue as the domain language for facts such as project.created or invoice.paid. Those are events. Queue can still execute the work caused by those events.
Entry Points
Define tasks and task handler collections from the package entrypoint:
import { createQueueHandlers, defineTask } from "@tulip-systems/queue";Create the server runtime from the server entrypoint:
import { Queue } from "@tulip-systems/queue/server";Use the QStash adapter when jobs should be delivered through QStash:
import { qstashAdapter } from "@tulip-systems/queue/qstash";Use the Vercel Queues adapter when the app runs on Vercel:
import { vercelQueueAdapter } from "@tulip-systems/queue/vercel";Define a Task
Tasks are stable contracts. The task name is stored in queued jobs and used during callback dispatch.
// app/admin/queue/_lib/tasks.ts
import { defineTask } from "@tulip-systems/queue";
import { z } from "zod";
export const sendWelcomeEmailTask = defineTask("email.send-welcome", {
schema: z.object({
userId: z.uuid(),
email: z.email(),
}),
});The schema validates payloads before publishing and again before executing the handler.
Initialize Queue
Create one queue runtime for the app. The adapter owns delivery. The queue runtime owns task payload validation and callback dispatch.
// server/queue/init.ts
import { url } from "@tulip-systems/core";
import { qstashAdapter } from "@tulip-systems/queue/qstash";
import { Queue } from "@tulip-systems/queue/server";
export const queue = Queue.init({
adapter: qstashAdapter({
baseUrl: process.env.QSTASH_URL!,
token: process.env.QSTASH_TOKEN!,
endpoint: url("/api/queue/dispatch"),
currentSigningKey: process.env.QSTASH_CURRENT_SIGNING_KEY!,
nextSigningKey: process.env.QSTASH_NEXT_SIGNING_KEY!,
queueName: "app-jobs",
label: "demo-code",
}),
});endpoint must be the public URL QStash will call. The same endpoint is used to verify QStash callback signatures.
Enqueue a Task
Call queue.enqueue(task, payload, options?) from server code.
import { queue } from "@/server/queue/init";
import { sendWelcomeEmailTask } from "./tasks";
await queue.enqueue(
sendWelcomeEmailTask,
{
userId: user.id,
email: user.email,
},
{
dedupeKey: `welcome-${user.id}`,
delay: "30s",
},
);dedupeKey and delay are passed to the adapter. With QStash, the dedupe key becomes the QStash deduplication id, so keep it provider-safe.
Handle Callbacks
Each queue callback route receives a collection of queue handlers.
// server/queue/handlers.ts
import { createQueueHandlers } from "@tulip-systems/queue";
import { sendWelcomeEmailTask } from "@/app/admin/queue/_lib/tasks";
export const queueHandlers = createQueueHandlers([
sendWelcomeEmailTask.handle("send-welcome-email", async ({ payload, job }) => {
await emailProvider.send({
to: payload.email,
subject: "Welcome",
idempotencyKey: job.id,
});
}),
]);Then expose the route handler:
// app/api/queue/dispatch/route.ts
import { queueHandlers } from "@/server/queue/handlers";
import { queue } from "@/server/queue/init";
export const POST = queue.handleCallback({ handlers: queueHandlers });The callback flow is:
- The adapter verifies the delivery and decodes the job.
- Queue finds the handler by task name.
- The task schema validates the job payload.
- The handler receives
{ payload, job }. - A thrown error is passed back to the adapter, which tells the provider to retry.
One Handler Per Task
Queue tasks are command-like, so each task should have one handler in a callback route.
createQueueHandlers([
sendWelcomeEmailTask.handle("send-welcome-email", async () => {}),
]);If you need fan-out to multiple side effects, model the source as an event and use @tulip-systems/events to enqueue one listener job per side effect.
Queue vs Events
| Concept | Meaning | Example |
|---|---|---|
| Queue task | Do this | email.send-welcome |
| Event | This happened | project.status-changed |
| Event listener | React to this | notifications:projectStatusChanged |
Queue is the durable execution layer. Events are the domain fact layer.
Failure Behavior
Callback failures are intentionally visible to the adapter. The QStash adapter answers:
- unknown task with
404 - invalid payload with
400 - handler failure with
500 QueueNonRetryableErrorwith489andUpstash-NonRetryable-Error: true, so QStash stops retrying
For retryable work, throw from the handler. When retrying can never succeed, for example because the record no longer exists, throw a QueueNonRetryableError:
import { QueueNonRetryableError } from "@tulip-systems/queue/server";
sendWelcomeEmailTask.handle("send-welcome-email", async ({ payload }) => {
const user = await findUser(payload.userId);
if (!user) {
throw new QueueNonRetryableError(`User ${payload.userId} no longer exists`);
}
await sendWelcomeEmail(user);
});isRetryableQueueError(error) from @tulip-systems/queue/server returns false for a QueueNonRetryableError, an invalid payload and an unknown task. Adapters use it to decide whether a provider should retry.
Writing an Adapter
An adapter publishes jobs and builds the callback route. createCallbackHandler receives a dispatch function that runs the matching task handler. It resolves when the job succeeded and throws when it failed, so the adapter can acknowledge or retry in the way its provider expects.
import type { QueueAdapter } from "@tulip-systems/queue/server";
import { queueJobSchema } from "@tulip-systems/queue/server";
export function exampleAdapter(): QueueAdapter {
return {
key: "example",
async publish({ job, options }) {
const { id } = await provider.publish(job, options);
return { id };
},
createCallbackHandler(dispatch) {
return async (request) => {
await provider.verify(request);
await dispatch(queueJobSchema.parse(await request.json()));
return new Response(null, { status: 200 });
};
},
};
}Adapters
QStash
import { qstashAdapter } from "@tulip-systems/queue/qstash";The adapter supports:
- QStash publishing
- callback signature verification
- delay headers
- dedupe headers
- queue name headers
- labels for filtering logs
Vercel Queues
import { vercelQueueAdapter } from "@tulip-systems/queue/vercel";Install the SDK next to the queue package:
pnpm add @vercel/queueThe adapter publishes every job to a topic. Vercel pushes the jobs to the route that subscribes to that topic in vercel.json. That route is private: it has no public URL and only Vercel Queues can call it, so there are no signing keys or callback URLs to configure. On Vercel the SDK authenticates through OIDC.
// server/queue/init.ts
import { Queue } from "@tulip-systems/queue/server";
import { vercelQueueAdapter } from "@tulip-systems/queue/vercel";
export const queue = Queue.init({
adapter: vercelQueueAdapter({
topic: "app-jobs",
maxAttempts: 8,
async onDeadLetter({ job, error, metadata }) {
await recordFailedJob({ job, error, attempts: metadata.deliveryCount });
},
}),
});// app/api/queue/consume/route.ts
import { queueHandlers } from "@/server/queue/handlers";
import { queue } from "@/server/queue/init";
export const POST = queue.handleCallback({ handlers: queueHandlers });// vercel.json
{
"functions": {
"src/app/api/queue/consume/route.ts": {
"maxDuration": 300,
"experimentalTriggers": [
{ "type": "queue/v2beta", "topic": "app-jobs", "maxDeliveries": 12 }
]
}
}
}The topic in vercel.json must match the adapter's topic. Topic names may only contain letters, numbers, _ and -. Use one consumer route per topic: every route that subscribes to a topic receives its own copy of each job, so two routes would run every job twice. A route with a queue trigger is private, so it can not double as a QStash callback route.
Retries and failed jobs:
- A failed job is retried with exponential backoff from 10 seconds, capped at 5 minutes. Pass
backoff(attempt)to change it. - After
maxAttemptsdeliveries (default 10), or straight away for aQueueNonRetryableError, an invalid payload or an unknown task, the job is handed toonDeadLetterand acknowledged. Vercel Queues has no dead-letter queue, so persist or report the job there. WithoutonDeadLetterthe job is logged withconsole.error. - Keep the trigger's
maxDeliveriesabovemaxAttempts. It is the platform limit for deliveries that never reach the adapter, such as crashes and timeouts. job.attemptsholds the delivery count, starting at 1.
Other options:
| Option | Description |
|---|---|
topic | Topic name, or (job) => topic to route jobs per task. Each topic needs its own trigger. |
retentionSeconds | Message TTL, from 60 seconds to 7 days. Vercel defaults to 24 hours. |
visibilityTimeoutSeconds | Initial lease per delivery. The SDK extends it while the handler runs. |
region | Queue region. Auto-detected from VERCEL_REGION on Vercel. |
client | A pre-built QueueClient, e.g. for tests. |
Enqueue options map to Vercel as follows: delay becomes delaySeconds and accepts seconds or a duration like "30s", "5m", "2h" or "1d". dedupeKey becomes the idempotency key, hashed when it is longer than 256 characters.
Vercel delivers jobs back to the deployment that published them. A job published before a deploy runs with the code of that older deployment, so payload changes are safe, but an older deployment keeps processing its own jobs until they succeed or expire.
For local development, link the project with vercel link and pull its environment variables with the Vercel CLI so the SDK can authenticate. In next dev, publishing a job sends it to Vercel Queues, and the SDK delivers it to the matching route from vercel.json in the dev server. The SDK reaches that route on localhost through the PORT environment variable.
Vercel Queues is in beta. The trigger type queue/v2beta and the SDK may still change.