r/nextjs • • 11d ago

Next.js 16 on Cloudflare Workers: CPU per request went from ~450 ms to ~100 ms. What actually moved it

I run Next.js 16 on Cloudflare Workers through OpenNext: a prerendered marketing site in 17 languages, a dashboard and public pages. For weeks, Workers analytics showed about 450 ms of CPU per request. It's about 100 ms now, and the slow tail of uncached renders (p90 across 20 probes worldwide) went from ~9.9 s to ~3.6 s. What did it:

1. Sentry's Node SDK was inside the Worker. Next builds the server for Node, so @sentry/nextjs bundled its Node SDK. It never even started in the Worker, but it was a quarter of the script and a third of every cold start. Point the server at Sentry's edge build:

// next.config.ts
function sentryBuild(file: string) {
  const pkg = path.dirname(require.resolve('@sentry/nextjs/package.json'));
  return `./${path.relative(__dirname, path.join(pkg, 'build/esm', file))}`;
}

const nextConfig: NextConfig = {
  turbopack: {
    resolveAlias: {
      '@sentry/nextjs': {
        browser: sentryBuild('index.client.js'),
        default: sentryBuild('edge/index.js')
      }
    }
  }
};

2. Script size is startup time. A Worker parses its whole script on every cold start. Ours was 37 MiB raw, half of it marketing text: every language's MDX and message catalogs compiled into the bundle. Moving that text to static assets, read at render through the ASSETS binding, brought it to 18 MiB, and Wrangler now reports 28 ms of startup.

3. A cookie keeps a page out of the edge cache. next-intl sets a locale cookie on the first visit, and the cache won't store a response with Set-Cookie. So every first visit and every crawler missed the cache. This stores the page without that one header:

Cache-Control: public, max-age=86400, stale-while-revalidate=86400, private="set-cookie"

The first visitor still gets the cookie, and everyone after is served from the edge.

4. Don't ask your auth server on every request. Verify the session JWT locally. A fresh isolate fetching the signing keys from a cold auth API waited up to 1.4 s, so the keys now go through the Cache API, which all isolates in a data center share.

5. A server action that sets a cookie re-renders the whole page. D1's read replicas need a session bookmark that travels in a cookie, so every server action set one, and Next re-rendered the full page after each write. Writes now go through a route handler; server actions are left for flows that end in a redirect.

6. The static-assets incremental cache is fast and read-only. Every page it serves has to be prerendered (dynamicParams = false), and nothing revalidates. Fine for a marketing site, but plan for it.

7. Watch the network tab after an OpenNext upgrade. With enableCacheInterception, @opennextjs/aws 4.1.0 answered the router's segment prefetches with the whole page, and open tabs kept prefetching in a loop. 4.1.6 fixed it.

One thing I haven't solved: telling cold requests from warm ones. I read CPU from Workers analytics and time to first byte from Globalping probes, but which requests were cold is still guesswork. How do you measure it?

7 Upvotes

8 comments sorted by

2

u/dusanodalovic 11d ago

no experience with workers myself, so take this as a guess. module scope runs once per isolate, so a module-level flag that is true on the first request and false after that would mark the cold ones. you could send it back in a Server-Timing header and have the probes record it next to the ttfb. curious if the numbers then match what analytics shows :)

1

u/Janczik_yelianny44 11d ago

putting it in the Server-Timing header is a really clean way to expose it to the probes tbh.

0

u/EventAssets 11d ago

Good call—V8 isolates reuse module scope across requests, so that should work cleanly. Will wire it into Server-Timing on the next deploy and give it a try, thanks!

2

u/Fun_Improvement7704 11d ago

you can track cold isolates by setting a global variable outside the request handler, like `globalThis.warm = true` after the first execution. it's not 100% scientific since an isolate can handle concurrent requests right as it spins up, but it's accurate enough for analytics.

1

u/voprosy 10d ago

Thanks for this.  I’m actually optimizing my app as well, and going through similar findings and this is helpful. 

1

u/Life_Cartographer782 10d ago

Depends on how much backend you want to own.

- Medusa: good if you want full control and self-hosting, but you're running a Node backend + Postgres yourself. Fine if you're comfortable with that.

- Saleor: similar idea, GraphQL-first, Python backend. Heavier.

- Shopify Hydrogen / Storefront API: least ops work. Shopify handles cart, checkout, payments, taxes; you just build the Next.js frontend. Vercel's Next.js Commerce starter shows the pattern.

- Stripe only: if the catalogue is small (under ~50 products), Stripe Checkout + a products table in your own DB is honestly enough and the simplest to maintain.

For a first store I'd go Shopify + Next.js or plain Stripe, and only reach for Medusa if you have a real reason to own checkout.

1

u/Dry_Flight_3156 3d ago

to get around the concurrency race on a brand-new isolate where multiple requests hit before the first finishes, you can check `performance.timeOrigin`

against the request timestamp. If `Date.now() - performance.timeOrigin < 50ms`, it's almost guaranteed to be in that initial cold-spawn window regardless of concurrent queueing.

Also, point #5 about Server Actions re-rendering the whole page due to D1 session cookies is huge. We hit the exact same friction where server action cookie mutations bust the router cache and trigger

full-tree re-renders on the edge. Moving mutations to standard route handlers and keeping server actions strictly for redirect flows saved us so much unnecessary compute.

Quality writeup all around.