| | |

Vitest 39 🧪 Performance — Pool options, isolation, and cache behavior

⏱️ Estimated read: 22 min | |

Two runs of the same suite can differ by a factor of five with no test changed. The first run happens on a fresh CI runner with an empty cache, a cold dependency graph, and a fresh environment for every file. The second happens on the developer’s laptop where the transform cache is warm, the workers are already alive, and the module graph from the previous run is still on disk. The tests are identical; the machine state is not. That gap is what the performance options exist to control.

The chapter covers the three levers that produce most of the difference. The first is the pool — the process model that decides whether a worker is a thread, a forked process, or a V8 vm context, and therefore how much each worker costs to start. The second is isolate — the option that decides whether each test file gets a fresh environment or shares one with its neighbours. The third is the cache — the on-disk transform cache, the dependency optimizer, and the invalidation rules that decide whether a rerun is warm or cold. Each section explains what the option does, what it costs, and what it breaks when set wrong.

Key point: the pool sets the cost per worker and isolate sets the cost per file; turning both down is the biggest local speedup and the biggest source of cross-file flake. The cache is the third lever and the only one that carries across runs, so a warm cache is often the difference between a three-second and a nine-second suite on an unchanged commit.


Why performance options exist

The startup-cost problem. Every worker is an execution unit that has to be created, has to load the Vite transform pipeline, has to evaluate the test file’s import graph, and has to be torn down. In a suite of three hundred files with roughly forty milliseconds of test time each, the twelve seconds of test time is routinely dwarfed by the startup cost paid once per worker plus the environment setup paid once per file. The pool and the isolation flag are exactly the two knobs that decide how much of that overhead the run pays, and they are separate knobs because they multiply: a cheap pool with expensive isolation is not much better than an expensive pool with cheap isolation.

The shared-state problem. Running each file in a fresh environment is the safe default because module-level state is real state. A singleton that increments a counter, a mocked fetch, a process.env write in a setup file — each of these persists if the environment is shared. Isolation is the guarantee that the next file starts clean, and turning it off is a promise that no file on that worker writes state another file reads. That promise is easy to make on the first day of a project and hard to keep on the four-hundredth test.

The transform-cache problem. Vitest runs on Vite, and Vite runs every TypeScript file through esbuild and caches the emitted JavaScript on disk, keyed by the file’s content hash plus the config plus the plugin versions. On a cold cache the first run of a suite pays the transform cost for every file it touches. On a warm cache the same run reads the cached output and skips the transform entirely. In watch mode the cache stays warm across runs, so the second run is frequently several times faster than the first, and that difference is cache, not test logic.

The CI-versus-local problem. A laptop has a warm cache, a persistent node_modules, and a file system that keeps the Vite cache directory between runs. A CI runner has none of those. The dashboard’s “the suite got slower this week” alert is frequently a cache miss on the runner rather than a slower test, and the fix is a cache action in the workflow, not a refactor of the tests. Measuring a performance change on a laptop and shipping it to a cold runner produces exactly the wrong conclusion.

The correctness trade-off. Every performance option in this chapter is a liability transfer. isolate: false moves the risk of cross-file leakage from the setup code to the developer’s discipline. pool: "forks" moves the risk of a native-module crash from the run’s correctness to the wall clock. --no-cache moves the risk of a stale transform from the test result to the duration. The options exist so the project can choose which risk it prefers to carry, and the choice has to be made per project rather than copied from a blog post.

The measurement problem. None of these options report their own benefit. A suite that runs in nine seconds with isolation and seven without does not print “isolation cost: two seconds” anywhere. The only way to know which of the three levers matters for a given suite is to change exactly one, run the suite on the same machine with the cache in the same state, and compare. Changing two at once produces a number that cannot be attributed.


a. The pool and its cost model

pool selects the process model that runs the tests, and in Vitest the default is forks. That default changed in Vitest 1.0 from threads, because a forked process is fully isolated from the main process and from the other workers, which eliminated a class of native-module and shared-memory crashes that the thread pool could not avoid. The cost of that isolation is startup time: a fork has to copy the process image, and a worker thread does not.

