Skip to content

@tailwindcss/vite: cached Root.compiler pins the build's plugin context, keeping the finished bundle alive (multi-GB RSS in Astro SSG) #20501

Closed

Description

@benjamineckstein

Verified against: @tailwindcss/vite 4.3.3, vite 8.3.0 (bundling with rolldown 1.2.9),
astro 7.3.3, Node 24.18.0

Summary

The build plugin caches a Root per (environment, css id) for the lifetime of the plugin
instance. The Root's compiler is created inside the transform hook and its onDependency
option closes over the addWatchFile callback that the hook was called with, which is
(file) => this.addWatchFile(file), i.e. a closure over the build's PluginContext.

Nothing releases that closure when the bundle is done, so the plugin context of that build
stays reachable for as long as the plugin instance lives. On Vite 8 the bundler is Rolldown,
so the context is a thin JS handle onto a native bundler arena: holding it keeps the finished
bundle alive in Rust memory rather than on the JS heap. In a one-shot vite build this is
invisible because the process exits right after. In any framework that keeps doing work inside
the same Vite build session, it is a multi-GB retainer.

Astro's static build is the clearest case: builder.buildApp() runs the SSR/prerender build
and then generatePages() inside the same call, so the prerender PluginContext is still
strongly reachable through rootsByEnv while every page is rendered.

Retainer chain

module-scope (per plugin instance)
  rootsByEnv: DefaultMap<string, Map<string, Root>>   // never cleared
    -> Map<cssId, Root>
      -> Root.compiler                                 // set in Root.generate()
        -> compile(..., { onDependency })              // @tailwindcss/node holds the option
          -> onDependency closure
            -> addWatchFile  === (file) => this.addWatchFile(file)
              -> PluginContext of the prerender build
                -> native Rolldown bundler arena for that build

Because the retained bytes sit in the native arena and not in V8, heap-after-GC does not move
at all. The cost is only visible in RSS. That is worth stating up front, since a heap-only
investigation concludes there is no leak.

The relevant code in packages/@tailwindcss-vite/src/index.ts:

let rootsByEnv = new DefaultMap<string, Map<string, Root>>((env: string) => new Map())

// ...
{
  name: '@tailwindcss/vite:generate:build',
  apply: 'build',
  enforce: 'pre',
  transform: {
    filter: { /* ... */ },
    async handler(src, id) {
      // ...
      let roots = rootsByEnv.get(this.environment?.name ?? 'default')
      let root = roots.get(id)
      if (!root) {
        root ??= createRoot(this.environment ?? null, id)
        roots.set(id, root)
      }

      let result = await root.generate(src, (file) => this.addWatchFile(file), I)
      // ...
    },
  },
}

and in Root.generate:

this.compiler = await compile(content, {
  from: this.enableSourceMaps ? this.id : undefined,
  base: inputBase,
  shouldRewriteUrls: true,
  onDependency: (path) => {
    addWatchFile(path)                                  // <- captured PluginContext
    addBuildDependenciesPromises.push(this.addBuildDependency(path))
  },
  customCssResolver: this.customCssResolver,
  customJsResolver: this.customJsResolver,
})

Note that addWatchFile is captured from the first transform call only. Later calls pass a
fresh callback that is used for the else branch, but the compiler keeps the original one
forever.

Impact (measured)

Astro 7.3.3 static site, 3,864 pages, one @tailwindcss/vite root CSS file, Node 24.18.0,
macOS 26.6 / M-series, 18 cores, astro build with build.concurrency: 4.

wall time peak RSS peak heap after forced GC
as shipped 224 s 16,404 MB 1,166 MB
context detached 172 s 9,782 MB 1,104 MB

Same pair with a global.gc() probe running every 3 s (so the numbers are directly
comparable to each other, not to the row above):

wall time peak RSS peak heap after forced GC
as shipped 180 s 21,332 MB 1,166 MB
context detached 174 s 7,593 MB 1,104 MB

