Skip to content
Tinbox

tutorials

How to send bulk email in batches from a Cloudflare Worker

November 6, 2026

#cloudflare-workers#cloudflare-queues#bulk-email#batch-send#tutorial
A buffered sequence of messages includes a safe retry loop.

You have a 50,000-row list and a Worker. The naive version, a for-loop that awaits a send per recipient, dies a third of the way through with no record of where it stopped. Here is the batched fan-out that actually finishes.

Sending one transactional email from a Worker is easy. Sending fifty thousand is a different problem, and the difference is not the email, it is the loop. The instant you await a send inside a single request handler, you have tied a long, failure-prone job to one invocation that Cloudflare will not keep alive long enough to finish.

Let's build the version that works: a producer that fans the list out onto a Cloudflare Queue, a consumer that drains it at a controlled rate with retries and idempotency, and a dead-letter queue for the recipients that never go through. Then, at the end, the shortcut if you would rather not own all of it.

Why can't I send a campaign to a large list in one Worker request?

Because a single Worker invocation has hard limits that a big list blows straight past. There are three you will hit, roughly in this order:

  1. The subrequest cap. A Worker can make at most 1,000 outbound subrequests per invocation. Every HTTPS send is a subrequest. At recipient 1,001 the runtime refuses the call and your loop throws.
  2. The CPU budget. Each invocation has a CPU-time limit (50ms on the free tier; higher on paid, but still bounded). Tens of thousands of serialized awaits will exhaust it, and the invocation is killed mid-list.
  3. The provider rate limit. Even if Cloudflare let you run forever, the delivery layer will not. Fire 50,000 sends as fast as a loop can issue them and you get a wall of 429 Too Many Requests, plus a reputation hit for looking like a burst attacker.

Here is the version everyone writes first, and exactly where it falls over:

// DON'T: one request, one giant loop. This never finishes.
export default {
  async fetch(req: Request, env: Env): Promise<Response> {
    const recipients = await loadList(env); // 50,000 rows

    for (const r of recipients) {
      // Subrequest #1, #2, ... #1000 -> then the runtime refuses.
      // And the CPU budget is gone long before that.
      await fetch("https://api.delivery.example/v1/send", {
        method: "POST",
        headers: { authorization: `Bearer ${env.API_KEY}` },
        body: JSON.stringify({ to: r.email, subject: "Big news", html: "..." }),
      });
    }

    return new Response("sent"); // you will never reach this line
  },
};

The fix is to stop thinking of the campaign as one job. It is fifty thousand tiny jobs, and a queue is the thing that spreads tiny jobs across many short invocations. For the underlying reliability mechanics (retries, backoff, DLQ) this builds on sending email reliably with Cloudflare Queues; here we focus on the fan-out and pacing that bulk lists need.

How do I send bulk email in batches from a Cloudflare Worker?

Split the work into a producer and a consumer. The producer reads the list and enqueues recipients in chunks; the consumer pulls batches and sends them, paced and retried. Cloudflare runs the consumer many times concurrently, so the list drains across hundreds of short invocations instead of one that times out.

The shape of the pipeline:

POST /campaigns/:id/send
        │
        ▼
   producer Worker ──sendBatch(100)──▶  campaign-send queue
                                             │
                            (Cloudflare invokes consumer in parallel)
                                             ▼
                                     consumer Worker  ──HTTPS──▶ delivery layer
                                             │
                               (exhausted retries fall through)
                                             ▼
                                      campaign-send-dlq

Step 1: Create the queues

You need two: the fan-out queue and a dead-letter queue for recipients that never succeed.

npx wrangler queues create campaign-send
npx wrangler queues create campaign-send-dlq
✅ Created queue campaign-send
✅ Created queue campaign-send-dlq

Step 2: Bind the producer and consumer

In wrangler.jsonc, declare the producer binding (so a route can enqueue) and the consumer config (so this Worker also drains the queue):

{
  "name": "campaign-mailer",
  "main": "src/index.ts",
  "compatibility_date": "2026-06-01",
  "queues": {
    // Producer: the /send route enqueues via env.CAMPAIGN_SEND
    "producers": [
      {
        "binding": "CAMPAIGN_SEND",
        "queue": "campaign-send",
      },
    ],
    // Consumer: this Worker drains the queue, paced for bulk
    "consumers": [
      {
        "queue": "campaign-send",
        "max_batch_size": 10, // small batches -> finer pacing and failure handling
        "max_batch_timeout": 5, // seconds
        "max_retries": 5,
        "max_concurrency": 3, // cap parallel invocations to respect provider limits
        "dead_letter_queue": "campaign-send-dlq",
      },
    ],
  },
}

