Skip to content

Consolidate per-request ALS scopes for reduced overhead on Workers #451

@Divkix

Description

@Divkix

Problem

Every App Router request in vinext runs through 5-6 nested AsyncLocalStorage.run() calls, each from a different shim module:

  1. runWithHeadersContext (headers.ts)
  2. runWithNavigationContext (navigation-state.ts)
  3. _runWithCacheState (cache.ts)
  4. runWithPrivateCache (cache-runtime.ts)
  5. runWithFetchCache (fetch-cache.ts)
  6. runWithExecutionContext (request-context.ts) — conditional, Workers only

Each ALS scope push/pop has measurable cost on Workers isolates. For simple static routes that don't use headers, cookies, or caching, all contexts are created unnecessarily.

Solution

Consolidate into a single UnifiedRequestContext backed by one ALS instance. Each shim module checks isInsideUnifiedScope() first and reads its sub-fields from the unified store, falling back to its own standalone ALS for backward compatibility (SSR environment, Pages Router).

Scope

Phase 1 (this issue)

  • App Router only — main request handler + ISR background regeneration
  • Dual-path migration: unified scope first, standalone ALS fallback
  • No changes to per-call ALS scopes (cacheContextStorage, _unstableCacheAls)

Phase 2 (follow-up)

  • Pages Router consolidation (router-state, head-state)
  • Production server (prod-server.ts) alignment

Related

Metadata

Metadata

Assignees

No one assigned

    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