Two things are worth calling out, because they make the bug easy to miss:

  1. The live heap does not grow. Heap-after-full-GC sits flat at ~905 MB through the whole
    of route generation in both variants. Looking only at heap-after-GC, the retention is
    invisible.
  2. The cost is a transient RSS explosion at the build/route-generation boundary. In the
    as-shipped run, RSS goes from 6.1 GB at t=54 s to 21.0 GB at t=68 s and then decays back to
    7.3 GB. With the context detached it never exceeds 7.5 GB. The retained context is what
    stops the bundler arena being released before the next phase starts allocating, so the two
    working sets overlap instead of succeeding one another.

Output is unaffected: identical emitted file set (6,309 files), all 2,445 non-HTML files
byte-identical, and 0 of 3,864 HTML pages differ once per-render random element ids are
normalised. The emitted CSS is byte-identical.

Linux CI for the same project (GitHub Actions, 16 GB runner, Node 24) reports peak RSS of
8,192 / 8,293 / 8,357 / 8,407 MB across four consecutive as-shipped runs. A 7 GB runner OOM'd
on this build, which is why the larger runner is in use at all.

Repro

No Astro needed. Wrap the build plugin's transform so it records a WeakRef to the
PluginContext Tailwind is called with, run a build, force a GC, then ask whether the context
is still alive.

// probe.mjs  ->  node --expose-gc probe.mjs   and   node --expose-gc probe.mjs --fix
import { build } from 'vite'
import tailwindcss from '@tailwindcss/vite'

const APPLY_FIX = process.argv.includes('--fix')
const NAME = '@tailwindcss/vite:generate:build'

let ctxRef = null
let attachmentRef = null

function instrument(plugins) {
  return plugins.map((plugin) => {
    if (plugin.name !== NAME) return plugin
    const original = plugin.transform.handler
    return {
      ...plugin,
      transform: {
        ...plugin.transform,
        handler(...args) {
          if (!ctxRef) {
            const hangingOffTheContext = { marker: 'reachable-through-plugin-context' }
            this.probeAttachment = hangingOffTheContext
            ctxRef = new WeakRef(this)
            attachmentRef = new WeakRef(hangingOffTheContext)
          }
          const self = APPLY_FIX ? { environment: this.environment, addWatchFile() {} } : this
          return original.apply(self, args)
        },
      },
    }
  })
}

await build({
  root: import.meta.dirname,
  logLevel: 'error',
  configFile: false,
  build: { write: false, lib: { entry: 'src/main.js', formats: ['es'], fileName: 'out' } },
  plugins: [instrument(tailwindcss())],
})

for (let i = 0; i < 5; i++) {
  global.gc()
  await new Promise((resolve) => setImmediate(resolve))
}

console.log(
  `mode=${APPLY_FIX ? 'fixed' : 'as-shipped'} ` +
    `pluginContextAlive=${ctxRef?.deref() !== undefined} ` +
    `attachmentAlive=${attachmentRef?.deref() !== undefined}`,
)

src/app.css is just @import "tailwindcss"; and src/main.js is import "./app.css".
Output on @tailwindcss/vite 4.3.3, vite 8.3.0, Node 24.18.0:

mode=as-shipped pluginContextAlive=true  attachmentAlive=true
mode=fixed      pluginContextAlive=false attachmentAlive=false

The build has fully completed and five major GCs have run, and the PluginContext plus
everything hanging off it is still strongly reachable.

For the real-world shape, use any Astro output: 'static' site with @tailwindcss/vite and a
few thousand pages, and sample process.memoryUsage().rss during the build. The spike sits
right at the handover from the bundler to route generation. Sample RSS, not heapUsed: the
retained bytes are in the native arena, so a heap-only probe shows nothing.

