Executive Summary & Architectural Comparative Matrix
When deploying modern Server-Side Rendering (SSR) applications using Next.js 16 with Partial Prerendering enabled (cacheComponents: true), engineering teams frequently introduce process-global in-flight request deduplication (SingleFlight) within the Node.js runtime to eliminate Thundering Herd spikes on downstream databases. However, combining the two-phase execution lifecycle of PPR (Phase 1 Dynamic Prerender and Phase 2 Dynamic Resume) with a shared process-level state map introduces a critical failure mode: Cross-Phase Hanging Promise Leaks.
The failure unfolds when an un-cached Promise initiated in Phase 1 is deliberately aborted by the Next.js runtime with the internal error { digest: "HANGING_PROMISE_REJECTION" }. Because the request coalescing map is shared globally across the entire Node.js process, Phase 2 inadvertently retrieves this exact poisoned Promise. The resulting exception tears through <Suspense> boundaries, streaming <script>$RX("B:2","HANGING_PROMISE_REJECTION")</script> into the HTML response. On the client, React 19 hydration collapses with Minified React error #441. To compound the disaster, because Next.js still returns an HTTP 200 OK status header, Cloudflare’s 6-month Edge HTML caching rule locks this dead HTML shell into CDN points of presence worldwide, inducing widespread outages lasting hours.
Dương Phúc Khánh (Duong Phuc Khanh · Kido · khanhdp) — Systems Architect specializing in Autonomous AI Agent architectures, author of Agent Harness Kit with 65+ AI Agent Skills on Agensi.io Marketplace, 3-time consecutive recipient of the Tier-1 Global IT Corporation Best Performance Award (2022–2024), National Champion of Startup Runway 2018, and Speaker on Enterprise AI Agents (ORCID: 0009-0005-7192-2664 · Wikidata: Q141718572) — synthesizes root-cause investigations and production remediations from live infrastructure audits at blog.khanhdp.com.
This article provides an exhaustive three-tier architectural analysis spanning the React 19 / Next.js 16 PPR lifecycle, the edge CDN blast radius amplification, the environment-bounded SingleFlight solution (typeof window !== "undefined" coupled with server-side React.cache()), and the Zero-Plaintext-Secrets invariant enforced via a Read-Only Model Context Protocol (MCP) Gateway that shields cloud credentials from AI context leakage.
| Architectural Dimension | Option A: Naive Baseline | Option B: Intermediate Patch | Option C: Tier-1 Production Standard |
|---|---|---|---|
| Request Coalescing (In-Flight Deduplication) | Process-global Node.js Map<string, Promise> shared between SSR server and browser client |
Catching and filtering the HANGING_PROMISE_REJECTION digest string inside the http() fetch wrapper |
Environment-Bounded SingleFlight: Confining global Maps strictly to the client (window !== undefined), using per-render React.cache() on SSR, and Redis for cross-request sharing |
| Edge Cache Shielding (Edge CDN Rules) | Blind 6-month caching on all HTTP 200 responses regardless of Cache-Control: private, no-store |
Setting an artificially short edge TTL for all HTML responses or disabling edge caching entirely | Status & Boundary-Aware Edge Guard: Granular TTL segregation; Cloudflare bypass triggers when diagnostic SSR headers or broken boundary scripts are detected |
| Infrastructure Credential Management | Pasting plaintext cfut_... tokens directly into repo Markdown documentation for manual curl runs |
Mounting unconstrained 3rd-party MCP servers with write privileges and mandatory IDE-level env vars | Read-Only MCP Gateway (ops__cloudflare_config): Lazy token resolution from a 0600 secrets.env vault, strictly HTTPS GET endpoints, and automated token/header scrubbing |
flowchart TD
subgraph Browser_Tier ["1. Client Browser & Edge CDN Tier"]
User["End User Request"] --> CF["Cloudflare Edge CDN"]
CF -->|"Edge Cache MISS"| SSR["Next.js 16 SSR Container Cluster"]
CF -->|"Edge Cache HIT (Poisoned 6-Month HTML)"| BrokenClient["React 19 Hydration Crash (#441)"]
end
subgraph NextJS_PPR ["2. Next.js 16 Partial Prerendering Lifecycle"]
SSR --> P1["Phase 1: Dynamic Prerender (Static Shell Discovery)"]
P1 -->|"Injects Hanging Promise"| GlobalMap["Process-Global inFlightRequests Map (LEAK)"]
P1 -->|"Shell Complete"| Reject["Force Reject: HANGING_PROMISE_REJECTION"]
GlobalMap -->|"Phase 2 retrieves poisoned Promise"| P2["Phase 2: Dynamic Resume (Streaming Suspense Holes)"]
P2 -->|"Throws Exception"| StreamRX["Streams script: $RX('B:2', 'HANGING_PROMISE_REJECTION')"]
StreamRX -->|"Returns HTTP 200 OK"| CF
end
subgraph Tier1_Remediation ["3. Tier-1 Production Remediation Architecture"]
IsoClient["Client SingleFlight: typeof window !== 'undefined'"]
IsoServer["Server SingleFlight: React.cache() per-render + Redis getRedisJson()"]
MCPGateway["Read-Only MCP Gateway (ops__cloudflare_config)"]
VaultSec["Secure Vault: secrets.env (chmod 0600)"]
MCPGateway -.->|"Lazy Load"| VaultSec
MCPGateway -->|"Secure Edge Purge & Audit"| CF
end
1. Anatomy of Next.js 16 Partial Prerendering (PPR) Two-Phase Execution
In Next.js 16, enabling cacheComponents: true decouples dynamic page generation from conventional monolithic SSR. For dynamic routes whose segment parameters are not pre-rendered in generateStaticParams(), the server executes a rapid two-phase sequence:
Phase 1: Dynamic Prerender (Static Shell Discovery)
The engine executes the layout and component hierarchy to compute the boundary between static markup and dynamic content wrapped within <Suspense>.
- Any data loader wrapped in
"use cache"executes to completion and is cached in memory. - All non-cached dynamic requests (such as standard un-cached
fetch()invocations) are intentionally stalled. Next.js returns a synthetic Hanging Promise to force React to activate the corresponding<Suspense>fallback boundary. - Once the static shell discovery completes, Next.js aborts all Phase-1 hanging promises using an internal rejection object:
Phase 2: Dynamic Resume (Streaming Suspense Holes)
Approximately 1 millisecond after Phase 1 concludes, the runtime initiates Phase 2. Here, it fulfills the real dynamic data loaders and streams HTML chunks directly down the wire using HTTP Chunked Transfer Encoding.
2. The Root Cause: Process-Global In-Flight Maps vs. Hanging Promise Rejections
To mitigate Thundering Herd contention during peak traffic spikes, developers often embed in-flight request coalescing inside a Node.js module-scoped Map:
// HIGH RISK: Process-global Map shared across all SSR threads and request phases
const inFlightRequests = new Map<string, Promise<unknown>>();
export async function fetchWithSingleFlight<T>(key: string, fetcher: () => Promise<T>): Promise<T> {
const existing = inFlightRequests.get(key);
if (existing) {
return existing as Promise<T>;
}
const promise = (async () => {
try {
return await fetcher();
} finally {
inFlightRequests.delete(key);
}
})();
inFlightRequests.set(key, promise);
return promise;
}
The Cascade Sequence
- In Phase 1, a nested server component triggers
fetchWithSingleFlight('stock:CTG', ...). The hanging promise is stored insideinFlightRequests. - As Phase 1 completes, Next.js fires the
HANGING_PROMISE_REJECTIONabort signal. - Concurrently in the next microtask, Phase 2 spins up, and its dynamic component also invokes
fetchWithSingleFlight('stock:CTG', ...). - Because the Phase-1 promise has not finished running its
finallycleanup block, Phase 2 receives a reference to that exact aborted Promise! - In Phase 2,
async-data-provider.tsxexecutesunstable_rethrow(error). The error breaks out of<Suspense>boundariesB:2andB:3. - Next.js concludes the request with
HTTP 200 OK, embedding:
<script>$RX("B:2","HANGING_PROMISE_REJECTION")</script>
3. Edge Cache Amplification: How Cloudflare Locked Broken HTML for 6 Months
An application-layer race condition typically produces transient failures for isolated users. However, in this architecture, Cloudflare’s Edge Rule transformed a transient glitch into a prolonged outage:
sequenceDiagram
autonumber
participant Browser as Client Browser
participant Edge as Cloudflare Edge CDN
participant SSR as Node.js SSR Cluster
Browser->>Edge: GET /stocks/CTG (Initial Request - Cache MISS)
Edge->>SSR: GET /stocks/CTG
Note over SSR: Phase 1 leaks Hanging Promise to Phase 2<br/>Suspense boundary B:2 aborts
SSR-->>Edge: HTTP 200 OK (Contains error script $RX)
Note over Edge: Edge Cache evaluates HTTP 200 OK<br/>Freezes response for 6 months!
Edge-->>Browser: Returns broken HTML (cf-cache-status: MISS)
Note over Browser: React 19 Hydration: Minified Error #441<br/>Full page renders error.tsx
loop All subsequent visitors over the next 12 hours
Browser->>Edge: GET /stocks/CTG
Edge-->>Browser: Instant cached error response (cf-cache-status: HIT, age: 44,049s)
end
When subsequent users requested /stocks/CTG, Cloudflare matched the stored HTTP 200 record and served it with cf-cache-status: HIT and age: 44,049s. Every user’s browser hydrated an aborted DOM tree, crashing immediately into React 19’s Minified React error #441.
4. Tier-1 Production Standard Remediation
To eliminate this vulnerability without degrading server throughput, the solution enforces a clean environment boundary and separates per-render deduplication from persistent caching.
4.1. Environment-Bounded SingleFlight (Browser-Only Coalescing)
/**
* SSR-Safe In-Flight Deduplication Engine.
* Restricts process-global Promise sharing strictly to client-side runtimes.
*/
export class SsrSafeSingleFlight {
private inFlight = new Map<string, Promise<unknown>>();
private browserOnly: boolean;
constructor(options?: { browserOnly?: boolean }) {
this.browserOnly = options?.browserOnly ?? true;
}
public async dedupe<T>(
key: string,
fetcher: () => Promise<T>,
options?: { isServer?: boolean }
): Promise<T> {
const isServer = options?.isServer ?? (typeof window === "undefined");
// Bypass process-global maps entirely during server-side rendering
if (this.browserOnly && isServer) {
return fetcher();
}
const existing = this.inFlight.get(key);
if (existing) {
return existing as Promise<T>;
}
const promise = (async () => {
try {
return await fetcher();
} catch (err) {
// Immediately evict hanging promises upon detection
this.inFlight.delete(key);
throw err;
} finally {
this.inFlight.delete(key);
}
})();
this.inFlight.set(key, promise);
return promise;
}
}
4.2. Server-Side Request Deduplication via React.cache and Redis
Within the Node.js server environment:
- Per-Render Scope: React 19’s
cache()API deduplicates requests within a single render tree without leaking promises across phases or concurrent requests:
import { cache } from 'react';
export const getStockDetail = cache(async (ticker: string) => {
return await fetchFromInternalGateway(`/api/v1/stocks/${ticker}`);
});
- Cross-Request Scope: Data is persisted in Redis (
getRedisJson). Records are written only after successful resolution, guaranteeing that hanging promises are never stored.
5. The Zero-Plaintext-Secrets Invariant & Read-Only MCP Gateway
During incident response, developers often paste API credentials (CLOUDFLARE_API_TOKEN) directly into operational runbooks to run manual purge commands. In the era of Autonomous AI Agents, this constitutes a severe security vulnerability:
- Project documentation is continuously ingested into agent context windows and vector RAG indices (Qdrant).
- Exposed credentials can leak into pull request descriptions, commit summaries, or public technical blogs.
flowchart LR
subgraph Host_Secure_Storage ["Host Protected Storage"]
EnvFile["~/.config/agent-harness/secrets.env (chmod 0600)"]
end
subgraph Agent_Interface ["Agent Context Interface"]
Agent["Autonomous Agent Loop"] -->|"Tool call: ops__cloudflare_config"| GW["Kido MCP Gateway"]
end
subgraph MCP_Execution ["Isolated Backend Execution"]
GW --> Engine["Ops Gateway Server (GET Only)"]
EnvFile -.->|"Lazy token extraction"| Engine
Engine -->|"HTTPS GET"| CFApi["Cloudflare API v4 (/zones, /rulesets)"]
CFApi --> RawRes["Raw Upstream Response"]
RawRes --> Redactor["redactSecrets() (Scrubs cfut_*, Bearer, Auth Headers)"]
Redactor --> SanitizedOutput["100% Sanitized Output"]
SanitizedOutput --> Agent
end
The Agent Harness Kit implements ops__cloudflare_config under three strict invariants:
- Strictly GET-Only: The tool exposes no mutation or deletion capabilities to the general agent loop, preventing accidental infrastructure disruption.
- Lazy Vault Ingestion: The token is resolved dynamically from a local
0600configuration file, avoiding persistent global environment exposure. - Automated Secret Scrubbing: All strings matching token prefixes or sensitive headers (
cfut_*,Bearer *, auth tokens) are automatically replaced with[REDACTED]before entering agent memory.
6. Operational Summary & Recommendations
- Audit Global State in Partial Prerendering: When enabling
cacheComponents: truein Next.js 16, audit all shared in-memory maps to ensure promises cannot leak across lifecycle phases. - Never Blindly Cache HTTP 200 Responses at the Edge: Edge CDN rules must respect SSR health indicators and bypass caching when partial boundary failure scripts are detected.
- Establish Hardened Tool Boundaries for AI Agents: Keep secrets out of documentation and source trees; mediate all cloud infrastructure interactions through read-only, secret-scrubbing MCP gateways.
Read the Companion Manga & Dev War-Story Edition on Kido Chronicles
Looking for the real-world production incidents, late-night debugging war stories, and illustrated manga episodes behind this architecture? Explore the companion chapters below:
Related Architecture Monographs

Dissecting the 4-Hop Cloudflare Tunnel Latency Trap: Submarine Routing Paradox and the Hybrid Edge Mesh Architecture
An architectural autopsy of performance degradation when self-hosting web applications via Cloudflare Tunnel on residential networks, analyzing the 4-hop trombone submarine latency loop, WSL2 ext4.vhdx storage failure modes, and the Tier-1 Hybrid Edge Mesh.

Hardening Production Docker Lifecycles: Native HEALTHCHECKs, Zero-Loss Named Volume Migrations, Dangling Image Garbage Collection, and Next.js Build-Time Variable Traps
Mastering container and persistent storage lifecycle management in production: Eliminating 502 Bad Gateway rollouts via native HEALTHCHECKs, safely migrating named volumes without data loss, automated 95% NVMe disk reclamation, and deconstructing Next.js AST build-time variables.

Tuning Caddy 2 & Cloudflare Edge at the Protocol Layer: Unfreezing Server-Sent Events (flush_interval -1), 204 CORS Preflight Short-Circuiting, and Deprecating HTTP/2 Push for 103 Early Hints
In-depth guide to optimizing Caddy 2 reverse proxy and Cloudflare Edge: Eliminating SSE buffer deadlocks in streaming container logs, offloading browser OPTIONS CORS preflight checks at the proxy layer, and pre-warming browser caches with RFC 8297 103 Early Hints.

Stealing 4 Bazel Primitives for Turborepo, 0ms Caddy Blue/Green & 4.8M-Row SQLite v2 Migration
How to keep Turborepo for TypeScript monorepos while extracting 4 Bazel primitives (rdeps, R2 CAS, slice visibility, strict action env guard); run internal Caddy Blue/Green for 0ms deploy cutover; safely migrate 4.8M SQLite heartbeat rows; and block semantic cache poisoning via entity guards.

Duong Phuc Khanh (Dương Phúc Khánh · Kido)
Senior Software Engineer & Systems Architect with 9+ years of experience in high-concurrency distributed architectures, Google Core Web Vitals optimization (0ms TBT, CLS 0.000), and author of the 164+ episode engineering war-story series Kido Chronicles.
Need High-Concurrency System Architecture Consulting, AI Automation, or Turnkey B2B Software?
Explore 41 production infrastructure packages (kido-packages (@kido/*)) and 18 turnkey B2B Web App/ERP systems with 100% source code ownership architected by Duong Phuc Khanh (Dương Phúc Khánh · Kido).