// vitest.config.ts — the default pool, made explicit
import { defineConfig } from "vitest/config";

export default defineConfig({
  test: {
    pool: "forks",     // full child_process isolation, the current default
    maxWorkers: 4,     // four forked workers running at once
    minWorkers: 1,     // keep one alive instead of respawning for every file
  },
});

The three pools differ in what they isolate and what they cost. The threads pool uses worker_threads, so the workers share the main process’s memory space and start in roughly ten to thirty milliseconds. The forks pool uses child_process, so each worker is a full Node process with its own memory, its own global object, and its own native-module table, and it costs roughly a hundred to two hundred milliseconds to start. The vmThreads pool runs inside threads but gives each test file a fresh V8 vm context, which is the most isolation and the slowest option because every context rebuilds the V8 built-ins.

// vitest.config.ts — the cheapest pool, for a suite that never touches a native module
export default defineConfig({
  test: {
    pool: "threads",   // worker_threads: fastest startup, shared process memory
    maxWorkers: 8,     // threads are cheap enough to run more of them
    minWorkers: 2,     // keep two warm between files and between watch runs
  },
});

The cost model is multiplicative and worth stating plainly: total startup cost equals the per-worker pool cost times the number of workers created. minWorkers is the option that amortises it, because a worker kept alive is a worker whose startup is paid once rather than once per file. In a one-shot vitest run the benefit is bounded by how many files each worker handles; in watch mode it is larger, because the pool survives between runs and only the changed files re-transform.

// vitest.config.ts — forks for a native module, with the count kept low
export default defineConfig({
  test: {
    pool: "forks",   // required: better-sqlite3 cannot load in a worker thread
    maxWorkers: 2,   // each fork is a full process; do not oversubscribe
    minWorkers: 2,   // pay the fork cost twice, then reuse both processes
  },
});

The vmThreads pool is the one to reach for when a test file writes a global and the test cannot be changed. Because each file gets its own vm context, a globalThis.__config = ... write in one file does not reach the next, even with isolate: false, because the context itself is per file. That is the narrow case the pool exists for, and it is not the default because it is the slowest of the three.

// vitest.config.ts — a file that leaks a global, isolated per file
export default defineConfig({
  test: {
    pool: "vmThreads", // a fresh vm context per test file
  },
});

maxWorkers is a ceiling and its default is the parallelism the operating system reports. On a CI runner that reports four cores but is throttled by a two-core quota, maxWorkers: 4 is a mistake, because the four workers contend for the same quota and the wall clock matches a two-worker run while the memory pressure does not. The useful rule is to set maxWorkers at or below the guaranteed core count of the smallest runner in the matrix, not the reported count of the biggest laptop.

fileParallelism is orthogonal and should not be confused with the pool. Setting fileParallelism: false makes the files run one at a time inside each worker, which means maxWorkers becomes nearly irrelevant because only one file is active per worker at any moment.

// The two knobs answer different questions
export default defineConfig({
  test: {
    maxWorkers: 4,          // four worker processes exist
    fileParallelism: false, // but each one runs its files sequentially
  },
});

b. Isolation and what it resets

isolate: true is the default, and it means every test file runs in a fresh environment. The module registry is cleared, the global object is rebuilt, the setup files run again for that file, vi.mock registrations from the previous file are gone, and the environment (the jsdom document, the happy-dom window) is recreated. The guarantee is that a file’s starting state does not depend on the order in which the files happened to be discovered.

// vitest.config.ts — the safe default, stated explicitly
export default defineConfig({
  test: {
    isolate: true, // fresh module registry and globals per file
  },
});

isolate: false shares the environment across every file that lands on the same worker. The setup file runs once per worker rather than once per file, the module registry persists, and the global object is the same object for each file the worker handles. The saving is the setup-and-teardown cycle, which on a suite whose setupFiles boots a database schema or registers a large mock surface is exactly where the seconds are.

// vitest.config.ts — files on a worker share the environment
export default defineConfig({
  test: {
    isolate: false, // one setup per worker, shared module graph
  },
});