Two settings carry the bulk story here. max_batch_size is deliberately small (10, not 100) so each invocation does a bounded amount of work and you can pace sends within it. max_concurrency caps how many consumer invocations run at once, which is your coarse lever on total throughput: effective rate is roughly per-invocation rate times concurrency.

How do I fan a large list out onto the queue?

The producer reads the list and calls sendBatch() in a loop, slicing into chunks of up to 100 messages. sendBatch is one network round-trip per chunk, so enqueuing 50,000 recipients is 500 sendBatch calls, not 50,000 send calls.

interface Recipient {
  campaignId: string;
  recipientId: string; // stable id, used for idempotency
  email: string;
}

interface Env {
  CAMPAIGN_SEND: Queue<Recipient>;
  API_KEY: string;
  DB: D1Database;
}

export default {
  async fetch(req: Request, env: Env): Promise<Response> {
    const { campaignId } = (await req.json()) as { campaignId: string };

    const recipients = await loadCampaignRecipients(env, campaignId); // 50,000 rows

    // sendBatch accepts up to 100 messages per call (and <256KB total).
    // Enqueue in chunks of 100; the loop is the fan-out.
    for (let i = 0; i < recipients.length; i += 100) {
      const chunk = recipients.slice(i, i + 100);
      await env.CAMPAIGN_SEND.sendBatch(chunk.map((body) => ({ body })));
    }

    // The whole list is now durably queued. Sending happens in the consumer.
    return new Response(`queued ${recipients.length} recipients`, { status: 202 });
  },
} satisfies ExportedHandler<Env>;

async function loadCampaignRecipients(env: Env, campaignId: string): Promise<Recipient[]> {
  const { results } = await env.DB.prepare(
    "SELECT id AS recipientId, email FROM subscribers WHERE active = 1",
  ).all<{ recipientId: string; email: string }>();
  return results.map((r) => ({ campaignId, recipientId: r.recipientId, email: r.email }));
}

One caveat for very large lists: loading 50,000 rows into memory in the producer is fine for tens of thousands, but at hundreds of thousands you will want to paginate the SELECT (keyset by id) and enqueue page by page, so the producer itself stays within its CPU budget. The fan-out pattern is identical; you are just reading the list in slices too.

Why a status of 202, not 200?

You are returning 202 Accepted: the campaign is accepted for delivery, not delivered. The actual sends happen over the next minutes in the consumer. Reflect that in your API and your UI (a "sending" state, not a "sent" state) so nobody assumes a green response means every inbox got the mail.

How do I rate-limit the send so the provider doesn't throttle me?

Throttle inside the consumer, not the producer. The producer should fill the queue as fast as it can; the consumer is where you meter sends against the delivery layer's rate limit. Pace within each batch to a target like 5-20 messages per second, and remember that max_concurrency multiplies it.

// Same file: add the queue() handler to the default export
const SEND_RATE_PER_SECOND = 8; // per invocation; real rate ≈ this × max_concurrency

export default {
  async fetch(req, env) {
    /* producer from above */
    return new Response("queued", { status: 202 });
  },

  async queue(batch: MessageBatch<Recipient>, env: Env): Promise<void> {
    const minGapMs = 1000 / SEND_RATE_PER_SECOND;

    for (const message of batch.messages) {
      const started = Date.now();
      const { campaignId, recipientId, email } = message.body;
      const dedupeId = `${campaignId}:${recipientId}`;

      try {
        // Skip if already sent (retry after partial failure) or suppressed.
        if (await alreadySent(env, dedupeId)) {
          message.ack();
          continue;
        }
        if (await isSuppressed(env, email)) {
          message.ack(); // unsubscribed / hard-bounced: never send, never retry
          continue;
        }

        const res = await fetch("https://api.delivery.example/v1/send", {
          method: "POST",
          headers: {
            authorization: `Bearer ${env.API_KEY}`,
            "idempotency-key": dedupeId,
          },
          body: JSON.stringify({ to: email, subject: "Big news", html: "..." }),
        });

        if (res.status === 429 || res.status >= 500) {
          // Transient: rate-limited or provider error. Retry with backoff.
          message.retry({ delaySeconds: backoffSeconds(message.attempts) });
          continue;
        }
        if (res.status >= 400) {
          // Permanent (bad address, rejected). Record and ack; retry won't help.
          await recordFailure(env, dedupeId, await res.text());
          message.ack();
          continue;
        }

        await markSent(env, dedupeId); // record BEFORE acking, for idempotency
        message.ack();
      } catch {
        message.retry({ delaySeconds: backoffSeconds(message.attempts) });
        continue;
      }

      // Pace: hold the invocation so we don't exceed the per-second target.
      const elapsed = Date.now() - started;
      if (elapsed < minGapMs) await sleep(minGapMs - elapsed);
    }
  },
} satisfies ExportedHandler<Env>;

function backoffSeconds(attempts: number): number {
  const base = Math.min(2 ** attempts, 300); // cap at 5 minutes
  return Math.round(base + Math.random() * base * 0.2); // jitter to spread retries
}

const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));

The pacing is deliberately simple: after each send, wait long enough that the loop cannot exceed SEND_RATE_PER_SECOND. With max_concurrency = 3 and a per-invocation rate of 8/s, your real ceiling is about 24/s. Start low, watch your delivery layer's response for 429s, and raise the rate only when you have headroom. It is far cheaper to send a 50,000-recipient campaign over twenty minutes than to get rate-limited, retried into a thundering herd, and flagged for a reputation review. (For the standalone primitive, see rate-limiting an email API on Workers.)

How do I avoid double-sends when the queue retries?

Give every recipient a stable idempotency key and record sends, so a redelivered message is a no-op. A queue message can be redelivered after a partial success: you sent the email, then the consumer crashed before acking. Without a guard, that recipient gets the campaign twice.

async function alreadySent(env: Env, dedupeId: string): Promise<boolean> {
  const row = await env.DB.prepare("SELECT 1 FROM campaign_sends WHERE dedupe_id = ?")
    .bind(dedupeId)
    .first();
  return row != null;
}

async function markSent(env: Env, dedupeId: string): Promise<void> {
  // INSERT OR IGNORE so a concurrent retry can't create a duplicate row.
  await env.DB.prepare(
    "INSERT OR IGNORE INTO campaign_sends (dedupe_id, sent_at) VALUES (?, ?)",
  )
    .bind(dedupeId, Date.now())
    .run();
}

async function isSuppressed(env: Env, email: string): Promise<boolean> {
  const row = await env.DB.prepare("SELECT 1 FROM suppressions WHERE email = ?")
    .bind(email)
    .first();
  return row != null;
}

Two defenses are doing work here. The idempotency-key header lets the delivery layer dedupe even if your own check races. The campaign_sends table lets your consumer skip recipients on retry. Belt and suspenders, because on a 50,000-recipient send, "this almost never double-sends" still means dozens of people get the email twice.

The suppression check matters just as much. A recipient who unsubscribed an hour ago is still sitting in the queue; checking the suppression list at send time, not at enqueue time, is what keeps a slow-draining campaign from mailing people who already opted out. That is also a legal line under one-click unsubscribe rules, covered in adding List-Unsubscribe headers.

How do I handle recipients that fail permanently?

Drain the dead-letter queue with a second consumer. After max_retries, Cloudflare moves the message to campaign-send-dlq. Capture those so a failed campaign is auditable, not a black box.

// Add a second consumer in the same wrangler.jsonc queues.consumers array.
{
  "queue": "campaign-send-dlq",
  "max_batch_size": 10,
  "max_batch_timeout": 30,
}
// DLQ consumer: persist exhausted recipients for inspection / replay
export default {
  async queue(batch: MessageBatch<Recipient>, env: Env): Promise<void> {
    for (const message of batch.messages) {
      await env.DB.prepare(
        "INSERT INTO campaign_failures (dedupe_id, email, failed_at) VALUES (?, ?, ?)",
      )
        .bind(`${message.body.campaignId}:${message.body.recipientId}`, message.body.email, Date.now())
        .run();
      message.ack();
    }
  },
} satisfies ExportedHandler<Env>;

Now every recipient in the campaign has exactly one terminal state: sent, suppressed, or recorded as a failure. That is the property you actually want from a bulk send, and the naive for-loop gives you none of it.

Common failure modes (and what they mean)

Error: Too many subrequests.

You are still sending inline in fetch() somewhere, not in the consumer. Each invocation tops out at 1,000 subrequests; move all sends into the queue() handler where the work is spread across invocations.

HTTP 413 / "message too large" from sendBatch

A sendBatch payload exceeded 256 KB, or a chunk had more than 100 messages. Keep chunks at 100 and put only ids and the email in the message body, not the full rendered HTML; render in the consumer.

Provider returns a wall of 429s mid-campaign

Your effective rate (per-invocation rate × max_concurrency) is above what the delivery layer allows. Lower SEND_RATE_PER_SECOND or max_concurrency. The retries will catch the already-queued ones; just slow the drain.

Some subscribers got the campaign twice

A message was redelivered after a partial success and the idempotency guard didn't catch it. Confirm markSent runs before ack() and that the idempotency-key header is set on the send.

The shortcut: the Tinbox campaign sender

Everything above is the correct architecture for bulk send on Workers, and it is also a real amount of plumbing to own: two queues, a paced consumer, idempotency tables, suppression checks, a DLQ drainer, and the cron to kick off scheduled campaigns. If you would rather not maintain all of it, this is exactly what the Tinbox newsletter sender provisions, on your own Cloudflare account.

npx tinbox init yourdomain.com

Under the hood it is the same pattern. A cron job picks up due campaigns and enqueues recipients onto a NEWSLETTER_QUEUE in chunks of 100 with sendBatch. The queue consumer drains them at a configurable rate (one variable, NEWSLETTER_SEND_RATE, default 5 per second), deduping per campaign-recipient and checking the suppression list on every message, so unsubscribes and bounces are skipped even on a slow drain. Your app code is one call:

import { tinbox } from "tinbox/cf";

// Create and send a campaign to a saved audience segment.
const campaign = await tinbox(env).campaigns.create({
  from: "news@yourdomain.com",
  subject: "Big news",
  html: "<p>Hello {{ first_name }}</p>",
  audience: "active-subscribers",
});

await tinbox(env).campaigns.send(campaign.id);
// Returns immediately; the cron + queue fan-out delivers over the next minutes.

The fan-out, pacing, idempotency, suppression, and dead-letter handling all run in the worker Tinbox deploys next to yours, on infrastructure you control, with no per-email pricing on top. Because Cloudflare Workers cannot open outbound port 25 for direct-to-MX SMTP, the actual delivery happens over HTTPS in that consumer; see why edge email needs an HTTPS sender for the why, and this honest comparison for where owning the queue beats paying a SaaS to run it.

Deploy this yourself: npx tinbox init yourdomain.com. The campaign queue, consumer, and rate configuration are in the Tinbox docs.

Frequently asked questions

Why can't I send a campaign to a large list in one Cloudflare Worker request?

A single Worker invocation has a CPU budget (50ms on the free tier, configurable higher on paid) and a cap of 1,000 subrequests. If you loop over 50,000 recipients and await an HTTPS send per recipient, you blow past both limits long before the list is done, and the request dies with the campaign half-sent and no record of where it stopped. You must move the sending out of the request and spread it across many invocations, which is what a queue gives you.

How do I send bulk email in batches from a Cloudflare Worker?

Split the work into a producer and a consumer. The producer reads your list and calls queue.sendBatch() to enqueue recipients in chunks of up to 100 messages. The consumer is a queue() handler that pulls a batch, sends each message over HTTPS, and acks or retries per message. Cloudflare invokes the consumer many times in parallel, so the list drains across hundreds of short invocations instead of one giant request that times out.

How do I rate-limit a campaign so I don't get throttled by the delivery layer?

Throttle inside the consumer, not the producer. Set a small max_batch_size and pace sends within each batch to a target like 5-20 messages per second using a short delay between sends. Because Cloudflare runs consumer invocations concurrently, your real throughput is roughly per-invocation-rate times concurrency, so start conservative and watch for 429s before raising it. Tinbox exposes this as a single NEWSLETTER_SEND_RATE variable.

What is the maximum batch size for queue.sendBatch in Cloudflare Queues?

queue.sendBatch() accepts up to 100 messages per call, and the total payload must stay under 256 KB. To enqueue 50,000 recipients you call sendBatch in a loop, slicing the list into chunks of 100. On the consumer side, max_batch_size (also up to 100) controls how many messages each consumer invocation receives.

How do I avoid sending the same person twice when a queue retries?

Give every recipient a stable idempotency key (campaign id plus recipient id) and record sent keys before or as you send. When a message is redelivered after a partial failure, check the record and skip recipients already sent. Tinbox dedupes per campaign-recipient automatically and also checks the suppression list, so unsubscribes and hard bounces are skipped on every retry.