Introducing a new way to review your PRs.

Read the announcement

shakacode / react_on_rails

Integration of React + Webpack + Rails including server-side rendering of React, enabling a better developer experience and faster client performance.

View on GitHub

19 documents · Updated Nov 18, 2026

docs / renderer-cache-and-rolling-deploys

Renderer cache and rolling deploys

Renderer cache preparation gives each Node Renderer the bundle files and companion manifests that it needs before it receives render traffic. The same cache contract supports current and draining Rails releases, so a rolling deploy can keep serving old requests without repeated 410 Gone responses and bundle uploads.

For the larger rendering model, see Pro rendering platform. The renderer process is described in Node renderer processes, and related request behavior is covered in async props and streaming SSR. License and telemetry concerns are covered in Pro licensing and observability.

System purpose

The cache system connects a Rails build to the Node Renderer runtime. It prepares a complete renderer artifact, gives it a stable cache identity, places it in the path the renderer reads, and keeps the active and draining release artifacts available during deployment.

The main design goals are:

  • Avoid a cold renderer lookup for the current release.
  • Keep a bundle paired with the manifests produced by the same build.
  • Let a new renderer serve requests from an older Rails release while that release drains.
  • Make cache replacement safe when several build or release processes act on one filesystem.
  • Allow cache invalidation by application data tags without confusing data-cache invalidation with renderer-bundle invalidation.

The high-level relationship between build output, cache preparation, and a rolling release is:

flowchart LR
  A[Built bundle and manifests] --> B[Artifact identity]
  B --> C[Renderer cache]
  D[Previous release] --> E[Rolling-deploy adapter]
  E --> C
  C --> F[New renderer instances]
  G[New Rails release] --> F
  H[Draining Rails release] --> F

Renderer artifacts

A renderer artifact is one bundle plus the companion files that must be read with that bundle. The artifact is the unit used for identity, staging, publication, and rolling-deploy retrieval.

Artifact identity

The artifact ID is a content-based identity for the bundle role and all runtime-visible companion bytes. The server bundle and the RSC bundle have separate roles. When RSC is enabled, both roles must be available to the renderer as separate cache entries.

Changing a manifest or other companion file changes the artifact ID. This prevents a renderer from pairing an old bundle with a new manifest and makes rendered-result cache keys change when the code that can affect the result changes.

At runtime, the RSC cache identity comes from the explicit Rails-provided ID when present, or from the renderer-injected bundle identity when no explicit ID is set. If both values exist and differ, the system warns in every environment because different workers could derive different cache keys. If neither value exists, a cache operation fails instead of creating an unscoped entry.

The main companion files are:

References: react_on_rails_pro/…/renderer_artifact.rb• L21-65 react_on_rails_pro/…/renderer_artifact.rb• L130-143 react_on_rails_pro/…/renderer_artifact_support.rb• L31-65 packages/…/buildIdProvider.ts• L22-81

Cache path

The renderer reads each artifact from a directory named by its ID. The stable on-disk contract is <cache>/…/<artifact-id>.js, with companion files in that same directory. The preferred cache-path setting is RENDERER_SERVER_BUNDLE_CACHE_PATH; the default is .node-renderer-bundles when no path is set. RENDERER_BUNDLE_PATH remains a legacy fallback.

The cache path must be the same path seen by the process that stages the files and by the Node Renderer. In production-like copy mode, set the path explicitly because the Ruby build process and the standalone Node process can have different working directories.

References: react_on_rails_pro/…/renderer_cache_path.rb• L18-46 react_on_rails_pro/…/pre_seed_renderer_cache.rb• L152-177 react_on_rails_pro/…/pre_seed_renderer_cache.rb• L268-305

Staging modes

Pre-seeding supports two deployment shapes. Both create the renderer-facing layout above, but they differ in where the bytes live:

ModeDeployment shapeCache behavior
copyDocker or another immutable image buildCopies complete artifact files into the image or target cache.
symlinkShared-filesystem or same-host deploymentLinks renderer-facing files to immutable per-artifact snapshots on the same filesystem.

The current artifact is built in a temporary directory and promoted as a complete directory. This means the renderer sees a prior complete artifact or a cache miss. It does not see a bundle with only some of its manifests. A failed current-artifact stage is a deployment failure because the new renderer must not start with an assumed complete cache.

References: react_on_rails_pro/…/pre_seed_renderer_cache.rb• L66-87 react_on_rails_pro/…/pre_seed_renderer_cache.rb• L178-197 react_on_rails_pro/…/pre_seed_renderer_cache.rb• L200-234

Rendered-result cache identity

Renderer artifact identity and rendered-result cache identity solve related but different problems. Artifact IDs identify the code and manifests used by the renderer. Rendered-result keys identify cached HTML or RSC output for application requests.

Bundle-aware cache keys

Pre-rendered component cache keys include the server artifact ID. When RSC is enabled, they also include the RSC artifact ID. A new build therefore reads as a new rendered-result version even when the application-level cache key is unchanged.

The Node-side unstable_cache path applies the same build boundary to cached RSC output. It combines the build identity with the cached function ID and a stable encoding of the function arguments. This keeps values from different builds or different inputs in separate entries, while equivalent object inputs produce the same key.

The cache also keeps output rendered with an active CSP nonce separate from output rendered without one. The key stores the nonce state rather than the nonce value, so requests can share safe entries without making each nonce create a new entry.

Non-prerendered output does not include bundle IDs because the server or RSC bundle did not produce that output. Application dependency digests can add another version when the application config enables dependency globs.

References: react_on_rails_pro/…/cache.rb• L146-207 react_on_rails_pro/…/cache.rb• L211-215 react_on_rails_pro/…/utils.rb• L97-110 packages/…/buildCacheKey.ts• L22-108 packages/…/unstable_cache.ts• L57-72

Rendered-result cache stores

The rendered-result cache uses a small handler contract for reading and writing a value with its expiry data. The default store is a bounded in-memory LRU cache, while Redis provides a shared store for workers that need a common cache. A tiered store can combine a fast local layer with a shared layer.

The tiered path preserves the shared entry's remaining lifetime when it promotes a value into the local layer. A local lifetime cap limits how long one worker can serve a value after another worker updates the shared layer. A non-positive cap disables the local layer rather than creating entries that never expire.

Cache handlers are selected by a named registry. Applications can register a custom handler when the built-in local or Redis choices do not match their storage needs. Handler failures degrade reads to misses and skip failed writes where the backend supports that behavior; they do not change the renderer artifact cache.

References: packages/…/CacheHandler.ts• L16-25 packages/…/InMemoryLRUCacheHandler.ts• L19-61 packages/…/RedisCacheHandler.ts• L61-125 packages/…/TieredCacheHandler.ts• L18-94 packages/…/cacheHandlerRegistry.ts• L19-35

RSC result population

On a rendered-result miss, unstable_cache runs the source function and stores the completed RSC stream for later replay. Concurrent requests for the same key share one in-progress render within a worker, so a burst does not create duplicate work. A render with an error is returned to the caller but is not stored as a successful cache entry.

The RSC renderer is built from the client and server manifests when the first cached result needs it. A failed renderer load can be retried, which keeps one transient manifest or module-load failure from permanently poisoning the worker's renderer promise.

References: packages/…/unstable_cache.ts• L52-154 packages/…/manifestLoader.ts• L22-59 packages/…/manifestLoaderServer.ts• L31-57

Cache tags and revalidation

Cache tags provide a data-based invalidation path for cached React output. A cached component can declare cache_tags; after a successful cache write, the system records the rendered-result key under each normalized tag. ReactOnRailsPro.revalidate_tag and ReactOnRailsPro.revalidate_tags then remove the recorded entries.

Tags can be strings, symbols, numbers, procs, arrays, or objects with a stable cache_key, such as a persisted Active Record record. The Revalidates concern connects model after_commit events to this path, so committed model changes can invalidate the output that depends on them. Revalidation ignores blank or unpersisted tags at its boundary, which keeps an incomplete record from targeting a cache entry.

Tag indexing is best effort. Concurrent index updates can lose an index entry, and the index can be evicted. Give tagged entries an expires_in or supported expires_at so a missed invalidation has a bounded lifetime. Callback-skipping writes such as bulk updates need an explicit revalidation call. The cache layer also converts expiration settings when the cache store does not support expires_at, so an expired write does not become an unbounded entry.

References: react_on_rails_pro/…/react_on_rails_pro_helper.rb• L55-83 react_on_rails_pro/…/cache.rb• L27-132 react_on_rails_pro/…/tag_index.rb• L21-40 react_on_rails_pro/…/revalidates.rb• L20-40

Pre-seeding flow

Pre-seeding runs after bundles are built and before the renderer revision is expected to serve traffic. It stages the current artifact first, then asks the rolling-deploy adapter for older artifacts that may still be referenced by draining Rails instances.

Current artifact preparation

The build resolves the complete current artifact set from the configured bundle paths and companion assets. RSC support adds a server artifact and an RSC artifact. Required RSC manifests must exist as local files or be materialized before publication; optional missing assets are skipped with a warning.

assets:precompile invokes pre-seeding for Node Renderer deployments. The explicit MODE choice controls whether the result is copied into an immutable image or linked to same-filesystem snapshots. The older PrepareNodeRenderBundles entry point remains a compatibility shim for the symlink mode.

References: react_on_rails_pro/…/renderer_artifact_support.rb• L31-65 react_on_rails_pro/…/renderer_cache_helpers.rb• L34-53 react_on_rails_pro/…/assets_precompile.rb• L75-93 react_on_rails_pro/…/prepare_node_renderer_bundles.rb• L18-35

Previous artifact preparation

After current staging, the rolling-deploy stager discovers previous artifact IDs and fetches each bundle with its companion assets. It removes current IDs from the previous set because those files are already staged. Missing or failed previous artifacts produce warnings and leave the runtime 410 recovery path available.

Previous entries are replaced as complete directories. The stager validates cache-key shapes before using them as directory names and bounds discovery and fetch time. It also cleans abandoned temporary directories on later runs. These safeguards keep a bad adapter response or an interrupted seed from turning into a partial cache entry.

References: react_on_rails_pro/…/rolling_deploy_cache_stager.rb• L22-45 react_on_rails_pro/…/rolling_deploy_cache_stager.rb• L79-97 react_on_rails_pro/…/rolling_deploy_cache_stager.rb• L128-186 react_on_rails_pro/…/rolling_deploy_cache_stager.rb• L501-555

Rolling-deploy adapters

A rolling-deploy adapter supplies the artifact history needed to bridge two Rails revisions. The current revision publishes its artifacts for a future deploy. The next revision discovers and retrieves artifacts that are still in use by the old revision.

Built-in HTTP adapter

The built-in adapter uses the still-running Rails deployment as the artifact source. The previous deployment exposes an authenticated manifest endpoint and bundle endpoint. Build or release-time seeding reads the advertised IDs and downloads the matching bundle plus companions.

Configure the adapter with rolling_deploy_adapter, a shared bearer token, and one or more previous deployment URLs. The adapter normalizes those URLs against the configured mount path, accepts explicit endpoint paths, removes duplicates, and skips unsafe or unsupported URL forms. Use HTTPS for non-loopback production traffic because the token is a bearer credential; HTTPS requests use peer certificate verification.

The adapter tracks which origin advertised each artifact. It omits a legacy hash when more than one origin advertises it because the payload source is ambiguous. Versioned artifact IDs can use multiple origins because the downloaded bytes are checked against the expected identity before the first acceptable payload is used. The adapter rejects invalid hash shapes and continues to another configured origin after a failed or mismatched fetch.

Bundle responses stream into a temporary file before extraction. The adapter limits both the compressed response body and the extracted payload, and it applies an operation-wide time limit to discovery, download, and extraction. Failed or oversized responses are cleaned up and reported as warnings.

The adapter's upload operation is intentionally empty. The running Rails deployment already owns the files that the next deployment must read. Multiple previous URLs allow a promoted image to retain a useful build-time fallback from more than one environment.

References: react_on_rails_pro/…/http.rb• L31-75 react_on_rails_pro/…/http.rb• L86-137 react_on_rails_pro/…/http.rb• L141-273 react_on_rails_pro/…/http.rb• L283-345 react_on_rails_pro/…/http.rb• L374-545 react_on_rails_pro/…/http_spec.rb• L27-164 react_on_rails_pro/…/http_spec.rb• L184-207 react_on_rails_pro/…/http_spec.rb• L360-456

Custom adapter support

Use a custom adapter when build systems cannot reach the prior deployment or when artifacts must live in a store independent of a running app. The adapter protocol has three responsibilities:

ResponsibilityContract
Discoveryprevious_bundle_hashes returns recent opaque artifact IDs.
Retrievalfetch(hash) returns a local bundle path and all companion asset paths, or nil when unavailable.
Publicationupload(hash, bundle:, assets:) stores one artifact for a future deploy.

An adapter must treat each server or RSC ID as an independent cache entry. With RSC enabled, publication occurs for both roles, and each entry must retain the complete companion set. S3, image-layer, and filesystem patterns are useful examples, but the storage system remains the adapter's responsibility.

References: react_on_rails_pro/…/rolling_deploy_cache_stager.rb• L28-40 docs/…/rolling-deploy-custom-adapters.md• L33-96 docs/…/rolling-deploy-custom-adapters.md• L108-117

Release-time staging

Build-time pre-seeding is sufficient when the image is built and deployed in the same environment. It is not sufficient for image promotion because the build cannot know which production artifact will be draining when a later promotion occurs.

Boot seed

For promoted images, run bundle exec rake react_on_rails_pro:pre_seed_renderer_cache in a Ruby-capable release, init, or startup step. Run it against the promoted app artifact and the target environment's production configuration while the old deployment still serves traffic. That timing lets the seed discover the exact draining artifact.

The seed step and a Node-only renderer must share the writable renderer cache path, or the completed cache must be copied into the renderer before startup. Gate renderer startup and readiness on the step completing. Gate on completion rather than success so a failed historical fetch falls back to runtime recovery instead of wedging the release.

Keep build-time multi-source seeding as a fallback floor. It improves warmth when the boot seed cannot reach the live endpoint, but it cannot replace the release-time lookup for the target environment.

References: react_on_rails_pro/…/0001-boot-seed-rolling-deploy-bundles.md• L5-20 react_on_rails_pro/…/0001-boot-seed-rolling-deploy-bundles.md• L22-49 docs/…/rolling-deploy-adapters.md• L141-172

Workload order

When Rails and the Node Renderer are separate workloads, deploy the new renderer before the new Rails revision accepts traffic. The new renderer must have the current and required draining artifacts available before new Rails sends it requests.

Use readiness state instead of a fixed sleep. The required sequence is:

  1. Stage or boot-seed the renderer cache.
  2. Start the new renderer revision.
  3. Wait for all new renderer instances to report ready.
  4. Promote the new Rails revision.

If Rails moves first, requests for the new bundle can reach renderers that have not loaded it. Those requests use the 410 upload-and-retry path and can create a deployment latency spike.

References: docs/…/rolling-deploy-adapters.md• L208-235 react_on_rails_pro/…/0001-boot-seed-rolling-deploy-bundles.md• L37-49

Current generation startup

The current-generation declaration tells a renderer worker which current artifact roles must be ready before it listens. It is separate from the cache directory contents, which may also contain draining artifacts for old Rails requests.

Generation declaration

Pre-seeding writes a content-addressed declaration for the current server artifact and optional RSC artifact under .current-generations in the renderer cache. Configure the new renderer revision with the exact declaration path through RENDERER_CURRENT_GENERATION_MANIFEST.

The Node Renderer validates the declaration and the artifact roots before compiling the declared set. A configured worker does not listen until this prewarm completes. The declaration must be immutable and must point to the expected cache or artifact-snapshot roots; a shared mutable current link would let old and new revisions race during a rollout.

References: react_on_rails_pro/…/pre_seed_renderer_cache.rb• L117-147 packages/…/currentGenerationManifest.ts• L220-302 packages/…/startCurrentGeneration.ts• L32-55

Pool capacity

The renderer must hold the declared current contexts and the contexts for draining generations during the overlap. SSR needs one context per generation. RSC needs two contexts per generation because it has server and RSC roles.

Size the worker pool for the number of overlapping generations and roles. If the pool is too small, the renderer can evict a context and rebuild it during traffic even though the files were pre-seeded. The built-in readiness signal covers the declared current set; end-to-end Rails smoke requests still help verify the full service path.

References: docs/…/rolling-deploy-adapters.md• L174-206 packages/…/vm.ts• L409-427

Change checklist

When these files or sections are changed, remember to consider these:

  • Keep the Ruby artifact ID rules aligned with the Node Renderer's accepted artifact IDs and current-generation declaration rules.
  • Keep explicit Rails build IDs aligned with the VM-injected bundle identity so all workers derive the same cache keys.
  • Keep the cache directory layout aligned with both the Rails staging path and the Node Renderer lookup path.
  • Keep CacheEntry expiry and timestamp meaning consistent across in-memory, Redis, tiered, and custom handlers.
  • Keep cache-handler failure behavior bounded to a cache miss or skipped write so a backend outage does not become a renderer outage.
  • Keep the build ID, cached function ID, and stable argument encoding aligned wherever unstable_cache keys are produced or consumed.
  • Keep manifest loading retryable and keep both client and server manifest inputs available before building an RSC renderer.
  • When adding a companion asset, include it in current staging, adapter publication, adapter retrieval, and artifact identity calculation.
  • When changing RSC roles, update the adapter's two-hash publication and retrieval contract and the renderer pool sizing guidance.
  • When changing the HTTP adapter contract, keep URL normalization, manifest provenance, payload identity checks, size limits, and time limits consistent with the running endpoint and the cache stager.
  • When changing release topology, re-check boot-seed timing, shared-volume access, renderer readiness, and Rails cutover order.
  • When changing tag registration or cache-key construction, preserve the expiry bound that limits missed tag-index updates and keep CSP nonce states in separate cache partitions.

Important failure modes

TriggerConsequenceGuard
Stager and renderer resolve different cache pathsPre-seeded files are not found and requests use the cold 410 pathSet RENDERER_SERVER_BUNDLE_CACHE_PATH explicitly for production-like image builds and share it with the renderer.
Bundle is staged without its matching manifestsChunk URLs or client hydration can fail for that releaseTreat the bundle and companion assets as one artifact ID and stage them together.
Explicit Rails build ID differs from the VM-injected bundle identityWorkers can derive different cache keys and cause a cache hit-rate dropKeep both identity sources aligned and treat the mismatch warning as a build or deploy defect.
No build identity is available for an unstable_cache callThe call cannot create a safe cross-worker keySet the Rails build ID or run the call in a renderer context that supplies the bundle identity.
A cache handler kind is not registeredThe cached render fails before it can read or write a resultRegister the handler before rendering or use the default kind.
Redis is unavailable or an entry exceeds its size limitShared rendered-result reads miss and writes are skippedTreat Redis as an optimization and use a suitable entry limit or another handler.
A tiered L1 promotes an aged entry with its original lifetimeOne worker can serve a result after the L2 entry should expirePreserve the remaining lifetime and apply a finite L1 cap.
A cached function receives an unsupported or circular argumentKey creation fails instead of producing a collision-prone entryUse supported stable values and plain data objects as cache arguments.
A manifest cannot be loaded while the RSC renderer is being builtThe first cached RSC render fails until the manifest or module is availableKeep manifest paths valid and allow the failed renderer load to reset for retry.
Previous adapter payload is missing, invalid, oversized, or does not match its versioned IDThat old hash is not warm on the new rendererValidate the payload, try another known origin when available, and retain runtime 410 recovery.
Multiple origins advertise the same legacy hashThe adapter cannot prove which payload belongs to that hashOmit the ambiguous legacy hash rather than select an unverified source.
Boot seed runs after Rails cutoverIt discovers the new hash instead of the draining hashRun the seed while old Rails still serves traffic and before renderer readiness.
Renderer pool is smaller than the overlapping role setContext eviction causes repeated compile work during rolloutSize maxVMPoolSize for old and new generations, including both RSC roles.
Tagged cache entry has no expiryA lost tag-index update can leave stale output longer than expectedSet expires_in or a supported expires_at on tagged entries.
One cache key is shared by nonce and nonce-free outputMarkup can carry the wrong CSP nonce behavior after a nonce setting changeKeep the CSP nonce state as a fixed cache-key partition before caller-controlled key values.

Key files

FileWhy to read it
react_on_rails_pro/…/renderer_artifact.rbDefines the unit of bundle-plus-companion identity.
react_on_rails_pro/…/renderer_cache_path.rbExplains cache-path precedence and the production path setting.
react_on_rails_pro/…/pre_seed_renderer_cache.rbShows current artifact staging, copy versus symlink modes, and generation declarations.
react_on_rails_pro/…/rolling_deploy_cache_stager.rbShows discovery, retrieval, validation, and replacement of previous artifacts.
react_on_rails_pro/…/http.rbDescribes the built-in authenticated HTTP artifact source and its safety checks.
react_on_rails_pro/…/http_spec.rbDescribes the HTTP adapter's URL, provenance, payload, security, and timeout guarantees.
docs/…/rolling-deploy-custom-adapters.mdDefines the custom adapter contract and storage patterns.
react_on_rails_pro/…/cache.rbConnects bundle-aware and CSP-aware rendered-result keys with cache options and tag revalidation.
packages/…/unstable_cache.tsConnects cache-key creation, single-flight rendering, result storage, and RSC replay.
packages/…/buildCacheKey.tsDefines the stable boundary between build identity, function identity, and cached arguments.
packages/…/CacheHandler.tsDefines the shared result-cache contract used by local, Redis, tiered, and custom stores.
packages/…/TieredCacheHandler.tsExplains shared-store promotion and the lifetime bound for local entries.
packages/…/buildIdProvider.tsDefines the explicit and renderer-injected sources for the RSC cache build identity.
packages/…/manifestLoader.tsShows how the client manifest builds the RSC client renderer and recovers after a failed load.
packages/…/manifestLoaderServer.tsShows how the server renderer uses the client manifest without entering non-RSC graphs.
react_on_rails_pro/…/tag_index.rbExplains tag registration, expiry, and best-effort revalidation.
packages/…/currentGenerationManifest.tsShows how the renderer validates and resolves the current generation.
packages/…/startCurrentGeneration.tsShows the startup barrier before the renderer begins listening.