Suggested fixes (either is enough)

  1. Do not capture the context. Store addWatchFile on the Root and have onDependency
    read this.currentAddWatchFile at call time, so it always uses the callback of the transform
    call that is actually running, instead of pinning the first one.

  2. Clear the cache when the bundle is done. Add to the build plugin:

    closeBundle() {
      rootsByEnv.clear()
    }

    This keeps the caching benefit within a build and drops the retention afterwards.

(1) is the more complete fix: it also prevents a stale context being used for watch
registration when several environments share a Root.

Workaround in userland

Wrapping the build plugin's transform.handler so Tailwind sees a stub this with the real
environment and an inert addWatchFile removes the retention entirely and produces
byte-identical output. addWatchFile is a no-op outside watch mode anyway, so nothing is lost
for a one-shot build.

🤖 Generated with Claude Code

Activity

  1. lumpinif commented on Sep 30, 2026

    @lumpinif

    We hit the same retention independently, with Rollup (Vite 7), not Rolldown. In our case it shows up on the JS heap and causes a real V8 JavaScript heap out of memory crash. So the problem is not limited to Rolldown or to RSS-only growth, and #20503 would fix it for us too.

    Setup

    • @tailwindcss/[email protected], Vite 7.3.2 (Rollup), Node 24.14.0
    • TanStack Start + @cloudflare/vite-plugin. A single createBuilder() instance runs build(client) → build(ssr) → buildApp() in one process.
    • Large app; the production build runs with --max-old-space-size=5120 (the CI runner has 8 GB).

    What we measured
    We forced GC and took a heap snapshot after each environment build. Dominators after the SSR build:

    GC roots → Vite resolved config → plugins → "@tailwindcss/vite:scan"
      → rootsByEnv (DefaultMap)                       ~2,988 MiB retained
      → rootsByEnv["client"] → Root (styles.css)      ~2,972 MiB
      → Root.compiler build closure → loadModule → onDependency
      → Rollup plugin context → FileEmitter / Graph   ~2,955 MiB
    

    (The sizes are nested, so they overlap.) Vite already sets rollupOptions.cache = false for non-watch builds and calls bundle.close(), so the closed client graph stays reachable only through this reference.

    Workaround we applied (via pnpm patch, the same idea as #20503)

    // in the build-only plugin (@tailwindcss/vite:generate:build)
    closeBundle() {
      rootsByEnv.delete(this.environment.name)
    }

    Results from three full production builds at a 5,120 MiB V8 limit:

    Peak V8 heap Heap retained after SSR + GC
    Before ~4,775 MiB (and OOM in a stricter packaging build) ~4,558 MiB
    After 4,059 / 4,281 / 4,122 MiB ~1,567 MiB

    The numbers above also include a separate, small cleanup in another plugin; that cleanup alone saved only about 60 MiB. We verified the built output with Workerd: SSR routes return 200, and server functions and hydration work.

    Thanks for #20503. We'd be glad to see it land, and we'll drop our local patch once it's released.

  2. eschultz commented on Oct 4, 2026

    @eschultz

    Same retention with Nuxt 3 static generation (nuxi generate): @tailwindcss/vite 4.3.0 (4.3.3 has the same code), Vite 7.3.6 with Rollup 4, Nuxt 3.21.11, Node 22.

    Nuxt keeps its Vite plugins in nuxt.options for the whole process, and Nitro builds and runs its prerenderer in that same process after the client build. A heap snapshot taken as Nitro's prerender starts shows the client build's Rollup Graph held through the chain described above:

    nuxt.options.vite.plugins
      -> @tailwindcss/vite:scan closure
        -> roots map
          -> Root.compiler
            -> onDependency
              -> plugin context
                -> graph
    

    That graph was about 1.7 GB of a 2.1 GB live heap.

    Measured on our app (about 7,600 client modules):

    as shipped context detached
    live heap after the first full GC in prerender 2,181 MB 764 MB
    --max-old-space-size=2560 "JavaScript heap out of memory" in Nitro's prerender passes
    3 GB / 2 CPU container, 2560 cap V8 heap OOM in prerender passes in 102 s
    3 GB / 2 CPU container, 4096 cap OOM-killed in prerender OOM-killed in prerender

    The last row is there because with a 4096 cap V8 lets the heap grow past 3 GB before collecting, so neither variant fits. On our 4 GB build host the build never crashed: the prerender step swap-thrashed until it crossed a 10-minute timeout.

    Until #20503 lands, we wrap the build plugin's transform handler so Tailwind gets a proxy for the plugin context, and null the proxy's target in buildEnd. For a one-shot build that should have the same effect as #20503, so we'd be glad to see that PR merged.

  3. PrzemeekMichalowski commented on Nov 19, 2026

    @PrzemeekMichalowski

    Same retention in Nuxt 4.4 (Vite 7.3, Rollup 4) running on Bun 1.3.14. Nuxt keeps tailwindcss() in nuxt.options.vite.plugins for the whole process, so after the client and SSR builds both Rollup graphs stay reachable while Nitro bundles the server: 2.0 GiB of live heap at Nitro's start in our app, and the build got OOM-killed on 8 GB CI runners.

    Some data on which versions fix it, in case it helps triage. Minimal repro: one vite.build() (Vite 7.3.8) of a small app, the tailwindcss() array kept alive afterwards, then forced GC; a probe plugin takes WeakRefs in buildStart to this.getModuleInfo (a closure over the Rollup graph) and to this.environment.

    @tailwindcss/vite Node 24.22 Bun 1.3.14
    4.3.2 graph alive, environment alive graph alive, environment alive
    4.3.5 graph freed, environment alive graph alive, environment alive
    0.0.0-insiders.e0a9863 graph freed, environment alive graph freed, environment alive
    • Release loader callbacks after compilation #20531 (4.3.4) releases the graph on Node but not on Bun; JSC seems to keep more of Root.generate's scope alive than V8.
    • Improve @tailwindcss/vite build performance by scanning the same sources only once per build #20678 (on main, not released yet) frees it on both, since a build outside watch mode no longer passes addWatchFile. Live heap at Nitro's start in our Nuxt build: 4.3.2 2,062 MiB, 4.3.5 2,073 MiB, insiders 514 MiB.
    • What remains on main: rootsByEnv is never cleared, and each Root's customCssResolver / customJsResolver close over the Vite environment given to createRoot(), so the environments (and the roots' compilers and scanners) stay reachable. Dropping the plugin's state entirely brings us to 385 MiB, so that is another ~130 MiB.

    Would you consider releasing #20678, and deleting an environment's roots in closeBundle outside watch mode as #20503 proposed? The second would also make the result independent of how a runtime captures closures. The repro is a short script; happy to attach it.

    Our workaround until then strips the plugin's hooks once Vite is done, in a Nuxt hook that runs before Nitro:

    const tailwind = tailwindcss()
    // vite: { plugins: [tailwind] }
    // hooks:
    'nitro:build:before': (nitro) => {
      if (nitro.options.dev) return
      for (const plugin of tailwind) {
        for (const key of Object.keys(plugin)) if (typeof plugin[key] !== 'string') delete plugin[key]
      }
    },
  4. self-assigned this
    on Nov 20, 2026
  5. RobinMalfait commented on Nov 23, 2026

    @RobinMalfait
    Contributor

    @tailwindcss/vite kept the compiler, scanner and resolvers of each root CSS file after a build had finished, so in a long-running process like Astro's static build they stayed in memory while the pages were rendered. Now the plugin releases the roots of an environment once its build is done (outside watch mode), and the compiler no longer holds on to the plugin context of the build.

    This should be fixed by #20736, and will be available in the next release.

    You can already try it with the insiders build. It is published a few minutes after the merge:

    npm install tailwindcss@insiders @tailwindcss/vite@insiders

    Sent by an AI assistant on behalf of @RobinMalfait.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions