Skip to content

fix(email-routing): handle admitted email that exceeds the KV value limit after encoding #36042

In review

Description

@coygeek

Existing documentation URL(s)

What changes are you suggesting?

Explain that the 25 MiB Email Routing limit applies to the incoming message and the 25 MiB Workers KV limit applies to the serialized value. In both examples, show how to check the serialized byte length before writing to KV and give larger values an explicit outcome before queueing, replying, or forwarding. A documented size policy or an alternative store for raw email would let users handle messages near the inbound limit predictably.

Additional information

Summary

Both examples place the full decoded email and its metadata in one JSON value. JSON escaping can make a message below the inbound limit exceed the KV limit.

Steps to reproduce

  1. Save the email storage MDX source as email-storage.mdx. Save the script below as probe-storage.mjs in the same directory.
  2. Run the script with Node.js. It extracts both published handlers, stubs the mail construction and platform bindings, and passes each handler a small control and a plain-text email with 338,000 CRLF-terminated lines of 74 ASCII characters. It reports the raw and serialized byte counts and asserts which operations ran.
node probe-storage.mjs
Reproduction script probe-storage.mjs
import assert from "node:assert/strict";
import { readFileSync, writeFileSync } from "node:fs";

const source = readFileSync("email-storage.mdx", "utf8");
const mailStubs = `
const EmailMessage = class {};
const createMimeMessage = () => ({
  setHeader() {}, setSender() {}, setRecipient() {}, setSubject() {},
  addMessage() {}, asRaw() { return "stub"; }
});
`;
const limit = 25 * 1024 * 1024;
const from = "source@example.com";
const to = "support@example.com";
const headers = new Headers({
  From: from,
  To: to,
  Subject: "help",
  Date: new Date().toUTCString(),
  "Message-ID": "<id@example.com>",
});
const header = `From: ${from}\r\nTo: ${to}\r\nSubject: help\r\nDate: ${headers.get("date")}\r\nMessage-ID: <id@example.com>\r\n\r\n`;
const small = header + "Please help.\r\n";
const nearLimit = header + ("A".repeat(74) + "\r\n").repeat(338000);

for (const [heading, expected] of [
  ["Store emails in KV", ["email KV put", "ticket KV put", "reply", "forward"]],
  ["Queue-based processing", ["email KV put", "enqueue", "reply"]],
]) {
  const section = source.split("## " + heading, 2)[1];
  const snippet = section.match(/```(?:javascript|typescript)\n([\s\S]*?)\n```/)[1];
  const module = new URL(`./${heading.replaceAll(" ", "-")}.ts`, import.meta.url);
  writeFileSync(module, mailStubs + snippet.replace(/^import .*\n/gm, ""));
  const { default: worker } = await import(module);

  for (const [label, raw] of [["small", small], ["near limit", nearLimit]]) {
    const events = [];
    let valueBytes;
    const emailKv = {
      async put(_key, value) {
        valueBytes = Buffer.byteLength(value);
        if (valueBytes > limit) throw new Error("simulated KV value size limit");
        events.push("email KV put");
      },
    };
    const env = {
      EMAILS: emailKv,
      EMAIL_STORAGE: emailKv,
      SUPPORT_TICKETS: { async put() { events.push("ticket KV put"); } },
      EMAIL_QUEUE: { async send() { events.push("enqueue"); } },
    };
    const msg = {
      from,
      to,
      headers,
      raw: new Blob([raw]).stream(),
      rawSize: Buffer.byteLength(raw),
      async reply() { events.push("reply"); },
      async forward() { events.push("forward"); },
    };

    if (label === "small") {
      await worker.email(msg, env);
      assert.deepEqual(events, expected);
    } else {
      assert.ok(msg.rawSize < limit);
      await assert.rejects(worker.email(msg, env), /simulated KV value size limit/);
      assert.deepEqual(events, []);
    }
    console.log(heading, label, { rawBytes: msg.rawSize, valueBytes, events });
  }
}

Expected behavior

The examples should document which message sizes their storage design supports and show what happens when the serialized value exceeds the KV limit. The handler should produce that outcome before any workflow step that assumes the message was stored.

Actual behavior

The near-limit input measured 25,688,135 bytes. The value passed to KV measured 26,364,346 bytes in Store emails in KV and 26,364,364 bytes in Queue-based processing. Both exceed the 26,214,400-byte KV limit. The size-checking KV stub rejected both writes before the subsequent workflow steps. With the small control, both handlers stored the message and reached their normal follow-up operations. The test used local stubs for storage, queueing, and mail operations.

Evidence

  • Expected source: Email Routing limits and Workers KV limits set the separate inbound message and storage value limits.
  • Failure source: The EMAILS.put() and EMAIL_STORAGE.put() calls write JSON.stringify(emailData) before any queueing, reply, or forwarding step.
  • Evidence provenance: observed
  • Local verification: reproduced
  • Reproduction completeness: complete

Restoration check

Run both revised examples with a small message and the near-limit fixture. The small message follows the ordinary workflow. The near-limit fixture receives the documented storage or rejection outcome before the handler reports or assumes that it stored the message.

Runtime or environment

Cloudflare Docs production revision cd5bf82ac1d0d34fe13997eb15c6727b498cd926 and Node.js v26.13.1. The hosted Email Routing and Workers KV services were outside the test.

Triage assessment

  • Impact level: P2
  • Assessment status: supported
  • Impact basis: A message within the published inbound size limit can fail the example's storage step, preventing the subsequent workflow for that email.
  • Workaround status: unverified
  • Workaround basis: A different store or an explicit size policy could handle this case. The local probe verifies the existing handlers and size checks.

Metadata

Metadata

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions