Vercel Queues tutorial: process background jobs reliably

By

Tagged: Services

Publish and consume Vercel Queue messages with retries, delayed delivery, idempotency keys, private consumers, and safe duplicate handling.

Vercel Queues lets you move slow work out of the HTTP request that triggered it. Instead of doing everything while the user waits, your route publishes a message to a topic and returns right away, while a separate Function picks up that message in the background.

In this tutorial, we’ll queue order receipts so checkout finishes fast. Keep in mind that Vercel Queues is still in beta, so check the docs for current limits, regions, and pricing before taking it to production.

What a queue changes

Without a queue, a checkout handler usually ends up doing all of this in one request:

save order -> charge payment -> generate receipt -> send email -> respond

Your customer sits there waiting for every single step to finish.

With a queue in place, the checkout route stops as soon as it publishes the background job:

save order -> charge payment -> publish receipt job -> respond
                                      |
                                      -> consumer sends email

That keeps checkout fast, and if your email provider fails, the queue can deliver the message again.

Create the Next.js app

Start by creating a new Next.js app:

npx create-next-app@latest queue-demo
cd queue-demo

Next, install the Queues SDK:

npm install @vercel/queue

The SDK authenticates with Vercel OIDC. Link your local folder to a Vercel project and pull down its environment variables:

npx vercel link
npx vercel env pull

Once you deploy to Vercel, the project gets its OIDC credentials automatically, so there’s nothing extra to configure in production.

Publish a message

Create app/api/orders/route.ts to handle incoming orders and send a message to the queue:

import { send } from '@vercel/queue'

type ReceiptJob = {
  orderId: string
  email: string
}

export async function POST(request: Request) {
  const job = (await request.json()) as ReceiptJob

  if (!job.orderId || !job.email) {
    return Response.json(
      { error: 'orderId and email are required' },
      { status: 400 },
    )
  }

  const { messageId } = await send('order-receipts', job, {
    idempotencyKey: `receipt-${job.orderId}`,
  })

  return Response.json(
    {
      orderId: job.orderId,
      receiptJob: messageId,
    },
    { status: 202 },
  )
}

Calling send() publishes the object to the order-receipts topic. The route responds with 202 Accepted because we’ve only queued the receipt, not sent it yet.

Notice the idempotency key too. If the producer submits the same order twice, Vercel deduplicates matching publishes while the original message is still within its retention window.

Create the consumer

Now let’s build the Function that processes those messages. Create app/api/queues/send-receipt/route.ts:

import { handleCallback } from '@vercel/queue'

type ReceiptJob = {
  orderId: string
  email: string
}

export const POST = handleCallback<ReceiptJob>(
  async (job, metadata) => {
    console.log(
      `Sending receipt for ${job.orderId} to ${job.email}`,
      metadata.messageId,
    )

    await sendReceiptEmail(job)
  },
)

async function sendReceiptEmail(job: ReceiptJob) {
  console.log(`Receipt sent for ${job.orderId}`)
}

handleCallback() hooks the Function into Vercel’s queue delivery protocol. When the callback finishes, Vercel acknowledges the message. When it throws an error, Vercel puts the message back for a retry.

For now, sendReceiptEmail() only logs to the console. Once you’ve confirmed the queue flow works, swap it out for your email provider.

Make the consumer private

Vercel needs to know which Function consumes your topic, so create vercel.json:

{
  "functions": {
    "app/api/queues/send-receipt/route.ts": {
      "experimentalTriggers": [
        {
          "type": "queue/v2beta",
          "topic": "order-receipts",
          "retryAfterSeconds": 60
        }
      ]
    }
  }
}

This trigger subscribes the Function to order-receipts and takes the route off the public internet. Only Vercel’s queue infrastructure can call it, so you don’t need to add HTTP authentication to your consumer.

Your producer route is still public, though, so protect it with your app’s normal authentication and authorization.

Test the queue

Start the local dev server:

npm run dev

In another terminal, send a test order to publish your first message:

curl -X POST http://localhost:3000/api/orders \
  -H 'content-type: application/json' \
  -d '{"orderId":"order_2048","email":"ada@example.net"}'

