Queues
Learning Focus
By the end of this lesson you will understand how Cloudflare Queues enable asynchronous processing between Workers and their free-tier limits.
What Are Cloudflare Queues?
Cloudflare Queues is a message broker that allows Workers to send and consume messages asynchronously. Instead of processing everything in a single request, you can offload work to a queue and process it later in a separate Worker.
flowchart LR
PRODUCER["Producer Worker\n(Handles request)"] -->|"Send message"| QUEUE["Queue\n(Message Buffer)"]
QUEUE -->|"Batch delivery"| CONSUMER["Consumer Worker\n(Background processing)"]
style QUEUE fill:#7c3aed,color:#fff,stroke:#6d28d9
style PRODUCER fill:#f6821f,color:#fff,stroke:#e5711e
style CONSUMER fill:#16a34a,color:#fff,stroke:#15803d
Use Cases
| Use Case | Description |
|---|---|
| Email sending | Queue email tasks, process in background |
| Image processing | Resize/optimize images asynchronously |
| Webhook delivery | Retry failed webhook deliveries |
| Log aggregation | Batch and process log entries |
| Data pipeline | Process data transformations step by step |
Free Tier
| Resource | Free Plan |
|---|---|
| Messages sent | 1 million per month |
| Messages read | 1 million per month |
| Queues | 100 |
Basic Example
Producer (Sends Messages)
src/producer.ts
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const body = await request.json() as any;
// Send a message to the queue
await env.MY_QUEUE.send({
type: "email",
to: body.email,
subject: "Welcome!",
body: "Thanks for signing up.",
});
return Response.json({ status: "queued" });
},
};
Consumer (Processes Messages)
src/consumer.ts
export default {
async queue(batch: MessageBatch, env: Env): Promise<void> {
for (const message of batch.messages) {
console.log(`Processing: ${JSON.stringify(message.body)}`);
// Process the message (e.g., send email, resize image)
// ...
// Acknowledge successful processing
message.ack();
}
},
};
wrangler.toml
name = "my-worker"
main = "src/producer.ts"
[[queues.producers]]
queue = "my-queue"
binding = "MY_QUEUE"
[[queues.consumers]]
queue = "my-queue"
max_batch_size = 10
max_batch_timeout = 30
Key Takeaways
- Queues enable asynchronous processing between Workers.
- Free tier: 1M messages sent/read per month.
- Messages are delivered in batches for efficiency.
- Ideal for background tasks, retries, and data pipelines.
What's Next
- Continue to Secrets Store and Version Management to learn about secure configuration and deployment versioning.