The risk is concrete and it is not theoretical. A module that holds a module-level const cache = new Map() will be visible to the second file that imports it, and an assertion that expects an empty cache will fail in an order-dependent way. A vi.mock("./api") registered in one file can affect a later file because the mock registry is not reset between files on the same worker. A process.env.NODE_ENV = "test" or a globalThis.fetch = stub written in a setup file leaks into every subsequent file on that worker. None of these fail deterministically, and all of them surface as the worst kind of bug: a test that passes alone and fails in the suite.

The practical split is by test type. isolate: false belongs to pure unit tests — functions with no global writes, no singletons, no environment mutation, no spies left unrestored, and no module-level mutable state. isolate: true belongs to anything that touches a database, a DOM that persists across files, a network mock, a timer that outlives the file, or a module whose state is real. A codebase that mixes the two can scope the flag per project in a monorepo, so the unit package runs unisolated and the integration package runs isolated.

// vitest.config.ts — isolation scoped to the package that needs it
export default defineConfig({
  test: {
    projects: [
      {
        test: {
          name: "unit",
          include: ["packages/unit/**/*.test.ts"],
          isolate: false, // pure functions, no shared mutable state
        },
      },
      {
        test: {
          name: "integration",
          include: ["packages/integration/**/*.test.ts"],
          isolate: true,  // database and network state must not leak
        },
      },
    ],
  },
});

Isolation and the pool compose rather than replace each other. On forks, isolate: false still gives each worker its own process and therefore its own memory, but the files inside that process share a module graph. On threads, isolate: false shares a module graph inside a shared memory space, which is the riskiest combination and the fastest. On vmThreads, isolate: false still recreates the vm context per file, so the module graph is shared within the context but the context itself is fresh — which is why that pool is the escape hatch for a file that cannot stop writing globals.

The CLI form of the flag is --isolate=false, and the useful debugging move is to run a failing subset with isolation explicitly on to confirm the failure is a leak rather than a genuine bug.


c. The cache and the dependency optimizer

The cache is the only lever in this chapter that survives between runs. It has three layers, and they invalidate on different events. The first is Vite’s transform cache, which stores the esbuild output for every TypeScript and JSX file it has seen and lives on disk under the Vite cache directory. The second is the dependency optimizer, which pre-bundles a package’s many CommonJS files into a single ESM file so that the first import is one read instead of a hundred. The third is the in-memory cache that watch mode keeps, which is why a save in watch mode re-transforms only the changed file.

// vitest.config.ts — point the cache somewhere the CI can persist it
export default defineConfig({
  test: {
    cache: {
      dir: "./node_modules/.vite", // the directory a CI cache action restores
    },
  },
});

The transform cache is keyed on the file’s content hash plus the config plus the plugin versions, and the invalidation rules follow from that key. Editing a test file invalidates that file. Editing vite.config.ts or vitest.config.ts invalidates the entire cache, because the config is part of the key. Upgrading a Vite plugin or a dependency that ships its own plugin invalidates the cache again. Installing a new node_modules changes the optimiser output. The cache is otherwise safe to keep, and deleting it is only necessary when a stale transform is suspected.

The dependency optimizer is the option that pays for itself on a cold cache and does nothing on a warm one. It runs once at the start of a session, writes the pre-bundled output into the cache directory, and every subsequent import of that dependency reads the bundled file. Enabling it for the test run is worth it when the suite has heavy dependencies — a component library, a date library, a large utility package with many small modules — and it is the difference between a first run that spends twenty seconds in dependency resolution and one that spends two.

// vitest.config.ts — pre-bundle the dependencies once per session
export default defineConfig({
  test: {
    deps: {
      optimizer: {
        web: { enabled: true }, // browser-targeted deps pre-bundled as ESM
        ssr: { enabled: true }, // Node-targeted deps pre-bundled as ESM
      },
    },
  },
});

--no-cache disables both reading and writing the cache for a single run. It re-transforms every file the run touches, which is slow, and it is the correct tool in exactly two situations: when a test passes on a clean checkout and fails on the developer’s machine, and when a transform has been observed to produce stale output after a config change. It is not a general-purpose debugging flag, because re-running with a cold cache changes so much of the timing that any performance observation from the run is meaningless.

# Force a cold transform for one run
npx vitest run --no-cache    # re-transform every file; slow, diagnostic only

# Confirm a suspected stale transform
rm -rf node_modules/.vite && npx vitest run   # a manual cold start

The cache is not shared across machines by default, which is the single largest reason the CI suite is slower than the local one. A workflow that restores the cache directory before the run and saves it after makes the runner’s first run behave like the developer’s second run. The cache key should include the lockfile hash so that a dependency change produces a new cache rather than a stale one, and it should not include the source files, because the transform cache is content-addressed and does not need to be invalidated when a source file changes.

# .github/workflows/test.yml — restore the transform cache before the suite
- uses: actions/cache@v4
  with:
    path: node_modules/.vite          # the directory the transform cache writes to
    key: vite-${{ hashFiles('package-lock.json') }}   # a new key per lockfile

Watch mode is where the cache is most visible and least surprising. The first run pays the transform cost for the whole import graph; every subsequent run pays only for the files that changed and their dependants. That behaviour is the reason a twenty-second cold run and a two-second warm save can be the same command, and it is the behaviour a CI cache action is trying to reproduce for the one-shot case.


Complete Example Session

// ============================================
// PART 1: THE DEFAULT, FOR REFERENCE
// ============================================
import { defineConfig } from "vitest/config";

export default defineConfig({
  test: {
    pool: "forks",   // the default pool since Vitest 1.0
    isolate: true,   // the default isolation
  },
});

// ============================================
// PART 2: THE NATIVE-MODULE SUITE
// ============================================
export default defineConfig({
  test: {
    pool: "forks",   // better-sqlite3 cannot load inside a worker thread
    maxWorkers: 2,   // each fork is a full process; keep the count low
    minWorkers: 2,   // reuse the two processes instead of respawning
  },
});

// ============================================
// PART 3: THE PURE-UNIT SUITE
// ============================================
export default defineConfig({
  test: {
    pool: "threads", // fastest startup; no native modules here
    maxWorkers: 8,   // threads are cheap enough to run more of them
    minWorkers: 2,   // keep two warm between files and between runs
  },
});

// ============================================
// PART 4: THE CEILING THAT MATCHES THE RUNNER
// ============================================
export default defineConfig({
  test: {
    maxWorkers: Number(process.env.CI_MAX_WORKERS) || 4, // never exceed the quota
  },
});

// ============================================
// PART 5: ISOLATION ON FOR THE INTEGRATION PACKAGE
// ============================================
export default defineConfig({
  test: {
    isolate: true, // a fresh module registry and globals per file
  },
});

// ============================================
// PART 6: ISOLATION OFF FOR THE UNIT PACKAGE
// ============================================
export default defineConfig({
  test: {
    isolate: false, // one setup per worker, shared module graph
  },
});

// ============================================
// PART 7: THE DEPENDENCY OPTIMIZER
// ============================================
export default defineConfig({
  test: {
    deps: {
      optimizer: {
        web: { enabled: true }, // browser-targeted deps bundled once per session
        ssr: { enabled: true }, // Node-targeted deps bundled once per session
      },
    },
  },
});

// ============================================
// PART 8: THE CACHE DIRECTORY
// ============================================
export default defineConfig({
  test: {
    cache: {
      dir: "./node_modules/.vite", // where the CI cache action looks
    },
  },
});

// ============================================
// PART 9: THE COLD-START DIAGNOSTIC
// ============================================
# Run with the cache disabled to reproduce a clean-checkout result
npx vitest run --no-cache

# Run with the cheapest pool and no isolation, for a timing baseline
npx vitest run --pool=threads --isolate=false
// ============================================
// PART 10: THE FULL CONFIGURATION
// ============================================
export default defineConfig({
  test: {
    pool: "forks",          // the default; each worker is a full process
    maxWorkers: 4,          // at or below the smallest runner's core count
    minWorkers: 2,          // two warm workers, reused across files
    isolate: true,          // the safe default; scope it off per project
    deps: {
      optimizer: {
        web: { enabled: true }, // pre-bundle once, read many times
      },
    },
    cache: {
      dir: "./node_modules/.vite", // the directory the CI restores
    },
  },
});

The ten parts covered the default configuration, the native-module suite that needs forks, the pure-unit suite that benefits from threads, a worker ceiling that follows the runner’s quota, isolation left on for integration tests, isolation turned off for unit tests, the dependency optimizer, the cache directory, the cold-start diagnostic, and the full file with all three levers set.


Quick Reference

The Three Pools

PoolModelStartupUse When
forkschild_process~100–200msDefault; native modules
threadsworker_threads~10–30msPure unit tests
vmThreadsvm context per fileHighestA file leaks globals

Isolation

SettingEffectRisk
isolate: trueFresh env per fileSetup cost per file
isolate: falseShared env per workerState leaks across files
--isolate=falseCLI form of the sameSame leak, easier to test

Cache Layers

LayerLocationInvalidated By
Transformcache.dirFile content, config, plugin version
Optimizercache.dirLockfile change, new dependency
In-memoryProcess onlyProcess exit, watch restart

Worker Knobs

OptionDefaultControls
maxWorkersavailableParallelism()Workers created
minWorkers0Workers kept warm
fileParallelismtrueFiles overlap inside a worker

Best Practices

✅ Do This:

// Set maxWorkers to the smallest runner's core count
maxWorkers: 4                                                  // ✅

// Keep workers alive so the startup is paid once
minWorkers: 2                                                  // ✅

// Use threads for a pure-function package
pool: "threads"                                                // ✅

// Use forks for anything with a native module
pool: "forks" // better-sqlite3, sharp, canvas                    // ✅

// Scope isolation off per project, not globally
projects: [{ test: { isolate: false } }]                       // ✅

// Enable the optimizer for heavy dependencies
deps: { optimizer: { web: { enabled: true } } }                // ✅

// Restore the transform cache in CI
// path: node_modules/.vite                                    // ✅

// Measure one lever at a time, same machine, same cache
// --no-cache before, --no-cache after                          // ✅

❌ Don’t Do This:

// Turn isolation off globally to save a few seconds
isolate: false                                                 // ❌

// Set maxWorkers above the runner's quota
maxWorkers: 16 // on a four-core quota                          // ❌

// Use threads with a native module
pool: "threads" // better-sqlite3 will fail to load             // ❌

// Use --no-cache as a permanent setting
// vitest run --no-cache in the CI script                       // ❌

// Benchmark a change on a cold cache and ship it
// (the number is transform time, not test time)               // ❌

// Leave fileParallelism true and expect maxWorkers: 1 to help
maxWorkers: 1 // files still queue behind one worker            // ❌

// Share a module-level singleton with isolate: false
// const cache = new Map() across two test files               // ❌

Common Pitfalls

PitfallWhy It HappensFix
Order-dependent failuresisolate: false with shared module stateRun that project isolated
Native module fails to loadpool: "threads" with a .node addonSwitch to forks
Slower after raising workersmaxWorkers above the CPU quotaLower it to the core count
First CI run is slowTransform cache is coldactions/cache on the cache dir
Stale transform after config changeOld cache key still matchesDelete the cache dir, rerun
Watch mode is fast, CI is notIn-memory cache does not persistPersist the on-disk cache
globalThis write leaksisolate: false on threadsUse vmThreads or isolate on
Optimizer has no effectCache already warmMeasure on a cold cache

Real-World Examples

1. The default pool

pool: "forks"; // full child_process isolation

2. The cheap pool

pool: "threads"; // worker_threads, fastest startup

3. The vm escape hatch

pool: "vmThreads"; // a fresh vm context per test file

4. The worker ceiling

maxWorkers: 4; // never above the runner's quota

5. The warm pool

minWorkers: 2; // pay startup once, reuse the workers

6. Isolation off

isolate: false; // shared module graph per worker

7. Isolation per package

projects: [{ test: { name: "unit", isolate: false } }];

8. The optimizer

deps: { optimizer: { web: { enabled: true } } };

9. The cache directory

cache: { dir: "./node_modules/.vite" };

10. The cold run

npx vitest run --no-cache   # reproduce a clean checkout

Visual

The Pool Cost Model

┌───────────────────────────────────────────────────────────┐
│  POOL         MODEL              STARTUP     ISOLATION    │
│  forks        child_process      ~100-200ms  full process │
│  threads      worker_threads     ~10-30ms    shared mem   │
│  vmThreads    vm context/file    highest     per file     │
│                                                           │
│  total startup = pool cost × number of workers            │
│  minWorkers keeps them alive, so it is paid once          │
└───────────────────────────────────────────────────────────┘

Isolation On and Off

┌───────────────────────────────────────────────────────────┐
│  isolate: true (default)                                  │
│    file A ──► fresh env A ──► teardown                    │
│    file B ──► fresh env B ──► teardown                    │
│                                                           │
│  isolate: false                                           │
│    file A ──► shared env ──┐                              │
│    file B ──► shared env ──┼── one setup per worker       │
│    file C ──► shared env ──┘                              │
│                                                           │
│  trade: setup time for state leakage across files         │
└───────────────────────────────────────────────────────────┘

The Transform Cache Path

┌───────────────────────────────────────────────────────────┐
│  file.ts ──► content hash ──► cache key                   │
│                                   │                       │
│                     hit ◄─────────┴──────► miss           │
│                      │                       │            │
│                      ▼                       ▼            │
│              read cached JS            esbuild transform  │
│                      │                       │            │
│                      └───────────┬───────────┘            │
│                                  ▼                        │
│                          write to cache.dir               │
└───────────────────────────────────────────────────────────┘

What the Cache Survives

┌───────────────────────────────────────────────────────────┐
│  PERSISTS ON DISK                DIES WITH THE PROCESS    │
│  transform output                module registry          │
│  optimizer bundles               vi.mock registrations    │
│  watch-mode artifacts            globalThis writes        │
│                                                           │
│  INVALIDATED BY                                           │
│    config change, lockfile change, plugin upgrade,        │
│    --no-cache, manual cache-dir deletion                  │
└───────────────────────────────────────────────────────────┘

Summary

ItemValue
Default poolforks
Cheapest poolthreads
Most isolated poolvmThreads
Default isolationtrue
Worker ceilingmaxWorkers
Warm workersminWorkers
Setup cost driverisolate
Startup cost driverpool × workers
Cross-run leverTransform cache
Cache disable flag--no-cache
Pre-bundle toggledeps.optimizer
CI cache pathnode_modules/.vite

Key takeaways:

  • The pool sets the cost per worker. forks costs a hundred to two hundred milliseconds per worker and buys full process isolation; threads costs a tenth of that and shares the process memory. The default is forks because the isolation is worth the startup.
  • isolate sets the cost per file. With isolation on, the setup file runs again for every file. With it off, the setup runs once per worker and the module graph is shared, which is faster and is where cross-file leaks come from.
  • The two multiply. A cheap pool with expensive isolation is not much faster than an expensive pool with cheap isolation. Measure them separately, because the total is the product.
  • minWorkers amortises the pool. A worker kept alive pays its startup once rather than once per file, and the effect is larger in watch mode than in a one-shot run.
  • The transform cache is the only cross-run lever. It lives on disk, is keyed on content plus config plus plugin versions, and makes the second run of a suite several times faster than the first.
  • The optimizer pays on a cold cache and not on a warm one. Pre-bundling a dependency turns a hundred file reads into one, which matters exactly when there is no cached bundle to read.
  • --no-cache is a diagnostic, not a setting. It re-transforms everything, and any timing observed from that run describes transform cost rather than test cost.
  • CI speed is a cache problem, not a test problem. A runner with a restored transform cache behaves like a laptop’s second run; a runner without one pays for the whole import graph on every job.

Remember: three levers control the wall clock, and each one trades a kind of safety for a kind of speed. The pool decides how expensive a worker is to start and how isolated it is from its neighbours. isolate decides how expensive a file is to set up and how isolated it is from the file before it. The cache decides how much of the previous run can be reused, and it is the only lever that survives a process exit. Set the pool to the cheapest model the suite can tolerate, set isolation to the strictest setting the tests can pass under, and keep the cache warm everywhere the suite runs.

Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!