React Server-Side Rendering (SSR) + Lume Engine: locating the root cause of a blank 502
The scene: it opens, it is blank, it returns 502
The first time I saw this was on 127.0.0.1:10090: the browser opened the homepage normally, static assets under public/ were all fine, but the photo area was a quiet stretch of white — no error banner, no loading indicator. Only in the console was there that inconspicuous failed request: /getPhotoMenu returning 502.
Behind that picture sit two processes. The Lume frontend is one; the thing that actually renders a page route into full HTML is the resident Node SSR backend on the other side, and the two talk FastCGI over a UNIX socket:
// nsbp-lume launcher: starts the resident React SSR backend, then the Lume
// engine which fronts the HTTP port and relays page routes to that backend.
Source: scripts/start.js. The order here is not a style choice: the backend starts first and the frontend second, because the frontend only owns the HTTP port and relays page routes to the backend. Dockerfile puts that relationship in the image's first sentence — React SSR served by the Lume C engine.
The same orchestration runs on the live instance https://nsbp.erishen.cn — the same two processes, the same socket, the same scripts/start.js. During the outage it showed exactly the picture below; /getPhotoMenu answers 200 again today.
Which is why "just restart it" fails by construction: make run, the backend process is there, the socket file is there, and the 502 survives a refresh. The problem is not "it did not come up"; it is that the thing being judged ready was not actually usable.
TL;DR
- The homepage opens and static assets load, but the photo area is blank and
/getPhotoMenureturns 502. - Lume is a frontend process; page routes are rendered by the resident Node SSR backend, and the two talk FastCGI over a UNIX socket.
- Minimal reproduction: start the Lume frontend alone without the backend — static assets still serve, everything routed through
react_prefixreturns 502. - The root cause is in startup orchestration: a leftover zombie socket makes
existsSyncmisjudge the backend as ready, so the frontend starts relaying immediately. make stopsends SIGTERM/SIGKILL and removes$(SSR_SOCK), yet the 502 survives a restart.
Source: https://github.com/erishen/nsbp-lume Live: https://nsbp.erishen.cn
Ruling out the suspects: three falsifications
Changing code first is the expensive mistake in troubleshooting: you end up having missed the disease and rewinding. So the three easiest suspicions go first.
One, processes did not exit cleanly? make stop reads .data/start.pids, sends SIGTERM and then SIGKILL, adds a pkill -f for server-ssr.cjs and lume nsbp.lume, and finally removes $(SSR_SOCK). Run stop and then run: the 502 is unchanged. They were killed; the problem is what they left behind.
Two, build artifacts missing? start.js has a direct guard:
if (!existsSync(backendBin)) {
console.error("missing build/server-ssr.cjs — run `pnpm build` first.");
process.exit(1);
}
Source: scripts/start.js. It only exits when build/server-ssr.cjs does not exist, and the script did reach the point of spawning the backend, so the artifact is present and the precheck passed. Re-running make build (esbuild bundles server and client) confirms the same: ruled out.
Three, frontend config or a type-level phantom? Static assets and the port are fine, and the failure lands only on routes relayed to the backend, so configuration does not hold; make check ($(LUME) --check nsbp.lume, Makefile) passes too, ruling out a type-level phantom.
Three falsifications leave exactly one cell: frontend in place, socket path not ready. The distribution of the symptom is itself the locator — static assets go through docroot and are served by Lume directly, page routes go through react_prefix relay; one works, one fails, so the failure sits precisely at "the moment the frontend starts relaying".
Root cause: existsSync standing in for "can connect"
start.js does wait for the backend to be ready, and the comment says so plainly. The three blocks below are the pre-fix implementation (recover it with git show 1ef4304^:scripts/start.js); line numbers refer to that revision:
let waited = 0;
while (!existsSync(sock)) {
if (backend.exitCode !== null) {
console.error("SSR backend exited early; not starting Lume front.");
clearPids();
process.exit(backend.exitCode ?? 1);
}
if (waited >= 5000) {
console.error("timed out waiting for FCGI socket; not starting Lume front.");
killProc(backend);
clearPids();
process.exit(1);
}
await wait(100);
waited += 100;
}
Pre-fix, that loop sits in the latter half of the file, with its comment two lines above: wait until the socket really appears, only then may the frontend leave the gate. The intent is fine; the disagreement is in the predicate — existsSync asks whether something exists at this path, not whether anyone is listening on this socket.
When the backend exits normally, the OS does not remove that socket file for you; it stays where it is and becomes a zombie socket. On the next start the backend is spawned, the loop begins to spin, but the old file is still there, so existsSync(sock) returns true on the first iteration, the loop body never runs, and the script goes straight on to spawn the frontend. The frontend then starts taking traffic while it is unknown whether the backend ever listened — static assets fine, page routes 502. This is also why the exitCode guard cannot catch it: the guard lives inside the loop body, and the loop was never entered.
Why does the old socket survive to the next start? Look at the cleanup:
await killStale();
await wait(400);
try {
unlinkSync(sock); // stale socket left by a dead backend
} catch {
/* none */
}
Pre-fix, this was a separate removal block. The logic is kill stale processes, wait 400 ms, then remove the stale socket — note the catch: if unlinkSync throws (file absent, or no permission to remove it), /* none */ swallows it without a character of output.
And killStale grabs both process names with pgrep -f and sends kill -9, with its own admission in the comment:
spawnSync("kill", ["-9", ...[...pids]]); // may EPERM; ignore
So in a restricted environment that self-healing path fails silently: unable to kill, no error, carry on. It is not the main cause here — the 502 survived make stop, which means the problem remains even when processes are genuinely gone — but it supplies one of the ways a stale socket gets left behind.
Chained together, the root cause is a single sentence: while (!existsSync(sock)) substitutes file existence for connection availability; together with the swallowed unlinkSync and kill -9's may EPERM; ignore, one stale socket file defeats the "backend is ready" judgement. The verdict point is the semantics of that line, not whether some process was killed cleanly.
The patch: three changes
These three changes landed in commit 1ef4304 (fix(start): probe the FCGI socket by connecting, not by file existence); the code below is the implementation as it now stands.
One, redefine readiness as "can connect". Try a connection with net; only a successful connect counts as ready, still bounded by the original five seconds:
function canConnect(path, timeoutMs = 250) {
return new Promise((resolve) => {
let settled = false;
const probe = net.connect(path);
const done = (ok) => {
if (settled) return;
settled = true;
probe.destroy();
resolve(ok);
};
probe.once("connect", () => done(true));
probe.once("error", () => done(false));
setTimeout(() => done(false), timeoutMs);
});
}
Source: scripts/start.js, with the net import at the top. The predicate is the while (!(await canConnect(sock))) loop; the probe carries its own 250 ms timeout, and together with the 100 ms poll interval it stays inside the original five-second budget.
The exitCode guard stays, because the two do different jobs: the connection probe answers "is it connected", exitCode answers "is there any point waiting". Both messages (SSR backend exited early / timed out waiting for FCGI socket) are left untouched — they already describe the failure accurately.
Two, stop swallowing unlinkSync's failure. If it cannot be removed, say so, and separate "was not there" from "could not remove":
try {
unlinkSync(sock); // stale socket left by a dead backend
} catch (err) {
// ENOENT means nothing to clean; anything else means the stale socket is
// still on disk and the readiness probe below has to cope with it.
if (err?.code !== "ENOENT") {
console.warn(`[start] stale socket not removed: ${err?.code ?? err?.message}`);
}
}
Source: scripts/start.js.
Now "the stale socket could not be removed" shows up in the terminal as a named reason instead of silence.
Three, at least leave a trace when killStale hits EPERM. It lands at scripts/start.js: Since we admit it may fail to kill, print the result: when spawnSync returns a non-zero status, say so, so "self-healing did not take effect" is traceable in the log rather than surfacing as a white page.
The entry point does not change: make run is still the documented path (Makefile, which only passes PORT into scripts/start.js), and every change lands inside the script. That also means verification runs the same entry a user actually walks.
Verification: putting the original failure condition back
"It does not return 502 after a refresh" is not proof of a fix. The nastiest property of this failure is that it is intermittent and quiet: it does not always break, and when it does, nothing is logged. So verification has to reconstruct the condition that breaks it.
make clean # removes .data too — a control case with no stale socket
make build # esbuild re-bundles server and client
make run # normal start: the frontend is released only after the backend is ready
A second thing to watch is ordering: the script prints ==> FCGI socket ready after Nms: … only once a connection has succeeded (scripts/start.js). Pre-fix, a zombie socket let readiness pass at 0ms while the backend had not bound yet; now that line has to wait for a real connection — measured here as after 300ms, with the terminal sequence showing the backend's listen line first, then this line, then Lume starting.
The key step is planting a zombie socket by hand: stop the service normally, drop a socket file into .data (no need to run a backend; it only has to fool existsSync), then make run. Before the fix, that leftover file let the loop pass on the first iteration, and page routes plus APIs went 502 wholesale. After it, the frontend should not be released: either it waits until the new backend genuinely accepts a connection, or it exits within five seconds with SSR backend exited early / timed out waiting for FCGI socket — never leave a "frontend here, backend elsewhere" pair sitting on 10090.
The criterion is not "it looks fixed"; it is "put the condition that fooled it back, and it no longer gets fooled".
Walk the container path separately (make docker-build, make docker-up, Makefile) to confirm orchestration holds inside the image. Keep the two layers apart: a passing container health check does not mean the script's readiness predicate is fixed, only that processes inside the image came up.
Boundaries
One thing cannot be changed here, and there is no pretending otherwise: /login and /logout are hard-coded reserved paths in the Lume engine's C layer. README.md says it outright — under react_prefix="/" they are not handled by the React relay but by the engine, and that is engine behaviour, not configurable at the DSL level. So the scope of this fix is strictly "the frontend must not start relaying before the backend is ready", and it says nothing about whether the login page can be SSR'd.
Verification deliberately avoids that path too, testing only homepage and photo-page relaying: what is reproduced and verified is the /getPhotoMenu fetch behind loadData in src/services/home.ts — the actual landing point of that 502. loadData did not change; what changed is whether the backend was there when it ran.
Retrospective: four lines
One, work out whose fault it is before touching anything. The symptom is always that surface combination — page opens, content empty, API 502 — so split it into "static assets fine / relayed routes 502". One works and one fails, and the failure is left in exactly one cell: frontend in place, socket path not ready.
Two, treat "the process is alive" and "the service is available" as two separate propositions. This is the core lesson: existsSync returning true only proves there is a file on disk, not that anyone is listening on the other end.
Three, treat every silent swallow as a pending hazard. catch { /* none */ } and // may EPERM; ignore are the same species: failure with no error, orchestration carries on, and the error surfaces in front of the user later. When you see that comment, ask: if this fails, does everything downstream still hold?
Four, verification must recreate the original bad condition. Intermittent, quiet failures are the easiest to be fooled by "ran it again and it was fine". Blocked counts as fixed; let through means you have not reached the point yet.
The health of this system never depends on whether some process is alive; it depends on whether "the backend socket accepts a connection" and "the frontend holds the port" hold as a pair. Next time the page opens and the content is quietly blank, the first question is not "which process died" but "what did the orchestration mistake for readiness".
Source code navigation
The body names files and symbols only; line numbers are omitted because they drift with every commit — search by symbol or by the quoted snippet.
Repository: https://github.com/erishen/nsbp-lume
Live: https://nsbp.erishen.cn
DockerfileMakefileREADME.mdscripts/start.jsnsbp.lumesrc/services/home.tssrc/services/photo.tssrc/utils/fetch.ts
Why does the page open and static assets load fine, but the photo area is blank and /getPhotoMenu returns 502?
The Lume frontend holds port 10090 and serves static assets, but page routes and data APIs are relayed through react_prefix to the Node SSR backend on the UNIX socket; with the backend absent the relay cannot write, so page routes and APIs return 502 together while the frontend never notices the backend is gone.
Why can't simply restarting the backend eliminate the 502?
The startup orchestration waits on whether the socket file exists, and a zombie socket left by a dead backend makes existsSync return true just the same, so the frontend believes the backend is ready and starts relaying — the restart pairs the new frontend with an obsolete socket file.
What does make stop clean up, and why can't it guarantee a healthy state?
It reads .data/start.pids, sends SIGTERM then SIGKILL, adds pkill -f 'server-ssr.cjs' and pkill -f 'lume nsbp.lume', and removes $(SSR_SOCK). But health does not depend on a process being alive; it depends on "the backend socket accepts a connection" and "the frontend holds the port" holding as a pair.
How do you reproduce the failure minimally?
Start the Lume frontend alone without the backend, then open the homepage: static assets such as /js/client.mjs and /js/client.css still serve, while every page route relayed through react_prefix returns 502.
Enjoy this article?
erishen/nsbp-lume
Comments (0)