Queue
Learn how to create, configure, and use Cloudflare Queues for background job processing in your Worker applications managed by Alchemy.
This guide explains how to create and use Cloudflare Queues with your Worker applications.
-
Create a Queue
Create a Queue with a type for the message payload:
import { Queue } from "alchemy/cloudflare";// Define the message payload typeexport const queue = await Queue<{name: string;email: string;}>("my-worker-queue"); -
Set up Producer (Send Messages)
Bind the Queue to your Worker as an environment variable to send messages:
import { Worker } from "alchemy/cloudflare";export const worker = await Worker("my-worker", {entrypoint: "./src/worker.ts",bindings: {QUEUE: queue, // Bind queue as QUEUE environment variable},}); -
Send Messages from Worker
Access the Queue from your Worker’s fetch handler to send messages:
src/worker.ts import type { worker } from "../alchemy.run";export default {async fetch(request: Request, env: typeof worker.Env) {// Send a message to the queueawait env.QUEUE.send({name: "John Doe",email: "john.doe@example.com",});return new Response("Ok");},}; -
Set up Consumer (Process Messages)
Register your Worker as a consumer of the Queue by adding it to eventSources:
export const worker = await Worker("my-worker", {entrypoint: "./src/worker.ts",bindings: {QUEUE: queue,},// Add the queue as an event source to consume messageseventSources: [queue],}); -
Process Messages in Worker
Implement the queue handler using a type-safe batch parameter:
src/worker.ts import type { queue, worker } from "../alchemy.run";export default {// Producer: send messagesasync fetch(request: Request, env: typeof worker.Env) {await env.QUEUE.send({name: "John Doe",email: "john.doe@example.com",});return new Response("Ok");},// Consumer: process messages with type safetyasync queue(batch: typeof queue.Batch, env: typeof worker.Env) {// Process each message in the batchfor (const message of batch.messages) {console.log(message);// Acknowledge individual messagemessage.ack();}// Or acknowledge all messages at once// batch.ackAll();},}; -
(Optional) Configure Consumer Settings
You can customize how your Worker consumes messages by providing settings:
export const worker = await Worker("my-worker", {entrypoint: "./src/worker.ts",eventSources: [{queue,settings: {batchSize: 25, // Process 25 messages at oncemaxConcurrency: 5, // Allow 5 concurrent invocationsmaxRetries: 3, // Retry failed messages up to 3 timesmaxWaitTimeMs: 1500, // Wait up to 1.5 seconds to fill a batch}}]});