You’ll get back a response containing both the order ID and the queue message ID:

{
  "orderId": "order_2048",
  "receiptJob": "msg_..."
}

Recent versions of the SDK connect local development directly to the Vercel Queue service and run your registered callback inside your local app process.

If authentication fails, refresh your local OIDC token:

npx vercel env pull

See a message retry

To watch retries happen, temporarily update the consumer so it fails on most runs:

async function sendReceiptEmail(job: ReceiptJob) {
  if (Math.random() < 0.7) {
    throw new Error('Email provider is unavailable')
  }

  console.log(`Receipt sent for ${job.orderId}`)
}

Because the callback throws most of the time, the queue keeps retrying until it succeeds or the message expires. Remove that random failure once you’re done testing.

When you want more control over backoff and limits, add a custom retry function:

export const POST = handleCallback<ReceiptJob>(
  async job => {
    await sendReceiptEmail(job)
  },
  {
    retry: (error, metadata) => {
      console.error(error)

      if (metadata.deliveryCount > 10) {
        return { acknowledge: true }
      }

      return {
        afterSeconds: Math.min(
          300,
          2 ** metadata.deliveryCount * 5,
        ),
      }
    },
  },
)

Each failed attempt waits longer before trying again. After ten deliveries, this handler acknowledges the message and stops retrying. Make sure you store the failed job somewhere before acknowledging it, otherwise you’ll lose the chance to inspect and replay it later.

At-least-once means duplicates are possible

Vercel Queues gives you at-least-once delivery, which means the same message can reach a consumer more than once. For example, the email might send fine, and then the consumer fails right before acknowledging the message.

The producer’s idempotency key only deduplicates publishes, so it won’t stop a consumer from running twice. Your consumer has to be idempotent too.

One way to handle that is to store a unique job key in your database:

CREATE TABLE processed_jobs (
  job_key TEXT PRIMARY KEY,
  processed_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

Then, right before sending the email, try to insert the key:

INSERT INTO processed_jobs (job_key)
VALUES ('receipt-order_2048')
ON CONFLICT DO NOTHING;

Only the consumer that inserted the row should continue. When you’re calling external APIs that support idempotency keys, pass a stable key there as well.

Delay a message

You don’t have to deliver a message immediately. For example, if you want to send a follow-up five days after an order, you can delay when it becomes visible:

await send(
  'order-follow-ups',
  {
    orderId: 'order_2048',
    email: 'ada@example.net',
  },
  {
    delaySeconds: 5 * 24 * 60 * 60,
    retentionSeconds: 7 * 24 * 60 * 60,
    idempotencyKey: 'follow-up-order_2048',
  },
)

Vercel supports retention and delivery delays up to seven days, and you should keep the retention window longer than the delay. If you need a process to wait longer than seven days or carry state across several steps, use a Workflow instead.

Add another consumer

A single topic can feed several independent consumer groups. Say you also want every order to update your analytics. You just create another route with its own trigger for order-receipts.

Now both consumers receive every message:

order-receipts
  ├── send-receipt consumer
  └── update-analytics consumer

If analytics fails, your receipt emails still go out. That fan-out model is one of the best reasons to use a queue instead of calling several services inside one Function.

Queues or Workflows?

Pick Queues when messages and consumers are the main thing you’re modeling.

Choose Queues for:

Use Vercel Workflows when you need:

Workflows use Queues under the hood, but they give you a higher-level TypeScript model. My advice is to start with Workflows for a business process, and reach for Queues when you specifically need message routing and control over consumers.

Deploy and inspect

Deploy a preview to test the setup on Vercel:

npx vercel

Publish an order to your preview URL, then open the Vercel dashboard to check queue activity and the consumer’s runtime logs. Trigger a failure before sending real traffic so you can see how retries show up in your logs. My Vercel Observability tutorial shows how I investigate a slow or failing Function.

When you’re ready to move from Preview to Production, check the Vercel deployment documentation for how both environments handle this queue setup.

Want me to talk about your product? You can sponsor this site.

Related posts about services: