Skip to content
Rohan Khatua

Writing

95% of My Worker Traffic Was AI Crawlers

5 min readweb

After moving my Hacker News reader, hn.rohankhatua.dev, onto Cloudflare Workers, I kept getting "Workers limit exceeded" emails. The site runs on the free plan, which allows 100,000 requests a day and 10 ms of CPU per request. A small side project shouldn't get anywhere near either limit.

My first instinct was to make page renders cheaper. I'm glad I checked who was making the requests first, because the answer was "almost nobody human."

Looking at the numbers

Cloudflare's GraphQL Analytics API gives you Worker invocations grouped by outcome. For the previous 24 hours, the hackernews Worker showed:

StatusRequests
success46,849
exceededResources8,130
scriptThrewException1,599

So about 57k requests a day, and the median successful request used 13.5 ms of CPU, already over the 10 ms free-plan limit. Daily traffic was also climbing fast: about 7.5k requests on November 30 and 44.5k on December 3.

Worker analytics don't break down by path or user agent, but zone-level HTTP analytics do. Grouping requests to the hostname by user agent was the turning point:

typescript
const query = `query($acc: string!, $since: Time!, $until: Time!) {
  viewer { accounts(filter: {accountTag: $acc}) {
    httpRequestsAdaptiveGroups(
      limit: 20,
      filter: { datetime_geq: $since, datetime_leq: $until,
                clientRequestHTTPHost: "hn.rohankhatua.dev" },
      orderBy: [count_DESC]
    ) {
      count
      dimensions { userAgent }
    }
  } }
}`;

The top of that list:

CrawlerRequests (24h)
Meta meta-externalagent (several UA variants)~35,000
ElevenlabsCrawler6,449
ClaudeBot6,007
Amazonbot3,690
SemrushBot607

Roughly 95% of the Worker's traffic was crawlers, mostly AI-training crawlers.

Filtering Meta's crawler by path made the pattern obvious. It requested /, /best, /newest, /ask, /show, /jobs, /topics, /search, /recommended and /auth/login about 1,500 times each per day. That's once a minute, for every nav page. Some of those paths were already disallowed in my robots.txt.

Why every crawler hit was expensive

Almost none of this traffic was served from cache: 56,458 requests had cache status none, and only 690 were cache hits. My OpenNext setup only caches rendered pages in the Worker's memory, so a crawler arriving on a fresh isolate triggers a full server render of the page.

That also explained a cluster of 500s on /topics, /search and /auth/login. About 8,000 requests a day were running past the CPU limit, which lines up with those errors.

So the real problem wasn't "rendering is slow." It was "I'm rendering pages tens of thousands of times a day for bots."

The fix: reject crawlers before Next.js starts

OpenNext lets you replace the Worker entry point with your own file that wraps the generated one. I pointed main in wrangler.jsonc at a small worker.ts that checks the user agent before handing off to OpenNext:

typescript
import { isBlockedBot } from "./lib/bots";
// @ts-ignore generated by `opennextjs-cloudflare build`
import { default as openNextWorker } from "./.open-next/worker.js";

const handler = openNextWorker as {
  fetch: (req: Request, env: CloudflareEnv, ctx: unknown) => Promise<Response>;
};

export default {
  async fetch(request: Request, env: CloudflareEnv, ctx: unknown) {
    if (isBlockedBot(request.headers.get("user-agent"))) {
      // Still serve robots.txt so crawlers that honor it learn they're blocked.
      if (new URL(request.url).pathname !== "/robots.txt") {
        return new Response("Crawling is not permitted. See /robots.txt.\n", {
          status: 403,
          headers: {
            "content-type": "text/plain; charset=utf-8",
            "cache-control": "public, max-age=86400",
          },
        });
      }
    }
    return handler.fetch(request, env, ctx);
  },
};

A regex test on a header costs well under a millisecond, compared with a full render that regularly went past 10 ms.

The crawler list lives in one shared file, lib/bots.ts, used in two places:

  • worker.ts returns the 403 for crawlers that ignore robots.txt.
  • app/robots.ts writes a Disallow: / rule for the same list, so crawlers that respect robots.txt stop on their own. I also disallowed /search for every crawler, since search result pages are expensive and useless to index.

The list covers AI-training crawlers (Meta's agents, ClaudeBot, GPTBot, Amazonbot, Bytespider, ElevenLabs and others) and a few SEO scrapers. Just as important is what I left off it: Googlebot, Bingbot and DuckDuckBot for search, and link-preview fetchers like facebookexternalhit, Twitterbot and Slackbot. Blocking those would break the previews when someone shares a link.

Testing it

Lint, tsc --noEmit, the OpenNext build and wrangler deploy --dry-run all passed. Then I ran the Worker locally with wrangler dev and sent requests with different user agents:

  • A Meta crawler user agent got a 403 on /best, and could still fetch robots.txt with the new rules.
  • A normal browser user agent got a 200.
  • facebookexternalhit got a 200, so link previews still work.

The change is in PR #27. It wasn't deployed when I wrote this, so I don't have production numbers yet.

The part code can't fix

A 403 from my Worker is still a Worker invocation. Blocking crawlers in code cuts the CPU problem (the exceededResources failures and the 500s), but each blocked request still counts toward the 100k-requests-a-day quota.

To stop the requests before the Worker runs at all, the block has to happen at Cloudflare's edge: either the Block AI bots setting under Security → Bots for the zone, or a WAF rule matching these user agents. That's a dashboard setting, not a code change, and it's the real fix for the quota emails. The code change is still worth having as a second layer, and for crawlers that slip past the edge rules.

What I'd do differently

  • Look at traffic before optimizing. I was ready to add a cache layer for rendered HTML. That would have helped a bit, but the real fix was to stop serving 95% of the requests at all.
  • Turn on bot blocking on day one for any free-tier site with lots of linkable pages. AI crawlers re-fetch every page on a fixed schedule, and on a free plan that adds up fast.
  • Don't trust robots.txt alone. Meta's crawler was fetching pages my robots.txt already disallowed. A Disallow rule is a request, not access control.
  • Set up usage alerts. The daily request count grew about 6× in three days. An alert at 80% of the quota would have flagged it before the emails started.

One small side effect: CI on the PR failed a dependency audit because of new advisories in two transitive packages (cross-spawn and ws) that had nothing to do with the change. Pinning them with overrides in package.json fixed it, but it was a good reminder that a security audit in CI can fail a PR because of a newly published advisory, even when the PR doesn't touch dependencies.